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