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