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