1 /*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "graph_visualizer.h"
18
19 #include <dlfcn.h>
20
21 #include <cctype>
22 #include <ios>
23 #include <sstream>
24
25 #include "android-base/stringprintf.h"
26 #include "art_method.h"
27 #include "art_method-inl.h"
28 #include "base/intrusive_forward_list.h"
29 #include "bounds_check_elimination.h"
30 #include "builder.h"
31 #include "code_generator.h"
32 #include "data_type-inl.h"
33 #include "dead_code_elimination.h"
34 #include "dex/descriptors_names.h"
35 #include "disassembler.h"
36 #include "inliner.h"
37 #include "licm.h"
38 #include "nodes.h"
39 #include "optimization.h"
40 #include "reference_type_propagation.h"
41 #include "register_allocator_linear_scan.h"
42 #include "scoped_thread_state_change-inl.h"
43 #include "ssa_liveness_analysis.h"
44 #include "utils/assembler.h"
45
46 namespace art {
47
48 // Unique pass-name to identify that the dump is for printing to log.
49 constexpr const char* kDebugDumpName = "debug";
50 constexpr const char* kDebugDumpGraphName = "debug_graph";
51
52 using android::base::StringPrintf;
53
HasWhitespace(const char * str)54 static bool HasWhitespace(const char* str) {
55 DCHECK(str != nullptr);
56 while (str[0] != 0) {
57 if (isspace(str[0])) {
58 return true;
59 }
60 str++;
61 }
62 return false;
63 }
64
65 class StringList {
66 public:
67 enum Format {
68 kArrayBrackets,
69 kSetBrackets,
70 };
71
72 // Create an empty list
StringList(Format format=kArrayBrackets)73 explicit StringList(Format format = kArrayBrackets) : format_(format), is_empty_(true) {}
74
75 // Construct StringList from a linked list. List element class T
76 // must provide methods `GetNext` and `Dump`.
77 template<class T>
StringList(T * first_entry,Format format=kArrayBrackets)78 explicit StringList(T* first_entry, Format format = kArrayBrackets) : StringList(format) {
79 for (T* current = first_entry; current != nullptr; current = current->GetNext()) {
80 current->Dump(NewEntryStream());
81 }
82 }
83 // Construct StringList from a list of elements. The value type must provide method `Dump`.
84 template <typename Container>
StringList(const Container & list,Format format=kArrayBrackets)85 explicit StringList(const Container& list, Format format = kArrayBrackets) : StringList(format) {
86 for (const typename Container::value_type& current : list) {
87 current.Dump(NewEntryStream());
88 }
89 }
90
NewEntryStream()91 std::ostream& NewEntryStream() {
92 if (is_empty_) {
93 is_empty_ = false;
94 } else {
95 sstream_ << ",";
96 }
97 return sstream_;
98 }
99
100 private:
101 Format format_;
102 bool is_empty_;
103 std::ostringstream sstream_;
104
105 friend std::ostream& operator<<(std::ostream& os, const StringList& list);
106 };
107
operator <<(std::ostream & os,const StringList & list)108 std::ostream& operator<<(std::ostream& os, const StringList& list) {
109 switch (list.format_) {
110 case StringList::kArrayBrackets: return os << "[" << list.sstream_.str() << "]";
111 case StringList::kSetBrackets: return os << "{" << list.sstream_.str() << "}";
112 default:
113 LOG(FATAL) << "Invalid StringList format";
114 UNREACHABLE();
115 }
116 }
117
118 #ifndef ART_STATIC_LIBART_COMPILER
119 using create_disasm_prototype = Disassembler*(InstructionSet, DisassemblerOptions*);
120 #endif
121
122 class HGraphVisualizerDisassembler {
123 public:
HGraphVisualizerDisassembler(InstructionSet instruction_set,const uint8_t * base_address,const uint8_t * end_address)124 HGraphVisualizerDisassembler(InstructionSet instruction_set,
125 const uint8_t* base_address,
126 const uint8_t* end_address)
127 : instruction_set_(instruction_set), disassembler_(nullptr) {
128 #ifndef ART_STATIC_LIBART_COMPILER
129 constexpr const char* libart_disassembler_so_name =
130 kIsDebugBuild ? "libartd-disassembler.so" : "libart-disassembler.so";
131 libart_disassembler_handle_ = dlopen(libart_disassembler_so_name, RTLD_NOW);
132 if (libart_disassembler_handle_ == nullptr) {
133 LOG(ERROR) << "Failed to dlopen " << libart_disassembler_so_name << ": " << dlerror();
134 return;
135 }
136 constexpr const char* create_disassembler_symbol = "create_disassembler";
137 create_disasm_prototype* create_disassembler = reinterpret_cast<create_disasm_prototype*>(
138 dlsym(libart_disassembler_handle_, create_disassembler_symbol));
139 if (create_disassembler == nullptr) {
140 LOG(ERROR) << "Could not find " << create_disassembler_symbol << " entry in "
141 << libart_disassembler_so_name << ": " << dlerror();
142 return;
143 }
144 #endif
145 // Reading the disassembly from 0x0 is easier, so we print relative
146 // addresses. We will only disassemble the code once everything has
147 // been generated, so we can read data in literal pools.
148 disassembler_ = std::unique_ptr<Disassembler>(create_disassembler(
149 instruction_set,
150 new DisassemblerOptions(/* absolute_addresses= */ false,
151 base_address,
152 end_address,
153 /* can_read_literals= */ true,
154 Is64BitInstructionSet(instruction_set)
155 ? &Thread::DumpThreadOffset<PointerSize::k64>
156 : &Thread::DumpThreadOffset<PointerSize::k32>)));
157 }
158
~HGraphVisualizerDisassembler()159 ~HGraphVisualizerDisassembler() {
160 // We need to call ~Disassembler() before we close the library.
161 disassembler_.reset();
162 #ifndef ART_STATIC_LIBART_COMPILER
163 if (libart_disassembler_handle_ != nullptr) {
164 dlclose(libart_disassembler_handle_);
165 }
166 #endif
167 }
168
Disassemble(std::ostream & output,size_t start,size_t end) const169 void Disassemble(std::ostream& output, size_t start, size_t end) const {
170 if (disassembler_ == nullptr) {
171 return;
172 }
173
174 const uint8_t* base = disassembler_->GetDisassemblerOptions()->base_address_;
175 if (instruction_set_ == InstructionSet::kThumb2) {
176 // ARM and Thumb-2 use the same disassembler. The bottom bit of the
177 // address is used to distinguish between the two.
178 base += 1;
179 }
180 disassembler_->Dump(output, base + start, base + end);
181 }
182
183 private:
184 InstructionSet instruction_set_;
185 std::unique_ptr<Disassembler> disassembler_;
186
187 #ifndef ART_STATIC_LIBART_COMPILER
188 void* libart_disassembler_handle_;
189 #endif
190 };
191
192
193 /**
194 * HGraph visitor to generate a file suitable for the c1visualizer tool and IRHydra.
195 */
196 class HGraphVisualizerPrinter : public HGraphDelegateVisitor {
197 public:
HGraphVisualizerPrinter(HGraph * graph,std::ostream & output,const char * pass_name,bool is_after_pass,bool graph_in_bad_state,const CodeGenerator * codegen,const BlockNamer & namer,const DisassemblyInformation * disasm_info=nullptr)198 HGraphVisualizerPrinter(HGraph* graph,
199 std::ostream& output,
200 const char* pass_name,
201 bool is_after_pass,
202 bool graph_in_bad_state,
203 const CodeGenerator* codegen,
204 const BlockNamer& namer,
205 const DisassemblyInformation* disasm_info = nullptr)
206 : HGraphDelegateVisitor(graph),
207 output_(output),
208 pass_name_(pass_name),
209 is_after_pass_(is_after_pass),
210 graph_in_bad_state_(graph_in_bad_state),
211 codegen_(codegen),
212 disasm_info_(disasm_info),
213 namer_(namer),
214 disassembler_(disasm_info_ != nullptr
215 ? new HGraphVisualizerDisassembler(
216 codegen_->GetInstructionSet(),
217 codegen_->GetAssembler().CodeBufferBaseAddress(),
218 codegen_->GetAssembler().CodeBufferBaseAddress()
219 + codegen_->GetAssembler().CodeSize())
220 : nullptr),
221 indent_(0) {}
222
Flush()223 void Flush() {
224 // We use "\n" instead of std::endl to avoid implicit flushing which
225 // generates too many syscalls during debug-GC tests (b/27826765).
226 output_ << std::flush;
227 }
228
StartTag(const char * name)229 void StartTag(const char* name) {
230 AddIndent();
231 output_ << "begin_" << name << "\n";
232 indent_++;
233 }
234
EndTag(const char * name)235 void EndTag(const char* name) {
236 indent_--;
237 AddIndent();
238 output_ << "end_" << name << "\n";
239 }
240
PrintProperty(const char * name,HBasicBlock * blk)241 void PrintProperty(const char* name, HBasicBlock* blk) {
242 AddIndent();
243 output_ << name << " \"" << namer_.GetName(blk) << "\"\n";
244 }
245
PrintProperty(const char * name,const char * property)246 void PrintProperty(const char* name, const char* property) {
247 AddIndent();
248 output_ << name << " \"" << property << "\"\n";
249 }
250
PrintProperty(const char * name,const char * property,int id)251 void PrintProperty(const char* name, const char* property, int id) {
252 AddIndent();
253 output_ << name << " \"" << property << id << "\"\n";
254 }
255
PrintEmptyProperty(const char * name)256 void PrintEmptyProperty(const char* name) {
257 AddIndent();
258 output_ << name << "\n";
259 }
260
PrintTime(const char * name)261 void PrintTime(const char* name) {
262 AddIndent();
263 output_ << name << " " << time(nullptr) << "\n";
264 }
265
PrintInt(const char * name,int value)266 void PrintInt(const char* name, int value) {
267 AddIndent();
268 output_ << name << " " << value << "\n";
269 }
270
AddIndent()271 void AddIndent() {
272 for (size_t i = 0; i < indent_; ++i) {
273 output_ << " ";
274 }
275 }
276
PrintPredecessors(HBasicBlock * block)277 void PrintPredecessors(HBasicBlock* block) {
278 AddIndent();
279 output_ << "predecessors";
280 for (HBasicBlock* predecessor : block->GetPredecessors()) {
281 output_ << " \"" << namer_.GetName(predecessor) << "\" ";
282 }
283 if (block->IsEntryBlock() && (disasm_info_ != nullptr)) {
284 output_ << " \"" << kDisassemblyBlockFrameEntry << "\" ";
285 }
286 output_<< "\n";
287 }
288
PrintSuccessors(HBasicBlock * block)289 void PrintSuccessors(HBasicBlock* block) {
290 AddIndent();
291 output_ << "successors";
292 for (HBasicBlock* successor : block->GetNormalSuccessors()) {
293 output_ << " \"" << namer_.GetName(successor) << "\" ";
294 }
295 output_<< "\n";
296 }
297
PrintExceptionHandlers(HBasicBlock * block)298 void PrintExceptionHandlers(HBasicBlock* block) {
299 bool has_slow_paths = block->IsExitBlock() &&
300 (disasm_info_ != nullptr) &&
301 !disasm_info_->GetSlowPathIntervals().empty();
302 if (IsDebugDump() && block->GetExceptionalSuccessors().empty() && !has_slow_paths) {
303 return;
304 }
305 AddIndent();
306 output_ << "xhandlers";
307 for (HBasicBlock* handler : block->GetExceptionalSuccessors()) {
308 output_ << " \"" << namer_.GetName(handler) << "\" ";
309 }
310 if (has_slow_paths) {
311 output_ << " \"" << kDisassemblyBlockSlowPaths << "\" ";
312 }
313 output_<< "\n";
314 }
315
DumpLocation(std::ostream & stream,const Location & location)316 void DumpLocation(std::ostream& stream, const Location& location) {
317 DCHECK(codegen_ != nullptr);
318 if (location.IsRegister()) {
319 codegen_->DumpCoreRegister(stream, location.reg());
320 } else if (location.IsFpuRegister()) {
321 codegen_->DumpFloatingPointRegister(stream, location.reg());
322 } else if (location.IsConstant()) {
323 stream << "#";
324 HConstant* constant = location.GetConstant();
325 if (constant->IsIntConstant()) {
326 stream << constant->AsIntConstant()->GetValue();
327 } else if (constant->IsLongConstant()) {
328 stream << constant->AsLongConstant()->GetValue();
329 } else if (constant->IsFloatConstant()) {
330 stream << constant->AsFloatConstant()->GetValue();
331 } else if (constant->IsDoubleConstant()) {
332 stream << constant->AsDoubleConstant()->GetValue();
333 } else if (constant->IsNullConstant()) {
334 stream << "null";
335 }
336 } else if (location.IsInvalid()) {
337 stream << "invalid";
338 } else if (location.IsStackSlot()) {
339 stream << location.GetStackIndex() << "(sp)";
340 } else if (location.IsFpuRegisterPair()) {
341 codegen_->DumpFloatingPointRegister(stream, location.low());
342 stream << "|";
343 codegen_->DumpFloatingPointRegister(stream, location.high());
344 } else if (location.IsRegisterPair()) {
345 codegen_->DumpCoreRegister(stream, location.low());
346 stream << "|";
347 codegen_->DumpCoreRegister(stream, location.high());
348 } else if (location.IsUnallocated()) {
349 stream << "unallocated";
350 } else if (location.IsDoubleStackSlot()) {
351 stream << "2x" << location.GetStackIndex() << "(sp)";
352 } else {
353 DCHECK(location.IsSIMDStackSlot());
354 stream << "4x" << location.GetStackIndex() << "(sp)";
355 }
356 }
357
StartAttributeStream(const char * name=nullptr)358 std::ostream& StartAttributeStream(const char* name = nullptr) {
359 if (name == nullptr) {
360 output_ << " ";
361 } else {
362 DCHECK(!HasWhitespace(name)) << "Checker does not allow spaces in attributes";
363 output_ << " " << name << ":";
364 }
365 return output_;
366 }
367
VisitParallelMove(HParallelMove * instruction)368 void VisitParallelMove(HParallelMove* instruction) override {
369 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
370 StringList moves;
371 for (size_t i = 0, e = instruction->NumMoves(); i < e; ++i) {
372 MoveOperands* move = instruction->MoveOperandsAt(i);
373 std::ostream& str = moves.NewEntryStream();
374 DumpLocation(str, move->GetSource());
375 str << "->";
376 DumpLocation(str, move->GetDestination());
377 }
378 StartAttributeStream("moves") << moves;
379 }
380
VisitIntConstant(HIntConstant * instruction)381 void VisitIntConstant(HIntConstant* instruction) override {
382 StartAttributeStream() << instruction->GetValue();
383 }
384
VisitLongConstant(HLongConstant * instruction)385 void VisitLongConstant(HLongConstant* instruction) override {
386 StartAttributeStream() << instruction->GetValue();
387 }
388
VisitFloatConstant(HFloatConstant * instruction)389 void VisitFloatConstant(HFloatConstant* instruction) override {
390 StartAttributeStream() << instruction->GetValue();
391 }
392
VisitDoubleConstant(HDoubleConstant * instruction)393 void VisitDoubleConstant(HDoubleConstant* instruction) override {
394 StartAttributeStream() << instruction->GetValue();
395 }
396
VisitPhi(HPhi * phi)397 void VisitPhi(HPhi* phi) override {
398 StartAttributeStream("reg") << phi->GetRegNumber();
399 StartAttributeStream("is_catch_phi") << std::boolalpha << phi->IsCatchPhi() << std::noboolalpha;
400 }
401
VisitMemoryBarrier(HMemoryBarrier * barrier)402 void VisitMemoryBarrier(HMemoryBarrier* barrier) override {
403 StartAttributeStream("kind") << barrier->GetBarrierKind();
404 }
405
VisitMonitorOperation(HMonitorOperation * monitor)406 void VisitMonitorOperation(HMonitorOperation* monitor) override {
407 StartAttributeStream("kind") << (monitor->IsEnter() ? "enter" : "exit");
408 }
409
VisitLoadClass(HLoadClass * load_class)410 void VisitLoadClass(HLoadClass* load_class) override {
411 StartAttributeStream("load_kind") << load_class->GetLoadKind();
412 StartAttributeStream("class_name")
413 << load_class->GetDexFile().PrettyType(load_class->GetTypeIndex());
414 StartAttributeStream("gen_clinit_check")
415 << std::boolalpha << load_class->MustGenerateClinitCheck() << std::noboolalpha;
416 StartAttributeStream("needs_access_check") << std::boolalpha
417 << load_class->NeedsAccessCheck() << std::noboolalpha;
418 }
419
VisitLoadMethodHandle(HLoadMethodHandle * load_method_handle)420 void VisitLoadMethodHandle(HLoadMethodHandle* load_method_handle) override {
421 StartAttributeStream("load_kind") << "RuntimeCall";
422 StartAttributeStream("method_handle_index") << load_method_handle->GetMethodHandleIndex();
423 }
424
VisitLoadMethodType(HLoadMethodType * load_method_type)425 void VisitLoadMethodType(HLoadMethodType* load_method_type) override {
426 StartAttributeStream("load_kind") << "RuntimeCall";
427 const DexFile& dex_file = load_method_type->GetDexFile();
428 if (dex_file.NumProtoIds() >= load_method_type->GetProtoIndex().index_) {
429 const dex::ProtoId& proto_id = dex_file.GetProtoId(load_method_type->GetProtoIndex());
430 StartAttributeStream("method_type") << dex_file.GetProtoSignature(proto_id);
431 } else {
432 StartAttributeStream("method_type")
433 << "<<Unknown proto-idx: " << load_method_type->GetProtoIndex() << ">>";
434 }
435 }
436
VisitLoadString(HLoadString * load_string)437 void VisitLoadString(HLoadString* load_string) override {
438 StartAttributeStream("load_kind") << load_string->GetLoadKind();
439 }
440
HandleTypeCheckInstruction(HTypeCheckInstruction * check)441 void HandleTypeCheckInstruction(HTypeCheckInstruction* check) {
442 StartAttributeStream("check_kind") << check->GetTypeCheckKind();
443 StartAttributeStream("must_do_null_check") << std::boolalpha
444 << check->MustDoNullCheck() << std::noboolalpha;
445 if (check->GetTypeCheckKind() == TypeCheckKind::kBitstringCheck) {
446 StartAttributeStream("path_to_root") << std::hex
447 << "0x" << check->GetBitstringPathToRoot() << std::dec;
448 StartAttributeStream("mask") << std::hex << "0x" << check->GetBitstringMask() << std::dec;
449 }
450 }
451
VisitCheckCast(HCheckCast * check_cast)452 void VisitCheckCast(HCheckCast* check_cast) override {
453 HandleTypeCheckInstruction(check_cast);
454 }
455
VisitInstanceOf(HInstanceOf * instance_of)456 void VisitInstanceOf(HInstanceOf* instance_of) override {
457 HandleTypeCheckInstruction(instance_of);
458 }
459
VisitArrayLength(HArrayLength * array_length)460 void VisitArrayLength(HArrayLength* array_length) override {
461 StartAttributeStream("is_string_length") << std::boolalpha
462 << array_length->IsStringLength() << std::noboolalpha;
463 if (array_length->IsEmittedAtUseSite()) {
464 StartAttributeStream("emitted_at_use") << "true";
465 }
466 }
467
VisitBoundsCheck(HBoundsCheck * bounds_check)468 void VisitBoundsCheck(HBoundsCheck* bounds_check) override {
469 StartAttributeStream("is_string_char_at") << std::boolalpha
470 << bounds_check->IsStringCharAt() << std::noboolalpha;
471 }
472
VisitArrayGet(HArrayGet * array_get)473 void VisitArrayGet(HArrayGet* array_get) override {
474 StartAttributeStream("is_string_char_at") << std::boolalpha
475 << array_get->IsStringCharAt() << std::noboolalpha;
476 }
477
VisitArraySet(HArraySet * array_set)478 void VisitArraySet(HArraySet* array_set) override {
479 StartAttributeStream("value_can_be_null") << std::boolalpha
480 << array_set->GetValueCanBeNull() << std::noboolalpha;
481 StartAttributeStream("needs_type_check") << std::boolalpha
482 << array_set->NeedsTypeCheck() << std::noboolalpha;
483 }
484
VisitCompare(HCompare * compare)485 void VisitCompare(HCompare* compare) override {
486 StartAttributeStream("bias") << compare->GetBias();
487 }
488
VisitInvoke(HInvoke * invoke)489 void VisitInvoke(HInvoke* invoke) override {
490 StartAttributeStream("dex_file_index") << invoke->GetMethodReference().index;
491 ArtMethod* method = invoke->GetResolvedMethod();
492 // We don't print signatures, which conflict with c1visualizer format.
493 static constexpr bool kWithSignature = false;
494 // Note that we can only use the graph's dex file for the unresolved case. The
495 // other invokes might be coming from inlined methods.
496 ScopedObjectAccess soa(Thread::Current());
497 std::string method_name = (method == nullptr)
498 ? invoke->GetMethodReference().PrettyMethod(kWithSignature)
499 : method->PrettyMethod(kWithSignature);
500 StartAttributeStream("method_name") << method_name;
501 StartAttributeStream("always_throws") << std::boolalpha
502 << invoke->AlwaysThrows()
503 << std::noboolalpha;
504 if (method != nullptr) {
505 StartAttributeStream("method_index") << method->GetMethodIndex();
506 }
507 }
508
VisitInvokeUnresolved(HInvokeUnresolved * invoke)509 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) override {
510 VisitInvoke(invoke);
511 StartAttributeStream("invoke_type") << invoke->GetInvokeType();
512 }
513
VisitInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)514 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) override {
515 VisitInvoke(invoke);
516 StartAttributeStream("method_load_kind") << invoke->GetMethodLoadKind();
517 StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
518 if (invoke->IsStatic()) {
519 StartAttributeStream("clinit_check") << invoke->GetClinitCheckRequirement();
520 }
521 }
522
VisitInvokeVirtual(HInvokeVirtual * invoke)523 void VisitInvokeVirtual(HInvokeVirtual* invoke) override {
524 VisitInvoke(invoke);
525 StartAttributeStream("intrinsic") << invoke->GetIntrinsic();
526 }
527
VisitInvokePolymorphic(HInvokePolymorphic * invoke)528 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) override {
529 VisitInvoke(invoke);
530 StartAttributeStream("invoke_type") << "InvokePolymorphic";
531 }
532
VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet * iget)533 void VisitPredicatedInstanceFieldGet(HPredicatedInstanceFieldGet* iget) override {
534 StartAttributeStream("field_name") <<
535 iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
536 /* with type */ false);
537 StartAttributeStream("field_type") << iget->GetFieldType();
538 }
539
VisitInstanceFieldGet(HInstanceFieldGet * iget)540 void VisitInstanceFieldGet(HInstanceFieldGet* iget) override {
541 StartAttributeStream("field_name") <<
542 iget->GetFieldInfo().GetDexFile().PrettyField(iget->GetFieldInfo().GetFieldIndex(),
543 /* with type */ false);
544 StartAttributeStream("field_type") << iget->GetFieldType();
545 }
546
VisitInstanceFieldSet(HInstanceFieldSet * iset)547 void VisitInstanceFieldSet(HInstanceFieldSet* iset) override {
548 StartAttributeStream("field_name") <<
549 iset->GetFieldInfo().GetDexFile().PrettyField(iset->GetFieldInfo().GetFieldIndex(),
550 /* with type */ false);
551 StartAttributeStream("field_type") << iset->GetFieldType();
552 StartAttributeStream("predicated") << std::boolalpha << iset->GetIsPredicatedSet();
553 }
554
VisitStaticFieldGet(HStaticFieldGet * sget)555 void VisitStaticFieldGet(HStaticFieldGet* sget) override {
556 StartAttributeStream("field_name") <<
557 sget->GetFieldInfo().GetDexFile().PrettyField(sget->GetFieldInfo().GetFieldIndex(),
558 /* with type */ false);
559 StartAttributeStream("field_type") << sget->GetFieldType();
560 }
561
VisitStaticFieldSet(HStaticFieldSet * sset)562 void VisitStaticFieldSet(HStaticFieldSet* sset) override {
563 StartAttributeStream("field_name") <<
564 sset->GetFieldInfo().GetDexFile().PrettyField(sset->GetFieldInfo().GetFieldIndex(),
565 /* with type */ false);
566 StartAttributeStream("field_type") << sset->GetFieldType();
567 }
568
VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet * field_access)569 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* field_access) override {
570 StartAttributeStream("field_type") << field_access->GetFieldType();
571 }
572
VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet * field_access)573 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* field_access) override {
574 StartAttributeStream("field_type") << field_access->GetFieldType();
575 }
576
VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet * field_access)577 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* field_access) override {
578 StartAttributeStream("field_type") << field_access->GetFieldType();
579 }
580
VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet * field_access)581 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* field_access) override {
582 StartAttributeStream("field_type") << field_access->GetFieldType();
583 }
584
VisitTryBoundary(HTryBoundary * try_boundary)585 void VisitTryBoundary(HTryBoundary* try_boundary) override {
586 StartAttributeStream("kind") << (try_boundary->IsEntry() ? "entry" : "exit");
587 }
588
VisitDeoptimize(HDeoptimize * deoptimize)589 void VisitDeoptimize(HDeoptimize* deoptimize) override {
590 StartAttributeStream("kind") << deoptimize->GetKind();
591 }
592
VisitVecOperation(HVecOperation * vec_operation)593 void VisitVecOperation(HVecOperation* vec_operation) override {
594 StartAttributeStream("packed_type") << vec_operation->GetPackedType();
595 }
596
VisitVecMemoryOperation(HVecMemoryOperation * vec_mem_operation)597 void VisitVecMemoryOperation(HVecMemoryOperation* vec_mem_operation) override {
598 StartAttributeStream("alignment") << vec_mem_operation->GetAlignment().ToString();
599 }
600
VisitVecHalvingAdd(HVecHalvingAdd * hadd)601 void VisitVecHalvingAdd(HVecHalvingAdd* hadd) override {
602 VisitVecBinaryOperation(hadd);
603 StartAttributeStream("rounded") << std::boolalpha << hadd->IsRounded() << std::noboolalpha;
604 }
605
VisitVecMultiplyAccumulate(HVecMultiplyAccumulate * instruction)606 void VisitVecMultiplyAccumulate(HVecMultiplyAccumulate* instruction) override {
607 VisitVecOperation(instruction);
608 StartAttributeStream("kind") << instruction->GetOpKind();
609 }
610
VisitVecDotProd(HVecDotProd * instruction)611 void VisitVecDotProd(HVecDotProd* instruction) override {
612 VisitVecOperation(instruction);
613 DataType::Type arg_type = instruction->InputAt(1)->AsVecOperation()->GetPackedType();
614 StartAttributeStream("type") << (instruction->IsZeroExtending() ?
615 DataType::ToUnsigned(arg_type) :
616 DataType::ToSigned(arg_type));
617 }
618
619 #if defined(ART_ENABLE_CODEGEN_arm) || defined(ART_ENABLE_CODEGEN_arm64)
VisitMultiplyAccumulate(HMultiplyAccumulate * instruction)620 void VisitMultiplyAccumulate(HMultiplyAccumulate* instruction) override {
621 StartAttributeStream("kind") << instruction->GetOpKind();
622 }
623
VisitBitwiseNegatedRight(HBitwiseNegatedRight * instruction)624 void VisitBitwiseNegatedRight(HBitwiseNegatedRight* instruction) override {
625 StartAttributeStream("kind") << instruction->GetOpKind();
626 }
627
VisitDataProcWithShifterOp(HDataProcWithShifterOp * instruction)628 void VisitDataProcWithShifterOp(HDataProcWithShifterOp* instruction) override {
629 StartAttributeStream("kind") << instruction->GetInstrKind() << "+" << instruction->GetOpKind();
630 if (HDataProcWithShifterOp::IsShiftOp(instruction->GetOpKind())) {
631 StartAttributeStream("shift") << instruction->GetShiftAmount();
632 }
633 }
634 #endif
635
IsPass(const char * name)636 bool IsPass(const char* name) {
637 return strcmp(pass_name_, name) == 0;
638 }
639
IsDebugDump()640 bool IsDebugDump() {
641 return IsPass(kDebugDumpGraphName) || IsPass(kDebugDumpName);
642 }
643
PrintInstruction(HInstruction * instruction)644 void PrintInstruction(HInstruction* instruction) {
645 output_ << instruction->DebugName();
646 HConstInputsRef inputs = instruction->GetInputs();
647 if (!inputs.empty()) {
648 StringList input_list;
649 for (const HInstruction* input : inputs) {
650 input_list.NewEntryStream() << DataType::TypeId(input->GetType()) << input->GetId();
651 }
652 StartAttributeStream() << input_list;
653 }
654 if (instruction->GetDexPc() != kNoDexPc) {
655 StartAttributeStream("dex_pc") << instruction->GetDexPc();
656 } else {
657 StartAttributeStream("dex_pc") << "n/a";
658 }
659 HBasicBlock* block = instruction->GetBlock();
660 if (IsPass(kDebugDumpName)) {
661 // Include block name for logcat use.
662 StartAttributeStream("block") << namer_.GetName(block);
663 }
664 instruction->Accept(this);
665 if (instruction->HasEnvironment()) {
666 StringList envs;
667 for (HEnvironment* environment = instruction->GetEnvironment();
668 environment != nullptr;
669 environment = environment->GetParent()) {
670 StringList vregs;
671 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
672 HInstruction* insn = environment->GetInstructionAt(i);
673 if (insn != nullptr) {
674 vregs.NewEntryStream() << DataType::TypeId(insn->GetType()) << insn->GetId();
675 } else {
676 vregs.NewEntryStream() << "_";
677 }
678 }
679 envs.NewEntryStream() << vregs;
680 }
681 StartAttributeStream("env") << envs;
682 }
683 if (IsPass(SsaLivenessAnalysis::kLivenessPassName)
684 && is_after_pass_
685 && instruction->GetLifetimePosition() != kNoLifetime) {
686 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
687 if (instruction->HasLiveInterval()) {
688 LiveInterval* interval = instruction->GetLiveInterval();
689 StartAttributeStream("ranges")
690 << StringList(interval->GetFirstRange(), StringList::kSetBrackets);
691 StartAttributeStream("uses") << StringList(interval->GetUses());
692 StartAttributeStream("env_uses") << StringList(interval->GetEnvironmentUses());
693 StartAttributeStream("is_fixed") << interval->IsFixed();
694 StartAttributeStream("is_split") << interval->IsSplit();
695 StartAttributeStream("is_low") << interval->IsLowInterval();
696 StartAttributeStream("is_high") << interval->IsHighInterval();
697 }
698 }
699
700 if (IsPass(RegisterAllocator::kRegisterAllocatorPassName) && is_after_pass_) {
701 StartAttributeStream("liveness") << instruction->GetLifetimePosition();
702 LocationSummary* locations = instruction->GetLocations();
703 if (locations != nullptr) {
704 StringList input_list;
705 for (size_t i = 0, e = locations->GetInputCount(); i < e; ++i) {
706 DumpLocation(input_list.NewEntryStream(), locations->InAt(i));
707 }
708 std::ostream& attr = StartAttributeStream("locations");
709 attr << input_list << "->";
710 DumpLocation(attr, locations->Out());
711 }
712 }
713
714 HLoopInformation* loop_info = (block != nullptr) ? block->GetLoopInformation() : nullptr;
715 if (loop_info == nullptr) {
716 StartAttributeStream("loop") << "none";
717 } else {
718 StartAttributeStream("loop") << namer_.GetName(loop_info->GetHeader());
719 HLoopInformation* outer = loop_info->GetPreHeader()->GetLoopInformation();
720 if (outer != nullptr) {
721 StartAttributeStream("outer_loop") << namer_.GetName(outer->GetHeader());
722 } else {
723 StartAttributeStream("outer_loop") << "none";
724 }
725 StartAttributeStream("irreducible")
726 << std::boolalpha << loop_info->IsIrreducible() << std::noboolalpha;
727 }
728
729 // For the builder and the inliner, we want to add extra information on HInstructions
730 // that have reference types, and also HInstanceOf/HCheckcast.
731 if ((IsPass(HGraphBuilder::kBuilderPassName)
732 || IsPass(HInliner::kInlinerPassName)
733 || IsDebugDump())
734 && (instruction->GetType() == DataType::Type::kReference ||
735 instruction->IsInstanceOf() ||
736 instruction->IsCheckCast())) {
737 ReferenceTypeInfo info = (instruction->GetType() == DataType::Type::kReference)
738 ? instruction->IsLoadClass()
739 ? instruction->AsLoadClass()->GetLoadedClassRTI()
740 : instruction->GetReferenceTypeInfo()
741 : instruction->IsInstanceOf()
742 ? instruction->AsInstanceOf()->GetTargetClassRTI()
743 : instruction->AsCheckCast()->GetTargetClassRTI();
744 ScopedObjectAccess soa(Thread::Current());
745 if (info.IsValid()) {
746 StartAttributeStream("klass")
747 << mirror::Class::PrettyDescriptor(info.GetTypeHandle().Get());
748 if (instruction->GetType() == DataType::Type::kReference) {
749 StartAttributeStream("can_be_null")
750 << std::boolalpha << instruction->CanBeNull() << std::noboolalpha;
751 }
752 StartAttributeStream("exact") << std::boolalpha << info.IsExact() << std::noboolalpha;
753 } else if (instruction->IsLoadClass() ||
754 instruction->IsInstanceOf() ||
755 instruction->IsCheckCast()) {
756 StartAttributeStream("klass") << "unresolved";
757 } else {
758 // The NullConstant may be added to the graph during other passes that happen between
759 // ReferenceTypePropagation and Inliner (e.g. InstructionSimplifier). If the inliner
760 // doesn't run or doesn't inline anything, the NullConstant remains untyped.
761 // So we should check NullConstants for validity only after reference type propagation.
762 DCHECK(graph_in_bad_state_ ||
763 IsDebugDump() ||
764 (!is_after_pass_ && IsPass(HGraphBuilder::kBuilderPassName)))
765 << instruction->DebugName() << instruction->GetId() << " has invalid rti "
766 << (is_after_pass_ ? "after" : "before") << " pass " << pass_name_;
767 }
768 }
769 if (disasm_info_ != nullptr) {
770 DCHECK(disassembler_ != nullptr);
771 // If the information is available, disassemble the code generated for
772 // this instruction.
773 auto it = disasm_info_->GetInstructionIntervals().find(instruction);
774 if (it != disasm_info_->GetInstructionIntervals().end()
775 && it->second.start != it->second.end) {
776 output_ << "\n";
777 disassembler_->Disassemble(output_, it->second.start, it->second.end);
778 }
779 }
780 }
781
PrintInstructions(const HInstructionList & list)782 void PrintInstructions(const HInstructionList& list) {
783 for (HInstructionIterator it(list); !it.Done(); it.Advance()) {
784 HInstruction* instruction = it.Current();
785 int bci = 0;
786 size_t num_uses = instruction->GetUses().SizeSlow();
787 AddIndent();
788 output_ << bci << " " << num_uses << " "
789 << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
790 PrintInstruction(instruction);
791 output_ << " " << kEndInstructionMarker << "\n";
792 }
793 }
794
DumpStartOfDisassemblyBlock(const char * block_name,int predecessor_index,int successor_index)795 void DumpStartOfDisassemblyBlock(const char* block_name,
796 int predecessor_index,
797 int successor_index) {
798 StartTag("block");
799 PrintProperty("name", block_name);
800 PrintInt("from_bci", -1);
801 PrintInt("to_bci", -1);
802 if (predecessor_index != -1) {
803 PrintProperty("predecessors", "B", predecessor_index);
804 } else {
805 PrintEmptyProperty("predecessors");
806 }
807 if (successor_index != -1) {
808 PrintProperty("successors", "B", successor_index);
809 } else {
810 PrintEmptyProperty("successors");
811 }
812 PrintEmptyProperty("xhandlers");
813 PrintEmptyProperty("flags");
814 StartTag("states");
815 StartTag("locals");
816 PrintInt("size", 0);
817 PrintProperty("method", "None");
818 EndTag("locals");
819 EndTag("states");
820 StartTag("HIR");
821 }
822
DumpEndOfDisassemblyBlock()823 void DumpEndOfDisassemblyBlock() {
824 EndTag("HIR");
825 EndTag("block");
826 }
827
DumpDisassemblyBlockForFrameEntry()828 void DumpDisassemblyBlockForFrameEntry() {
829 DumpStartOfDisassemblyBlock(kDisassemblyBlockFrameEntry,
830 -1,
831 GetGraph()->GetEntryBlock()->GetBlockId());
832 output_ << " 0 0 disasm " << kDisassemblyBlockFrameEntry << " ";
833 GeneratedCodeInterval frame_entry = disasm_info_->GetFrameEntryInterval();
834 if (frame_entry.start != frame_entry.end) {
835 output_ << "\n";
836 disassembler_->Disassemble(output_, frame_entry.start, frame_entry.end);
837 }
838 output_ << kEndInstructionMarker << "\n";
839 DumpEndOfDisassemblyBlock();
840 }
841
DumpDisassemblyBlockForSlowPaths()842 void DumpDisassemblyBlockForSlowPaths() {
843 if (disasm_info_->GetSlowPathIntervals().empty()) {
844 return;
845 }
846 // If the graph has an exit block we attach the block for the slow paths
847 // after it. Else we just add the block to the graph without linking it to
848 // any other.
849 DumpStartOfDisassemblyBlock(
850 kDisassemblyBlockSlowPaths,
851 GetGraph()->HasExitBlock() ? GetGraph()->GetExitBlock()->GetBlockId() : -1,
852 -1);
853 for (SlowPathCodeInfo info : disasm_info_->GetSlowPathIntervals()) {
854 output_ << " 0 0 disasm " << info.slow_path->GetDescription() << "\n";
855 disassembler_->Disassemble(output_, info.code_interval.start, info.code_interval.end);
856 output_ << kEndInstructionMarker << "\n";
857 }
858 DumpEndOfDisassemblyBlock();
859 }
860
Run()861 void Run() {
862 StartTag("cfg");
863 std::ostringstream oss;
864 oss << pass_name_;
865 if (!IsDebugDump()) {
866 oss << " (" << (is_after_pass_ ? "after" : "before")
867 << (graph_in_bad_state_ ? ", bad_state" : "") << ")";
868 }
869 PrintProperty("name", oss.str().c_str());
870 if (disasm_info_ != nullptr) {
871 DumpDisassemblyBlockForFrameEntry();
872 }
873 VisitInsertionOrder();
874 if (disasm_info_ != nullptr) {
875 DumpDisassemblyBlockForSlowPaths();
876 }
877 EndTag("cfg");
878 Flush();
879 }
880
Run(HInstruction * instruction)881 void Run(HInstruction* instruction) {
882 output_ << DataType::TypeId(instruction->GetType()) << instruction->GetId() << " ";
883 PrintInstruction(instruction);
884 Flush();
885 }
886
VisitBasicBlock(HBasicBlock * block)887 void VisitBasicBlock(HBasicBlock* block) override {
888 StartTag("block");
889 PrintProperty("name", block);
890 if (block->GetLifetimeStart() != kNoLifetime) {
891 // Piggy back on these fields to show the lifetime of the block.
892 PrintInt("from_bci", block->GetLifetimeStart());
893 PrintInt("to_bci", block->GetLifetimeEnd());
894 } else if (!IsDebugDump()) {
895 // Don't print useless information to logcat.
896 PrintInt("from_bci", -1);
897 PrintInt("to_bci", -1);
898 }
899 PrintPredecessors(block);
900 PrintSuccessors(block);
901 PrintExceptionHandlers(block);
902
903 if (block->IsCatchBlock()) {
904 PrintProperty("flags", "catch_block");
905 } else if (!IsDebugDump()) {
906 // Don't print useless information to logcat
907 PrintEmptyProperty("flags");
908 }
909
910 if (block->GetDominator() != nullptr) {
911 PrintProperty("dominator", block->GetDominator());
912 }
913
914 if (!IsDebugDump() || !block->GetPhis().IsEmpty()) {
915 StartTag("states");
916 StartTag("locals");
917 PrintInt("size", 0);
918 PrintProperty("method", "None");
919 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
920 AddIndent();
921 HInstruction* instruction = it.Current();
922 output_ << instruction->GetId() << " " << DataType::TypeId(instruction->GetType())
923 << instruction->GetId() << "[ ";
924 for (const HInstruction* input : instruction->GetInputs()) {
925 output_ << input->GetId() << " ";
926 }
927 output_ << "]\n";
928 }
929 EndTag("locals");
930 EndTag("states");
931 }
932
933 StartTag("HIR");
934 PrintInstructions(block->GetPhis());
935 PrintInstructions(block->GetInstructions());
936 EndTag("HIR");
937 EndTag("block");
938 }
939
940 static constexpr const char* const kEndInstructionMarker = "<|@";
941 static constexpr const char* const kDisassemblyBlockFrameEntry = "FrameEntry";
942 static constexpr const char* const kDisassemblyBlockSlowPaths = "SlowPaths";
943
944 private:
945 std::ostream& output_;
946 const char* pass_name_;
947 const bool is_after_pass_;
948 const bool graph_in_bad_state_;
949 const CodeGenerator* codegen_;
950 const DisassemblyInformation* disasm_info_;
951 const BlockNamer& namer_;
952 std::unique_ptr<HGraphVisualizerDisassembler> disassembler_;
953 size_t indent_;
954
955 DISALLOW_COPY_AND_ASSIGN(HGraphVisualizerPrinter);
956 };
957
PrintName(std::ostream & os,HBasicBlock * blk) const958 std::ostream& HGraphVisualizer::OptionalDefaultNamer::PrintName(std::ostream& os,
959 HBasicBlock* blk) const {
960 if (namer_) {
961 return namer_->get().PrintName(os, blk);
962 } else {
963 return BlockNamer::PrintName(os, blk);
964 }
965 }
966
HGraphVisualizer(std::ostream * output,HGraph * graph,const CodeGenerator * codegen,std::optional<std::reference_wrapper<const BlockNamer>> namer)967 HGraphVisualizer::HGraphVisualizer(std::ostream* output,
968 HGraph* graph,
969 const CodeGenerator* codegen,
970 std::optional<std::reference_wrapper<const BlockNamer>> namer)
971 : output_(output), graph_(graph), codegen_(codegen), namer_(namer) {}
972
PrintHeader(const char * method_name) const973 void HGraphVisualizer::PrintHeader(const char* method_name) const {
974 DCHECK(output_ != nullptr);
975 HGraphVisualizerPrinter printer(graph_, *output_, "", true, false, codegen_, namer_);
976 printer.StartTag("compilation");
977 printer.PrintProperty("name", method_name);
978 printer.PrintProperty("method", method_name);
979 printer.PrintTime("date");
980 printer.EndTag("compilation");
981 printer.Flush();
982 }
983
InsertMetaDataAsCompilationBlock(const std::string & meta_data)984 std::string HGraphVisualizer::InsertMetaDataAsCompilationBlock(const std::string& meta_data) {
985 std::string time_str = std::to_string(time(nullptr));
986 std::string quoted_meta_data = "\"" + meta_data + "\"";
987 return StringPrintf("begin_compilation\n"
988 " name %s\n"
989 " method %s\n"
990 " date %s\n"
991 "end_compilation\n",
992 quoted_meta_data.c_str(),
993 quoted_meta_data.c_str(),
994 time_str.c_str());
995 }
996
DumpGraphDebug() const997 void HGraphVisualizer::DumpGraphDebug() const {
998 DumpGraph(/* pass_name= */ kDebugDumpGraphName,
999 /* is_after_pass= */ false,
1000 /* graph_in_bad_state= */ true);
1001 }
1002
DumpGraph(const char * pass_name,bool is_after_pass,bool graph_in_bad_state) const1003 void HGraphVisualizer::DumpGraph(const char* pass_name,
1004 bool is_after_pass,
1005 bool graph_in_bad_state) const {
1006 DCHECK(output_ != nullptr);
1007 if (!graph_->GetBlocks().empty()) {
1008 HGraphVisualizerPrinter printer(graph_,
1009 *output_,
1010 pass_name,
1011 is_after_pass,
1012 graph_in_bad_state,
1013 codegen_,
1014 namer_);
1015 printer.Run();
1016 }
1017 }
1018
DumpGraphWithDisassembly() const1019 void HGraphVisualizer::DumpGraphWithDisassembly() const {
1020 DCHECK(output_ != nullptr);
1021 if (!graph_->GetBlocks().empty()) {
1022 HGraphVisualizerPrinter printer(graph_,
1023 *output_,
1024 "disassembly",
1025 /* is_after_pass= */ true,
1026 /* graph_in_bad_state= */ false,
1027 codegen_,
1028 namer_,
1029 codegen_->GetDisassemblyInformation());
1030 printer.Run();
1031 }
1032 }
1033
DumpInstruction(std::ostream * output,HGraph * graph,HInstruction * instruction)1034 void HGraphVisualizer::DumpInstruction(std::ostream* output,
1035 HGraph* graph,
1036 HInstruction* instruction) {
1037 BlockNamer namer;
1038 HGraphVisualizerPrinter printer(graph,
1039 *output,
1040 /* pass_name= */ kDebugDumpName,
1041 /* is_after_pass= */ false,
1042 /* graph_in_bad_state= */ false,
1043 /* codegen= */ nullptr,
1044 /* namer= */ namer);
1045 printer.Run(instruction);
1046 }
1047
1048 } // namespace art
1049