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