1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This library implements `print` family of functions in classes like 11 // Module, Function, Value, etc. In-memory representation of those classes is 12 // converted to IR strings. 13 // 14 // Note that these routines must be extremely tolerant of various errors in the 15 // LLVM code, because it can be used for debugging transformations. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/None.h" 24 #include "llvm/ADT/Optional.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetVector.h" 27 #include "llvm/ADT/SmallString.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/StringExtras.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/iterator_range.h" 32 #include "llvm/BinaryFormat/Dwarf.h" 33 #include "llvm/Config/llvm-config.h" 34 #include "llvm/IR/Argument.h" 35 #include "llvm/IR/AssemblyAnnotationWriter.h" 36 #include "llvm/IR/Attributes.h" 37 #include "llvm/IR/BasicBlock.h" 38 #include "llvm/IR/CFG.h" 39 #include "llvm/IR/CallSite.h" 40 #include "llvm/IR/CallingConv.h" 41 #include "llvm/IR/Comdat.h" 42 #include "llvm/IR/Constant.h" 43 #include "llvm/IR/Constants.h" 44 #include "llvm/IR/DebugInfoMetadata.h" 45 #include "llvm/IR/DerivedTypes.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/GlobalAlias.h" 48 #include "llvm/IR/GlobalIFunc.h" 49 #include "llvm/IR/GlobalIndirectSymbol.h" 50 #include "llvm/IR/GlobalObject.h" 51 #include "llvm/IR/GlobalValue.h" 52 #include "llvm/IR/GlobalVariable.h" 53 #include "llvm/IR/IRPrintingPasses.h" 54 #include "llvm/IR/InlineAsm.h" 55 #include "llvm/IR/InstrTypes.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/LLVMContext.h" 59 #include "llvm/IR/Metadata.h" 60 #include "llvm/IR/Module.h" 61 #include "llvm/IR/ModuleSlotTracker.h" 62 #include "llvm/IR/ModuleSummaryIndex.h" 63 #include "llvm/IR/Operator.h" 64 #include "llvm/IR/Statepoint.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/IR/TypeFinder.h" 67 #include "llvm/IR/Use.h" 68 #include "llvm/IR/UseListOrder.h" 69 #include "llvm/IR/User.h" 70 #include "llvm/IR/Value.h" 71 #include "llvm/Support/AtomicOrdering.h" 72 #include "llvm/Support/Casting.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/ErrorHandling.h" 76 #include "llvm/Support/Format.h" 77 #include "llvm/Support/FormattedStream.h" 78 #include "llvm/Support/raw_ostream.h" 79 #include <algorithm> 80 #include <cassert> 81 #include <cctype> 82 #include <cstddef> 83 #include <cstdint> 84 #include <iterator> 85 #include <memory> 86 #include <string> 87 #include <tuple> 88 #include <utility> 89 #include <vector> 90 91 using namespace llvm; 92 93 // Make virtual table appear in this compilation unit. 94 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default; 95 96 //===----------------------------------------------------------------------===// 97 // Helper Functions 98 //===----------------------------------------------------------------------===// 99 100 namespace { 101 102 struct OrderMap { 103 DenseMap<const Value *, std::pair<unsigned, bool>> IDs; 104 105 unsigned size() const { return IDs.size(); } 106 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; } 107 108 std::pair<unsigned, bool> lookup(const Value *V) const { 109 return IDs.lookup(V); 110 } 111 112 void index(const Value *V) { 113 // Explicitly sequence get-size and insert-value operations to avoid UB. 114 unsigned ID = IDs.size() + 1; 115 IDs[V].first = ID; 116 } 117 }; 118 119 } // end anonymous namespace 120 121 static void orderValue(const Value *V, OrderMap &OM) { 122 if (OM.lookup(V).first) 123 return; 124 125 if (const Constant *C = dyn_cast<Constant>(V)) 126 if (C->getNumOperands() && !isa<GlobalValue>(C)) 127 for (const Value *Op : C->operands()) 128 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op)) 129 orderValue(Op, OM); 130 131 // Note: we cannot cache this lookup above, since inserting into the map 132 // changes the map's size, and thus affects the other IDs. 133 OM.index(V); 134 } 135 136 static OrderMap orderModule(const Module *M) { 137 // This needs to match the order used by ValueEnumerator::ValueEnumerator() 138 // and ValueEnumerator::incorporateFunction(). 139 OrderMap OM; 140 141 for (const GlobalVariable &G : M->globals()) { 142 if (G.hasInitializer()) 143 if (!isa<GlobalValue>(G.getInitializer())) 144 orderValue(G.getInitializer(), OM); 145 orderValue(&G, OM); 146 } 147 for (const GlobalAlias &A : M->aliases()) { 148 if (!isa<GlobalValue>(A.getAliasee())) 149 orderValue(A.getAliasee(), OM); 150 orderValue(&A, OM); 151 } 152 for (const GlobalIFunc &I : M->ifuncs()) { 153 if (!isa<GlobalValue>(I.getResolver())) 154 orderValue(I.getResolver(), OM); 155 orderValue(&I, OM); 156 } 157 for (const Function &F : *M) { 158 for (const Use &U : F.operands()) 159 if (!isa<GlobalValue>(U.get())) 160 orderValue(U.get(), OM); 161 162 orderValue(&F, OM); 163 164 if (F.isDeclaration()) 165 continue; 166 167 for (const Argument &A : F.args()) 168 orderValue(&A, OM); 169 for (const BasicBlock &BB : F) { 170 orderValue(&BB, OM); 171 for (const Instruction &I : BB) { 172 for (const Value *Op : I.operands()) 173 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) || 174 isa<InlineAsm>(*Op)) 175 orderValue(Op, OM); 176 orderValue(&I, OM); 177 } 178 } 179 } 180 return OM; 181 } 182 183 static void predictValueUseListOrderImpl(const Value *V, const Function *F, 184 unsigned ID, const OrderMap &OM, 185 UseListOrderStack &Stack) { 186 // Predict use-list order for this one. 187 using Entry = std::pair<const Use *, unsigned>; 188 SmallVector<Entry, 64> List; 189 for (const Use &U : V->uses()) 190 // Check if this user will be serialized. 191 if (OM.lookup(U.getUser()).first) 192 List.push_back(std::make_pair(&U, List.size())); 193 194 if (List.size() < 2) 195 // We may have lost some users. 196 return; 197 198 bool GetsReversed = 199 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V); 200 if (auto *BA = dyn_cast<BlockAddress>(V)) 201 ID = OM.lookup(BA->getBasicBlock()).first; 202 llvm::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) { 203 const Use *LU = L.first; 204 const Use *RU = R.first; 205 if (LU == RU) 206 return false; 207 208 auto LID = OM.lookup(LU->getUser()).first; 209 auto RID = OM.lookup(RU->getUser()).first; 210 211 // If ID is 4, then expect: 7 6 5 1 2 3. 212 if (LID < RID) { 213 if (GetsReversed) 214 if (RID <= ID) 215 return true; 216 return false; 217 } 218 if (RID < LID) { 219 if (GetsReversed) 220 if (LID <= ID) 221 return false; 222 return true; 223 } 224 225 // LID and RID are equal, so we have different operands of the same user. 226 // Assume operands are added in order for all instructions. 227 if (GetsReversed) 228 if (LID <= ID) 229 return LU->getOperandNo() < RU->getOperandNo(); 230 return LU->getOperandNo() > RU->getOperandNo(); 231 }); 232 233 if (std::is_sorted( 234 List.begin(), List.end(), 235 [](const Entry &L, const Entry &R) { return L.second < R.second; })) 236 // Order is already correct. 237 return; 238 239 // Store the shuffle. 240 Stack.emplace_back(V, F, List.size()); 241 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size"); 242 for (size_t I = 0, E = List.size(); I != E; ++I) 243 Stack.back().Shuffle[I] = List[I].second; 244 } 245 246 static void predictValueUseListOrder(const Value *V, const Function *F, 247 OrderMap &OM, UseListOrderStack &Stack) { 248 auto &IDPair = OM[V]; 249 assert(IDPair.first && "Unmapped value"); 250 if (IDPair.second) 251 // Already predicted. 252 return; 253 254 // Do the actual prediction. 255 IDPair.second = true; 256 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end()) 257 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack); 258 259 // Recursive descent into constants. 260 if (const Constant *C = dyn_cast<Constant>(V)) 261 if (C->getNumOperands()) // Visit GlobalValues. 262 for (const Value *Op : C->operands()) 263 if (isa<Constant>(Op)) // Visit GlobalValues. 264 predictValueUseListOrder(Op, F, OM, Stack); 265 } 266 267 static UseListOrderStack predictUseListOrder(const Module *M) { 268 OrderMap OM = orderModule(M); 269 270 // Use-list orders need to be serialized after all the users have been added 271 // to a value, or else the shuffles will be incomplete. Store them per 272 // function in a stack. 273 // 274 // Aside from function order, the order of values doesn't matter much here. 275 UseListOrderStack Stack; 276 277 // We want to visit the functions backward now so we can list function-local 278 // constants in the last Function they're used in. Module-level constants 279 // have already been visited above. 280 for (const Function &F : make_range(M->rbegin(), M->rend())) { 281 if (F.isDeclaration()) 282 continue; 283 for (const BasicBlock &BB : F) 284 predictValueUseListOrder(&BB, &F, OM, Stack); 285 for (const Argument &A : F.args()) 286 predictValueUseListOrder(&A, &F, OM, Stack); 287 for (const BasicBlock &BB : F) 288 for (const Instruction &I : BB) 289 for (const Value *Op : I.operands()) 290 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues. 291 predictValueUseListOrder(Op, &F, OM, Stack); 292 for (const BasicBlock &BB : F) 293 for (const Instruction &I : BB) 294 predictValueUseListOrder(&I, &F, OM, Stack); 295 } 296 297 // Visit globals last. 298 for (const GlobalVariable &G : M->globals()) 299 predictValueUseListOrder(&G, nullptr, OM, Stack); 300 for (const Function &F : *M) 301 predictValueUseListOrder(&F, nullptr, OM, Stack); 302 for (const GlobalAlias &A : M->aliases()) 303 predictValueUseListOrder(&A, nullptr, OM, Stack); 304 for (const GlobalIFunc &I : M->ifuncs()) 305 predictValueUseListOrder(&I, nullptr, OM, Stack); 306 for (const GlobalVariable &G : M->globals()) 307 if (G.hasInitializer()) 308 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack); 309 for (const GlobalAlias &A : M->aliases()) 310 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack); 311 for (const GlobalIFunc &I : M->ifuncs()) 312 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack); 313 for (const Function &F : *M) 314 for (const Use &U : F.operands()) 315 predictValueUseListOrder(U.get(), nullptr, OM, Stack); 316 317 return Stack; 318 } 319 320 static const Module *getModuleFromVal(const Value *V) { 321 if (const Argument *MA = dyn_cast<Argument>(V)) 322 return MA->getParent() ? MA->getParent()->getParent() : nullptr; 323 324 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 325 return BB->getParent() ? BB->getParent()->getParent() : nullptr; 326 327 if (const Instruction *I = dyn_cast<Instruction>(V)) { 328 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr; 329 return M ? M->getParent() : nullptr; 330 } 331 332 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 333 return GV->getParent(); 334 335 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) { 336 for (const User *U : MAV->users()) 337 if (isa<Instruction>(U)) 338 if (const Module *M = getModuleFromVal(U)) 339 return M; 340 return nullptr; 341 } 342 343 return nullptr; 344 } 345 346 static void PrintCallingConv(unsigned cc, raw_ostream &Out) { 347 switch (cc) { 348 default: Out << "cc" << cc; break; 349 case CallingConv::Fast: Out << "fastcc"; break; 350 case CallingConv::Cold: Out << "coldcc"; break; 351 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break; 352 case CallingConv::AnyReg: Out << "anyregcc"; break; 353 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break; 354 case CallingConv::PreserveAll: Out << "preserve_allcc"; break; 355 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break; 356 case CallingConv::GHC: Out << "ghccc"; break; 357 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break; 358 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break; 359 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break; 360 case CallingConv::X86_RegCall: Out << "x86_regcallcc"; break; 361 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break; 362 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break; 363 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break; 364 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break; 365 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break; 366 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break; 367 case CallingConv::AVR_INTR: Out << "avr_intrcc "; break; 368 case CallingConv::AVR_SIGNAL: Out << "avr_signalcc "; break; 369 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break; 370 case CallingConv::PTX_Device: Out << "ptx_device"; break; 371 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break; 372 case CallingConv::Win64: Out << "win64cc"; break; 373 case CallingConv::SPIR_FUNC: Out << "spir_func"; break; 374 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break; 375 case CallingConv::Swift: Out << "swiftcc"; break; 376 case CallingConv::X86_INTR: Out << "x86_intrcc"; break; 377 case CallingConv::HHVM: Out << "hhvmcc"; break; 378 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break; 379 case CallingConv::AMDGPU_VS: Out << "amdgpu_vs"; break; 380 case CallingConv::AMDGPU_LS: Out << "amdgpu_ls"; break; 381 case CallingConv::AMDGPU_HS: Out << "amdgpu_hs"; break; 382 case CallingConv::AMDGPU_ES: Out << "amdgpu_es"; break; 383 case CallingConv::AMDGPU_GS: Out << "amdgpu_gs"; break; 384 case CallingConv::AMDGPU_PS: Out << "amdgpu_ps"; break; 385 case CallingConv::AMDGPU_CS: Out << "amdgpu_cs"; break; 386 case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break; 387 } 388 } 389 390 enum PrefixType { 391 GlobalPrefix, 392 ComdatPrefix, 393 LabelPrefix, 394 LocalPrefix, 395 NoPrefix 396 }; 397 398 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) { 399 assert(!Name.empty() && "Cannot get empty name!"); 400 401 // Scan the name to see if it needs quotes first. 402 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0])); 403 if (!NeedsQuotes) { 404 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 405 // By making this unsigned, the value passed in to isalnum will always be 406 // in the range 0-255. This is important when building with MSVC because 407 // its implementation will assert. This situation can arise when dealing 408 // with UTF-8 multibyte characters. 409 unsigned char C = Name[i]; 410 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' && 411 C != '_') { 412 NeedsQuotes = true; 413 break; 414 } 415 } 416 } 417 418 // If we didn't need any quotes, just write out the name in one blast. 419 if (!NeedsQuotes) { 420 OS << Name; 421 return; 422 } 423 424 // Okay, we need quotes. Output the quotes and escape any scary characters as 425 // needed. 426 OS << '"'; 427 printEscapedString(Name, OS); 428 OS << '"'; 429 } 430 431 /// Turn the specified name into an 'LLVM name', which is either prefixed with % 432 /// (if the string only contains simple characters) or is surrounded with ""'s 433 /// (if it has special chars in it). Print it out. 434 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) { 435 switch (Prefix) { 436 case NoPrefix: 437 break; 438 case GlobalPrefix: 439 OS << '@'; 440 break; 441 case ComdatPrefix: 442 OS << '$'; 443 break; 444 case LabelPrefix: 445 break; 446 case LocalPrefix: 447 OS << '%'; 448 break; 449 } 450 printLLVMNameWithoutPrefix(OS, Name); 451 } 452 453 /// Turn the specified name into an 'LLVM name', which is either prefixed with % 454 /// (if the string only contains simple characters) or is surrounded with ""'s 455 /// (if it has special chars in it). Print it out. 456 static void PrintLLVMName(raw_ostream &OS, const Value *V) { 457 PrintLLVMName(OS, V->getName(), 458 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 459 } 460 461 namespace { 462 463 class TypePrinting { 464 public: 465 TypePrinting(const Module *M = nullptr) : DeferredM(M) {} 466 467 TypePrinting(const TypePrinting &) = delete; 468 TypePrinting &operator=(const TypePrinting &) = delete; 469 470 /// The named types that are used by the current module. 471 TypeFinder &getNamedTypes(); 472 473 /// The numbered types, number to type mapping. 474 std::vector<StructType *> &getNumberedTypes(); 475 476 bool empty(); 477 478 void print(Type *Ty, raw_ostream &OS); 479 480 void printStructBody(StructType *Ty, raw_ostream &OS); 481 482 private: 483 void incorporateTypes(); 484 485 /// A module to process lazily when needed. Set to nullptr as soon as used. 486 const Module *DeferredM; 487 488 TypeFinder NamedTypes; 489 490 // The numbered types, along with their value. 491 DenseMap<StructType *, unsigned> Type2Number; 492 493 std::vector<StructType *> NumberedTypes; 494 }; 495 496 } // end anonymous namespace 497 498 TypeFinder &TypePrinting::getNamedTypes() { 499 incorporateTypes(); 500 return NamedTypes; 501 } 502 503 std::vector<StructType *> &TypePrinting::getNumberedTypes() { 504 incorporateTypes(); 505 506 // We know all the numbers that each type is used and we know that it is a 507 // dense assignment. Convert the map to an index table, if it's not done 508 // already (judging from the sizes): 509 if (NumberedTypes.size() == Type2Number.size()) 510 return NumberedTypes; 511 512 NumberedTypes.resize(Type2Number.size()); 513 for (const auto &P : Type2Number) { 514 assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?"); 515 assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?"); 516 NumberedTypes[P.second] = P.first; 517 } 518 return NumberedTypes; 519 } 520 521 bool TypePrinting::empty() { 522 incorporateTypes(); 523 return NamedTypes.empty() && Type2Number.empty(); 524 } 525 526 void TypePrinting::incorporateTypes() { 527 if (!DeferredM) 528 return; 529 530 NamedTypes.run(*DeferredM, false); 531 DeferredM = nullptr; 532 533 // The list of struct types we got back includes all the struct types, split 534 // the unnamed ones out to a numbering and remove the anonymous structs. 535 unsigned NextNumber = 0; 536 537 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E; 538 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) { 539 StructType *STy = *I; 540 541 // Ignore anonymous types. 542 if (STy->isLiteral()) 543 continue; 544 545 if (STy->getName().empty()) 546 Type2Number[STy] = NextNumber++; 547 else 548 *NextToUse++ = STy; 549 } 550 551 NamedTypes.erase(NextToUse, NamedTypes.end()); 552 } 553 554 /// Write the specified type to the specified raw_ostream, making use of type 555 /// names or up references to shorten the type name where possible. 556 void TypePrinting::print(Type *Ty, raw_ostream &OS) { 557 switch (Ty->getTypeID()) { 558 case Type::VoidTyID: OS << "void"; return; 559 case Type::HalfTyID: OS << "half"; return; 560 case Type::FloatTyID: OS << "float"; return; 561 case Type::DoubleTyID: OS << "double"; return; 562 case Type::X86_FP80TyID: OS << "x86_fp80"; return; 563 case Type::FP128TyID: OS << "fp128"; return; 564 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return; 565 case Type::LabelTyID: OS << "label"; return; 566 case Type::MetadataTyID: OS << "metadata"; return; 567 case Type::X86_MMXTyID: OS << "x86_mmx"; return; 568 case Type::TokenTyID: OS << "token"; return; 569 case Type::IntegerTyID: 570 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 571 return; 572 573 case Type::FunctionTyID: { 574 FunctionType *FTy = cast<FunctionType>(Ty); 575 print(FTy->getReturnType(), OS); 576 OS << " ("; 577 for (FunctionType::param_iterator I = FTy->param_begin(), 578 E = FTy->param_end(); I != E; ++I) { 579 if (I != FTy->param_begin()) 580 OS << ", "; 581 print(*I, OS); 582 } 583 if (FTy->isVarArg()) { 584 if (FTy->getNumParams()) OS << ", "; 585 OS << "..."; 586 } 587 OS << ')'; 588 return; 589 } 590 case Type::StructTyID: { 591 StructType *STy = cast<StructType>(Ty); 592 593 if (STy->isLiteral()) 594 return printStructBody(STy, OS); 595 596 if (!STy->getName().empty()) 597 return PrintLLVMName(OS, STy->getName(), LocalPrefix); 598 599 incorporateTypes(); 600 const auto I = Type2Number.find(STy); 601 if (I != Type2Number.end()) 602 OS << '%' << I->second; 603 else // Not enumerated, print the hex address. 604 OS << "%\"type " << STy << '\"'; 605 return; 606 } 607 case Type::PointerTyID: { 608 PointerType *PTy = cast<PointerType>(Ty); 609 print(PTy->getElementType(), OS); 610 if (unsigned AddressSpace = PTy->getAddressSpace()) 611 OS << " addrspace(" << AddressSpace << ')'; 612 OS << '*'; 613 return; 614 } 615 case Type::ArrayTyID: { 616 ArrayType *ATy = cast<ArrayType>(Ty); 617 OS << '[' << ATy->getNumElements() << " x "; 618 print(ATy->getElementType(), OS); 619 OS << ']'; 620 return; 621 } 622 case Type::VectorTyID: { 623 VectorType *PTy = cast<VectorType>(Ty); 624 OS << "<" << PTy->getNumElements() << " x "; 625 print(PTy->getElementType(), OS); 626 OS << '>'; 627 return; 628 } 629 } 630 llvm_unreachable("Invalid TypeID"); 631 } 632 633 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) { 634 if (STy->isOpaque()) { 635 OS << "opaque"; 636 return; 637 } 638 639 if (STy->isPacked()) 640 OS << '<'; 641 642 if (STy->getNumElements() == 0) { 643 OS << "{}"; 644 } else { 645 StructType::element_iterator I = STy->element_begin(); 646 OS << "{ "; 647 print(*I++, OS); 648 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) { 649 OS << ", "; 650 print(*I, OS); 651 } 652 653 OS << " }"; 654 } 655 if (STy->isPacked()) 656 OS << '>'; 657 } 658 659 namespace llvm { 660 661 //===----------------------------------------------------------------------===// 662 // SlotTracker Class: Enumerate slot numbers for unnamed values 663 //===----------------------------------------------------------------------===// 664 /// This class provides computation of slot numbers for LLVM Assembly writing. 665 /// 666 class SlotTracker { 667 public: 668 /// ValueMap - A mapping of Values to slot numbers. 669 using ValueMap = DenseMap<const Value *, unsigned>; 670 671 private: 672 /// TheModule - The module for which we are holding slot numbers. 673 const Module* TheModule; 674 675 /// TheFunction - The function for which we are holding slot numbers. 676 const Function* TheFunction = nullptr; 677 bool FunctionProcessed = false; 678 bool ShouldInitializeAllMetadata; 679 680 /// The summary index for which we are holding slot numbers. 681 const ModuleSummaryIndex *TheIndex = nullptr; 682 683 /// mMap - The slot map for the module level data. 684 ValueMap mMap; 685 unsigned mNext = 0; 686 687 /// fMap - The slot map for the function level data. 688 ValueMap fMap; 689 unsigned fNext = 0; 690 691 /// mdnMap - Map for MDNodes. 692 DenseMap<const MDNode*, unsigned> mdnMap; 693 unsigned mdnNext = 0; 694 695 /// asMap - The slot map for attribute sets. 696 DenseMap<AttributeSet, unsigned> asMap; 697 unsigned asNext = 0; 698 699 /// GUIDMap - The slot map for GUIDs used in the summary index. 700 DenseMap<GlobalValue::GUID, unsigned> GUIDMap; 701 unsigned GUIDNext = 0; 702 703 public: 704 /// Construct from a module. 705 /// 706 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all 707 /// functions, giving correct numbering for metadata referenced only from 708 /// within a function (even if no functions have been initialized). 709 explicit SlotTracker(const Module *M, 710 bool ShouldInitializeAllMetadata = false); 711 712 /// Construct from a function, starting out in incorp state. 713 /// 714 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all 715 /// functions, giving correct numbering for metadata referenced only from 716 /// within a function (even if no functions have been initialized). 717 explicit SlotTracker(const Function *F, 718 bool ShouldInitializeAllMetadata = false); 719 720 /// Construct from a module summary index. 721 explicit SlotTracker(const ModuleSummaryIndex *Index); 722 723 SlotTracker(const SlotTracker &) = delete; 724 SlotTracker &operator=(const SlotTracker &) = delete; 725 726 /// Return the slot number of the specified value in it's type 727 /// plane. If something is not in the SlotTracker, return -1. 728 int getLocalSlot(const Value *V); 729 int getGlobalSlot(const GlobalValue *V); 730 int getMetadataSlot(const MDNode *N); 731 int getAttributeGroupSlot(AttributeSet AS); 732 int getGUIDSlot(GlobalValue::GUID GUID); 733 734 /// If you'd like to deal with a function instead of just a module, use 735 /// this method to get its data into the SlotTracker. 736 void incorporateFunction(const Function *F) { 737 TheFunction = F; 738 FunctionProcessed = false; 739 } 740 741 const Function *getFunction() const { return TheFunction; } 742 743 /// After calling incorporateFunction, use this method to remove the 744 /// most recently incorporated function from the SlotTracker. This 745 /// will reset the state of the machine back to just the module contents. 746 void purgeFunction(); 747 748 /// MDNode map iterators. 749 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator; 750 751 mdn_iterator mdn_begin() { return mdnMap.begin(); } 752 mdn_iterator mdn_end() { return mdnMap.end(); } 753 unsigned mdn_size() const { return mdnMap.size(); } 754 bool mdn_empty() const { return mdnMap.empty(); } 755 756 /// AttributeSet map iterators. 757 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator; 758 759 as_iterator as_begin() { return asMap.begin(); } 760 as_iterator as_end() { return asMap.end(); } 761 unsigned as_size() const { return asMap.size(); } 762 bool as_empty() const { return asMap.empty(); } 763 764 /// GUID map iterators. 765 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator; 766 767 /// These functions do the actual initialization. 768 inline void initialize(); 769 void initializeIndex(); 770 771 // Implementation Details 772 private: 773 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 774 void CreateModuleSlot(const GlobalValue *V); 775 776 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 777 void CreateMetadataSlot(const MDNode *N); 778 779 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 780 void CreateFunctionSlot(const Value *V); 781 782 /// Insert the specified AttributeSet into the slot table. 783 void CreateAttributeSetSlot(AttributeSet AS); 784 785 void CreateGUIDSlot(GlobalValue::GUID GUID); 786 787 /// Add all of the module level global variables (and their initializers) 788 /// and function declarations, but not the contents of those functions. 789 void processModule(); 790 void processIndex(); 791 792 /// Add all of the functions arguments, basic blocks, and instructions. 793 void processFunction(); 794 795 /// Add the metadata directly attached to a GlobalObject. 796 void processGlobalObjectMetadata(const GlobalObject &GO); 797 798 /// Add all of the metadata from a function. 799 void processFunctionMetadata(const Function &F); 800 801 /// Add all of the metadata from an instruction. 802 void processInstructionMetadata(const Instruction &I); 803 }; 804 805 } // end namespace llvm 806 807 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M, 808 const Function *F) 809 : M(M), F(F), Machine(&Machine) {} 810 811 ModuleSlotTracker::ModuleSlotTracker(const Module *M, 812 bool ShouldInitializeAllMetadata) 813 : ShouldCreateStorage(M), 814 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {} 815 816 ModuleSlotTracker::~ModuleSlotTracker() = default; 817 818 SlotTracker *ModuleSlotTracker::getMachine() { 819 if (!ShouldCreateStorage) 820 return Machine; 821 822 ShouldCreateStorage = false; 823 MachineStorage = 824 llvm::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata); 825 Machine = MachineStorage.get(); 826 return Machine; 827 } 828 829 void ModuleSlotTracker::incorporateFunction(const Function &F) { 830 // Using getMachine() may lazily create the slot tracker. 831 if (!getMachine()) 832 return; 833 834 // Nothing to do if this is the right function already. 835 if (this->F == &F) 836 return; 837 if (this->F) 838 Machine->purgeFunction(); 839 Machine->incorporateFunction(&F); 840 this->F = &F; 841 } 842 843 int ModuleSlotTracker::getLocalSlot(const Value *V) { 844 assert(F && "No function incorporated"); 845 return Machine->getLocalSlot(V); 846 } 847 848 static SlotTracker *createSlotTracker(const Value *V) { 849 if (const Argument *FA = dyn_cast<Argument>(V)) 850 return new SlotTracker(FA->getParent()); 851 852 if (const Instruction *I = dyn_cast<Instruction>(V)) 853 if (I->getParent()) 854 return new SlotTracker(I->getParent()->getParent()); 855 856 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 857 return new SlotTracker(BB->getParent()); 858 859 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 860 return new SlotTracker(GV->getParent()); 861 862 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 863 return new SlotTracker(GA->getParent()); 864 865 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V)) 866 return new SlotTracker(GIF->getParent()); 867 868 if (const Function *Func = dyn_cast<Function>(V)) 869 return new SlotTracker(Func); 870 871 return nullptr; 872 } 873 874 #if 0 875 #define ST_DEBUG(X) dbgs() << X 876 #else 877 #define ST_DEBUG(X) 878 #endif 879 880 // Module level constructor. Causes the contents of the Module (sans functions) 881 // to be added to the slot table. 882 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata) 883 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {} 884 885 // Function level constructor. Causes the contents of the Module and the one 886 // function provided to be added to the slot table. 887 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata) 888 : TheModule(F ? F->getParent() : nullptr), TheFunction(F), 889 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {} 890 891 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index) 892 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {} 893 894 inline void SlotTracker::initialize() { 895 if (TheModule) { 896 processModule(); 897 TheModule = nullptr; ///< Prevent re-processing next time we're called. 898 } 899 900 if (TheFunction && !FunctionProcessed) 901 processFunction(); 902 } 903 904 void SlotTracker::initializeIndex() { 905 if (!TheIndex) 906 return; 907 processIndex(); 908 TheIndex = nullptr; ///< Prevent re-processing next time we're called. 909 } 910 911 // Iterate through all the global variables, functions, and global 912 // variable initializers and create slots for them. 913 void SlotTracker::processModule() { 914 ST_DEBUG("begin processModule!\n"); 915 916 // Add all of the unnamed global variables to the value table. 917 for (const GlobalVariable &Var : TheModule->globals()) { 918 if (!Var.hasName()) 919 CreateModuleSlot(&Var); 920 processGlobalObjectMetadata(Var); 921 auto Attrs = Var.getAttributes(); 922 if (Attrs.hasAttributes()) 923 CreateAttributeSetSlot(Attrs); 924 } 925 926 for (const GlobalAlias &A : TheModule->aliases()) { 927 if (!A.hasName()) 928 CreateModuleSlot(&A); 929 } 930 931 for (const GlobalIFunc &I : TheModule->ifuncs()) { 932 if (!I.hasName()) 933 CreateModuleSlot(&I); 934 } 935 936 // Add metadata used by named metadata. 937 for (const NamedMDNode &NMD : TheModule->named_metadata()) { 938 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) 939 CreateMetadataSlot(NMD.getOperand(i)); 940 } 941 942 for (const Function &F : *TheModule) { 943 if (!F.hasName()) 944 // Add all the unnamed functions to the table. 945 CreateModuleSlot(&F); 946 947 if (ShouldInitializeAllMetadata) 948 processFunctionMetadata(F); 949 950 // Add all the function attributes to the table. 951 // FIXME: Add attributes of other objects? 952 AttributeSet FnAttrs = F.getAttributes().getFnAttributes(); 953 if (FnAttrs.hasAttributes()) 954 CreateAttributeSetSlot(FnAttrs); 955 } 956 957 ST_DEBUG("end processModule!\n"); 958 } 959 960 // Process the arguments, basic blocks, and instructions of a function. 961 void SlotTracker::processFunction() { 962 ST_DEBUG("begin processFunction!\n"); 963 fNext = 0; 964 965 // Process function metadata if it wasn't hit at the module-level. 966 if (!ShouldInitializeAllMetadata) 967 processFunctionMetadata(*TheFunction); 968 969 // Add all the function arguments with no names. 970 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 971 AE = TheFunction->arg_end(); AI != AE; ++AI) 972 if (!AI->hasName()) 973 CreateFunctionSlot(&*AI); 974 975 ST_DEBUG("Inserting Instructions:\n"); 976 977 // Add all of the basic blocks and instructions with no names. 978 for (auto &BB : *TheFunction) { 979 if (!BB.hasName()) 980 CreateFunctionSlot(&BB); 981 982 for (auto &I : BB) { 983 if (!I.getType()->isVoidTy() && !I.hasName()) 984 CreateFunctionSlot(&I); 985 986 // We allow direct calls to any llvm.foo function here, because the 987 // target may not be linked into the optimizer. 988 if (auto CS = ImmutableCallSite(&I)) { 989 // Add all the call attributes to the table. 990 AttributeSet Attrs = CS.getAttributes().getFnAttributes(); 991 if (Attrs.hasAttributes()) 992 CreateAttributeSetSlot(Attrs); 993 } 994 } 995 } 996 997 FunctionProcessed = true; 998 999 ST_DEBUG("end processFunction!\n"); 1000 } 1001 1002 // Iterate through all the GUID in the index and create slots for them. 1003 void SlotTracker::processIndex() { 1004 ST_DEBUG("begin processIndex!\n"); 1005 assert(TheIndex); 1006 1007 // The first block of slots are just the module ids, which start at 0 and are 1008 // assigned consecutively. Start numbering the GUIDs after the module ids. 1009 GUIDNext = TheIndex->modulePaths().size(); 1010 1011 for (auto &GlobalList : *TheIndex) 1012 CreateGUIDSlot(GlobalList.first); 1013 1014 for (auto &TId : TheIndex->typeIds()) 1015 CreateGUIDSlot(GlobalValue::getGUID(TId.first)); 1016 1017 ST_DEBUG("end processIndex!\n"); 1018 } 1019 1020 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) { 1021 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1022 GO.getAllMetadata(MDs); 1023 for (auto &MD : MDs) 1024 CreateMetadataSlot(MD.second); 1025 } 1026 1027 void SlotTracker::processFunctionMetadata(const Function &F) { 1028 processGlobalObjectMetadata(F); 1029 for (auto &BB : F) { 1030 for (auto &I : BB) 1031 processInstructionMetadata(I); 1032 } 1033 } 1034 1035 void SlotTracker::processInstructionMetadata(const Instruction &I) { 1036 // Process metadata used directly by intrinsics. 1037 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 1038 if (Function *F = CI->getCalledFunction()) 1039 if (F->isIntrinsic()) 1040 for (auto &Op : I.operands()) 1041 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 1042 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata())) 1043 CreateMetadataSlot(N); 1044 1045 // Process metadata attached to this instruction. 1046 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1047 I.getAllMetadata(MDs); 1048 for (auto &MD : MDs) 1049 CreateMetadataSlot(MD.second); 1050 } 1051 1052 /// Clean up after incorporating a function. This is the only way to get out of 1053 /// the function incorporation state that affects get*Slot/Create*Slot. Function 1054 /// incorporation state is indicated by TheFunction != 0. 1055 void SlotTracker::purgeFunction() { 1056 ST_DEBUG("begin purgeFunction!\n"); 1057 fMap.clear(); // Simply discard the function level map 1058 TheFunction = nullptr; 1059 FunctionProcessed = false; 1060 ST_DEBUG("end purgeFunction!\n"); 1061 } 1062 1063 /// getGlobalSlot - Get the slot number of a global value. 1064 int SlotTracker::getGlobalSlot(const GlobalValue *V) { 1065 // Check for uninitialized state and do lazy initialization. 1066 initialize(); 1067 1068 // Find the value in the module map 1069 ValueMap::iterator MI = mMap.find(V); 1070 return MI == mMap.end() ? -1 : (int)MI->second; 1071 } 1072 1073 /// getMetadataSlot - Get the slot number of a MDNode. 1074 int SlotTracker::getMetadataSlot(const MDNode *N) { 1075 // Check for uninitialized state and do lazy initialization. 1076 initialize(); 1077 1078 // Find the MDNode in the module map 1079 mdn_iterator MI = mdnMap.find(N); 1080 return MI == mdnMap.end() ? -1 : (int)MI->second; 1081 } 1082 1083 /// getLocalSlot - Get the slot number for a value that is local to a function. 1084 int SlotTracker::getLocalSlot(const Value *V) { 1085 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 1086 1087 // Check for uninitialized state and do lazy initialization. 1088 initialize(); 1089 1090 ValueMap::iterator FI = fMap.find(V); 1091 return FI == fMap.end() ? -1 : (int)FI->second; 1092 } 1093 1094 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) { 1095 // Check for uninitialized state and do lazy initialization. 1096 initialize(); 1097 1098 // Find the AttributeSet in the module map. 1099 as_iterator AI = asMap.find(AS); 1100 return AI == asMap.end() ? -1 : (int)AI->second; 1101 } 1102 1103 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) { 1104 // Check for uninitialized state and do lazy initialization. 1105 initializeIndex(); 1106 1107 // Find the GUID in the map 1108 guid_iterator I = GUIDMap.find(GUID); 1109 return I == GUIDMap.end() ? -1 : (int)I->second; 1110 } 1111 1112 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 1113 void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 1114 assert(V && "Can't insert a null Value into SlotTracker!"); 1115 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); 1116 assert(!V->hasName() && "Doesn't need a slot!"); 1117 1118 unsigned DestSlot = mNext++; 1119 mMap[V] = DestSlot; 1120 1121 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 1122 DestSlot << " ["); 1123 // G = Global, F = Function, A = Alias, I = IFunc, o = other 1124 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 1125 (isa<Function>(V) ? 'F' : 1126 (isa<GlobalAlias>(V) ? 'A' : 1127 (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n"); 1128 } 1129 1130 /// CreateSlot - Create a new slot for the specified value if it has no name. 1131 void SlotTracker::CreateFunctionSlot(const Value *V) { 1132 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); 1133 1134 unsigned DestSlot = fNext++; 1135 fMap[V] = DestSlot; 1136 1137 // G = Global, F = Function, o = other 1138 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 1139 DestSlot << " [o]\n"); 1140 } 1141 1142 /// CreateModuleSlot - Insert the specified MDNode* into the slot table. 1143 void SlotTracker::CreateMetadataSlot(const MDNode *N) { 1144 assert(N && "Can't insert a null Value into SlotTracker!"); 1145 1146 // Don't make slots for DIExpressions. We just print them inline everywhere. 1147 if (isa<DIExpression>(N)) 1148 return; 1149 1150 unsigned DestSlot = mdnNext; 1151 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second) 1152 return; 1153 ++mdnNext; 1154 1155 // Recursively add any MDNodes referenced by operands. 1156 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1157 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i))) 1158 CreateMetadataSlot(Op); 1159 } 1160 1161 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) { 1162 assert(AS.hasAttributes() && "Doesn't need a slot!"); 1163 1164 as_iterator I = asMap.find(AS); 1165 if (I != asMap.end()) 1166 return; 1167 1168 unsigned DestSlot = asNext++; 1169 asMap[AS] = DestSlot; 1170 } 1171 1172 /// Create a new slot for the specified GUID 1173 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) { 1174 GUIDMap[GUID] = GUIDNext++; 1175 } 1176 1177 //===----------------------------------------------------------------------===// 1178 // AsmWriter Implementation 1179 //===----------------------------------------------------------------------===// 1180 1181 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 1182 TypePrinting *TypePrinter, 1183 SlotTracker *Machine, 1184 const Module *Context); 1185 1186 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 1187 TypePrinting *TypePrinter, 1188 SlotTracker *Machine, const Module *Context, 1189 bool FromValue = false); 1190 1191 static void writeAtomicRMWOperation(raw_ostream &Out, 1192 AtomicRMWInst::BinOp Op) { 1193 switch (Op) { 1194 default: Out << " <unknown operation " << Op << ">"; break; 1195 case AtomicRMWInst::Xchg: Out << " xchg"; break; 1196 case AtomicRMWInst::Add: Out << " add"; break; 1197 case AtomicRMWInst::Sub: Out << " sub"; break; 1198 case AtomicRMWInst::And: Out << " and"; break; 1199 case AtomicRMWInst::Nand: Out << " nand"; break; 1200 case AtomicRMWInst::Or: Out << " or"; break; 1201 case AtomicRMWInst::Xor: Out << " xor"; break; 1202 case AtomicRMWInst::Max: Out << " max"; break; 1203 case AtomicRMWInst::Min: Out << " min"; break; 1204 case AtomicRMWInst::UMax: Out << " umax"; break; 1205 case AtomicRMWInst::UMin: Out << " umin"; break; 1206 } 1207 } 1208 1209 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 1210 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) { 1211 // 'Fast' is an abbreviation for all fast-math-flags. 1212 if (FPO->isFast()) 1213 Out << " fast"; 1214 else { 1215 if (FPO->hasAllowReassoc()) 1216 Out << " reassoc"; 1217 if (FPO->hasNoNaNs()) 1218 Out << " nnan"; 1219 if (FPO->hasNoInfs()) 1220 Out << " ninf"; 1221 if (FPO->hasNoSignedZeros()) 1222 Out << " nsz"; 1223 if (FPO->hasAllowReciprocal()) 1224 Out << " arcp"; 1225 if (FPO->hasAllowContract()) 1226 Out << " contract"; 1227 if (FPO->hasApproxFunc()) 1228 Out << " afn"; 1229 } 1230 } 1231 1232 if (const OverflowingBinaryOperator *OBO = 1233 dyn_cast<OverflowingBinaryOperator>(U)) { 1234 if (OBO->hasNoUnsignedWrap()) 1235 Out << " nuw"; 1236 if (OBO->hasNoSignedWrap()) 1237 Out << " nsw"; 1238 } else if (const PossiblyExactOperator *Div = 1239 dyn_cast<PossiblyExactOperator>(U)) { 1240 if (Div->isExact()) 1241 Out << " exact"; 1242 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 1243 if (GEP->isInBounds()) 1244 Out << " inbounds"; 1245 } 1246 } 1247 1248 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, 1249 TypePrinting &TypePrinter, 1250 SlotTracker *Machine, 1251 const Module *Context) { 1252 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1253 if (CI->getType()->isIntegerTy(1)) { 1254 Out << (CI->getZExtValue() ? "true" : "false"); 1255 return; 1256 } 1257 Out << CI->getValue(); 1258 return; 1259 } 1260 1261 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 1262 const APFloat &APF = CFP->getValueAPF(); 1263 if (&APF.getSemantics() == &APFloat::IEEEsingle() || 1264 &APF.getSemantics() == &APFloat::IEEEdouble()) { 1265 // We would like to output the FP constant value in exponential notation, 1266 // but we cannot do this if doing so will lose precision. Check here to 1267 // make sure that we only output it in exponential format if we can parse 1268 // the value back and get the same value. 1269 // 1270 bool ignored; 1271 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble(); 1272 bool isInf = APF.isInfinity(); 1273 bool isNaN = APF.isNaN(); 1274 if (!isInf && !isNaN) { 1275 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat(); 1276 SmallString<128> StrVal; 1277 APF.toString(StrVal, 6, 0, false); 1278 // Check to make sure that the stringized number is not some string like 1279 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 1280 // that the string matches the "[-+]?[0-9]" regex. 1281 // 1282 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') || 1283 ((StrVal[0] == '-' || StrVal[0] == '+') && 1284 (StrVal[1] >= '0' && StrVal[1] <= '9'))) && 1285 "[-+]?[0-9] regex does not match!"); 1286 // Reparse stringized version! 1287 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) { 1288 Out << StrVal; 1289 return; 1290 } 1291 } 1292 // Otherwise we could not reparse it to exactly the same value, so we must 1293 // output the string in hexadecimal format! Note that loading and storing 1294 // floating point types changes the bits of NaNs on some hosts, notably 1295 // x86, so we must not use these types. 1296 static_assert(sizeof(double) == sizeof(uint64_t), 1297 "assuming that double is 64 bits!"); 1298 APFloat apf = APF; 1299 // Floats are represented in ASCII IR as double, convert. 1300 if (!isDouble) 1301 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 1302 &ignored); 1303 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true); 1304 return; 1305 } 1306 1307 // Either half, or some form of long double. 1308 // These appear as a magic letter identifying the type, then a 1309 // fixed number of hex digits. 1310 Out << "0x"; 1311 APInt API = APF.bitcastToAPInt(); 1312 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) { 1313 Out << 'K'; 1314 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4, 1315 /*Upper=*/true); 1316 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1317 /*Upper=*/true); 1318 return; 1319 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) { 1320 Out << 'L'; 1321 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1322 /*Upper=*/true); 1323 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1324 /*Upper=*/true); 1325 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) { 1326 Out << 'M'; 1327 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1328 /*Upper=*/true); 1329 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1330 /*Upper=*/true); 1331 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) { 1332 Out << 'H'; 1333 Out << format_hex_no_prefix(API.getZExtValue(), 4, 1334 /*Upper=*/true); 1335 } else 1336 llvm_unreachable("Unsupported floating point type"); 1337 return; 1338 } 1339 1340 if (isa<ConstantAggregateZero>(CV)) { 1341 Out << "zeroinitializer"; 1342 return; 1343 } 1344 1345 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 1346 Out << "blockaddress("; 1347 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine, 1348 Context); 1349 Out << ", "; 1350 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine, 1351 Context); 1352 Out << ")"; 1353 return; 1354 } 1355 1356 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 1357 Type *ETy = CA->getType()->getElementType(); 1358 Out << '['; 1359 TypePrinter.print(ETy, Out); 1360 Out << ' '; 1361 WriteAsOperandInternal(Out, CA->getOperand(0), 1362 &TypePrinter, Machine, 1363 Context); 1364 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 1365 Out << ", "; 1366 TypePrinter.print(ETy, Out); 1367 Out << ' '; 1368 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine, 1369 Context); 1370 } 1371 Out << ']'; 1372 return; 1373 } 1374 1375 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) { 1376 // As a special case, print the array as a string if it is an array of 1377 // i8 with ConstantInt values. 1378 if (CA->isString()) { 1379 Out << "c\""; 1380 printEscapedString(CA->getAsString(), Out); 1381 Out << '"'; 1382 return; 1383 } 1384 1385 Type *ETy = CA->getType()->getElementType(); 1386 Out << '['; 1387 TypePrinter.print(ETy, Out); 1388 Out << ' '; 1389 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), 1390 &TypePrinter, Machine, 1391 Context); 1392 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) { 1393 Out << ", "; 1394 TypePrinter.print(ETy, Out); 1395 Out << ' '; 1396 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter, 1397 Machine, Context); 1398 } 1399 Out << ']'; 1400 return; 1401 } 1402 1403 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 1404 if (CS->getType()->isPacked()) 1405 Out << '<'; 1406 Out << '{'; 1407 unsigned N = CS->getNumOperands(); 1408 if (N) { 1409 Out << ' '; 1410 TypePrinter.print(CS->getOperand(0)->getType(), Out); 1411 Out << ' '; 1412 1413 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine, 1414 Context); 1415 1416 for (unsigned i = 1; i < N; i++) { 1417 Out << ", "; 1418 TypePrinter.print(CS->getOperand(i)->getType(), Out); 1419 Out << ' '; 1420 1421 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine, 1422 Context); 1423 } 1424 Out << ' '; 1425 } 1426 1427 Out << '}'; 1428 if (CS->getType()->isPacked()) 1429 Out << '>'; 1430 return; 1431 } 1432 1433 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) { 1434 Type *ETy = CV->getType()->getVectorElementType(); 1435 Out << '<'; 1436 TypePrinter.print(ETy, Out); 1437 Out << ' '; 1438 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter, 1439 Machine, Context); 1440 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){ 1441 Out << ", "; 1442 TypePrinter.print(ETy, Out); 1443 Out << ' '; 1444 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter, 1445 Machine, Context); 1446 } 1447 Out << '>'; 1448 return; 1449 } 1450 1451 if (isa<ConstantPointerNull>(CV)) { 1452 Out << "null"; 1453 return; 1454 } 1455 1456 if (isa<ConstantTokenNone>(CV)) { 1457 Out << "none"; 1458 return; 1459 } 1460 1461 if (isa<UndefValue>(CV)) { 1462 Out << "undef"; 1463 return; 1464 } 1465 1466 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1467 Out << CE->getOpcodeName(); 1468 WriteOptimizationInfo(Out, CE); 1469 if (CE->isCompare()) 1470 Out << ' ' << CmpInst::getPredicateName( 1471 static_cast<CmpInst::Predicate>(CE->getPredicate())); 1472 Out << " ("; 1473 1474 Optional<unsigned> InRangeOp; 1475 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) { 1476 TypePrinter.print(GEP->getSourceElementType(), Out); 1477 Out << ", "; 1478 InRangeOp = GEP->getInRangeIndex(); 1479 if (InRangeOp) 1480 ++*InRangeOp; 1481 } 1482 1483 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 1484 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp) 1485 Out << "inrange "; 1486 TypePrinter.print((*OI)->getType(), Out); 1487 Out << ' '; 1488 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context); 1489 if (OI+1 != CE->op_end()) 1490 Out << ", "; 1491 } 1492 1493 if (CE->hasIndices()) { 1494 ArrayRef<unsigned> Indices = CE->getIndices(); 1495 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 1496 Out << ", " << Indices[i]; 1497 } 1498 1499 if (CE->isCast()) { 1500 Out << " to "; 1501 TypePrinter.print(CE->getType(), Out); 1502 } 1503 1504 Out << ')'; 1505 return; 1506 } 1507 1508 Out << "<placeholder or erroneous Constant>"; 1509 } 1510 1511 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, 1512 TypePrinting *TypePrinter, SlotTracker *Machine, 1513 const Module *Context) { 1514 Out << "!{"; 1515 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1516 const Metadata *MD = Node->getOperand(mi); 1517 if (!MD) 1518 Out << "null"; 1519 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) { 1520 Value *V = MDV->getValue(); 1521 TypePrinter->print(V->getType(), Out); 1522 Out << ' '; 1523 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context); 1524 } else { 1525 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1526 } 1527 if (mi + 1 != me) 1528 Out << ", "; 1529 } 1530 1531 Out << "}"; 1532 } 1533 1534 namespace { 1535 1536 struct FieldSeparator { 1537 bool Skip = true; 1538 const char *Sep; 1539 1540 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {} 1541 }; 1542 1543 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) { 1544 if (FS.Skip) { 1545 FS.Skip = false; 1546 return OS; 1547 } 1548 return OS << FS.Sep; 1549 } 1550 1551 struct MDFieldPrinter { 1552 raw_ostream &Out; 1553 FieldSeparator FS; 1554 TypePrinting *TypePrinter = nullptr; 1555 SlotTracker *Machine = nullptr; 1556 const Module *Context = nullptr; 1557 1558 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {} 1559 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter, 1560 SlotTracker *Machine, const Module *Context) 1561 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) { 1562 } 1563 1564 void printTag(const DINode *N); 1565 void printMacinfoType(const DIMacroNode *N); 1566 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N); 1567 void printString(StringRef Name, StringRef Value, 1568 bool ShouldSkipEmpty = true); 1569 void printMetadata(StringRef Name, const Metadata *MD, 1570 bool ShouldSkipNull = true); 1571 template <class IntTy> 1572 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true); 1573 void printBool(StringRef Name, bool Value, Optional<bool> Default = None); 1574 void printDIFlags(StringRef Name, DINode::DIFlags Flags); 1575 template <class IntTy, class Stringifier> 1576 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString, 1577 bool ShouldSkipZero = true); 1578 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK); 1579 }; 1580 1581 } // end anonymous namespace 1582 1583 void MDFieldPrinter::printTag(const DINode *N) { 1584 Out << FS << "tag: "; 1585 auto Tag = dwarf::TagString(N->getTag()); 1586 if (!Tag.empty()) 1587 Out << Tag; 1588 else 1589 Out << N->getTag(); 1590 } 1591 1592 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) { 1593 Out << FS << "type: "; 1594 auto Type = dwarf::MacinfoString(N->getMacinfoType()); 1595 if (!Type.empty()) 1596 Out << Type; 1597 else 1598 Out << N->getMacinfoType(); 1599 } 1600 1601 void MDFieldPrinter::printChecksum( 1602 const DIFile::ChecksumInfo<StringRef> &Checksum) { 1603 Out << FS << "checksumkind: " << Checksum.getKindAsString(); 1604 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false); 1605 } 1606 1607 void MDFieldPrinter::printString(StringRef Name, StringRef Value, 1608 bool ShouldSkipEmpty) { 1609 if (ShouldSkipEmpty && Value.empty()) 1610 return; 1611 1612 Out << FS << Name << ": \""; 1613 printEscapedString(Value, Out); 1614 Out << "\""; 1615 } 1616 1617 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD, 1618 TypePrinting *TypePrinter, 1619 SlotTracker *Machine, 1620 const Module *Context) { 1621 if (!MD) { 1622 Out << "null"; 1623 return; 1624 } 1625 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1626 } 1627 1628 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD, 1629 bool ShouldSkipNull) { 1630 if (ShouldSkipNull && !MD) 1631 return; 1632 1633 Out << FS << Name << ": "; 1634 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context); 1635 } 1636 1637 template <class IntTy> 1638 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) { 1639 if (ShouldSkipZero && !Int) 1640 return; 1641 1642 Out << FS << Name << ": " << Int; 1643 } 1644 1645 void MDFieldPrinter::printBool(StringRef Name, bool Value, 1646 Optional<bool> Default) { 1647 if (Default && Value == *Default) 1648 return; 1649 Out << FS << Name << ": " << (Value ? "true" : "false"); 1650 } 1651 1652 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) { 1653 if (!Flags) 1654 return; 1655 1656 Out << FS << Name << ": "; 1657 1658 SmallVector<DINode::DIFlags, 8> SplitFlags; 1659 auto Extra = DINode::splitFlags(Flags, SplitFlags); 1660 1661 FieldSeparator FlagsFS(" | "); 1662 for (auto F : SplitFlags) { 1663 auto StringF = DINode::getFlagString(F); 1664 assert(!StringF.empty() && "Expected valid flag"); 1665 Out << FlagsFS << StringF; 1666 } 1667 if (Extra || SplitFlags.empty()) 1668 Out << FlagsFS << Extra; 1669 } 1670 1671 void MDFieldPrinter::printEmissionKind(StringRef Name, 1672 DICompileUnit::DebugEmissionKind EK) { 1673 Out << FS << Name << ": " << DICompileUnit::EmissionKindString(EK); 1674 } 1675 1676 template <class IntTy, class Stringifier> 1677 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value, 1678 Stringifier toString, bool ShouldSkipZero) { 1679 if (!Value) 1680 return; 1681 1682 Out << FS << Name << ": "; 1683 auto S = toString(Value); 1684 if (!S.empty()) 1685 Out << S; 1686 else 1687 Out << Value; 1688 } 1689 1690 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, 1691 TypePrinting *TypePrinter, SlotTracker *Machine, 1692 const Module *Context) { 1693 Out << "!GenericDINode("; 1694 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1695 Printer.printTag(N); 1696 Printer.printString("header", N->getHeader()); 1697 if (N->getNumDwarfOperands()) { 1698 Out << Printer.FS << "operands: {"; 1699 FieldSeparator IFS; 1700 for (auto &I : N->dwarf_operands()) { 1701 Out << IFS; 1702 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context); 1703 } 1704 Out << "}"; 1705 } 1706 Out << ")"; 1707 } 1708 1709 static void writeDILocation(raw_ostream &Out, const DILocation *DL, 1710 TypePrinting *TypePrinter, SlotTracker *Machine, 1711 const Module *Context) { 1712 Out << "!DILocation("; 1713 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1714 // Always output the line, since 0 is a relevant and important value for it. 1715 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false); 1716 Printer.printInt("column", DL->getColumn()); 1717 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false); 1718 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt()); 1719 Out << ")"; 1720 } 1721 1722 static void writeDISubrange(raw_ostream &Out, const DISubrange *N, 1723 TypePrinting *TypePrinter, SlotTracker *Machine, 1724 const Module *Context) { 1725 Out << "!DISubrange("; 1726 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1727 if (auto *CE = N->getCount().dyn_cast<ConstantInt*>()) 1728 Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false); 1729 else 1730 Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable*>(), 1731 /*ShouldSkipNull */ false); 1732 Printer.printInt("lowerBound", N->getLowerBound()); 1733 Out << ")"; 1734 } 1735 1736 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, 1737 TypePrinting *, SlotTracker *, const Module *) { 1738 Out << "!DIEnumerator("; 1739 MDFieldPrinter Printer(Out); 1740 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false); 1741 if (N->isUnsigned()) { 1742 auto Value = static_cast<uint64_t>(N->getValue()); 1743 Printer.printInt("value", Value, /* ShouldSkipZero */ false); 1744 Printer.printBool("isUnsigned", true); 1745 } else { 1746 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false); 1747 } 1748 Out << ")"; 1749 } 1750 1751 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, 1752 TypePrinting *, SlotTracker *, const Module *) { 1753 Out << "!DIBasicType("; 1754 MDFieldPrinter Printer(Out); 1755 if (N->getTag() != dwarf::DW_TAG_base_type) 1756 Printer.printTag(N); 1757 Printer.printString("name", N->getName()); 1758 Printer.printInt("size", N->getSizeInBits()); 1759 Printer.printInt("align", N->getAlignInBits()); 1760 Printer.printDwarfEnum("encoding", N->getEncoding(), 1761 dwarf::AttributeEncodingString); 1762 Out << ")"; 1763 } 1764 1765 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, 1766 TypePrinting *TypePrinter, SlotTracker *Machine, 1767 const Module *Context) { 1768 Out << "!DIDerivedType("; 1769 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1770 Printer.printTag(N); 1771 Printer.printString("name", N->getName()); 1772 Printer.printMetadata("scope", N->getRawScope()); 1773 Printer.printMetadata("file", N->getRawFile()); 1774 Printer.printInt("line", N->getLine()); 1775 Printer.printMetadata("baseType", N->getRawBaseType(), 1776 /* ShouldSkipNull */ false); 1777 Printer.printInt("size", N->getSizeInBits()); 1778 Printer.printInt("align", N->getAlignInBits()); 1779 Printer.printInt("offset", N->getOffsetInBits()); 1780 Printer.printDIFlags("flags", N->getFlags()); 1781 Printer.printMetadata("extraData", N->getRawExtraData()); 1782 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 1783 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace, 1784 /* ShouldSkipZero */ false); 1785 Out << ")"; 1786 } 1787 1788 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, 1789 TypePrinting *TypePrinter, 1790 SlotTracker *Machine, const Module *Context) { 1791 Out << "!DICompositeType("; 1792 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1793 Printer.printTag(N); 1794 Printer.printString("name", N->getName()); 1795 Printer.printMetadata("scope", N->getRawScope()); 1796 Printer.printMetadata("file", N->getRawFile()); 1797 Printer.printInt("line", N->getLine()); 1798 Printer.printMetadata("baseType", N->getRawBaseType()); 1799 Printer.printInt("size", N->getSizeInBits()); 1800 Printer.printInt("align", N->getAlignInBits()); 1801 Printer.printInt("offset", N->getOffsetInBits()); 1802 Printer.printDIFlags("flags", N->getFlags()); 1803 Printer.printMetadata("elements", N->getRawElements()); 1804 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(), 1805 dwarf::LanguageString); 1806 Printer.printMetadata("vtableHolder", N->getRawVTableHolder()); 1807 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 1808 Printer.printString("identifier", N->getIdentifier()); 1809 Printer.printMetadata("discriminator", N->getRawDiscriminator()); 1810 Out << ")"; 1811 } 1812 1813 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, 1814 TypePrinting *TypePrinter, 1815 SlotTracker *Machine, const Module *Context) { 1816 Out << "!DISubroutineType("; 1817 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1818 Printer.printDIFlags("flags", N->getFlags()); 1819 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString); 1820 Printer.printMetadata("types", N->getRawTypeArray(), 1821 /* ShouldSkipNull */ false); 1822 Out << ")"; 1823 } 1824 1825 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *, 1826 SlotTracker *, const Module *) { 1827 Out << "!DIFile("; 1828 MDFieldPrinter Printer(Out); 1829 Printer.printString("filename", N->getFilename(), 1830 /* ShouldSkipEmpty */ false); 1831 Printer.printString("directory", N->getDirectory(), 1832 /* ShouldSkipEmpty */ false); 1833 // Print all values for checksum together, or not at all. 1834 if (N->getChecksum()) 1835 Printer.printChecksum(*N->getChecksum()); 1836 Printer.printString("source", N->getSource().getValueOr(StringRef()), 1837 /* ShouldSkipEmpty */ true); 1838 Out << ")"; 1839 } 1840 1841 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, 1842 TypePrinting *TypePrinter, SlotTracker *Machine, 1843 const Module *Context) { 1844 Out << "!DICompileUnit("; 1845 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1846 Printer.printDwarfEnum("language", N->getSourceLanguage(), 1847 dwarf::LanguageString, /* ShouldSkipZero */ false); 1848 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 1849 Printer.printString("producer", N->getProducer()); 1850 Printer.printBool("isOptimized", N->isOptimized()); 1851 Printer.printString("flags", N->getFlags()); 1852 Printer.printInt("runtimeVersion", N->getRuntimeVersion(), 1853 /* ShouldSkipZero */ false); 1854 Printer.printString("splitDebugFilename", N->getSplitDebugFilename()); 1855 Printer.printEmissionKind("emissionKind", N->getEmissionKind()); 1856 Printer.printMetadata("enums", N->getRawEnumTypes()); 1857 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes()); 1858 Printer.printMetadata("globals", N->getRawGlobalVariables()); 1859 Printer.printMetadata("imports", N->getRawImportedEntities()); 1860 Printer.printMetadata("macros", N->getRawMacros()); 1861 Printer.printInt("dwoId", N->getDWOId()); 1862 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true); 1863 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(), 1864 false); 1865 Printer.printBool("gnuPubnames", N->getGnuPubnames(), false); 1866 Out << ")"; 1867 } 1868 1869 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, 1870 TypePrinting *TypePrinter, SlotTracker *Machine, 1871 const Module *Context) { 1872 Out << "!DISubprogram("; 1873 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1874 Printer.printString("name", N->getName()); 1875 Printer.printString("linkageName", N->getLinkageName()); 1876 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1877 Printer.printMetadata("file", N->getRawFile()); 1878 Printer.printInt("line", N->getLine()); 1879 Printer.printMetadata("type", N->getRawType()); 1880 Printer.printBool("isLocal", N->isLocalToUnit()); 1881 Printer.printBool("isDefinition", N->isDefinition()); 1882 Printer.printInt("scopeLine", N->getScopeLine()); 1883 Printer.printMetadata("containingType", N->getRawContainingType()); 1884 Printer.printDwarfEnum("virtuality", N->getVirtuality(), 1885 dwarf::VirtualityString); 1886 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none || 1887 N->getVirtualIndex() != 0) 1888 Printer.printInt("virtualIndex", N->getVirtualIndex(), false); 1889 Printer.printInt("thisAdjustment", N->getThisAdjustment()); 1890 Printer.printDIFlags("flags", N->getFlags()); 1891 Printer.printBool("isOptimized", N->isOptimized()); 1892 Printer.printMetadata("unit", N->getRawUnit()); 1893 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 1894 Printer.printMetadata("declaration", N->getRawDeclaration()); 1895 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes()); 1896 Printer.printMetadata("thrownTypes", N->getRawThrownTypes()); 1897 Out << ")"; 1898 } 1899 1900 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, 1901 TypePrinting *TypePrinter, SlotTracker *Machine, 1902 const Module *Context) { 1903 Out << "!DILexicalBlock("; 1904 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1905 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1906 Printer.printMetadata("file", N->getRawFile()); 1907 Printer.printInt("line", N->getLine()); 1908 Printer.printInt("column", N->getColumn()); 1909 Out << ")"; 1910 } 1911 1912 static void writeDILexicalBlockFile(raw_ostream &Out, 1913 const DILexicalBlockFile *N, 1914 TypePrinting *TypePrinter, 1915 SlotTracker *Machine, 1916 const Module *Context) { 1917 Out << "!DILexicalBlockFile("; 1918 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1919 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1920 Printer.printMetadata("file", N->getRawFile()); 1921 Printer.printInt("discriminator", N->getDiscriminator(), 1922 /* ShouldSkipZero */ false); 1923 Out << ")"; 1924 } 1925 1926 static void writeDINamespace(raw_ostream &Out, const DINamespace *N, 1927 TypePrinting *TypePrinter, SlotTracker *Machine, 1928 const Module *Context) { 1929 Out << "!DINamespace("; 1930 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1931 Printer.printString("name", N->getName()); 1932 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1933 Printer.printBool("exportSymbols", N->getExportSymbols(), false); 1934 Out << ")"; 1935 } 1936 1937 static void writeDIMacro(raw_ostream &Out, const DIMacro *N, 1938 TypePrinting *TypePrinter, SlotTracker *Machine, 1939 const Module *Context) { 1940 Out << "!DIMacro("; 1941 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1942 Printer.printMacinfoType(N); 1943 Printer.printInt("line", N->getLine()); 1944 Printer.printString("name", N->getName()); 1945 Printer.printString("value", N->getValue()); 1946 Out << ")"; 1947 } 1948 1949 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, 1950 TypePrinting *TypePrinter, SlotTracker *Machine, 1951 const Module *Context) { 1952 Out << "!DIMacroFile("; 1953 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1954 Printer.printInt("line", N->getLine()); 1955 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 1956 Printer.printMetadata("nodes", N->getRawElements()); 1957 Out << ")"; 1958 } 1959 1960 static void writeDIModule(raw_ostream &Out, const DIModule *N, 1961 TypePrinting *TypePrinter, SlotTracker *Machine, 1962 const Module *Context) { 1963 Out << "!DIModule("; 1964 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1965 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1966 Printer.printString("name", N->getName()); 1967 Printer.printString("configMacros", N->getConfigurationMacros()); 1968 Printer.printString("includePath", N->getIncludePath()); 1969 Printer.printString("isysroot", N->getISysRoot()); 1970 Out << ")"; 1971 } 1972 1973 1974 static void writeDITemplateTypeParameter(raw_ostream &Out, 1975 const DITemplateTypeParameter *N, 1976 TypePrinting *TypePrinter, 1977 SlotTracker *Machine, 1978 const Module *Context) { 1979 Out << "!DITemplateTypeParameter("; 1980 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1981 Printer.printString("name", N->getName()); 1982 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false); 1983 Out << ")"; 1984 } 1985 1986 static void writeDITemplateValueParameter(raw_ostream &Out, 1987 const DITemplateValueParameter *N, 1988 TypePrinting *TypePrinter, 1989 SlotTracker *Machine, 1990 const Module *Context) { 1991 Out << "!DITemplateValueParameter("; 1992 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1993 if (N->getTag() != dwarf::DW_TAG_template_value_parameter) 1994 Printer.printTag(N); 1995 Printer.printString("name", N->getName()); 1996 Printer.printMetadata("type", N->getRawType()); 1997 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false); 1998 Out << ")"; 1999 } 2000 2001 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, 2002 TypePrinting *TypePrinter, 2003 SlotTracker *Machine, const Module *Context) { 2004 Out << "!DIGlobalVariable("; 2005 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2006 Printer.printString("name", N->getName()); 2007 Printer.printString("linkageName", N->getLinkageName()); 2008 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2009 Printer.printMetadata("file", N->getRawFile()); 2010 Printer.printInt("line", N->getLine()); 2011 Printer.printMetadata("type", N->getRawType()); 2012 Printer.printBool("isLocal", N->isLocalToUnit()); 2013 Printer.printBool("isDefinition", N->isDefinition()); 2014 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration()); 2015 Printer.printInt("align", N->getAlignInBits()); 2016 Out << ")"; 2017 } 2018 2019 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, 2020 TypePrinting *TypePrinter, 2021 SlotTracker *Machine, const Module *Context) { 2022 Out << "!DILocalVariable("; 2023 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2024 Printer.printString("name", N->getName()); 2025 Printer.printInt("arg", N->getArg()); 2026 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2027 Printer.printMetadata("file", N->getRawFile()); 2028 Printer.printInt("line", N->getLine()); 2029 Printer.printMetadata("type", N->getRawType()); 2030 Printer.printDIFlags("flags", N->getFlags()); 2031 Printer.printInt("align", N->getAlignInBits()); 2032 Out << ")"; 2033 } 2034 2035 static void writeDILabel(raw_ostream &Out, const DILabel *N, 2036 TypePrinting *TypePrinter, 2037 SlotTracker *Machine, const Module *Context) { 2038 Out << "!DILabel("; 2039 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2040 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2041 Printer.printString("name", N->getName()); 2042 Printer.printMetadata("file", N->getRawFile()); 2043 Printer.printInt("line", N->getLine()); 2044 Out << ")"; 2045 } 2046 2047 static void writeDIExpression(raw_ostream &Out, const DIExpression *N, 2048 TypePrinting *TypePrinter, SlotTracker *Machine, 2049 const Module *Context) { 2050 Out << "!DIExpression("; 2051 FieldSeparator FS; 2052 if (N->isValid()) { 2053 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) { 2054 auto OpStr = dwarf::OperationEncodingString(I->getOp()); 2055 assert(!OpStr.empty() && "Expected valid opcode"); 2056 2057 Out << FS << OpStr; 2058 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A) 2059 Out << FS << I->getArg(A); 2060 } 2061 } else { 2062 for (const auto &I : N->getElements()) 2063 Out << FS << I; 2064 } 2065 Out << ")"; 2066 } 2067 2068 static void writeDIGlobalVariableExpression(raw_ostream &Out, 2069 const DIGlobalVariableExpression *N, 2070 TypePrinting *TypePrinter, 2071 SlotTracker *Machine, 2072 const Module *Context) { 2073 Out << "!DIGlobalVariableExpression("; 2074 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2075 Printer.printMetadata("var", N->getVariable()); 2076 Printer.printMetadata("expr", N->getExpression()); 2077 Out << ")"; 2078 } 2079 2080 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, 2081 TypePrinting *TypePrinter, SlotTracker *Machine, 2082 const Module *Context) { 2083 Out << "!DIObjCProperty("; 2084 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2085 Printer.printString("name", N->getName()); 2086 Printer.printMetadata("file", N->getRawFile()); 2087 Printer.printInt("line", N->getLine()); 2088 Printer.printString("setter", N->getSetterName()); 2089 Printer.printString("getter", N->getGetterName()); 2090 Printer.printInt("attributes", N->getAttributes()); 2091 Printer.printMetadata("type", N->getRawType()); 2092 Out << ")"; 2093 } 2094 2095 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, 2096 TypePrinting *TypePrinter, 2097 SlotTracker *Machine, const Module *Context) { 2098 Out << "!DIImportedEntity("; 2099 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 2100 Printer.printTag(N); 2101 Printer.printString("name", N->getName()); 2102 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2103 Printer.printMetadata("entity", N->getRawEntity()); 2104 Printer.printMetadata("file", N->getRawFile()); 2105 Printer.printInt("line", N->getLine()); 2106 Out << ")"; 2107 } 2108 2109 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 2110 TypePrinting *TypePrinter, 2111 SlotTracker *Machine, 2112 const Module *Context) { 2113 if (Node->isDistinct()) 2114 Out << "distinct "; 2115 else if (Node->isTemporary()) 2116 Out << "<temporary!> "; // Handle broken code. 2117 2118 switch (Node->getMetadataID()) { 2119 default: 2120 llvm_unreachable("Expected uniquable MDNode"); 2121 #define HANDLE_MDNODE_LEAF(CLASS) \ 2122 case Metadata::CLASS##Kind: \ 2123 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \ 2124 break; 2125 #include "llvm/IR/Metadata.def" 2126 } 2127 } 2128 2129 // Full implementation of printing a Value as an operand with support for 2130 // TypePrinting, etc. 2131 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 2132 TypePrinting *TypePrinter, 2133 SlotTracker *Machine, 2134 const Module *Context) { 2135 if (V->hasName()) { 2136 PrintLLVMName(Out, V); 2137 return; 2138 } 2139 2140 const Constant *CV = dyn_cast<Constant>(V); 2141 if (CV && !isa<GlobalValue>(CV)) { 2142 assert(TypePrinter && "Constants require TypePrinting!"); 2143 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context); 2144 return; 2145 } 2146 2147 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2148 Out << "asm "; 2149 if (IA->hasSideEffects()) 2150 Out << "sideeffect "; 2151 if (IA->isAlignStack()) 2152 Out << "alignstack "; 2153 // We don't emit the AD_ATT dialect as it's the assumed default. 2154 if (IA->getDialect() == InlineAsm::AD_Intel) 2155 Out << "inteldialect "; 2156 Out << '"'; 2157 printEscapedString(IA->getAsmString(), Out); 2158 Out << "\", \""; 2159 printEscapedString(IA->getConstraintString(), Out); 2160 Out << '"'; 2161 return; 2162 } 2163 2164 if (auto *MD = dyn_cast<MetadataAsValue>(V)) { 2165 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine, 2166 Context, /* FromValue */ true); 2167 return; 2168 } 2169 2170 char Prefix = '%'; 2171 int Slot; 2172 // If we have a SlotTracker, use it. 2173 if (Machine) { 2174 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2175 Slot = Machine->getGlobalSlot(GV); 2176 Prefix = '@'; 2177 } else { 2178 Slot = Machine->getLocalSlot(V); 2179 2180 // If the local value didn't succeed, then we may be referring to a value 2181 // from a different function. Translate it, as this can happen when using 2182 // address of blocks. 2183 if (Slot == -1) 2184 if ((Machine = createSlotTracker(V))) { 2185 Slot = Machine->getLocalSlot(V); 2186 delete Machine; 2187 } 2188 } 2189 } else if ((Machine = createSlotTracker(V))) { 2190 // Otherwise, create one to get the # and then destroy it. 2191 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2192 Slot = Machine->getGlobalSlot(GV); 2193 Prefix = '@'; 2194 } else { 2195 Slot = Machine->getLocalSlot(V); 2196 } 2197 delete Machine; 2198 Machine = nullptr; 2199 } else { 2200 Slot = -1; 2201 } 2202 2203 if (Slot != -1) 2204 Out << Prefix << Slot; 2205 else 2206 Out << "<badref>"; 2207 } 2208 2209 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 2210 TypePrinting *TypePrinter, 2211 SlotTracker *Machine, const Module *Context, 2212 bool FromValue) { 2213 // Write DIExpressions inline when used as a value. Improves readability of 2214 // debug info intrinsics. 2215 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) { 2216 writeDIExpression(Out, Expr, TypePrinter, Machine, Context); 2217 return; 2218 } 2219 2220 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2221 std::unique_ptr<SlotTracker> MachineStorage; 2222 if (!Machine) { 2223 MachineStorage = make_unique<SlotTracker>(Context); 2224 Machine = MachineStorage.get(); 2225 } 2226 int Slot = Machine->getMetadataSlot(N); 2227 if (Slot == -1) 2228 // Give the pointer value instead of "badref", since this comes up all 2229 // the time when debugging. 2230 Out << "<" << N << ">"; 2231 else 2232 Out << '!' << Slot; 2233 return; 2234 } 2235 2236 if (const MDString *MDS = dyn_cast<MDString>(MD)) { 2237 Out << "!\""; 2238 printEscapedString(MDS->getString(), Out); 2239 Out << '"'; 2240 return; 2241 } 2242 2243 auto *V = cast<ValueAsMetadata>(MD); 2244 assert(TypePrinter && "TypePrinter required for metadata values"); 2245 assert((FromValue || !isa<LocalAsMetadata>(V)) && 2246 "Unexpected function-local metadata outside of value argument"); 2247 2248 TypePrinter->print(V->getValue()->getType(), Out); 2249 Out << ' '; 2250 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context); 2251 } 2252 2253 namespace { 2254 2255 class AssemblyWriter { 2256 formatted_raw_ostream &Out; 2257 const Module *TheModule = nullptr; 2258 const ModuleSummaryIndex *TheIndex = nullptr; 2259 std::unique_ptr<SlotTracker> SlotTrackerStorage; 2260 SlotTracker &Machine; 2261 TypePrinting TypePrinter; 2262 AssemblyAnnotationWriter *AnnotationWriter = nullptr; 2263 SetVector<const Comdat *> Comdats; 2264 bool IsForDebug; 2265 bool ShouldPreserveUseListOrder; 2266 UseListOrderStack UseListOrders; 2267 SmallVector<StringRef, 8> MDNames; 2268 /// Synchronization scope names registered with LLVMContext. 2269 SmallVector<StringRef, 8> SSNs; 2270 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap; 2271 2272 public: 2273 /// Construct an AssemblyWriter with an external SlotTracker 2274 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, 2275 AssemblyAnnotationWriter *AAW, bool IsForDebug, 2276 bool ShouldPreserveUseListOrder = false); 2277 2278 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2279 const ModuleSummaryIndex *Index, bool IsForDebug); 2280 2281 void printMDNodeBody(const MDNode *MD); 2282 void printNamedMDNode(const NamedMDNode *NMD); 2283 2284 void printModule(const Module *M); 2285 2286 void writeOperand(const Value *Op, bool PrintType); 2287 void writeParamOperand(const Value *Operand, AttributeSet Attrs); 2288 void writeOperandBundles(ImmutableCallSite CS); 2289 void writeSyncScope(const LLVMContext &Context, 2290 SyncScope::ID SSID); 2291 void writeAtomic(const LLVMContext &Context, 2292 AtomicOrdering Ordering, 2293 SyncScope::ID SSID); 2294 void writeAtomicCmpXchg(const LLVMContext &Context, 2295 AtomicOrdering SuccessOrdering, 2296 AtomicOrdering FailureOrdering, 2297 SyncScope::ID SSID); 2298 2299 void writeAllMDNodes(); 2300 void writeMDNode(unsigned Slot, const MDNode *Node); 2301 void writeAllAttributeGroups(); 2302 2303 void printTypeIdentities(); 2304 void printGlobal(const GlobalVariable *GV); 2305 void printIndirectSymbol(const GlobalIndirectSymbol *GIS); 2306 void printComdat(const Comdat *C); 2307 void printFunction(const Function *F); 2308 void printArgument(const Argument *FA, AttributeSet Attrs); 2309 void printBasicBlock(const BasicBlock *BB); 2310 void printInstructionLine(const Instruction &I); 2311 void printInstruction(const Instruction &I); 2312 2313 void printUseListOrder(const UseListOrder &Order); 2314 void printUseLists(const Function *F); 2315 2316 void printModuleSummaryIndex(); 2317 void printSummaryInfo(unsigned Slot, const ValueInfo &VI); 2318 void printSummary(const GlobalValueSummary &Summary); 2319 void printAliasSummary(const AliasSummary *AS); 2320 void printGlobalVarSummary(const GlobalVarSummary *GS); 2321 void printFunctionSummary(const FunctionSummary *FS); 2322 void printTypeIdSummary(const TypeIdSummary &TIS); 2323 void printTypeTestResolution(const TypeTestResolution &TTRes); 2324 void printArgs(const std::vector<uint64_t> &Args); 2325 void printWPDRes(const WholeProgramDevirtResolution &WPDRes); 2326 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo); 2327 void printVFuncId(const FunctionSummary::VFuncId VFId); 2328 void 2329 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList, 2330 const char *Tag); 2331 void 2332 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList, 2333 const char *Tag); 2334 2335 private: 2336 /// Print out metadata attachments. 2337 void printMetadataAttachments( 2338 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 2339 StringRef Separator); 2340 2341 // printInfoComment - Print a little comment after the instruction indicating 2342 // which slot it occupies. 2343 void printInfoComment(const Value &V); 2344 2345 // printGCRelocateComment - print comment after call to the gc.relocate 2346 // intrinsic indicating base and derived pointer names. 2347 void printGCRelocateComment(const GCRelocateInst &Relocate); 2348 }; 2349 2350 } // end anonymous namespace 2351 2352 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2353 const Module *M, AssemblyAnnotationWriter *AAW, 2354 bool IsForDebug, bool ShouldPreserveUseListOrder) 2355 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW), 2356 IsForDebug(IsForDebug), 2357 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 2358 if (!TheModule) 2359 return; 2360 for (const GlobalObject &GO : TheModule->global_objects()) 2361 if (const Comdat *C = GO.getComdat()) 2362 Comdats.insert(C); 2363 } 2364 2365 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2366 const ModuleSummaryIndex *Index, bool IsForDebug) 2367 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr), 2368 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {} 2369 2370 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 2371 if (!Operand) { 2372 Out << "<null operand!>"; 2373 return; 2374 } 2375 if (PrintType) { 2376 TypePrinter.print(Operand->getType(), Out); 2377 Out << ' '; 2378 } 2379 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2380 } 2381 2382 void AssemblyWriter::writeSyncScope(const LLVMContext &Context, 2383 SyncScope::ID SSID) { 2384 switch (SSID) { 2385 case SyncScope::System: { 2386 break; 2387 } 2388 default: { 2389 if (SSNs.empty()) 2390 Context.getSyncScopeNames(SSNs); 2391 2392 Out << " syncscope(\""; 2393 printEscapedString(SSNs[SSID], Out); 2394 Out << "\")"; 2395 break; 2396 } 2397 } 2398 } 2399 2400 void AssemblyWriter::writeAtomic(const LLVMContext &Context, 2401 AtomicOrdering Ordering, 2402 SyncScope::ID SSID) { 2403 if (Ordering == AtomicOrdering::NotAtomic) 2404 return; 2405 2406 writeSyncScope(Context, SSID); 2407 Out << " " << toIRString(Ordering); 2408 } 2409 2410 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context, 2411 AtomicOrdering SuccessOrdering, 2412 AtomicOrdering FailureOrdering, 2413 SyncScope::ID SSID) { 2414 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 2415 FailureOrdering != AtomicOrdering::NotAtomic); 2416 2417 writeSyncScope(Context, SSID); 2418 Out << " " << toIRString(SuccessOrdering); 2419 Out << " " << toIRString(FailureOrdering); 2420 } 2421 2422 void AssemblyWriter::writeParamOperand(const Value *Operand, 2423 AttributeSet Attrs) { 2424 if (!Operand) { 2425 Out << "<null operand!>"; 2426 return; 2427 } 2428 2429 // Print the type 2430 TypePrinter.print(Operand->getType(), Out); 2431 // Print parameter attributes list 2432 if (Attrs.hasAttributes()) 2433 Out << ' ' << Attrs.getAsString(); 2434 Out << ' '; 2435 // Print the operand 2436 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2437 } 2438 2439 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) { 2440 if (!CS.hasOperandBundles()) 2441 return; 2442 2443 Out << " [ "; 2444 2445 bool FirstBundle = true; 2446 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2447 OperandBundleUse BU = CS.getOperandBundleAt(i); 2448 2449 if (!FirstBundle) 2450 Out << ", "; 2451 FirstBundle = false; 2452 2453 Out << '"'; 2454 printEscapedString(BU.getTagName(), Out); 2455 Out << '"'; 2456 2457 Out << '('; 2458 2459 bool FirstInput = true; 2460 for (const auto &Input : BU.Inputs) { 2461 if (!FirstInput) 2462 Out << ", "; 2463 FirstInput = false; 2464 2465 TypePrinter.print(Input->getType(), Out); 2466 Out << " "; 2467 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule); 2468 } 2469 2470 Out << ')'; 2471 } 2472 2473 Out << " ]"; 2474 } 2475 2476 void AssemblyWriter::printModule(const Module *M) { 2477 Machine.initialize(); 2478 2479 if (ShouldPreserveUseListOrder) 2480 UseListOrders = predictUseListOrder(M); 2481 2482 if (!M->getModuleIdentifier().empty() && 2483 // Don't print the ID if it will start a new line (which would 2484 // require a comment char before it). 2485 M->getModuleIdentifier().find('\n') == std::string::npos) 2486 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 2487 2488 if (!M->getSourceFileName().empty()) { 2489 Out << "source_filename = \""; 2490 printEscapedString(M->getSourceFileName(), Out); 2491 Out << "\"\n"; 2492 } 2493 2494 const std::string &DL = M->getDataLayoutStr(); 2495 if (!DL.empty()) 2496 Out << "target datalayout = \"" << DL << "\"\n"; 2497 if (!M->getTargetTriple().empty()) 2498 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 2499 2500 if (!M->getModuleInlineAsm().empty()) { 2501 Out << '\n'; 2502 2503 // Split the string into lines, to make it easier to read the .ll file. 2504 StringRef Asm = M->getModuleInlineAsm(); 2505 do { 2506 StringRef Front; 2507 std::tie(Front, Asm) = Asm.split('\n'); 2508 2509 // We found a newline, print the portion of the asm string from the 2510 // last newline up to this newline. 2511 Out << "module asm \""; 2512 printEscapedString(Front, Out); 2513 Out << "\"\n"; 2514 } while (!Asm.empty()); 2515 } 2516 2517 printTypeIdentities(); 2518 2519 // Output all comdats. 2520 if (!Comdats.empty()) 2521 Out << '\n'; 2522 for (const Comdat *C : Comdats) { 2523 printComdat(C); 2524 if (C != Comdats.back()) 2525 Out << '\n'; 2526 } 2527 2528 // Output all globals. 2529 if (!M->global_empty()) Out << '\n'; 2530 for (const GlobalVariable &GV : M->globals()) { 2531 printGlobal(&GV); Out << '\n'; 2532 } 2533 2534 // Output all aliases. 2535 if (!M->alias_empty()) Out << "\n"; 2536 for (const GlobalAlias &GA : M->aliases()) 2537 printIndirectSymbol(&GA); 2538 2539 // Output all ifuncs. 2540 if (!M->ifunc_empty()) Out << "\n"; 2541 for (const GlobalIFunc &GI : M->ifuncs()) 2542 printIndirectSymbol(&GI); 2543 2544 // Output global use-lists. 2545 printUseLists(nullptr); 2546 2547 // Output all of the functions. 2548 for (const Function &F : *M) 2549 printFunction(&F); 2550 assert(UseListOrders.empty() && "All use-lists should have been consumed"); 2551 2552 // Output all attribute groups. 2553 if (!Machine.as_empty()) { 2554 Out << '\n'; 2555 writeAllAttributeGroups(); 2556 } 2557 2558 // Output named metadata. 2559 if (!M->named_metadata_empty()) Out << '\n'; 2560 2561 for (const NamedMDNode &Node : M->named_metadata()) 2562 printNamedMDNode(&Node); 2563 2564 // Output metadata. 2565 if (!Machine.mdn_empty()) { 2566 Out << '\n'; 2567 writeAllMDNodes(); 2568 } 2569 } 2570 2571 void AssemblyWriter::printModuleSummaryIndex() { 2572 assert(TheIndex); 2573 Machine.initializeIndex(); 2574 2575 Out << "\n"; 2576 2577 // Print module path entries, using the module id as the slot number. To 2578 // print in order, add paths to a vector indexed by module id. 2579 std::vector<std::pair<std::string, ModuleHash>> moduleVec; 2580 std::string RegularLTOModuleName = "[Regular LTO]"; 2581 moduleVec.resize(TheIndex->modulePaths().size()); 2582 for (auto &ModPath : TheIndex->modulePaths()) { 2583 // A module id of -1 is a special entry for a regular LTO module created 2584 // during the thin link. 2585 if (ModPath.second.first == -1u) 2586 moduleVec[TheIndex->modulePaths().size() - 1] = 2587 std::make_pair(RegularLTOModuleName, ModPath.second.second); 2588 else { 2589 assert(ModPath.second.first < moduleVec.size()); 2590 moduleVec[ModPath.second.first] = 2591 std::make_pair(ModPath.first(), ModPath.second.second); 2592 } 2593 } 2594 unsigned i = 0; 2595 for (auto &ModPair : moduleVec) { 2596 Out << "^" << i++ << " = module: ("; 2597 Out << "path: \"" << ModPair.first << "\""; 2598 Out << ", hash: ("; 2599 FieldSeparator FS; 2600 for (auto Hash : ModPair.second) 2601 Out << FS << Hash; 2602 Out << "))\n"; 2603 } 2604 2605 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer 2606 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID). 2607 for (auto &GlobalList : *TheIndex) { 2608 auto GUID = GlobalList.first; 2609 for (auto &Summary : GlobalList.second.SummaryList) 2610 SummaryToGUIDMap[Summary.get()] = GUID; 2611 } 2612 2613 // Print the global value summary entries. 2614 for (auto &GlobalList : *TheIndex) { 2615 auto GUID = GlobalList.first; 2616 auto VI = TheIndex->getValueInfo(GlobalList); 2617 printSummaryInfo(Machine.getGUIDSlot(GUID), VI); 2618 } 2619 2620 // Print the TypeIdMap entries. 2621 for (auto &TId : TheIndex->typeIds()) { 2622 auto GUID = GlobalValue::getGUID(TId.first); 2623 Out << "^" << Machine.getGUIDSlot(GUID) << " = typeid: (name: \"" 2624 << TId.first << "\""; 2625 printTypeIdSummary(TId.second); 2626 Out << ") ; guid = " << GUID << "\n"; 2627 } 2628 } 2629 2630 static const char * 2631 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) { 2632 switch (K) { 2633 case WholeProgramDevirtResolution::Indir: 2634 return "indir"; 2635 case WholeProgramDevirtResolution::SingleImpl: 2636 return "singleImpl"; 2637 case WholeProgramDevirtResolution::BranchFunnel: 2638 return "branchFunnel"; 2639 } 2640 llvm_unreachable("invalid WholeProgramDevirtResolution kind"); 2641 } 2642 2643 static const char *getWholeProgDevirtResByArgKindName( 2644 WholeProgramDevirtResolution::ByArg::Kind K) { 2645 switch (K) { 2646 case WholeProgramDevirtResolution::ByArg::Indir: 2647 return "indir"; 2648 case WholeProgramDevirtResolution::ByArg::UniformRetVal: 2649 return "uniformRetVal"; 2650 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: 2651 return "uniqueRetVal"; 2652 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: 2653 return "virtualConstProp"; 2654 } 2655 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind"); 2656 } 2657 2658 static const char *getTTResKindName(TypeTestResolution::Kind K) { 2659 switch (K) { 2660 case TypeTestResolution::Unsat: 2661 return "unsat"; 2662 case TypeTestResolution::ByteArray: 2663 return "byteArray"; 2664 case TypeTestResolution::Inline: 2665 return "inline"; 2666 case TypeTestResolution::Single: 2667 return "single"; 2668 case TypeTestResolution::AllOnes: 2669 return "allOnes"; 2670 } 2671 llvm_unreachable("invalid TypeTestResolution kind"); 2672 } 2673 2674 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) { 2675 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind) 2676 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth; 2677 2678 // The following fields are only used if the target does not support the use 2679 // of absolute symbols to store constants. Print only if non-zero. 2680 if (TTRes.AlignLog2) 2681 Out << ", alignLog2: " << TTRes.AlignLog2; 2682 if (TTRes.SizeM1) 2683 Out << ", sizeM1: " << TTRes.SizeM1; 2684 if (TTRes.BitMask) 2685 // BitMask is uint8_t which causes it to print the corresponding char. 2686 Out << ", bitMask: " << (unsigned)TTRes.BitMask; 2687 if (TTRes.InlineBits) 2688 Out << ", inlineBits: " << TTRes.InlineBits; 2689 2690 Out << ")"; 2691 } 2692 2693 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) { 2694 Out << ", summary: ("; 2695 printTypeTestResolution(TIS.TTRes); 2696 if (!TIS.WPDRes.empty()) { 2697 Out << ", wpdResolutions: ("; 2698 FieldSeparator FS; 2699 for (auto &WPDRes : TIS.WPDRes) { 2700 Out << FS; 2701 Out << "(offset: " << WPDRes.first << ", "; 2702 printWPDRes(WPDRes.second); 2703 Out << ")"; 2704 } 2705 Out << ")"; 2706 } 2707 Out << ")"; 2708 } 2709 2710 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) { 2711 Out << "args: ("; 2712 FieldSeparator FS; 2713 for (auto arg : Args) { 2714 Out << FS; 2715 Out << arg; 2716 } 2717 Out << ")"; 2718 } 2719 2720 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) { 2721 Out << "wpdRes: (kind: "; 2722 Out << getWholeProgDevirtResKindName(WPDRes.TheKind); 2723 2724 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl) 2725 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\""; 2726 2727 if (!WPDRes.ResByArg.empty()) { 2728 Out << ", resByArg: ("; 2729 FieldSeparator FS; 2730 for (auto &ResByArg : WPDRes.ResByArg) { 2731 Out << FS; 2732 printArgs(ResByArg.first); 2733 Out << ", byArg: (kind: "; 2734 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind); 2735 if (ResByArg.second.TheKind == 2736 WholeProgramDevirtResolution::ByArg::UniformRetVal || 2737 ResByArg.second.TheKind == 2738 WholeProgramDevirtResolution::ByArg::UniqueRetVal) 2739 Out << ", info: " << ResByArg.second.Info; 2740 2741 // The following fields are only used if the target does not support the 2742 // use of absolute symbols to store constants. Print only if non-zero. 2743 if (ResByArg.second.Byte || ResByArg.second.Bit) 2744 Out << ", byte: " << ResByArg.second.Byte 2745 << ", bit: " << ResByArg.second.Bit; 2746 2747 Out << ")"; 2748 } 2749 Out << ")"; 2750 } 2751 Out << ")"; 2752 } 2753 2754 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) { 2755 switch (SK) { 2756 case GlobalValueSummary::AliasKind: 2757 return "alias"; 2758 case GlobalValueSummary::FunctionKind: 2759 return "function"; 2760 case GlobalValueSummary::GlobalVarKind: 2761 return "variable"; 2762 } 2763 llvm_unreachable("invalid summary kind"); 2764 } 2765 2766 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) { 2767 Out << ", aliasee: ^" 2768 << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]); 2769 } 2770 2771 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) { 2772 // Nothing for now 2773 } 2774 2775 static std::string getLinkageName(GlobalValue::LinkageTypes LT) { 2776 switch (LT) { 2777 case GlobalValue::ExternalLinkage: 2778 return "external"; 2779 case GlobalValue::PrivateLinkage: 2780 return "private"; 2781 case GlobalValue::InternalLinkage: 2782 return "internal"; 2783 case GlobalValue::LinkOnceAnyLinkage: 2784 return "linkonce"; 2785 case GlobalValue::LinkOnceODRLinkage: 2786 return "linkonce_odr"; 2787 case GlobalValue::WeakAnyLinkage: 2788 return "weak"; 2789 case GlobalValue::WeakODRLinkage: 2790 return "weak_odr"; 2791 case GlobalValue::CommonLinkage: 2792 return "common"; 2793 case GlobalValue::AppendingLinkage: 2794 return "appending"; 2795 case GlobalValue::ExternalWeakLinkage: 2796 return "extern_weak"; 2797 case GlobalValue::AvailableExternallyLinkage: 2798 return "available_externally"; 2799 } 2800 llvm_unreachable("invalid linkage"); 2801 } 2802 2803 // When printing the linkage types in IR where the ExternalLinkage is 2804 // not printed, and other linkage types are expected to be printed with 2805 // a space after the name. 2806 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) { 2807 if (LT == GlobalValue::ExternalLinkage) 2808 return ""; 2809 return getLinkageName(LT) + " "; 2810 } 2811 2812 static const char *getHotnessName(CalleeInfo::HotnessType HT) { 2813 switch (HT) { 2814 case CalleeInfo::HotnessType::Unknown: 2815 return "unknown"; 2816 case CalleeInfo::HotnessType::Cold: 2817 return "cold"; 2818 case CalleeInfo::HotnessType::None: 2819 return "none"; 2820 case CalleeInfo::HotnessType::Hot: 2821 return "hot"; 2822 case CalleeInfo::HotnessType::Critical: 2823 return "critical"; 2824 } 2825 llvm_unreachable("invalid hotness"); 2826 } 2827 2828 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) { 2829 Out << ", insts: " << FS->instCount(); 2830 2831 FunctionSummary::FFlags FFlags = FS->fflags(); 2832 if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse | 2833 FFlags.ReturnDoesNotAlias) { 2834 Out << ", funcFlags: ("; 2835 Out << "readNone: " << FFlags.ReadNone; 2836 Out << ", readOnly: " << FFlags.ReadOnly; 2837 Out << ", noRecurse: " << FFlags.NoRecurse; 2838 Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias; 2839 Out << ")"; 2840 } 2841 if (!FS->calls().empty()) { 2842 Out << ", calls: ("; 2843 FieldSeparator IFS; 2844 for (auto &Call : FS->calls()) { 2845 Out << IFS; 2846 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID()); 2847 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown) 2848 Out << ", hotness: " << getHotnessName(Call.second.getHotness()); 2849 else if (Call.second.RelBlockFreq) 2850 Out << ", relbf: " << Call.second.RelBlockFreq; 2851 Out << ")"; 2852 } 2853 Out << ")"; 2854 } 2855 2856 if (const auto *TIdInfo = FS->getTypeIdInfo()) 2857 printTypeIdInfo(*TIdInfo); 2858 } 2859 2860 void AssemblyWriter::printTypeIdInfo( 2861 const FunctionSummary::TypeIdInfo &TIDInfo) { 2862 Out << ", typeIdInfo: ("; 2863 FieldSeparator TIDFS; 2864 if (!TIDInfo.TypeTests.empty()) { 2865 Out << TIDFS; 2866 Out << "typeTests: ("; 2867 FieldSeparator FS; 2868 for (auto &GUID : TIDInfo.TypeTests) { 2869 Out << FS; 2870 auto Slot = Machine.getGUIDSlot(GUID); 2871 if (Slot != -1) 2872 Out << "^" << Slot; 2873 else 2874 Out << GUID; 2875 } 2876 Out << ")"; 2877 } 2878 if (!TIDInfo.TypeTestAssumeVCalls.empty()) { 2879 Out << TIDFS; 2880 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls"); 2881 } 2882 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) { 2883 Out << TIDFS; 2884 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls"); 2885 } 2886 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) { 2887 Out << TIDFS; 2888 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls, 2889 "typeTestAssumeConstVCalls"); 2890 } 2891 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) { 2892 Out << TIDFS; 2893 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls, 2894 "typeCheckedLoadConstVCalls"); 2895 } 2896 Out << ")"; 2897 } 2898 2899 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) { 2900 Out << "vFuncId: ("; 2901 auto Slot = Machine.getGUIDSlot(VFId.GUID); 2902 if (Slot != -1) 2903 Out << "^" << Slot; 2904 else 2905 Out << "guid: " << VFId.GUID; 2906 Out << ", offset: " << VFId.Offset; 2907 Out << ")"; 2908 } 2909 2910 void AssemblyWriter::printNonConstVCalls( 2911 const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) { 2912 Out << Tag << ": ("; 2913 FieldSeparator FS; 2914 for (auto &VFuncId : VCallList) { 2915 Out << FS; 2916 printVFuncId(VFuncId); 2917 } 2918 Out << ")"; 2919 } 2920 2921 void AssemblyWriter::printConstVCalls( 2922 const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) { 2923 Out << Tag << ": ("; 2924 FieldSeparator FS; 2925 for (auto &ConstVCall : VCallList) { 2926 Out << FS; 2927 printVFuncId(ConstVCall.VFunc); 2928 if (!ConstVCall.Args.empty()) { 2929 Out << ", "; 2930 printArgs(ConstVCall.Args); 2931 } 2932 } 2933 Out << ")"; 2934 } 2935 2936 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) { 2937 GlobalValueSummary::GVFlags GVFlags = Summary.flags(); 2938 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage; 2939 Out << getSummaryKindName(Summary.getSummaryKind()) << ": "; 2940 Out << "(module: ^" << TheIndex->getModuleId(Summary.modulePath()) 2941 << ", flags: ("; 2942 Out << "linkage: " << getLinkageName(LT); 2943 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport; 2944 Out << ", live: " << GVFlags.Live; 2945 Out << ", dsoLocal: " << GVFlags.DSOLocal; 2946 Out << ")"; 2947 2948 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind) 2949 printAliasSummary(cast<AliasSummary>(&Summary)); 2950 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind) 2951 printFunctionSummary(cast<FunctionSummary>(&Summary)); 2952 else 2953 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary)); 2954 2955 auto RefList = Summary.refs(); 2956 if (!RefList.empty()) { 2957 Out << ", refs: ("; 2958 FieldSeparator FS; 2959 for (auto &Ref : RefList) { 2960 Out << FS; 2961 Out << "^" << Machine.getGUIDSlot(Ref.getGUID()); 2962 } 2963 Out << ")"; 2964 } 2965 2966 Out << ")"; 2967 } 2968 2969 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) { 2970 Out << "^" << Slot << " = gv: ("; 2971 if (!VI.name().empty()) 2972 Out << "name: \"" << VI.name() << "\""; 2973 else 2974 Out << "guid: " << VI.getGUID(); 2975 if (!VI.getSummaryList().empty()) { 2976 Out << ", summaries: ("; 2977 FieldSeparator FS; 2978 for (auto &Summary : VI.getSummaryList()) { 2979 Out << FS; 2980 printSummary(*Summary); 2981 } 2982 Out << ")"; 2983 } 2984 Out << ")"; 2985 if (!VI.name().empty()) 2986 Out << " ; guid = " << VI.getGUID(); 2987 Out << "\n"; 2988 } 2989 2990 static void printMetadataIdentifier(StringRef Name, 2991 formatted_raw_ostream &Out) { 2992 if (Name.empty()) { 2993 Out << "<empty name> "; 2994 } else { 2995 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' || 2996 Name[0] == '$' || Name[0] == '.' || Name[0] == '_') 2997 Out << Name[0]; 2998 else 2999 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 3000 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 3001 unsigned char C = Name[i]; 3002 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 3003 C == '.' || C == '_') 3004 Out << C; 3005 else 3006 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 3007 } 3008 } 3009 } 3010 3011 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 3012 Out << '!'; 3013 printMetadataIdentifier(NMD->getName(), Out); 3014 Out << " = !{"; 3015 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 3016 if (i) 3017 Out << ", "; 3018 3019 // Write DIExpressions inline. 3020 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose. 3021 MDNode *Op = NMD->getOperand(i); 3022 if (auto *Expr = dyn_cast<DIExpression>(Op)) { 3023 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr); 3024 continue; 3025 } 3026 3027 int Slot = Machine.getMetadataSlot(Op); 3028 if (Slot == -1) 3029 Out << "<badref>"; 3030 else 3031 Out << '!' << Slot; 3032 } 3033 Out << "}\n"; 3034 } 3035 3036 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 3037 formatted_raw_ostream &Out) { 3038 switch (Vis) { 3039 case GlobalValue::DefaultVisibility: break; 3040 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 3041 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 3042 } 3043 } 3044 3045 static void PrintDSOLocation(const GlobalValue &GV, 3046 formatted_raw_ostream &Out) { 3047 // GVs with local linkage or non default visibility are implicitly dso_local, 3048 // so we don't print it. 3049 bool Implicit = GV.hasLocalLinkage() || 3050 (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility()); 3051 if (GV.isDSOLocal() && !Implicit) 3052 Out << "dso_local "; 3053 } 3054 3055 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 3056 formatted_raw_ostream &Out) { 3057 switch (SCT) { 3058 case GlobalValue::DefaultStorageClass: break; 3059 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 3060 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 3061 } 3062 } 3063 3064 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 3065 formatted_raw_ostream &Out) { 3066 switch (TLM) { 3067 case GlobalVariable::NotThreadLocal: 3068 break; 3069 case GlobalVariable::GeneralDynamicTLSModel: 3070 Out << "thread_local "; 3071 break; 3072 case GlobalVariable::LocalDynamicTLSModel: 3073 Out << "thread_local(localdynamic) "; 3074 break; 3075 case GlobalVariable::InitialExecTLSModel: 3076 Out << "thread_local(initialexec) "; 3077 break; 3078 case GlobalVariable::LocalExecTLSModel: 3079 Out << "thread_local(localexec) "; 3080 break; 3081 } 3082 } 3083 3084 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) { 3085 switch (UA) { 3086 case GlobalVariable::UnnamedAddr::None: 3087 return ""; 3088 case GlobalVariable::UnnamedAddr::Local: 3089 return "local_unnamed_addr"; 3090 case GlobalVariable::UnnamedAddr::Global: 3091 return "unnamed_addr"; 3092 } 3093 llvm_unreachable("Unknown UnnamedAddr"); 3094 } 3095 3096 static void maybePrintComdat(formatted_raw_ostream &Out, 3097 const GlobalObject &GO) { 3098 const Comdat *C = GO.getComdat(); 3099 if (!C) 3100 return; 3101 3102 if (isa<GlobalVariable>(GO)) 3103 Out << ','; 3104 Out << " comdat"; 3105 3106 if (GO.getName() == C->getName()) 3107 return; 3108 3109 Out << '('; 3110 PrintLLVMName(Out, C->getName(), ComdatPrefix); 3111 Out << ')'; 3112 } 3113 3114 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 3115 if (GV->isMaterializable()) 3116 Out << "; Materializable\n"; 3117 3118 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent()); 3119 Out << " = "; 3120 3121 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 3122 Out << "external "; 3123 3124 Out << getLinkageNameWithSpace(GV->getLinkage()); 3125 PrintDSOLocation(*GV, Out); 3126 PrintVisibility(GV->getVisibility(), Out); 3127 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 3128 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 3129 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr()); 3130 if (!UA.empty()) 3131 Out << UA << ' '; 3132 3133 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 3134 Out << "addrspace(" << AddressSpace << ") "; 3135 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 3136 Out << (GV->isConstant() ? "constant " : "global "); 3137 TypePrinter.print(GV->getValueType(), Out); 3138 3139 if (GV->hasInitializer()) { 3140 Out << ' '; 3141 writeOperand(GV->getInitializer(), false); 3142 } 3143 3144 if (GV->hasSection()) { 3145 Out << ", section \""; 3146 printEscapedString(GV->getSection(), Out); 3147 Out << '"'; 3148 } 3149 maybePrintComdat(Out, *GV); 3150 if (GV->getAlignment()) 3151 Out << ", align " << GV->getAlignment(); 3152 3153 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3154 GV->getAllMetadata(MDs); 3155 printMetadataAttachments(MDs, ", "); 3156 3157 auto Attrs = GV->getAttributes(); 3158 if (Attrs.hasAttributes()) 3159 Out << " #" << Machine.getAttributeGroupSlot(Attrs); 3160 3161 printInfoComment(*GV); 3162 } 3163 3164 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) { 3165 if (GIS->isMaterializable()) 3166 Out << "; Materializable\n"; 3167 3168 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent()); 3169 Out << " = "; 3170 3171 Out << getLinkageNameWithSpace(GIS->getLinkage()); 3172 PrintDSOLocation(*GIS, Out); 3173 PrintVisibility(GIS->getVisibility(), Out); 3174 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out); 3175 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out); 3176 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr()); 3177 if (!UA.empty()) 3178 Out << UA << ' '; 3179 3180 if (isa<GlobalAlias>(GIS)) 3181 Out << "alias "; 3182 else if (isa<GlobalIFunc>(GIS)) 3183 Out << "ifunc "; 3184 else 3185 llvm_unreachable("Not an alias or ifunc!"); 3186 3187 TypePrinter.print(GIS->getValueType(), Out); 3188 3189 Out << ", "; 3190 3191 const Constant *IS = GIS->getIndirectSymbol(); 3192 3193 if (!IS) { 3194 TypePrinter.print(GIS->getType(), Out); 3195 Out << " <<NULL ALIASEE>>"; 3196 } else { 3197 writeOperand(IS, !isa<ConstantExpr>(IS)); 3198 } 3199 3200 printInfoComment(*GIS); 3201 Out << '\n'; 3202 } 3203 3204 void AssemblyWriter::printComdat(const Comdat *C) { 3205 C->print(Out); 3206 } 3207 3208 void AssemblyWriter::printTypeIdentities() { 3209 if (TypePrinter.empty()) 3210 return; 3211 3212 Out << '\n'; 3213 3214 // Emit all numbered types. 3215 auto &NumberedTypes = TypePrinter.getNumberedTypes(); 3216 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) { 3217 Out << '%' << I << " = type "; 3218 3219 // Make sure we print out at least one level of the type structure, so 3220 // that we do not get %2 = type %2 3221 TypePrinter.printStructBody(NumberedTypes[I], Out); 3222 Out << '\n'; 3223 } 3224 3225 auto &NamedTypes = TypePrinter.getNamedTypes(); 3226 for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) { 3227 PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix); 3228 Out << " = type "; 3229 3230 // Make sure we print out at least one level of the type structure, so 3231 // that we do not get %FILE = type %FILE 3232 TypePrinter.printStructBody(NamedTypes[I], Out); 3233 Out << '\n'; 3234 } 3235 } 3236 3237 /// printFunction - Print all aspects of a function. 3238 void AssemblyWriter::printFunction(const Function *F) { 3239 // Print out the return type and name. 3240 Out << '\n'; 3241 3242 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 3243 3244 if (F->isMaterializable()) 3245 Out << "; Materializable\n"; 3246 3247 const AttributeList &Attrs = F->getAttributes(); 3248 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) { 3249 AttributeSet AS = Attrs.getFnAttributes(); 3250 std::string AttrStr; 3251 3252 for (const Attribute &Attr : AS) { 3253 if (!Attr.isStringAttribute()) { 3254 if (!AttrStr.empty()) AttrStr += ' '; 3255 AttrStr += Attr.getAsString(); 3256 } 3257 } 3258 3259 if (!AttrStr.empty()) 3260 Out << "; Function Attrs: " << AttrStr << '\n'; 3261 } 3262 3263 Machine.incorporateFunction(F); 3264 3265 if (F->isDeclaration()) { 3266 Out << "declare"; 3267 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3268 F->getAllMetadata(MDs); 3269 printMetadataAttachments(MDs, " "); 3270 Out << ' '; 3271 } else 3272 Out << "define "; 3273 3274 Out << getLinkageNameWithSpace(F->getLinkage()); 3275 PrintDSOLocation(*F, Out); 3276 PrintVisibility(F->getVisibility(), Out); 3277 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 3278 3279 // Print the calling convention. 3280 if (F->getCallingConv() != CallingConv::C) { 3281 PrintCallingConv(F->getCallingConv(), Out); 3282 Out << " "; 3283 } 3284 3285 FunctionType *FT = F->getFunctionType(); 3286 if (Attrs.hasAttributes(AttributeList::ReturnIndex)) 3287 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' '; 3288 TypePrinter.print(F->getReturnType(), Out); 3289 Out << ' '; 3290 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 3291 Out << '('; 3292 3293 // Loop over the arguments, printing them... 3294 if (F->isDeclaration() && !IsForDebug) { 3295 // We're only interested in the type here - don't print argument names. 3296 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) { 3297 // Insert commas as we go... the first arg doesn't get a comma 3298 if (I) 3299 Out << ", "; 3300 // Output type... 3301 TypePrinter.print(FT->getParamType(I), Out); 3302 3303 AttributeSet ArgAttrs = Attrs.getParamAttributes(I); 3304 if (ArgAttrs.hasAttributes()) 3305 Out << ' ' << ArgAttrs.getAsString(); 3306 } 3307 } else { 3308 // The arguments are meaningful here, print them in detail. 3309 for (const Argument &Arg : F->args()) { 3310 // Insert commas as we go... the first arg doesn't get a comma 3311 if (Arg.getArgNo() != 0) 3312 Out << ", "; 3313 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo())); 3314 } 3315 } 3316 3317 // Finish printing arguments... 3318 if (FT->isVarArg()) { 3319 if (FT->getNumParams()) Out << ", "; 3320 Out << "..."; // Output varargs portion of signature! 3321 } 3322 Out << ')'; 3323 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr()); 3324 if (!UA.empty()) 3325 Out << ' ' << UA; 3326 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) 3327 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes()); 3328 if (F->hasSection()) { 3329 Out << " section \""; 3330 printEscapedString(F->getSection(), Out); 3331 Out << '"'; 3332 } 3333 maybePrintComdat(Out, *F); 3334 if (F->getAlignment()) 3335 Out << " align " << F->getAlignment(); 3336 if (F->hasGC()) 3337 Out << " gc \"" << F->getGC() << '"'; 3338 if (F->hasPrefixData()) { 3339 Out << " prefix "; 3340 writeOperand(F->getPrefixData(), true); 3341 } 3342 if (F->hasPrologueData()) { 3343 Out << " prologue "; 3344 writeOperand(F->getPrologueData(), true); 3345 } 3346 if (F->hasPersonalityFn()) { 3347 Out << " personality "; 3348 writeOperand(F->getPersonalityFn(), /*PrintType=*/true); 3349 } 3350 3351 if (F->isDeclaration()) { 3352 Out << '\n'; 3353 } else { 3354 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3355 F->getAllMetadata(MDs); 3356 printMetadataAttachments(MDs, " "); 3357 3358 Out << " {"; 3359 // Output all of the function's basic blocks. 3360 for (const BasicBlock &BB : *F) 3361 printBasicBlock(&BB); 3362 3363 // Output the function's use-lists. 3364 printUseLists(F); 3365 3366 Out << "}\n"; 3367 } 3368 3369 Machine.purgeFunction(); 3370 } 3371 3372 /// printArgument - This member is called for every argument that is passed into 3373 /// the function. Simply print it out 3374 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) { 3375 // Output type... 3376 TypePrinter.print(Arg->getType(), Out); 3377 3378 // Output parameter attributes list 3379 if (Attrs.hasAttributes()) 3380 Out << ' ' << Attrs.getAsString(); 3381 3382 // Output name, if available... 3383 if (Arg->hasName()) { 3384 Out << ' '; 3385 PrintLLVMName(Out, Arg); 3386 } 3387 } 3388 3389 /// printBasicBlock - This member is called for each basic block in a method. 3390 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 3391 if (BB->hasName()) { // Print out the label if it exists... 3392 Out << "\n"; 3393 PrintLLVMName(Out, BB->getName(), LabelPrefix); 3394 Out << ':'; 3395 } else if (!BB->use_empty()) { // Don't print block # of no uses... 3396 Out << "\n; <label>:"; 3397 int Slot = Machine.getLocalSlot(BB); 3398 if (Slot != -1) 3399 Out << Slot << ":"; 3400 else 3401 Out << "<badref>"; 3402 } 3403 3404 if (!BB->getParent()) { 3405 Out.PadToColumn(50); 3406 Out << "; Error: Block without parent!"; 3407 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 3408 // Output predecessors for the block. 3409 Out.PadToColumn(50); 3410 Out << ";"; 3411 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 3412 3413 if (PI == PE) { 3414 Out << " No predecessors!"; 3415 } else { 3416 Out << " preds = "; 3417 writeOperand(*PI, false); 3418 for (++PI; PI != PE; ++PI) { 3419 Out << ", "; 3420 writeOperand(*PI, false); 3421 } 3422 } 3423 } 3424 3425 Out << "\n"; 3426 3427 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 3428 3429 // Output all of the instructions in the basic block... 3430 for (const Instruction &I : *BB) { 3431 printInstructionLine(I); 3432 } 3433 3434 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 3435 } 3436 3437 /// printInstructionLine - Print an instruction and a newline character. 3438 void AssemblyWriter::printInstructionLine(const Instruction &I) { 3439 printInstruction(I); 3440 Out << '\n'; 3441 } 3442 3443 /// printGCRelocateComment - print comment after call to the gc.relocate 3444 /// intrinsic indicating base and derived pointer names. 3445 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) { 3446 Out << " ; ("; 3447 writeOperand(Relocate.getBasePtr(), false); 3448 Out << ", "; 3449 writeOperand(Relocate.getDerivedPtr(), false); 3450 Out << ")"; 3451 } 3452 3453 /// printInfoComment - Print a little comment after the instruction indicating 3454 /// which slot it occupies. 3455 void AssemblyWriter::printInfoComment(const Value &V) { 3456 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V)) 3457 printGCRelocateComment(*Relocate); 3458 3459 if (AnnotationWriter) 3460 AnnotationWriter->printInfoComment(V, Out); 3461 } 3462 3463 // This member is called for each Instruction in a function.. 3464 void AssemblyWriter::printInstruction(const Instruction &I) { 3465 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 3466 3467 // Print out indentation for an instruction. 3468 Out << " "; 3469 3470 // Print out name if it exists... 3471 if (I.hasName()) { 3472 PrintLLVMName(Out, &I); 3473 Out << " = "; 3474 } else if (!I.getType()->isVoidTy()) { 3475 // Print out the def slot taken. 3476 int SlotNum = Machine.getLocalSlot(&I); 3477 if (SlotNum == -1) 3478 Out << "<badref> = "; 3479 else 3480 Out << '%' << SlotNum << " = "; 3481 } 3482 3483 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 3484 if (CI->isMustTailCall()) 3485 Out << "musttail "; 3486 else if (CI->isTailCall()) 3487 Out << "tail "; 3488 else if (CI->isNoTailCall()) 3489 Out << "notail "; 3490 } 3491 3492 // Print out the opcode... 3493 Out << I.getOpcodeName(); 3494 3495 // If this is an atomic load or store, print out the atomic marker. 3496 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 3497 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 3498 Out << " atomic"; 3499 3500 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 3501 Out << " weak"; 3502 3503 // If this is a volatile operation, print out the volatile marker. 3504 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 3505 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 3506 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 3507 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 3508 Out << " volatile"; 3509 3510 // Print out optimization information. 3511 WriteOptimizationInfo(Out, &I); 3512 3513 // Print out the compare instruction predicates 3514 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 3515 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate()); 3516 3517 // Print out the atomicrmw operation 3518 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 3519 writeAtomicRMWOperation(Out, RMWI->getOperation()); 3520 3521 // Print out the type of the operands... 3522 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 3523 3524 // Special case conditional branches to swizzle the condition out to the front 3525 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 3526 const BranchInst &BI(cast<BranchInst>(I)); 3527 Out << ' '; 3528 writeOperand(BI.getCondition(), true); 3529 Out << ", "; 3530 writeOperand(BI.getSuccessor(0), true); 3531 Out << ", "; 3532 writeOperand(BI.getSuccessor(1), true); 3533 3534 } else if (isa<SwitchInst>(I)) { 3535 const SwitchInst& SI(cast<SwitchInst>(I)); 3536 // Special case switch instruction to get formatting nice and correct. 3537 Out << ' '; 3538 writeOperand(SI.getCondition(), true); 3539 Out << ", "; 3540 writeOperand(SI.getDefaultDest(), true); 3541 Out << " ["; 3542 for (auto Case : SI.cases()) { 3543 Out << "\n "; 3544 writeOperand(Case.getCaseValue(), true); 3545 Out << ", "; 3546 writeOperand(Case.getCaseSuccessor(), true); 3547 } 3548 Out << "\n ]"; 3549 } else if (isa<IndirectBrInst>(I)) { 3550 // Special case indirectbr instruction to get formatting nice and correct. 3551 Out << ' '; 3552 writeOperand(Operand, true); 3553 Out << ", ["; 3554 3555 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 3556 if (i != 1) 3557 Out << ", "; 3558 writeOperand(I.getOperand(i), true); 3559 } 3560 Out << ']'; 3561 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 3562 Out << ' '; 3563 TypePrinter.print(I.getType(), Out); 3564 Out << ' '; 3565 3566 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 3567 if (op) Out << ", "; 3568 Out << "[ "; 3569 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 3570 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 3571 } 3572 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 3573 Out << ' '; 3574 writeOperand(I.getOperand(0), true); 3575 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 3576 Out << ", " << *i; 3577 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 3578 Out << ' '; 3579 writeOperand(I.getOperand(0), true); Out << ", "; 3580 writeOperand(I.getOperand(1), true); 3581 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 3582 Out << ", " << *i; 3583 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 3584 Out << ' '; 3585 TypePrinter.print(I.getType(), Out); 3586 if (LPI->isCleanup() || LPI->getNumClauses() != 0) 3587 Out << '\n'; 3588 3589 if (LPI->isCleanup()) 3590 Out << " cleanup"; 3591 3592 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 3593 if (i != 0 || LPI->isCleanup()) Out << "\n"; 3594 if (LPI->isCatch(i)) 3595 Out << " catch "; 3596 else 3597 Out << " filter "; 3598 3599 writeOperand(LPI->getClause(i), true); 3600 } 3601 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) { 3602 Out << " within "; 3603 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false); 3604 Out << " ["; 3605 unsigned Op = 0; 3606 for (const BasicBlock *PadBB : CatchSwitch->handlers()) { 3607 if (Op > 0) 3608 Out << ", "; 3609 writeOperand(PadBB, /*PrintType=*/true); 3610 ++Op; 3611 } 3612 Out << "] unwind "; 3613 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest()) 3614 writeOperand(UnwindDest, /*PrintType=*/true); 3615 else 3616 Out << "to caller"; 3617 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) { 3618 Out << " within "; 3619 writeOperand(FPI->getParentPad(), /*PrintType=*/false); 3620 Out << " ["; 3621 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps; 3622 ++Op) { 3623 if (Op > 0) 3624 Out << ", "; 3625 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true); 3626 } 3627 Out << ']'; 3628 } else if (isa<ReturnInst>(I) && !Operand) { 3629 Out << " void"; 3630 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) { 3631 Out << " from "; 3632 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 3633 3634 Out << " to "; 3635 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 3636 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) { 3637 Out << " from "; 3638 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 3639 3640 Out << " unwind "; 3641 if (CRI->hasUnwindDest()) 3642 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 3643 else 3644 Out << "to caller"; 3645 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 3646 // Print the calling convention being used. 3647 if (CI->getCallingConv() != CallingConv::C) { 3648 Out << " "; 3649 PrintCallingConv(CI->getCallingConv(), Out); 3650 } 3651 3652 Operand = CI->getCalledValue(); 3653 FunctionType *FTy = CI->getFunctionType(); 3654 Type *RetTy = FTy->getReturnType(); 3655 const AttributeList &PAL = CI->getAttributes(); 3656 3657 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 3658 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 3659 3660 // If possible, print out the short form of the call instruction. We can 3661 // only do this if the first argument is a pointer to a nonvararg function, 3662 // and if the return type is not a pointer to a function. 3663 // 3664 Out << ' '; 3665 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 3666 Out << ' '; 3667 writeOperand(Operand, false); 3668 Out << '('; 3669 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 3670 if (op > 0) 3671 Out << ", "; 3672 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op)); 3673 } 3674 3675 // Emit an ellipsis if this is a musttail call in a vararg function. This 3676 // is only to aid readability, musttail calls forward varargs by default. 3677 if (CI->isMustTailCall() && CI->getParent() && 3678 CI->getParent()->getParent() && 3679 CI->getParent()->getParent()->isVarArg()) 3680 Out << ", ..."; 3681 3682 Out << ')'; 3683 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 3684 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 3685 3686 writeOperandBundles(CI); 3687 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 3688 Operand = II->getCalledValue(); 3689 FunctionType *FTy = II->getFunctionType(); 3690 Type *RetTy = FTy->getReturnType(); 3691 const AttributeList &PAL = II->getAttributes(); 3692 3693 // Print the calling convention being used. 3694 if (II->getCallingConv() != CallingConv::C) { 3695 Out << " "; 3696 PrintCallingConv(II->getCallingConv(), Out); 3697 } 3698 3699 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 3700 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 3701 3702 // If possible, print out the short form of the invoke instruction. We can 3703 // only do this if the first argument is a pointer to a nonvararg function, 3704 // and if the return type is not a pointer to a function. 3705 // 3706 Out << ' '; 3707 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 3708 Out << ' '; 3709 writeOperand(Operand, false); 3710 Out << '('; 3711 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 3712 if (op) 3713 Out << ", "; 3714 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op)); 3715 } 3716 3717 Out << ')'; 3718 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 3719 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 3720 3721 writeOperandBundles(II); 3722 3723 Out << "\n to "; 3724 writeOperand(II->getNormalDest(), true); 3725 Out << " unwind "; 3726 writeOperand(II->getUnwindDest(), true); 3727 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 3728 Out << ' '; 3729 if (AI->isUsedWithInAlloca()) 3730 Out << "inalloca "; 3731 if (AI->isSwiftError()) 3732 Out << "swifterror "; 3733 TypePrinter.print(AI->getAllocatedType(), Out); 3734 3735 // Explicitly write the array size if the code is broken, if it's an array 3736 // allocation, or if the type is not canonical for scalar allocations. The 3737 // latter case prevents the type from mutating when round-tripping through 3738 // assembly. 3739 if (!AI->getArraySize() || AI->isArrayAllocation() || 3740 !AI->getArraySize()->getType()->isIntegerTy(32)) { 3741 Out << ", "; 3742 writeOperand(AI->getArraySize(), true); 3743 } 3744 if (AI->getAlignment()) { 3745 Out << ", align " << AI->getAlignment(); 3746 } 3747 3748 unsigned AddrSpace = AI->getType()->getAddressSpace(); 3749 if (AddrSpace != 0) { 3750 Out << ", addrspace(" << AddrSpace << ')'; 3751 } 3752 } else if (isa<CastInst>(I)) { 3753 if (Operand) { 3754 Out << ' '; 3755 writeOperand(Operand, true); // Work with broken code 3756 } 3757 Out << " to "; 3758 TypePrinter.print(I.getType(), Out); 3759 } else if (isa<VAArgInst>(I)) { 3760 if (Operand) { 3761 Out << ' '; 3762 writeOperand(Operand, true); // Work with broken code 3763 } 3764 Out << ", "; 3765 TypePrinter.print(I.getType(), Out); 3766 } else if (Operand) { // Print the normal way. 3767 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 3768 Out << ' '; 3769 TypePrinter.print(GEP->getSourceElementType(), Out); 3770 Out << ','; 3771 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) { 3772 Out << ' '; 3773 TypePrinter.print(LI->getType(), Out); 3774 Out << ','; 3775 } 3776 3777 // PrintAllTypes - Instructions who have operands of all the same type 3778 // omit the type from all but the first operand. If the instruction has 3779 // different type operands (for example br), then they are all printed. 3780 bool PrintAllTypes = false; 3781 Type *TheType = Operand->getType(); 3782 3783 // Select, Store and ShuffleVector always print all types. 3784 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 3785 || isa<ReturnInst>(I)) { 3786 PrintAllTypes = true; 3787 } else { 3788 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 3789 Operand = I.getOperand(i); 3790 // note that Operand shouldn't be null, but the test helps make dump() 3791 // more tolerant of malformed IR 3792 if (Operand && Operand->getType() != TheType) { 3793 PrintAllTypes = true; // We have differing types! Print them all! 3794 break; 3795 } 3796 } 3797 } 3798 3799 if (!PrintAllTypes) { 3800 Out << ' '; 3801 TypePrinter.print(TheType, Out); 3802 } 3803 3804 Out << ' '; 3805 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 3806 if (i) Out << ", "; 3807 writeOperand(I.getOperand(i), PrintAllTypes); 3808 } 3809 } 3810 3811 // Print atomic ordering/alignment for memory operations 3812 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 3813 if (LI->isAtomic()) 3814 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID()); 3815 if (LI->getAlignment()) 3816 Out << ", align " << LI->getAlignment(); 3817 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 3818 if (SI->isAtomic()) 3819 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID()); 3820 if (SI->getAlignment()) 3821 Out << ", align " << SI->getAlignment(); 3822 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 3823 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(), 3824 CXI->getFailureOrdering(), CXI->getSyncScopeID()); 3825 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 3826 writeAtomic(RMWI->getContext(), RMWI->getOrdering(), 3827 RMWI->getSyncScopeID()); 3828 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 3829 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID()); 3830 } 3831 3832 // Print Metadata info. 3833 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD; 3834 I.getAllMetadata(InstMD); 3835 printMetadataAttachments(InstMD, ", "); 3836 3837 // Print a nice comment. 3838 printInfoComment(I); 3839 } 3840 3841 void AssemblyWriter::printMetadataAttachments( 3842 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 3843 StringRef Separator) { 3844 if (MDs.empty()) 3845 return; 3846 3847 if (MDNames.empty()) 3848 MDs[0].second->getContext().getMDKindNames(MDNames); 3849 3850 for (const auto &I : MDs) { 3851 unsigned Kind = I.first; 3852 Out << Separator; 3853 if (Kind < MDNames.size()) { 3854 Out << "!"; 3855 printMetadataIdentifier(MDNames[Kind], Out); 3856 } else 3857 Out << "!<unknown kind #" << Kind << ">"; 3858 Out << ' '; 3859 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule); 3860 } 3861 } 3862 3863 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 3864 Out << '!' << Slot << " = "; 3865 printMDNodeBody(Node); 3866 Out << "\n"; 3867 } 3868 3869 void AssemblyWriter::writeAllMDNodes() { 3870 SmallVector<const MDNode *, 16> Nodes; 3871 Nodes.resize(Machine.mdn_size()); 3872 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 3873 I != E; ++I) 3874 Nodes[I->second] = cast<MDNode>(I->first); 3875 3876 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 3877 writeMDNode(i, Nodes[i]); 3878 } 3879 } 3880 3881 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 3882 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 3883 } 3884 3885 void AssemblyWriter::writeAllAttributeGroups() { 3886 std::vector<std::pair<AttributeSet, unsigned>> asVec; 3887 asVec.resize(Machine.as_size()); 3888 3889 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end(); 3890 I != E; ++I) 3891 asVec[I->second] = *I; 3892 3893 for (const auto &I : asVec) 3894 Out << "attributes #" << I.second << " = { " 3895 << I.first.getAsString(true) << " }\n"; 3896 } 3897 3898 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) { 3899 bool IsInFunction = Machine.getFunction(); 3900 if (IsInFunction) 3901 Out << " "; 3902 3903 Out << "uselistorder"; 3904 if (const BasicBlock *BB = 3905 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) { 3906 Out << "_bb "; 3907 writeOperand(BB->getParent(), false); 3908 Out << ", "; 3909 writeOperand(BB, false); 3910 } else { 3911 Out << " "; 3912 writeOperand(Order.V, true); 3913 } 3914 Out << ", { "; 3915 3916 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3917 Out << Order.Shuffle[0]; 3918 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I) 3919 Out << ", " << Order.Shuffle[I]; 3920 Out << " }\n"; 3921 } 3922 3923 void AssemblyWriter::printUseLists(const Function *F) { 3924 auto hasMore = 3925 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; }; 3926 if (!hasMore()) 3927 // Nothing to do. 3928 return; 3929 3930 Out << "\n; uselistorder directives\n"; 3931 while (hasMore()) { 3932 printUseListOrder(UseListOrders.back()); 3933 UseListOrders.pop_back(); 3934 } 3935 } 3936 3937 //===----------------------------------------------------------------------===// 3938 // External Interface declarations 3939 //===----------------------------------------------------------------------===// 3940 3941 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 3942 bool ShouldPreserveUseListOrder, 3943 bool IsForDebug) const { 3944 SlotTracker SlotTable(this->getParent()); 3945 formatted_raw_ostream OS(ROS); 3946 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW, 3947 IsForDebug, 3948 ShouldPreserveUseListOrder); 3949 W.printFunction(this); 3950 } 3951 3952 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 3953 bool ShouldPreserveUseListOrder, bool IsForDebug) const { 3954 SlotTracker SlotTable(this); 3955 formatted_raw_ostream OS(ROS); 3956 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug, 3957 ShouldPreserveUseListOrder); 3958 W.printModule(this); 3959 } 3960 3961 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const { 3962 SlotTracker SlotTable(getParent()); 3963 formatted_raw_ostream OS(ROS); 3964 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug); 3965 W.printNamedMDNode(this); 3966 } 3967 3968 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST, 3969 bool IsForDebug) const { 3970 Optional<SlotTracker> LocalST; 3971 SlotTracker *SlotTable; 3972 if (auto *ST = MST.getMachine()) 3973 SlotTable = ST; 3974 else { 3975 LocalST.emplace(getParent()); 3976 SlotTable = &*LocalST; 3977 } 3978 3979 formatted_raw_ostream OS(ROS); 3980 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug); 3981 W.printNamedMDNode(this); 3982 } 3983 3984 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const { 3985 PrintLLVMName(ROS, getName(), ComdatPrefix); 3986 ROS << " = comdat "; 3987 3988 switch (getSelectionKind()) { 3989 case Comdat::Any: 3990 ROS << "any"; 3991 break; 3992 case Comdat::ExactMatch: 3993 ROS << "exactmatch"; 3994 break; 3995 case Comdat::Largest: 3996 ROS << "largest"; 3997 break; 3998 case Comdat::NoDuplicates: 3999 ROS << "noduplicates"; 4000 break; 4001 case Comdat::SameSize: 4002 ROS << "samesize"; 4003 break; 4004 } 4005 4006 ROS << '\n'; 4007 } 4008 4009 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const { 4010 TypePrinting TP; 4011 TP.print(const_cast<Type*>(this), OS); 4012 4013 if (NoDetails) 4014 return; 4015 4016 // If the type is a named struct type, print the body as well. 4017 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 4018 if (!STy->isLiteral()) { 4019 OS << " = type "; 4020 TP.printStructBody(STy, OS); 4021 } 4022 } 4023 4024 static bool isReferencingMDNode(const Instruction &I) { 4025 if (const auto *CI = dyn_cast<CallInst>(&I)) 4026 if (Function *F = CI->getCalledFunction()) 4027 if (F->isIntrinsic()) 4028 for (auto &Op : I.operands()) 4029 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 4030 if (isa<MDNode>(V->getMetadata())) 4031 return true; 4032 return false; 4033 } 4034 4035 void Value::print(raw_ostream &ROS, bool IsForDebug) const { 4036 bool ShouldInitializeAllMetadata = false; 4037 if (auto *I = dyn_cast<Instruction>(this)) 4038 ShouldInitializeAllMetadata = isReferencingMDNode(*I); 4039 else if (isa<Function>(this) || isa<MetadataAsValue>(this)) 4040 ShouldInitializeAllMetadata = true; 4041 4042 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata); 4043 print(ROS, MST, IsForDebug); 4044 } 4045 4046 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4047 bool IsForDebug) const { 4048 formatted_raw_ostream OS(ROS); 4049 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr)); 4050 SlotTracker &SlotTable = 4051 MST.getMachine() ? *MST.getMachine() : EmptySlotTable; 4052 auto incorporateFunction = [&](const Function *F) { 4053 if (F) 4054 MST.incorporateFunction(*F); 4055 }; 4056 4057 if (const Instruction *I = dyn_cast<Instruction>(this)) { 4058 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr); 4059 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug); 4060 W.printInstruction(*I); 4061 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 4062 incorporateFunction(BB->getParent()); 4063 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug); 4064 W.printBasicBlock(BB); 4065 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 4066 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug); 4067 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 4068 W.printGlobal(V); 4069 else if (const Function *F = dyn_cast<Function>(GV)) 4070 W.printFunction(F); 4071 else 4072 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV)); 4073 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) { 4074 V->getMetadata()->print(ROS, MST, getModuleFromVal(V)); 4075 } else if (const Constant *C = dyn_cast<Constant>(this)) { 4076 TypePrinting TypePrinter; 4077 TypePrinter.print(C->getType(), OS); 4078 OS << ' '; 4079 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr); 4080 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) { 4081 this->printAsOperand(OS, /* PrintType */ true, MST); 4082 } else { 4083 llvm_unreachable("Unknown value to print out!"); 4084 } 4085 } 4086 4087 /// Print without a type, skipping the TypePrinting object. 4088 /// 4089 /// \return \c true iff printing was successful. 4090 static bool printWithoutType(const Value &V, raw_ostream &O, 4091 SlotTracker *Machine, const Module *M) { 4092 if (V.hasName() || isa<GlobalValue>(V) || 4093 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) { 4094 WriteAsOperandInternal(O, &V, nullptr, Machine, M); 4095 return true; 4096 } 4097 return false; 4098 } 4099 4100 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, 4101 ModuleSlotTracker &MST) { 4102 TypePrinting TypePrinter(MST.getModule()); 4103 if (PrintType) { 4104 TypePrinter.print(V.getType(), O); 4105 O << ' '; 4106 } 4107 4108 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(), 4109 MST.getModule()); 4110 } 4111 4112 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4113 const Module *M) const { 4114 if (!M) 4115 M = getModuleFromVal(this); 4116 4117 if (!PrintType) 4118 if (printWithoutType(*this, O, nullptr, M)) 4119 return; 4120 4121 SlotTracker Machine( 4122 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this)); 4123 ModuleSlotTracker MST(Machine, M); 4124 printAsOperandImpl(*this, O, PrintType, MST); 4125 } 4126 4127 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4128 ModuleSlotTracker &MST) const { 4129 if (!PrintType) 4130 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule())) 4131 return; 4132 4133 printAsOperandImpl(*this, O, PrintType, MST); 4134 } 4135 4136 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, 4137 ModuleSlotTracker &MST, const Module *M, 4138 bool OnlyAsOperand) { 4139 formatted_raw_ostream OS(ROS); 4140 4141 TypePrinting TypePrinter(M); 4142 4143 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M, 4144 /* FromValue */ true); 4145 4146 auto *N = dyn_cast<MDNode>(&MD); 4147 if (OnlyAsOperand || !N || isa<DIExpression>(MD)) 4148 return; 4149 4150 OS << " = "; 4151 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M); 4152 } 4153 4154 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const { 4155 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4156 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4157 } 4158 4159 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, 4160 const Module *M) const { 4161 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4162 } 4163 4164 void Metadata::print(raw_ostream &OS, const Module *M, 4165 bool /*IsForDebug*/) const { 4166 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4167 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4168 } 4169 4170 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST, 4171 const Module *M, bool /*IsForDebug*/) const { 4172 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4173 } 4174 4175 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const { 4176 SlotTracker SlotTable(this); 4177 formatted_raw_ostream OS(ROS); 4178 AssemblyWriter W(OS, SlotTable, this, IsForDebug); 4179 W.printModuleSummaryIndex(); 4180 } 4181 4182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4183 // Value::dump - allow easy printing of Values from the debugger. 4184 LLVM_DUMP_METHOD 4185 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4186 4187 // Type::dump - allow easy printing of Types from the debugger. 4188 LLVM_DUMP_METHOD 4189 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4190 4191 // Module::dump() - Allow printing of Modules from the debugger. 4192 LLVM_DUMP_METHOD 4193 void Module::dump() const { 4194 print(dbgs(), nullptr, 4195 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true); 4196 } 4197 4198 // Allow printing of Comdats from the debugger. 4199 LLVM_DUMP_METHOD 4200 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4201 4202 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 4203 LLVM_DUMP_METHOD 4204 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4205 4206 LLVM_DUMP_METHOD 4207 void Metadata::dump() const { dump(nullptr); } 4208 4209 LLVM_DUMP_METHOD 4210 void Metadata::dump(const Module *M) const { 4211 print(dbgs(), M, /*IsForDebug=*/true); 4212 dbgs() << '\n'; 4213 } 4214 4215 // Allow printing of ModuleSummaryIndex from the debugger. 4216 LLVM_DUMP_METHOD 4217 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4218 #endif 4219