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->getElementType(), 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.printInt("size", N->getSizeInBits()); 1990 Printer.printInt("align", N->getAlignInBits()); 1991 Printer.printDwarfEnum("encoding", N->getEncoding(), 1992 dwarf::AttributeEncodingString); 1993 Out << ")"; 1994 } 1995 1996 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, 1997 AsmWriterContext &WriterCtx) { 1998 Out << "!DIDerivedType("; 1999 MDFieldPrinter Printer(Out, WriterCtx); 2000 Printer.printTag(N); 2001 Printer.printString("name", N->getName()); 2002 Printer.printMetadata("scope", N->getRawScope()); 2003 Printer.printMetadata("file", N->getRawFile()); 2004 Printer.printInt("line", N->getLine()); 2005 Printer.printMetadata("baseType", N->getRawBaseType(), 2006 /* ShouldSkipNull */ false); 2007 Printer.printInt("size", N->getSizeInBits()); 2008 Printer.printInt("align", N->getAlignInBits()); 2009 Printer.printInt("offset", N->getOffsetInBits()); 2010 Printer.printDIFlags("flags", N->getFlags()); 2011 Printer.printMetadata("extraData", N->getRawExtraData()); 2012 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 2013 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace, 2014 /* ShouldSkipZero */ false); 2015 Printer.printMetadata("annotations", N->getRawAnnotations()); 2016 Out << ")"; 2017 } 2018 2019 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, 2020 AsmWriterContext &WriterCtx) { 2021 Out << "!DICompositeType("; 2022 MDFieldPrinter Printer(Out, WriterCtx); 2023 Printer.printTag(N); 2024 Printer.printString("name", N->getName()); 2025 Printer.printMetadata("scope", N->getRawScope()); 2026 Printer.printMetadata("file", N->getRawFile()); 2027 Printer.printInt("line", N->getLine()); 2028 Printer.printMetadata("baseType", N->getRawBaseType()); 2029 Printer.printInt("size", N->getSizeInBits()); 2030 Printer.printInt("align", N->getAlignInBits()); 2031 Printer.printInt("offset", N->getOffsetInBits()); 2032 Printer.printDIFlags("flags", N->getFlags()); 2033 Printer.printMetadata("elements", N->getRawElements()); 2034 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(), 2035 dwarf::LanguageString); 2036 Printer.printMetadata("vtableHolder", N->getRawVTableHolder()); 2037 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2038 Printer.printString("identifier", N->getIdentifier()); 2039 Printer.printMetadata("discriminator", N->getRawDiscriminator()); 2040 Printer.printMetadata("dataLocation", N->getRawDataLocation()); 2041 Printer.printMetadata("associated", N->getRawAssociated()); 2042 Printer.printMetadata("allocated", N->getRawAllocated()); 2043 if (auto *RankConst = N->getRankConst()) 2044 Printer.printInt("rank", RankConst->getSExtValue(), 2045 /* ShouldSkipZero */ false); 2046 else 2047 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true); 2048 Printer.printMetadata("annotations", N->getRawAnnotations()); 2049 Out << ")"; 2050 } 2051 2052 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, 2053 AsmWriterContext &WriterCtx) { 2054 Out << "!DISubroutineType("; 2055 MDFieldPrinter Printer(Out, WriterCtx); 2056 Printer.printDIFlags("flags", N->getFlags()); 2057 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString); 2058 Printer.printMetadata("types", N->getRawTypeArray(), 2059 /* ShouldSkipNull */ false); 2060 Out << ")"; 2061 } 2062 2063 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) { 2064 Out << "!DIFile("; 2065 MDFieldPrinter Printer(Out); 2066 Printer.printString("filename", N->getFilename(), 2067 /* ShouldSkipEmpty */ false); 2068 Printer.printString("directory", N->getDirectory(), 2069 /* ShouldSkipEmpty */ false); 2070 // Print all values for checksum together, or not at all. 2071 if (N->getChecksum()) 2072 Printer.printChecksum(*N->getChecksum()); 2073 Printer.printString("source", N->getSource().getValueOr(StringRef()), 2074 /* ShouldSkipEmpty */ true); 2075 Out << ")"; 2076 } 2077 2078 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, 2079 AsmWriterContext &WriterCtx) { 2080 Out << "!DICompileUnit("; 2081 MDFieldPrinter Printer(Out, WriterCtx); 2082 Printer.printDwarfEnum("language", N->getSourceLanguage(), 2083 dwarf::LanguageString, /* ShouldSkipZero */ false); 2084 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 2085 Printer.printString("producer", N->getProducer()); 2086 Printer.printBool("isOptimized", N->isOptimized()); 2087 Printer.printString("flags", N->getFlags()); 2088 Printer.printInt("runtimeVersion", N->getRuntimeVersion(), 2089 /* ShouldSkipZero */ false); 2090 Printer.printString("splitDebugFilename", N->getSplitDebugFilename()); 2091 Printer.printEmissionKind("emissionKind", N->getEmissionKind()); 2092 Printer.printMetadata("enums", N->getRawEnumTypes()); 2093 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes()); 2094 Printer.printMetadata("globals", N->getRawGlobalVariables()); 2095 Printer.printMetadata("imports", N->getRawImportedEntities()); 2096 Printer.printMetadata("macros", N->getRawMacros()); 2097 Printer.printInt("dwoId", N->getDWOId()); 2098 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true); 2099 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(), 2100 false); 2101 Printer.printNameTableKind("nameTableKind", N->getNameTableKind()); 2102 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false); 2103 Printer.printString("sysroot", N->getSysRoot()); 2104 Printer.printString("sdk", N->getSDK()); 2105 Out << ")"; 2106 } 2107 2108 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, 2109 AsmWriterContext &WriterCtx) { 2110 Out << "!DISubprogram("; 2111 MDFieldPrinter Printer(Out, WriterCtx); 2112 Printer.printString("name", N->getName()); 2113 Printer.printString("linkageName", N->getLinkageName()); 2114 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2115 Printer.printMetadata("file", N->getRawFile()); 2116 Printer.printInt("line", N->getLine()); 2117 Printer.printMetadata("type", N->getRawType()); 2118 Printer.printInt("scopeLine", N->getScopeLine()); 2119 Printer.printMetadata("containingType", N->getRawContainingType()); 2120 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none || 2121 N->getVirtualIndex() != 0) 2122 Printer.printInt("virtualIndex", N->getVirtualIndex(), false); 2123 Printer.printInt("thisAdjustment", N->getThisAdjustment()); 2124 Printer.printDIFlags("flags", N->getFlags()); 2125 Printer.printDISPFlags("spFlags", N->getSPFlags()); 2126 Printer.printMetadata("unit", N->getRawUnit()); 2127 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2128 Printer.printMetadata("declaration", N->getRawDeclaration()); 2129 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes()); 2130 Printer.printMetadata("thrownTypes", N->getRawThrownTypes()); 2131 Printer.printMetadata("annotations", N->getRawAnnotations()); 2132 Out << ")"; 2133 } 2134 2135 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, 2136 AsmWriterContext &WriterCtx) { 2137 Out << "!DILexicalBlock("; 2138 MDFieldPrinter Printer(Out, WriterCtx); 2139 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2140 Printer.printMetadata("file", N->getRawFile()); 2141 Printer.printInt("line", N->getLine()); 2142 Printer.printInt("column", N->getColumn()); 2143 Out << ")"; 2144 } 2145 2146 static void writeDILexicalBlockFile(raw_ostream &Out, 2147 const DILexicalBlockFile *N, 2148 AsmWriterContext &WriterCtx) { 2149 Out << "!DILexicalBlockFile("; 2150 MDFieldPrinter Printer(Out, WriterCtx); 2151 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2152 Printer.printMetadata("file", N->getRawFile()); 2153 Printer.printInt("discriminator", N->getDiscriminator(), 2154 /* ShouldSkipZero */ false); 2155 Out << ")"; 2156 } 2157 2158 static void writeDINamespace(raw_ostream &Out, const DINamespace *N, 2159 AsmWriterContext &WriterCtx) { 2160 Out << "!DINamespace("; 2161 MDFieldPrinter Printer(Out, WriterCtx); 2162 Printer.printString("name", N->getName()); 2163 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2164 Printer.printBool("exportSymbols", N->getExportSymbols(), false); 2165 Out << ")"; 2166 } 2167 2168 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N, 2169 AsmWriterContext &WriterCtx) { 2170 Out << "!DICommonBlock("; 2171 MDFieldPrinter Printer(Out, WriterCtx); 2172 Printer.printMetadata("scope", N->getRawScope(), false); 2173 Printer.printMetadata("declaration", N->getRawDecl(), false); 2174 Printer.printString("name", N->getName()); 2175 Printer.printMetadata("file", N->getRawFile()); 2176 Printer.printInt("line", N->getLineNo()); 2177 Out << ")"; 2178 } 2179 2180 static void writeDIMacro(raw_ostream &Out, const DIMacro *N, 2181 AsmWriterContext &WriterCtx) { 2182 Out << "!DIMacro("; 2183 MDFieldPrinter Printer(Out, WriterCtx); 2184 Printer.printMacinfoType(N); 2185 Printer.printInt("line", N->getLine()); 2186 Printer.printString("name", N->getName()); 2187 Printer.printString("value", N->getValue()); 2188 Out << ")"; 2189 } 2190 2191 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, 2192 AsmWriterContext &WriterCtx) { 2193 Out << "!DIMacroFile("; 2194 MDFieldPrinter Printer(Out, WriterCtx); 2195 Printer.printInt("line", N->getLine()); 2196 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 2197 Printer.printMetadata("nodes", N->getRawElements()); 2198 Out << ")"; 2199 } 2200 2201 static void writeDIModule(raw_ostream &Out, const DIModule *N, 2202 AsmWriterContext &WriterCtx) { 2203 Out << "!DIModule("; 2204 MDFieldPrinter Printer(Out, WriterCtx); 2205 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2206 Printer.printString("name", N->getName()); 2207 Printer.printString("configMacros", N->getConfigurationMacros()); 2208 Printer.printString("includePath", N->getIncludePath()); 2209 Printer.printString("apinotes", N->getAPINotesFile()); 2210 Printer.printMetadata("file", N->getRawFile()); 2211 Printer.printInt("line", N->getLineNo()); 2212 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false); 2213 Out << ")"; 2214 } 2215 2216 static void writeDITemplateTypeParameter(raw_ostream &Out, 2217 const DITemplateTypeParameter *N, 2218 AsmWriterContext &WriterCtx) { 2219 Out << "!DITemplateTypeParameter("; 2220 MDFieldPrinter Printer(Out, WriterCtx); 2221 Printer.printString("name", N->getName()); 2222 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false); 2223 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false); 2224 Out << ")"; 2225 } 2226 2227 static void writeDITemplateValueParameter(raw_ostream &Out, 2228 const DITemplateValueParameter *N, 2229 AsmWriterContext &WriterCtx) { 2230 Out << "!DITemplateValueParameter("; 2231 MDFieldPrinter Printer(Out, WriterCtx); 2232 if (N->getTag() != dwarf::DW_TAG_template_value_parameter) 2233 Printer.printTag(N); 2234 Printer.printString("name", N->getName()); 2235 Printer.printMetadata("type", N->getRawType()); 2236 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false); 2237 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false); 2238 Out << ")"; 2239 } 2240 2241 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, 2242 AsmWriterContext &WriterCtx) { 2243 Out << "!DIGlobalVariable("; 2244 MDFieldPrinter Printer(Out, WriterCtx); 2245 Printer.printString("name", N->getName()); 2246 Printer.printString("linkageName", N->getLinkageName()); 2247 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2248 Printer.printMetadata("file", N->getRawFile()); 2249 Printer.printInt("line", N->getLine()); 2250 Printer.printMetadata("type", N->getRawType()); 2251 Printer.printBool("isLocal", N->isLocalToUnit()); 2252 Printer.printBool("isDefinition", N->isDefinition()); 2253 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration()); 2254 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 2255 Printer.printInt("align", N->getAlignInBits()); 2256 Printer.printMetadata("annotations", N->getRawAnnotations()); 2257 Out << ")"; 2258 } 2259 2260 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, 2261 AsmWriterContext &WriterCtx) { 2262 Out << "!DILocalVariable("; 2263 MDFieldPrinter Printer(Out, WriterCtx); 2264 Printer.printString("name", N->getName()); 2265 Printer.printInt("arg", N->getArg()); 2266 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2267 Printer.printMetadata("file", N->getRawFile()); 2268 Printer.printInt("line", N->getLine()); 2269 Printer.printMetadata("type", N->getRawType()); 2270 Printer.printDIFlags("flags", N->getFlags()); 2271 Printer.printInt("align", N->getAlignInBits()); 2272 Printer.printMetadata("annotations", N->getRawAnnotations()); 2273 Out << ")"; 2274 } 2275 2276 static void writeDILabel(raw_ostream &Out, const DILabel *N, 2277 AsmWriterContext &WriterCtx) { 2278 Out << "!DILabel("; 2279 MDFieldPrinter Printer(Out, WriterCtx); 2280 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2281 Printer.printString("name", N->getName()); 2282 Printer.printMetadata("file", N->getRawFile()); 2283 Printer.printInt("line", N->getLine()); 2284 Out << ")"; 2285 } 2286 2287 static void writeDIExpression(raw_ostream &Out, const DIExpression *N, 2288 AsmWriterContext &WriterCtx) { 2289 Out << "!DIExpression("; 2290 FieldSeparator FS; 2291 if (N->isValid()) { 2292 for (const DIExpression::ExprOperand &Op : N->expr_ops()) { 2293 auto OpStr = dwarf::OperationEncodingString(Op.getOp()); 2294 assert(!OpStr.empty() && "Expected valid opcode"); 2295 2296 Out << FS << OpStr; 2297 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) { 2298 Out << FS << Op.getArg(0); 2299 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1)); 2300 } else { 2301 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A) 2302 Out << FS << Op.getArg(A); 2303 } 2304 } 2305 } else { 2306 for (const auto &I : N->getElements()) 2307 Out << FS << I; 2308 } 2309 Out << ")"; 2310 } 2311 2312 static void writeDIArgList(raw_ostream &Out, const DIArgList *N, 2313 AsmWriterContext &WriterCtx, 2314 bool FromValue = false) { 2315 assert(FromValue && 2316 "Unexpected DIArgList metadata outside of value argument"); 2317 Out << "!DIArgList("; 2318 FieldSeparator FS; 2319 MDFieldPrinter Printer(Out, WriterCtx); 2320 for (Metadata *Arg : N->getArgs()) { 2321 Out << FS; 2322 WriteAsOperandInternal(Out, Arg, WriterCtx, true); 2323 } 2324 Out << ")"; 2325 } 2326 2327 static void writeDIGlobalVariableExpression(raw_ostream &Out, 2328 const DIGlobalVariableExpression *N, 2329 AsmWriterContext &WriterCtx) { 2330 Out << "!DIGlobalVariableExpression("; 2331 MDFieldPrinter Printer(Out, WriterCtx); 2332 Printer.printMetadata("var", N->getVariable()); 2333 Printer.printMetadata("expr", N->getExpression()); 2334 Out << ")"; 2335 } 2336 2337 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, 2338 AsmWriterContext &WriterCtx) { 2339 Out << "!DIObjCProperty("; 2340 MDFieldPrinter Printer(Out, WriterCtx); 2341 Printer.printString("name", N->getName()); 2342 Printer.printMetadata("file", N->getRawFile()); 2343 Printer.printInt("line", N->getLine()); 2344 Printer.printString("setter", N->getSetterName()); 2345 Printer.printString("getter", N->getGetterName()); 2346 Printer.printInt("attributes", N->getAttributes()); 2347 Printer.printMetadata("type", N->getRawType()); 2348 Out << ")"; 2349 } 2350 2351 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, 2352 AsmWriterContext &WriterCtx) { 2353 Out << "!DIImportedEntity("; 2354 MDFieldPrinter Printer(Out, WriterCtx); 2355 Printer.printTag(N); 2356 Printer.printString("name", N->getName()); 2357 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 2358 Printer.printMetadata("entity", N->getRawEntity()); 2359 Printer.printMetadata("file", N->getRawFile()); 2360 Printer.printInt("line", N->getLine()); 2361 Printer.printMetadata("elements", N->getRawElements()); 2362 Out << ")"; 2363 } 2364 2365 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 2366 AsmWriterContext &Ctx) { 2367 if (Node->isDistinct()) 2368 Out << "distinct "; 2369 else if (Node->isTemporary()) 2370 Out << "<temporary!> "; // Handle broken code. 2371 2372 switch (Node->getMetadataID()) { 2373 default: 2374 llvm_unreachable("Expected uniquable MDNode"); 2375 #define HANDLE_MDNODE_LEAF(CLASS) \ 2376 case Metadata::CLASS##Kind: \ 2377 write##CLASS(Out, cast<CLASS>(Node), Ctx); \ 2378 break; 2379 #include "llvm/IR/Metadata.def" 2380 } 2381 } 2382 2383 // Full implementation of printing a Value as an operand with support for 2384 // TypePrinting, etc. 2385 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 2386 AsmWriterContext &WriterCtx) { 2387 if (V->hasName()) { 2388 PrintLLVMName(Out, V); 2389 return; 2390 } 2391 2392 const Constant *CV = dyn_cast<Constant>(V); 2393 if (CV && !isa<GlobalValue>(CV)) { 2394 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!"); 2395 WriteConstantInternal(Out, CV, WriterCtx); 2396 return; 2397 } 2398 2399 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2400 Out << "asm "; 2401 if (IA->hasSideEffects()) 2402 Out << "sideeffect "; 2403 if (IA->isAlignStack()) 2404 Out << "alignstack "; 2405 // We don't emit the AD_ATT dialect as it's the assumed default. 2406 if (IA->getDialect() == InlineAsm::AD_Intel) 2407 Out << "inteldialect "; 2408 if (IA->canThrow()) 2409 Out << "unwind "; 2410 Out << '"'; 2411 printEscapedString(IA->getAsmString(), Out); 2412 Out << "\", \""; 2413 printEscapedString(IA->getConstraintString(), Out); 2414 Out << '"'; 2415 return; 2416 } 2417 2418 if (auto *MD = dyn_cast<MetadataAsValue>(V)) { 2419 WriteAsOperandInternal(Out, MD->getMetadata(), WriterCtx, 2420 /* FromValue */ true); 2421 return; 2422 } 2423 2424 char Prefix = '%'; 2425 int Slot; 2426 auto *Machine = WriterCtx.Machine; 2427 // If we have a SlotTracker, use it. 2428 if (Machine) { 2429 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2430 Slot = Machine->getGlobalSlot(GV); 2431 Prefix = '@'; 2432 } else { 2433 Slot = Machine->getLocalSlot(V); 2434 2435 // If the local value didn't succeed, then we may be referring to a value 2436 // from a different function. Translate it, as this can happen when using 2437 // address of blocks. 2438 if (Slot == -1) 2439 if ((Machine = createSlotTracker(V))) { 2440 Slot = Machine->getLocalSlot(V); 2441 delete Machine; 2442 } 2443 } 2444 } else if ((Machine = createSlotTracker(V))) { 2445 // Otherwise, create one to get the # and then destroy it. 2446 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2447 Slot = Machine->getGlobalSlot(GV); 2448 Prefix = '@'; 2449 } else { 2450 Slot = Machine->getLocalSlot(V); 2451 } 2452 delete Machine; 2453 Machine = nullptr; 2454 } else { 2455 Slot = -1; 2456 } 2457 2458 if (Slot != -1) 2459 Out << Prefix << Slot; 2460 else 2461 Out << "<badref>"; 2462 } 2463 2464 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 2465 AsmWriterContext &WriterCtx, 2466 bool FromValue) { 2467 // Write DIExpressions and DIArgLists inline when used as a value. Improves 2468 // readability of debug info intrinsics. 2469 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) { 2470 writeDIExpression(Out, Expr, WriterCtx); 2471 return; 2472 } 2473 if (const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) { 2474 writeDIArgList(Out, ArgList, WriterCtx, FromValue); 2475 return; 2476 } 2477 2478 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2479 std::unique_ptr<SlotTracker> MachineStorage; 2480 SaveAndRestore<SlotTracker *> SARMachine(WriterCtx.Machine); 2481 if (!WriterCtx.Machine) { 2482 MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context); 2483 WriterCtx.Machine = MachineStorage.get(); 2484 } 2485 int Slot = WriterCtx.Machine->getMetadataSlot(N); 2486 if (Slot == -1) { 2487 if (const DILocation *Loc = dyn_cast<DILocation>(N)) { 2488 writeDILocation(Out, Loc, WriterCtx); 2489 return; 2490 } 2491 // Give the pointer value instead of "badref", since this comes up all 2492 // the time when debugging. 2493 Out << "<" << N << ">"; 2494 } else 2495 Out << '!' << Slot; 2496 return; 2497 } 2498 2499 if (const MDString *MDS = dyn_cast<MDString>(MD)) { 2500 Out << "!\""; 2501 printEscapedString(MDS->getString(), Out); 2502 Out << '"'; 2503 return; 2504 } 2505 2506 auto *V = cast<ValueAsMetadata>(MD); 2507 assert(WriterCtx.TypePrinter && "TypePrinter required for metadata values"); 2508 assert((FromValue || !isa<LocalAsMetadata>(V)) && 2509 "Unexpected function-local metadata outside of value argument"); 2510 2511 WriterCtx.TypePrinter->print(V->getValue()->getType(), Out); 2512 Out << ' '; 2513 WriteAsOperandInternal(Out, V->getValue(), WriterCtx); 2514 } 2515 2516 namespace { 2517 2518 class AssemblyWriter { 2519 formatted_raw_ostream &Out; 2520 const Module *TheModule = nullptr; 2521 const ModuleSummaryIndex *TheIndex = nullptr; 2522 std::unique_ptr<SlotTracker> SlotTrackerStorage; 2523 SlotTracker &Machine; 2524 TypePrinting TypePrinter; 2525 AssemblyAnnotationWriter *AnnotationWriter = nullptr; 2526 SetVector<const Comdat *> Comdats; 2527 bool IsForDebug; 2528 bool ShouldPreserveUseListOrder; 2529 UseListOrderMap UseListOrders; 2530 SmallVector<StringRef, 8> MDNames; 2531 /// Synchronization scope names registered with LLVMContext. 2532 SmallVector<StringRef, 8> SSNs; 2533 DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap; 2534 2535 public: 2536 /// Construct an AssemblyWriter with an external SlotTracker 2537 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, 2538 AssemblyAnnotationWriter *AAW, bool IsForDebug, 2539 bool ShouldPreserveUseListOrder = false); 2540 2541 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2542 const ModuleSummaryIndex *Index, bool IsForDebug); 2543 2544 AsmWriterContext getContext() { 2545 return AsmWriterContext(&TypePrinter, &Machine, TheModule); 2546 } 2547 2548 void printMDNodeBody(const MDNode *MD); 2549 void printNamedMDNode(const NamedMDNode *NMD); 2550 2551 void printModule(const Module *M); 2552 2553 void writeOperand(const Value *Op, bool PrintType); 2554 void writeParamOperand(const Value *Operand, AttributeSet Attrs); 2555 void writeOperandBundles(const CallBase *Call); 2556 void writeSyncScope(const LLVMContext &Context, 2557 SyncScope::ID SSID); 2558 void writeAtomic(const LLVMContext &Context, 2559 AtomicOrdering Ordering, 2560 SyncScope::ID SSID); 2561 void writeAtomicCmpXchg(const LLVMContext &Context, 2562 AtomicOrdering SuccessOrdering, 2563 AtomicOrdering FailureOrdering, 2564 SyncScope::ID SSID); 2565 2566 void writeAllMDNodes(); 2567 void writeMDNode(unsigned Slot, const MDNode *Node); 2568 void writeAttribute(const Attribute &Attr, bool InAttrGroup = false); 2569 void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false); 2570 void writeAllAttributeGroups(); 2571 2572 void printTypeIdentities(); 2573 void printGlobal(const GlobalVariable *GV); 2574 void printAlias(const GlobalAlias *GA); 2575 void printIFunc(const GlobalIFunc *GI); 2576 void printComdat(const Comdat *C); 2577 void printFunction(const Function *F); 2578 void printArgument(const Argument *FA, AttributeSet Attrs); 2579 void printBasicBlock(const BasicBlock *BB); 2580 void printInstructionLine(const Instruction &I); 2581 void printInstruction(const Instruction &I); 2582 2583 void printUseListOrder(const Value *V, const std::vector<unsigned> &Shuffle); 2584 void printUseLists(const Function *F); 2585 2586 void printModuleSummaryIndex(); 2587 void printSummaryInfo(unsigned Slot, const ValueInfo &VI); 2588 void printSummary(const GlobalValueSummary &Summary); 2589 void printAliasSummary(const AliasSummary *AS); 2590 void printGlobalVarSummary(const GlobalVarSummary *GS); 2591 void printFunctionSummary(const FunctionSummary *FS); 2592 void printTypeIdSummary(const TypeIdSummary &TIS); 2593 void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI); 2594 void printTypeTestResolution(const TypeTestResolution &TTRes); 2595 void printArgs(const std::vector<uint64_t> &Args); 2596 void printWPDRes(const WholeProgramDevirtResolution &WPDRes); 2597 void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo); 2598 void printVFuncId(const FunctionSummary::VFuncId VFId); 2599 void 2600 printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList, 2601 const char *Tag); 2602 void 2603 printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList, 2604 const char *Tag); 2605 2606 private: 2607 /// Print out metadata attachments. 2608 void printMetadataAttachments( 2609 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 2610 StringRef Separator); 2611 2612 // printInfoComment - Print a little comment after the instruction indicating 2613 // which slot it occupies. 2614 void printInfoComment(const Value &V); 2615 2616 // printGCRelocateComment - print comment after call to the gc.relocate 2617 // intrinsic indicating base and derived pointer names. 2618 void printGCRelocateComment(const GCRelocateInst &Relocate); 2619 }; 2620 2621 } // end anonymous namespace 2622 2623 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2624 const Module *M, AssemblyAnnotationWriter *AAW, 2625 bool IsForDebug, bool ShouldPreserveUseListOrder) 2626 : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW), 2627 IsForDebug(IsForDebug), 2628 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 2629 if (!TheModule) 2630 return; 2631 for (const GlobalObject &GO : TheModule->global_objects()) 2632 if (const Comdat *C = GO.getComdat()) 2633 Comdats.insert(C); 2634 } 2635 2636 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2637 const ModuleSummaryIndex *Index, bool IsForDebug) 2638 : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr), 2639 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {} 2640 2641 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 2642 if (!Operand) { 2643 Out << "<null operand!>"; 2644 return; 2645 } 2646 if (PrintType) { 2647 TypePrinter.print(Operand->getType(), Out); 2648 Out << ' '; 2649 } 2650 auto WriterCtx = getContext(); 2651 WriteAsOperandInternal(Out, Operand, WriterCtx); 2652 } 2653 2654 void AssemblyWriter::writeSyncScope(const LLVMContext &Context, 2655 SyncScope::ID SSID) { 2656 switch (SSID) { 2657 case SyncScope::System: { 2658 break; 2659 } 2660 default: { 2661 if (SSNs.empty()) 2662 Context.getSyncScopeNames(SSNs); 2663 2664 Out << " syncscope(\""; 2665 printEscapedString(SSNs[SSID], Out); 2666 Out << "\")"; 2667 break; 2668 } 2669 } 2670 } 2671 2672 void AssemblyWriter::writeAtomic(const LLVMContext &Context, 2673 AtomicOrdering Ordering, 2674 SyncScope::ID SSID) { 2675 if (Ordering == AtomicOrdering::NotAtomic) 2676 return; 2677 2678 writeSyncScope(Context, SSID); 2679 Out << " " << toIRString(Ordering); 2680 } 2681 2682 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context, 2683 AtomicOrdering SuccessOrdering, 2684 AtomicOrdering FailureOrdering, 2685 SyncScope::ID SSID) { 2686 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 2687 FailureOrdering != AtomicOrdering::NotAtomic); 2688 2689 writeSyncScope(Context, SSID); 2690 Out << " " << toIRString(SuccessOrdering); 2691 Out << " " << toIRString(FailureOrdering); 2692 } 2693 2694 void AssemblyWriter::writeParamOperand(const Value *Operand, 2695 AttributeSet Attrs) { 2696 if (!Operand) { 2697 Out << "<null operand!>"; 2698 return; 2699 } 2700 2701 // Print the type 2702 TypePrinter.print(Operand->getType(), Out); 2703 // Print parameter attributes list 2704 if (Attrs.hasAttributes()) { 2705 Out << ' '; 2706 writeAttributeSet(Attrs); 2707 } 2708 Out << ' '; 2709 // Print the operand 2710 auto WriterCtx = getContext(); 2711 WriteAsOperandInternal(Out, Operand, WriterCtx); 2712 } 2713 2714 void AssemblyWriter::writeOperandBundles(const CallBase *Call) { 2715 if (!Call->hasOperandBundles()) 2716 return; 2717 2718 Out << " [ "; 2719 2720 bool FirstBundle = true; 2721 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) { 2722 OperandBundleUse BU = Call->getOperandBundleAt(i); 2723 2724 if (!FirstBundle) 2725 Out << ", "; 2726 FirstBundle = false; 2727 2728 Out << '"'; 2729 printEscapedString(BU.getTagName(), Out); 2730 Out << '"'; 2731 2732 Out << '('; 2733 2734 bool FirstInput = true; 2735 auto WriterCtx = getContext(); 2736 for (const auto &Input : BU.Inputs) { 2737 if (!FirstInput) 2738 Out << ", "; 2739 FirstInput = false; 2740 2741 TypePrinter.print(Input->getType(), Out); 2742 Out << " "; 2743 WriteAsOperandInternal(Out, Input, WriterCtx); 2744 } 2745 2746 Out << ')'; 2747 } 2748 2749 Out << " ]"; 2750 } 2751 2752 void AssemblyWriter::printModule(const Module *M) { 2753 Machine.initializeIfNeeded(); 2754 2755 if (ShouldPreserveUseListOrder) 2756 UseListOrders = predictUseListOrder(M); 2757 2758 if (!M->getModuleIdentifier().empty() && 2759 // Don't print the ID if it will start a new line (which would 2760 // require a comment char before it). 2761 M->getModuleIdentifier().find('\n') == std::string::npos) 2762 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 2763 2764 if (!M->getSourceFileName().empty()) { 2765 Out << "source_filename = \""; 2766 printEscapedString(M->getSourceFileName(), Out); 2767 Out << "\"\n"; 2768 } 2769 2770 const std::string &DL = M->getDataLayoutStr(); 2771 if (!DL.empty()) 2772 Out << "target datalayout = \"" << DL << "\"\n"; 2773 if (!M->getTargetTriple().empty()) 2774 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 2775 2776 if (!M->getModuleInlineAsm().empty()) { 2777 Out << '\n'; 2778 2779 // Split the string into lines, to make it easier to read the .ll file. 2780 StringRef Asm = M->getModuleInlineAsm(); 2781 do { 2782 StringRef Front; 2783 std::tie(Front, Asm) = Asm.split('\n'); 2784 2785 // We found a newline, print the portion of the asm string from the 2786 // last newline up to this newline. 2787 Out << "module asm \""; 2788 printEscapedString(Front, Out); 2789 Out << "\"\n"; 2790 } while (!Asm.empty()); 2791 } 2792 2793 printTypeIdentities(); 2794 2795 // Output all comdats. 2796 if (!Comdats.empty()) 2797 Out << '\n'; 2798 for (const Comdat *C : Comdats) { 2799 printComdat(C); 2800 if (C != Comdats.back()) 2801 Out << '\n'; 2802 } 2803 2804 // Output all globals. 2805 if (!M->global_empty()) Out << '\n'; 2806 for (const GlobalVariable &GV : M->globals()) { 2807 printGlobal(&GV); Out << '\n'; 2808 } 2809 2810 // Output all aliases. 2811 if (!M->alias_empty()) Out << "\n"; 2812 for (const GlobalAlias &GA : M->aliases()) 2813 printAlias(&GA); 2814 2815 // Output all ifuncs. 2816 if (!M->ifunc_empty()) Out << "\n"; 2817 for (const GlobalIFunc &GI : M->ifuncs()) 2818 printIFunc(&GI); 2819 2820 // Output all of the functions. 2821 for (const Function &F : *M) { 2822 Out << '\n'; 2823 printFunction(&F); 2824 } 2825 2826 // Output global use-lists. 2827 printUseLists(nullptr); 2828 2829 // Output all attribute groups. 2830 if (!Machine.as_empty()) { 2831 Out << '\n'; 2832 writeAllAttributeGroups(); 2833 } 2834 2835 // Output named metadata. 2836 if (!M->named_metadata_empty()) Out << '\n'; 2837 2838 for (const NamedMDNode &Node : M->named_metadata()) 2839 printNamedMDNode(&Node); 2840 2841 // Output metadata. 2842 if (!Machine.mdn_empty()) { 2843 Out << '\n'; 2844 writeAllMDNodes(); 2845 } 2846 } 2847 2848 void AssemblyWriter::printModuleSummaryIndex() { 2849 assert(TheIndex); 2850 int NumSlots = Machine.initializeIndexIfNeeded(); 2851 2852 Out << "\n"; 2853 2854 // Print module path entries. To print in order, add paths to a vector 2855 // indexed by module slot. 2856 std::vector<std::pair<std::string, ModuleHash>> moduleVec; 2857 std::string RegularLTOModuleName = 2858 ModuleSummaryIndex::getRegularLTOModuleName(); 2859 moduleVec.resize(TheIndex->modulePaths().size()); 2860 for (auto &ModPath : TheIndex->modulePaths()) 2861 moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair( 2862 // A module id of -1 is a special entry for a regular LTO module created 2863 // during the thin link. 2864 ModPath.second.first == -1u ? RegularLTOModuleName 2865 : (std::string)std::string(ModPath.first()), 2866 ModPath.second.second); 2867 2868 unsigned i = 0; 2869 for (auto &ModPair : moduleVec) { 2870 Out << "^" << i++ << " = module: ("; 2871 Out << "path: \""; 2872 printEscapedString(ModPair.first, Out); 2873 Out << "\", hash: ("; 2874 FieldSeparator FS; 2875 for (auto Hash : ModPair.second) 2876 Out << FS << Hash; 2877 Out << "))\n"; 2878 } 2879 2880 // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer 2881 // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID). 2882 for (auto &GlobalList : *TheIndex) { 2883 auto GUID = GlobalList.first; 2884 for (auto &Summary : GlobalList.second.SummaryList) 2885 SummaryToGUIDMap[Summary.get()] = GUID; 2886 } 2887 2888 // Print the global value summary entries. 2889 for (auto &GlobalList : *TheIndex) { 2890 auto GUID = GlobalList.first; 2891 auto VI = TheIndex->getValueInfo(GlobalList); 2892 printSummaryInfo(Machine.getGUIDSlot(GUID), VI); 2893 } 2894 2895 // Print the TypeIdMap entries. 2896 for (const auto &TID : TheIndex->typeIds()) { 2897 Out << "^" << Machine.getTypeIdSlot(TID.second.first) 2898 << " = typeid: (name: \"" << TID.second.first << "\""; 2899 printTypeIdSummary(TID.second.second); 2900 Out << ") ; guid = " << TID.first << "\n"; 2901 } 2902 2903 // Print the TypeIdCompatibleVtableMap entries. 2904 for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) { 2905 auto GUID = GlobalValue::getGUID(TId.first); 2906 Out << "^" << Machine.getGUIDSlot(GUID) 2907 << " = typeidCompatibleVTable: (name: \"" << TId.first << "\""; 2908 printTypeIdCompatibleVtableSummary(TId.second); 2909 Out << ") ; guid = " << GUID << "\n"; 2910 } 2911 2912 // Don't emit flags when it's not really needed (value is zero by default). 2913 if (TheIndex->getFlags()) { 2914 Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n"; 2915 ++NumSlots; 2916 } 2917 2918 Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount() 2919 << "\n"; 2920 } 2921 2922 static const char * 2923 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) { 2924 switch (K) { 2925 case WholeProgramDevirtResolution::Indir: 2926 return "indir"; 2927 case WholeProgramDevirtResolution::SingleImpl: 2928 return "singleImpl"; 2929 case WholeProgramDevirtResolution::BranchFunnel: 2930 return "branchFunnel"; 2931 } 2932 llvm_unreachable("invalid WholeProgramDevirtResolution kind"); 2933 } 2934 2935 static const char *getWholeProgDevirtResByArgKindName( 2936 WholeProgramDevirtResolution::ByArg::Kind K) { 2937 switch (K) { 2938 case WholeProgramDevirtResolution::ByArg::Indir: 2939 return "indir"; 2940 case WholeProgramDevirtResolution::ByArg::UniformRetVal: 2941 return "uniformRetVal"; 2942 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: 2943 return "uniqueRetVal"; 2944 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: 2945 return "virtualConstProp"; 2946 } 2947 llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind"); 2948 } 2949 2950 static const char *getTTResKindName(TypeTestResolution::Kind K) { 2951 switch (K) { 2952 case TypeTestResolution::Unknown: 2953 return "unknown"; 2954 case TypeTestResolution::Unsat: 2955 return "unsat"; 2956 case TypeTestResolution::ByteArray: 2957 return "byteArray"; 2958 case TypeTestResolution::Inline: 2959 return "inline"; 2960 case TypeTestResolution::Single: 2961 return "single"; 2962 case TypeTestResolution::AllOnes: 2963 return "allOnes"; 2964 } 2965 llvm_unreachable("invalid TypeTestResolution kind"); 2966 } 2967 2968 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) { 2969 Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind) 2970 << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth; 2971 2972 // The following fields are only used if the target does not support the use 2973 // of absolute symbols to store constants. Print only if non-zero. 2974 if (TTRes.AlignLog2) 2975 Out << ", alignLog2: " << TTRes.AlignLog2; 2976 if (TTRes.SizeM1) 2977 Out << ", sizeM1: " << TTRes.SizeM1; 2978 if (TTRes.BitMask) 2979 // BitMask is uint8_t which causes it to print the corresponding char. 2980 Out << ", bitMask: " << (unsigned)TTRes.BitMask; 2981 if (TTRes.InlineBits) 2982 Out << ", inlineBits: " << TTRes.InlineBits; 2983 2984 Out << ")"; 2985 } 2986 2987 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) { 2988 Out << ", summary: ("; 2989 printTypeTestResolution(TIS.TTRes); 2990 if (!TIS.WPDRes.empty()) { 2991 Out << ", wpdResolutions: ("; 2992 FieldSeparator FS; 2993 for (auto &WPDRes : TIS.WPDRes) { 2994 Out << FS; 2995 Out << "(offset: " << WPDRes.first << ", "; 2996 printWPDRes(WPDRes.second); 2997 Out << ")"; 2998 } 2999 Out << ")"; 3000 } 3001 Out << ")"; 3002 } 3003 3004 void AssemblyWriter::printTypeIdCompatibleVtableSummary( 3005 const TypeIdCompatibleVtableInfo &TI) { 3006 Out << ", summary: ("; 3007 FieldSeparator FS; 3008 for (auto &P : TI) { 3009 Out << FS; 3010 Out << "(offset: " << P.AddressPointOffset << ", "; 3011 Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID()); 3012 Out << ")"; 3013 } 3014 Out << ")"; 3015 } 3016 3017 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) { 3018 Out << "args: ("; 3019 FieldSeparator FS; 3020 for (auto arg : Args) { 3021 Out << FS; 3022 Out << arg; 3023 } 3024 Out << ")"; 3025 } 3026 3027 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) { 3028 Out << "wpdRes: (kind: "; 3029 Out << getWholeProgDevirtResKindName(WPDRes.TheKind); 3030 3031 if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl) 3032 Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\""; 3033 3034 if (!WPDRes.ResByArg.empty()) { 3035 Out << ", resByArg: ("; 3036 FieldSeparator FS; 3037 for (auto &ResByArg : WPDRes.ResByArg) { 3038 Out << FS; 3039 printArgs(ResByArg.first); 3040 Out << ", byArg: (kind: "; 3041 Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind); 3042 if (ResByArg.second.TheKind == 3043 WholeProgramDevirtResolution::ByArg::UniformRetVal || 3044 ResByArg.second.TheKind == 3045 WholeProgramDevirtResolution::ByArg::UniqueRetVal) 3046 Out << ", info: " << ResByArg.second.Info; 3047 3048 // The following fields are only used if the target does not support the 3049 // use of absolute symbols to store constants. Print only if non-zero. 3050 if (ResByArg.second.Byte || ResByArg.second.Bit) 3051 Out << ", byte: " << ResByArg.second.Byte 3052 << ", bit: " << ResByArg.second.Bit; 3053 3054 Out << ")"; 3055 } 3056 Out << ")"; 3057 } 3058 Out << ")"; 3059 } 3060 3061 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) { 3062 switch (SK) { 3063 case GlobalValueSummary::AliasKind: 3064 return "alias"; 3065 case GlobalValueSummary::FunctionKind: 3066 return "function"; 3067 case GlobalValueSummary::GlobalVarKind: 3068 return "variable"; 3069 } 3070 llvm_unreachable("invalid summary kind"); 3071 } 3072 3073 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) { 3074 Out << ", aliasee: "; 3075 // The indexes emitted for distributed backends may not include the 3076 // aliasee summary (only if it is being imported directly). Handle 3077 // that case by just emitting "null" as the aliasee. 3078 if (AS->hasAliasee()) 3079 Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]); 3080 else 3081 Out << "null"; 3082 } 3083 3084 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) { 3085 auto VTableFuncs = GS->vTableFuncs(); 3086 Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", " 3087 << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", " 3088 << "constant: " << GS->VarFlags.Constant; 3089 if (!VTableFuncs.empty()) 3090 Out << ", " 3091 << "vcall_visibility: " << GS->VarFlags.VCallVisibility; 3092 Out << ")"; 3093 3094 if (!VTableFuncs.empty()) { 3095 Out << ", vTableFuncs: ("; 3096 FieldSeparator FS; 3097 for (auto &P : VTableFuncs) { 3098 Out << FS; 3099 Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID()) 3100 << ", offset: " << P.VTableOffset; 3101 Out << ")"; 3102 } 3103 Out << ")"; 3104 } 3105 } 3106 3107 static std::string getLinkageName(GlobalValue::LinkageTypes LT) { 3108 switch (LT) { 3109 case GlobalValue::ExternalLinkage: 3110 return "external"; 3111 case GlobalValue::PrivateLinkage: 3112 return "private"; 3113 case GlobalValue::InternalLinkage: 3114 return "internal"; 3115 case GlobalValue::LinkOnceAnyLinkage: 3116 return "linkonce"; 3117 case GlobalValue::LinkOnceODRLinkage: 3118 return "linkonce_odr"; 3119 case GlobalValue::WeakAnyLinkage: 3120 return "weak"; 3121 case GlobalValue::WeakODRLinkage: 3122 return "weak_odr"; 3123 case GlobalValue::CommonLinkage: 3124 return "common"; 3125 case GlobalValue::AppendingLinkage: 3126 return "appending"; 3127 case GlobalValue::ExternalWeakLinkage: 3128 return "extern_weak"; 3129 case GlobalValue::AvailableExternallyLinkage: 3130 return "available_externally"; 3131 } 3132 llvm_unreachable("invalid linkage"); 3133 } 3134 3135 // When printing the linkage types in IR where the ExternalLinkage is 3136 // not printed, and other linkage types are expected to be printed with 3137 // a space after the name. 3138 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) { 3139 if (LT == GlobalValue::ExternalLinkage) 3140 return ""; 3141 return getLinkageName(LT) + " "; 3142 } 3143 3144 static const char *getVisibilityName(GlobalValue::VisibilityTypes Vis) { 3145 switch (Vis) { 3146 case GlobalValue::DefaultVisibility: 3147 return "default"; 3148 case GlobalValue::HiddenVisibility: 3149 return "hidden"; 3150 case GlobalValue::ProtectedVisibility: 3151 return "protected"; 3152 } 3153 llvm_unreachable("invalid visibility"); 3154 } 3155 3156 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) { 3157 Out << ", insts: " << FS->instCount(); 3158 if (FS->fflags().anyFlagSet()) 3159 Out << ", " << FS->fflags(); 3160 3161 if (!FS->calls().empty()) { 3162 Out << ", calls: ("; 3163 FieldSeparator IFS; 3164 for (auto &Call : FS->calls()) { 3165 Out << IFS; 3166 Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID()); 3167 if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown) 3168 Out << ", hotness: " << getHotnessName(Call.second.getHotness()); 3169 else if (Call.second.RelBlockFreq) 3170 Out << ", relbf: " << Call.second.RelBlockFreq; 3171 Out << ")"; 3172 } 3173 Out << ")"; 3174 } 3175 3176 if (const auto *TIdInfo = FS->getTypeIdInfo()) 3177 printTypeIdInfo(*TIdInfo); 3178 3179 auto PrintRange = [&](const ConstantRange &Range) { 3180 Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]"; 3181 }; 3182 3183 if (!FS->paramAccesses().empty()) { 3184 Out << ", params: ("; 3185 FieldSeparator IFS; 3186 for (auto &PS : FS->paramAccesses()) { 3187 Out << IFS; 3188 Out << "(param: " << PS.ParamNo; 3189 Out << ", offset: "; 3190 PrintRange(PS.Use); 3191 if (!PS.Calls.empty()) { 3192 Out << ", calls: ("; 3193 FieldSeparator IFS; 3194 for (auto &Call : PS.Calls) { 3195 Out << IFS; 3196 Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID()); 3197 Out << ", param: " << Call.ParamNo; 3198 Out << ", offset: "; 3199 PrintRange(Call.Offsets); 3200 Out << ")"; 3201 } 3202 Out << ")"; 3203 } 3204 Out << ")"; 3205 } 3206 Out << ")"; 3207 } 3208 } 3209 3210 void AssemblyWriter::printTypeIdInfo( 3211 const FunctionSummary::TypeIdInfo &TIDInfo) { 3212 Out << ", typeIdInfo: ("; 3213 FieldSeparator TIDFS; 3214 if (!TIDInfo.TypeTests.empty()) { 3215 Out << TIDFS; 3216 Out << "typeTests: ("; 3217 FieldSeparator FS; 3218 for (auto &GUID : TIDInfo.TypeTests) { 3219 auto TidIter = TheIndex->typeIds().equal_range(GUID); 3220 if (TidIter.first == TidIter.second) { 3221 Out << FS; 3222 Out << GUID; 3223 continue; 3224 } 3225 // Print all type id that correspond to this GUID. 3226 for (auto It = TidIter.first; It != TidIter.second; ++It) { 3227 Out << FS; 3228 auto Slot = Machine.getTypeIdSlot(It->second.first); 3229 assert(Slot != -1); 3230 Out << "^" << Slot; 3231 } 3232 } 3233 Out << ")"; 3234 } 3235 if (!TIDInfo.TypeTestAssumeVCalls.empty()) { 3236 Out << TIDFS; 3237 printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls"); 3238 } 3239 if (!TIDInfo.TypeCheckedLoadVCalls.empty()) { 3240 Out << TIDFS; 3241 printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls"); 3242 } 3243 if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) { 3244 Out << TIDFS; 3245 printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls, 3246 "typeTestAssumeConstVCalls"); 3247 } 3248 if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) { 3249 Out << TIDFS; 3250 printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls, 3251 "typeCheckedLoadConstVCalls"); 3252 } 3253 Out << ")"; 3254 } 3255 3256 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) { 3257 auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID); 3258 if (TidIter.first == TidIter.second) { 3259 Out << "vFuncId: ("; 3260 Out << "guid: " << VFId.GUID; 3261 Out << ", offset: " << VFId.Offset; 3262 Out << ")"; 3263 return; 3264 } 3265 // Print all type id that correspond to this GUID. 3266 FieldSeparator FS; 3267 for (auto It = TidIter.first; It != TidIter.second; ++It) { 3268 Out << FS; 3269 Out << "vFuncId: ("; 3270 auto Slot = Machine.getTypeIdSlot(It->second.first); 3271 assert(Slot != -1); 3272 Out << "^" << Slot; 3273 Out << ", offset: " << VFId.Offset; 3274 Out << ")"; 3275 } 3276 } 3277 3278 void AssemblyWriter::printNonConstVCalls( 3279 const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) { 3280 Out << Tag << ": ("; 3281 FieldSeparator FS; 3282 for (auto &VFuncId : VCallList) { 3283 Out << FS; 3284 printVFuncId(VFuncId); 3285 } 3286 Out << ")"; 3287 } 3288 3289 void AssemblyWriter::printConstVCalls( 3290 const std::vector<FunctionSummary::ConstVCall> &VCallList, 3291 const char *Tag) { 3292 Out << Tag << ": ("; 3293 FieldSeparator FS; 3294 for (auto &ConstVCall : VCallList) { 3295 Out << FS; 3296 Out << "("; 3297 printVFuncId(ConstVCall.VFunc); 3298 if (!ConstVCall.Args.empty()) { 3299 Out << ", "; 3300 printArgs(ConstVCall.Args); 3301 } 3302 Out << ")"; 3303 } 3304 Out << ")"; 3305 } 3306 3307 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) { 3308 GlobalValueSummary::GVFlags GVFlags = Summary.flags(); 3309 GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage; 3310 Out << getSummaryKindName(Summary.getSummaryKind()) << ": "; 3311 Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath()) 3312 << ", flags: ("; 3313 Out << "linkage: " << getLinkageName(LT); 3314 Out << ", visibility: " 3315 << getVisibilityName((GlobalValue::VisibilityTypes)GVFlags.Visibility); 3316 Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport; 3317 Out << ", live: " << GVFlags.Live; 3318 Out << ", dsoLocal: " << GVFlags.DSOLocal; 3319 Out << ", canAutoHide: " << GVFlags.CanAutoHide; 3320 Out << ")"; 3321 3322 if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind) 3323 printAliasSummary(cast<AliasSummary>(&Summary)); 3324 else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind) 3325 printFunctionSummary(cast<FunctionSummary>(&Summary)); 3326 else 3327 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary)); 3328 3329 auto RefList = Summary.refs(); 3330 if (!RefList.empty()) { 3331 Out << ", refs: ("; 3332 FieldSeparator FS; 3333 for (auto &Ref : RefList) { 3334 Out << FS; 3335 if (Ref.isReadOnly()) 3336 Out << "readonly "; 3337 else if (Ref.isWriteOnly()) 3338 Out << "writeonly "; 3339 Out << "^" << Machine.getGUIDSlot(Ref.getGUID()); 3340 } 3341 Out << ")"; 3342 } 3343 3344 Out << ")"; 3345 } 3346 3347 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) { 3348 Out << "^" << Slot << " = gv: ("; 3349 if (!VI.name().empty()) 3350 Out << "name: \"" << VI.name() << "\""; 3351 else 3352 Out << "guid: " << VI.getGUID(); 3353 if (!VI.getSummaryList().empty()) { 3354 Out << ", summaries: ("; 3355 FieldSeparator FS; 3356 for (auto &Summary : VI.getSummaryList()) { 3357 Out << FS; 3358 printSummary(*Summary); 3359 } 3360 Out << ")"; 3361 } 3362 Out << ")"; 3363 if (!VI.name().empty()) 3364 Out << " ; guid = " << VI.getGUID(); 3365 Out << "\n"; 3366 } 3367 3368 static void printMetadataIdentifier(StringRef Name, 3369 formatted_raw_ostream &Out) { 3370 if (Name.empty()) { 3371 Out << "<empty name> "; 3372 } else { 3373 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' || 3374 Name[0] == '$' || Name[0] == '.' || Name[0] == '_') 3375 Out << Name[0]; 3376 else 3377 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 3378 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 3379 unsigned char C = Name[i]; 3380 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 3381 C == '.' || C == '_') 3382 Out << C; 3383 else 3384 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 3385 } 3386 } 3387 } 3388 3389 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 3390 Out << '!'; 3391 printMetadataIdentifier(NMD->getName(), Out); 3392 Out << " = !{"; 3393 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 3394 if (i) 3395 Out << ", "; 3396 3397 // Write DIExpressions inline. 3398 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose. 3399 MDNode *Op = NMD->getOperand(i); 3400 assert(!isa<DIArgList>(Op) && 3401 "DIArgLists should not appear in NamedMDNodes"); 3402 if (auto *Expr = dyn_cast<DIExpression>(Op)) { 3403 writeDIExpression(Out, Expr, AsmWriterContext::getEmpty()); 3404 continue; 3405 } 3406 3407 int Slot = Machine.getMetadataSlot(Op); 3408 if (Slot == -1) 3409 Out << "<badref>"; 3410 else 3411 Out << '!' << Slot; 3412 } 3413 Out << "}\n"; 3414 } 3415 3416 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 3417 formatted_raw_ostream &Out) { 3418 switch (Vis) { 3419 case GlobalValue::DefaultVisibility: break; 3420 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 3421 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 3422 } 3423 } 3424 3425 static void PrintDSOLocation(const GlobalValue &GV, 3426 formatted_raw_ostream &Out) { 3427 if (GV.isDSOLocal() && !GV.isImplicitDSOLocal()) 3428 Out << "dso_local "; 3429 } 3430 3431 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 3432 formatted_raw_ostream &Out) { 3433 switch (SCT) { 3434 case GlobalValue::DefaultStorageClass: break; 3435 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 3436 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 3437 } 3438 } 3439 3440 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 3441 formatted_raw_ostream &Out) { 3442 switch (TLM) { 3443 case GlobalVariable::NotThreadLocal: 3444 break; 3445 case GlobalVariable::GeneralDynamicTLSModel: 3446 Out << "thread_local "; 3447 break; 3448 case GlobalVariable::LocalDynamicTLSModel: 3449 Out << "thread_local(localdynamic) "; 3450 break; 3451 case GlobalVariable::InitialExecTLSModel: 3452 Out << "thread_local(initialexec) "; 3453 break; 3454 case GlobalVariable::LocalExecTLSModel: 3455 Out << "thread_local(localexec) "; 3456 break; 3457 } 3458 } 3459 3460 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) { 3461 switch (UA) { 3462 case GlobalVariable::UnnamedAddr::None: 3463 return ""; 3464 case GlobalVariable::UnnamedAddr::Local: 3465 return "local_unnamed_addr"; 3466 case GlobalVariable::UnnamedAddr::Global: 3467 return "unnamed_addr"; 3468 } 3469 llvm_unreachable("Unknown UnnamedAddr"); 3470 } 3471 3472 static void maybePrintComdat(formatted_raw_ostream &Out, 3473 const GlobalObject &GO) { 3474 const Comdat *C = GO.getComdat(); 3475 if (!C) 3476 return; 3477 3478 if (isa<GlobalVariable>(GO)) 3479 Out << ','; 3480 Out << " comdat"; 3481 3482 if (GO.getName() == C->getName()) 3483 return; 3484 3485 Out << '('; 3486 PrintLLVMName(Out, C->getName(), ComdatPrefix); 3487 Out << ')'; 3488 } 3489 3490 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 3491 if (GV->isMaterializable()) 3492 Out << "; Materializable\n"; 3493 3494 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GV->getParent()); 3495 WriteAsOperandInternal(Out, GV, WriterCtx); 3496 Out << " = "; 3497 3498 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 3499 Out << "external "; 3500 3501 Out << getLinkageNameWithSpace(GV->getLinkage()); 3502 PrintDSOLocation(*GV, Out); 3503 PrintVisibility(GV->getVisibility(), Out); 3504 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 3505 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 3506 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr()); 3507 if (!UA.empty()) 3508 Out << UA << ' '; 3509 3510 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 3511 Out << "addrspace(" << AddressSpace << ") "; 3512 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 3513 Out << (GV->isConstant() ? "constant " : "global "); 3514 TypePrinter.print(GV->getValueType(), Out); 3515 3516 if (GV->hasInitializer()) { 3517 Out << ' '; 3518 writeOperand(GV->getInitializer(), false); 3519 } 3520 3521 if (GV->hasSection()) { 3522 Out << ", section \""; 3523 printEscapedString(GV->getSection(), Out); 3524 Out << '"'; 3525 } 3526 if (GV->hasPartition()) { 3527 Out << ", partition \""; 3528 printEscapedString(GV->getPartition(), Out); 3529 Out << '"'; 3530 } 3531 3532 maybePrintComdat(Out, *GV); 3533 if (MaybeAlign A = GV->getAlign()) 3534 Out << ", align " << A->value(); 3535 3536 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3537 GV->getAllMetadata(MDs); 3538 printMetadataAttachments(MDs, ", "); 3539 3540 auto Attrs = GV->getAttributes(); 3541 if (Attrs.hasAttributes()) 3542 Out << " #" << Machine.getAttributeGroupSlot(Attrs); 3543 3544 printInfoComment(*GV); 3545 } 3546 3547 void AssemblyWriter::printAlias(const GlobalAlias *GA) { 3548 if (GA->isMaterializable()) 3549 Out << "; Materializable\n"; 3550 3551 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GA->getParent()); 3552 WriteAsOperandInternal(Out, GA, WriterCtx); 3553 Out << " = "; 3554 3555 Out << getLinkageNameWithSpace(GA->getLinkage()); 3556 PrintDSOLocation(*GA, Out); 3557 PrintVisibility(GA->getVisibility(), Out); 3558 PrintDLLStorageClass(GA->getDLLStorageClass(), Out); 3559 PrintThreadLocalModel(GA->getThreadLocalMode(), Out); 3560 StringRef UA = getUnnamedAddrEncoding(GA->getUnnamedAddr()); 3561 if (!UA.empty()) 3562 Out << UA << ' '; 3563 3564 Out << "alias "; 3565 3566 TypePrinter.print(GA->getValueType(), Out); 3567 Out << ", "; 3568 3569 if (const Constant *Aliasee = GA->getAliasee()) { 3570 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee)); 3571 } else { 3572 TypePrinter.print(GA->getType(), Out); 3573 Out << " <<NULL ALIASEE>>"; 3574 } 3575 3576 if (GA->hasPartition()) { 3577 Out << ", partition \""; 3578 printEscapedString(GA->getPartition(), Out); 3579 Out << '"'; 3580 } 3581 3582 printInfoComment(*GA); 3583 Out << '\n'; 3584 } 3585 3586 void AssemblyWriter::printIFunc(const GlobalIFunc *GI) { 3587 if (GI->isMaterializable()) 3588 Out << "; Materializable\n"; 3589 3590 AsmWriterContext WriterCtx(&TypePrinter, &Machine, GI->getParent()); 3591 WriteAsOperandInternal(Out, GI, WriterCtx); 3592 Out << " = "; 3593 3594 Out << getLinkageNameWithSpace(GI->getLinkage()); 3595 PrintDSOLocation(*GI, Out); 3596 PrintVisibility(GI->getVisibility(), Out); 3597 3598 Out << "ifunc "; 3599 3600 TypePrinter.print(GI->getValueType(), Out); 3601 Out << ", "; 3602 3603 if (const Constant *Resolver = GI->getResolver()) { 3604 writeOperand(Resolver, !isa<ConstantExpr>(Resolver)); 3605 } else { 3606 TypePrinter.print(GI->getType(), Out); 3607 Out << " <<NULL RESOLVER>>"; 3608 } 3609 3610 if (GI->hasPartition()) { 3611 Out << ", partition \""; 3612 printEscapedString(GI->getPartition(), Out); 3613 Out << '"'; 3614 } 3615 3616 printInfoComment(*GI); 3617 Out << '\n'; 3618 } 3619 3620 void AssemblyWriter::printComdat(const Comdat *C) { 3621 C->print(Out); 3622 } 3623 3624 void AssemblyWriter::printTypeIdentities() { 3625 if (TypePrinter.empty()) 3626 return; 3627 3628 Out << '\n'; 3629 3630 // Emit all numbered types. 3631 auto &NumberedTypes = TypePrinter.getNumberedTypes(); 3632 for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) { 3633 Out << '%' << I << " = type "; 3634 3635 // Make sure we print out at least one level of the type structure, so 3636 // that we do not get %2 = type %2 3637 TypePrinter.printStructBody(NumberedTypes[I], Out); 3638 Out << '\n'; 3639 } 3640 3641 auto &NamedTypes = TypePrinter.getNamedTypes(); 3642 for (StructType *NamedType : NamedTypes) { 3643 PrintLLVMName(Out, NamedType->getName(), LocalPrefix); 3644 Out << " = type "; 3645 3646 // Make sure we print out at least one level of the type structure, so 3647 // that we do not get %FILE = type %FILE 3648 TypePrinter.printStructBody(NamedType, Out); 3649 Out << '\n'; 3650 } 3651 } 3652 3653 /// printFunction - Print all aspects of a function. 3654 void AssemblyWriter::printFunction(const Function *F) { 3655 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 3656 3657 if (F->isMaterializable()) 3658 Out << "; Materializable\n"; 3659 3660 const AttributeList &Attrs = F->getAttributes(); 3661 if (Attrs.hasFnAttrs()) { 3662 AttributeSet AS = Attrs.getFnAttrs(); 3663 std::string AttrStr; 3664 3665 for (const Attribute &Attr : AS) { 3666 if (!Attr.isStringAttribute()) { 3667 if (!AttrStr.empty()) AttrStr += ' '; 3668 AttrStr += Attr.getAsString(); 3669 } 3670 } 3671 3672 if (!AttrStr.empty()) 3673 Out << "; Function Attrs: " << AttrStr << '\n'; 3674 } 3675 3676 Machine.incorporateFunction(F); 3677 3678 if (F->isDeclaration()) { 3679 Out << "declare"; 3680 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3681 F->getAllMetadata(MDs); 3682 printMetadataAttachments(MDs, " "); 3683 Out << ' '; 3684 } else 3685 Out << "define "; 3686 3687 Out << getLinkageNameWithSpace(F->getLinkage()); 3688 PrintDSOLocation(*F, Out); 3689 PrintVisibility(F->getVisibility(), Out); 3690 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 3691 3692 // Print the calling convention. 3693 if (F->getCallingConv() != CallingConv::C) { 3694 PrintCallingConv(F->getCallingConv(), Out); 3695 Out << " "; 3696 } 3697 3698 FunctionType *FT = F->getFunctionType(); 3699 if (Attrs.hasRetAttrs()) 3700 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' '; 3701 TypePrinter.print(F->getReturnType(), Out); 3702 AsmWriterContext WriterCtx(&TypePrinter, &Machine, F->getParent()); 3703 Out << ' '; 3704 WriteAsOperandInternal(Out, F, WriterCtx); 3705 Out << '('; 3706 3707 // Loop over the arguments, printing them... 3708 if (F->isDeclaration() && !IsForDebug) { 3709 // We're only interested in the type here - don't print argument names. 3710 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) { 3711 // Insert commas as we go... the first arg doesn't get a comma 3712 if (I) 3713 Out << ", "; 3714 // Output type... 3715 TypePrinter.print(FT->getParamType(I), Out); 3716 3717 AttributeSet ArgAttrs = Attrs.getParamAttrs(I); 3718 if (ArgAttrs.hasAttributes()) { 3719 Out << ' '; 3720 writeAttributeSet(ArgAttrs); 3721 } 3722 } 3723 } else { 3724 // The arguments are meaningful here, print them in detail. 3725 for (const Argument &Arg : F->args()) { 3726 // Insert commas as we go... the first arg doesn't get a comma 3727 if (Arg.getArgNo() != 0) 3728 Out << ", "; 3729 printArgument(&Arg, Attrs.getParamAttrs(Arg.getArgNo())); 3730 } 3731 } 3732 3733 // Finish printing arguments... 3734 if (FT->isVarArg()) { 3735 if (FT->getNumParams()) Out << ", "; 3736 Out << "..."; // Output varargs portion of signature! 3737 } 3738 Out << ')'; 3739 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr()); 3740 if (!UA.empty()) 3741 Out << ' ' << UA; 3742 // We print the function address space if it is non-zero or if we are writing 3743 // a module with a non-zero program address space or if there is no valid 3744 // Module* so that the file can be parsed without the datalayout string. 3745 const Module *Mod = F->getParent(); 3746 if (F->getAddressSpace() != 0 || !Mod || 3747 Mod->getDataLayout().getProgramAddressSpace() != 0) 3748 Out << " addrspace(" << F->getAddressSpace() << ")"; 3749 if (Attrs.hasFnAttrs()) 3750 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttrs()); 3751 if (F->hasSection()) { 3752 Out << " section \""; 3753 printEscapedString(F->getSection(), Out); 3754 Out << '"'; 3755 } 3756 if (F->hasPartition()) { 3757 Out << " partition \""; 3758 printEscapedString(F->getPartition(), Out); 3759 Out << '"'; 3760 } 3761 maybePrintComdat(Out, *F); 3762 if (MaybeAlign A = F->getAlign()) 3763 Out << " align " << A->value(); 3764 if (F->hasGC()) 3765 Out << " gc \"" << F->getGC() << '"'; 3766 if (F->hasPrefixData()) { 3767 Out << " prefix "; 3768 writeOperand(F->getPrefixData(), true); 3769 } 3770 if (F->hasPrologueData()) { 3771 Out << " prologue "; 3772 writeOperand(F->getPrologueData(), true); 3773 } 3774 if (F->hasPersonalityFn()) { 3775 Out << " personality "; 3776 writeOperand(F->getPersonalityFn(), /*PrintType=*/true); 3777 } 3778 3779 if (F->isDeclaration()) { 3780 Out << '\n'; 3781 } else { 3782 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 3783 F->getAllMetadata(MDs); 3784 printMetadataAttachments(MDs, " "); 3785 3786 Out << " {"; 3787 // Output all of the function's basic blocks. 3788 for (const BasicBlock &BB : *F) 3789 printBasicBlock(&BB); 3790 3791 // Output the function's use-lists. 3792 printUseLists(F); 3793 3794 Out << "}\n"; 3795 } 3796 3797 Machine.purgeFunction(); 3798 } 3799 3800 /// printArgument - This member is called for every argument that is passed into 3801 /// the function. Simply print it out 3802 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) { 3803 // Output type... 3804 TypePrinter.print(Arg->getType(), Out); 3805 3806 // Output parameter attributes list 3807 if (Attrs.hasAttributes()) { 3808 Out << ' '; 3809 writeAttributeSet(Attrs); 3810 } 3811 3812 // Output name, if available... 3813 if (Arg->hasName()) { 3814 Out << ' '; 3815 PrintLLVMName(Out, Arg); 3816 } else { 3817 int Slot = Machine.getLocalSlot(Arg); 3818 assert(Slot != -1 && "expect argument in function here"); 3819 Out << " %" << Slot; 3820 } 3821 } 3822 3823 /// printBasicBlock - This member is called for each basic block in a method. 3824 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 3825 bool IsEntryBlock = BB->getParent() && BB->isEntryBlock(); 3826 if (BB->hasName()) { // Print out the label if it exists... 3827 Out << "\n"; 3828 PrintLLVMName(Out, BB->getName(), LabelPrefix); 3829 Out << ':'; 3830 } else if (!IsEntryBlock) { 3831 Out << "\n"; 3832 int Slot = Machine.getLocalSlot(BB); 3833 if (Slot != -1) 3834 Out << Slot << ":"; 3835 else 3836 Out << "<badref>:"; 3837 } 3838 3839 if (!IsEntryBlock) { 3840 // Output predecessors for the block. 3841 Out.PadToColumn(50); 3842 Out << ";"; 3843 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 3844 3845 if (PI == PE) { 3846 Out << " No predecessors!"; 3847 } else { 3848 Out << " preds = "; 3849 writeOperand(*PI, false); 3850 for (++PI; PI != PE; ++PI) { 3851 Out << ", "; 3852 writeOperand(*PI, false); 3853 } 3854 } 3855 } 3856 3857 Out << "\n"; 3858 3859 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 3860 3861 // Output all of the instructions in the basic block... 3862 for (const Instruction &I : *BB) { 3863 printInstructionLine(I); 3864 } 3865 3866 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 3867 } 3868 3869 /// printInstructionLine - Print an instruction and a newline character. 3870 void AssemblyWriter::printInstructionLine(const Instruction &I) { 3871 printInstruction(I); 3872 Out << '\n'; 3873 } 3874 3875 /// printGCRelocateComment - print comment after call to the gc.relocate 3876 /// intrinsic indicating base and derived pointer names. 3877 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) { 3878 Out << " ; ("; 3879 writeOperand(Relocate.getBasePtr(), false); 3880 Out << ", "; 3881 writeOperand(Relocate.getDerivedPtr(), false); 3882 Out << ")"; 3883 } 3884 3885 /// printInfoComment - Print a little comment after the instruction indicating 3886 /// which slot it occupies. 3887 void AssemblyWriter::printInfoComment(const Value &V) { 3888 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V)) 3889 printGCRelocateComment(*Relocate); 3890 3891 if (AnnotationWriter) 3892 AnnotationWriter->printInfoComment(V, Out); 3893 } 3894 3895 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I, 3896 raw_ostream &Out) { 3897 // We print the address space of the call if it is non-zero. 3898 unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace(); 3899 bool PrintAddrSpace = CallAddrSpace != 0; 3900 if (!PrintAddrSpace) { 3901 const Module *Mod = getModuleFromVal(I); 3902 // We also print it if it is zero but not equal to the program address space 3903 // or if we can't find a valid Module* to make it possible to parse 3904 // the resulting file even without a datalayout string. 3905 if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0) 3906 PrintAddrSpace = true; 3907 } 3908 if (PrintAddrSpace) 3909 Out << " addrspace(" << CallAddrSpace << ")"; 3910 } 3911 3912 // This member is called for each Instruction in a function.. 3913 void AssemblyWriter::printInstruction(const Instruction &I) { 3914 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 3915 3916 // Print out indentation for an instruction. 3917 Out << " "; 3918 3919 // Print out name if it exists... 3920 if (I.hasName()) { 3921 PrintLLVMName(Out, &I); 3922 Out << " = "; 3923 } else if (!I.getType()->isVoidTy()) { 3924 // Print out the def slot taken. 3925 int SlotNum = Machine.getLocalSlot(&I); 3926 if (SlotNum == -1) 3927 Out << "<badref> = "; 3928 else 3929 Out << '%' << SlotNum << " = "; 3930 } 3931 3932 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 3933 if (CI->isMustTailCall()) 3934 Out << "musttail "; 3935 else if (CI->isTailCall()) 3936 Out << "tail "; 3937 else if (CI->isNoTailCall()) 3938 Out << "notail "; 3939 } 3940 3941 // Print out the opcode... 3942 Out << I.getOpcodeName(); 3943 3944 // If this is an atomic load or store, print out the atomic marker. 3945 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 3946 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 3947 Out << " atomic"; 3948 3949 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 3950 Out << " weak"; 3951 3952 // If this is a volatile operation, print out the volatile marker. 3953 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 3954 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 3955 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 3956 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 3957 Out << " volatile"; 3958 3959 // Print out optimization information. 3960 WriteOptimizationInfo(Out, &I); 3961 3962 // Print out the compare instruction predicates 3963 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 3964 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate()); 3965 3966 // Print out the atomicrmw operation 3967 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 3968 Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation()); 3969 3970 // Print out the type of the operands... 3971 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 3972 3973 // Special case conditional branches to swizzle the condition out to the front 3974 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 3975 const BranchInst &BI(cast<BranchInst>(I)); 3976 Out << ' '; 3977 writeOperand(BI.getCondition(), true); 3978 Out << ", "; 3979 writeOperand(BI.getSuccessor(0), true); 3980 Out << ", "; 3981 writeOperand(BI.getSuccessor(1), true); 3982 3983 } else if (isa<SwitchInst>(I)) { 3984 const SwitchInst& SI(cast<SwitchInst>(I)); 3985 // Special case switch instruction to get formatting nice and correct. 3986 Out << ' '; 3987 writeOperand(SI.getCondition(), true); 3988 Out << ", "; 3989 writeOperand(SI.getDefaultDest(), true); 3990 Out << " ["; 3991 for (auto Case : SI.cases()) { 3992 Out << "\n "; 3993 writeOperand(Case.getCaseValue(), true); 3994 Out << ", "; 3995 writeOperand(Case.getCaseSuccessor(), true); 3996 } 3997 Out << "\n ]"; 3998 } else if (isa<IndirectBrInst>(I)) { 3999 // Special case indirectbr instruction to get formatting nice and correct. 4000 Out << ' '; 4001 writeOperand(Operand, true); 4002 Out << ", ["; 4003 4004 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 4005 if (i != 1) 4006 Out << ", "; 4007 writeOperand(I.getOperand(i), true); 4008 } 4009 Out << ']'; 4010 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 4011 Out << ' '; 4012 TypePrinter.print(I.getType(), Out); 4013 Out << ' '; 4014 4015 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 4016 if (op) Out << ", "; 4017 Out << "[ "; 4018 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 4019 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 4020 } 4021 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 4022 Out << ' '; 4023 writeOperand(I.getOperand(0), true); 4024 for (unsigned i : EVI->indices()) 4025 Out << ", " << i; 4026 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 4027 Out << ' '; 4028 writeOperand(I.getOperand(0), true); Out << ", "; 4029 writeOperand(I.getOperand(1), true); 4030 for (unsigned i : IVI->indices()) 4031 Out << ", " << i; 4032 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 4033 Out << ' '; 4034 TypePrinter.print(I.getType(), Out); 4035 if (LPI->isCleanup() || LPI->getNumClauses() != 0) 4036 Out << '\n'; 4037 4038 if (LPI->isCleanup()) 4039 Out << " cleanup"; 4040 4041 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 4042 if (i != 0 || LPI->isCleanup()) Out << "\n"; 4043 if (LPI->isCatch(i)) 4044 Out << " catch "; 4045 else 4046 Out << " filter "; 4047 4048 writeOperand(LPI->getClause(i), true); 4049 } 4050 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) { 4051 Out << " within "; 4052 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false); 4053 Out << " ["; 4054 unsigned Op = 0; 4055 for (const BasicBlock *PadBB : CatchSwitch->handlers()) { 4056 if (Op > 0) 4057 Out << ", "; 4058 writeOperand(PadBB, /*PrintType=*/true); 4059 ++Op; 4060 } 4061 Out << "] unwind "; 4062 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest()) 4063 writeOperand(UnwindDest, /*PrintType=*/true); 4064 else 4065 Out << "to caller"; 4066 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) { 4067 Out << " within "; 4068 writeOperand(FPI->getParentPad(), /*PrintType=*/false); 4069 Out << " ["; 4070 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps; 4071 ++Op) { 4072 if (Op > 0) 4073 Out << ", "; 4074 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true); 4075 } 4076 Out << ']'; 4077 } else if (isa<ReturnInst>(I) && !Operand) { 4078 Out << " void"; 4079 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) { 4080 Out << " from "; 4081 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 4082 4083 Out << " to "; 4084 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 4085 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) { 4086 Out << " from "; 4087 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 4088 4089 Out << " unwind "; 4090 if (CRI->hasUnwindDest()) 4091 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 4092 else 4093 Out << "to caller"; 4094 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 4095 // Print the calling convention being used. 4096 if (CI->getCallingConv() != CallingConv::C) { 4097 Out << " "; 4098 PrintCallingConv(CI->getCallingConv(), Out); 4099 } 4100 4101 Operand = CI->getCalledOperand(); 4102 FunctionType *FTy = CI->getFunctionType(); 4103 Type *RetTy = FTy->getReturnType(); 4104 const AttributeList &PAL = CI->getAttributes(); 4105 4106 if (PAL.hasRetAttrs()) 4107 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4108 4109 // Only print addrspace(N) if necessary: 4110 maybePrintCallAddrSpace(Operand, &I, Out); 4111 4112 // If possible, print out the short form of the call instruction. We can 4113 // only do this if the first argument is a pointer to a nonvararg function, 4114 // and if the return type is not a pointer to a function. 4115 // 4116 Out << ' '; 4117 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4118 Out << ' '; 4119 writeOperand(Operand, false); 4120 Out << '('; 4121 for (unsigned op = 0, Eop = CI->arg_size(); op < Eop; ++op) { 4122 if (op > 0) 4123 Out << ", "; 4124 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttrs(op)); 4125 } 4126 4127 // Emit an ellipsis if this is a musttail call in a vararg function. This 4128 // is only to aid readability, musttail calls forward varargs by default. 4129 if (CI->isMustTailCall() && CI->getParent() && 4130 CI->getParent()->getParent() && 4131 CI->getParent()->getParent()->isVarArg()) 4132 Out << ", ..."; 4133 4134 Out << ')'; 4135 if (PAL.hasFnAttrs()) 4136 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs()); 4137 4138 writeOperandBundles(CI); 4139 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 4140 Operand = II->getCalledOperand(); 4141 FunctionType *FTy = II->getFunctionType(); 4142 Type *RetTy = FTy->getReturnType(); 4143 const AttributeList &PAL = II->getAttributes(); 4144 4145 // Print the calling convention being used. 4146 if (II->getCallingConv() != CallingConv::C) { 4147 Out << " "; 4148 PrintCallingConv(II->getCallingConv(), Out); 4149 } 4150 4151 if (PAL.hasRetAttrs()) 4152 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4153 4154 // Only print addrspace(N) if necessary: 4155 maybePrintCallAddrSpace(Operand, &I, Out); 4156 4157 // If possible, print out the short form of the invoke instruction. We can 4158 // only do this if the first argument is a pointer to a nonvararg function, 4159 // and if the return type is not a pointer to a function. 4160 // 4161 Out << ' '; 4162 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4163 Out << ' '; 4164 writeOperand(Operand, false); 4165 Out << '('; 4166 for (unsigned op = 0, Eop = II->arg_size(); op < Eop; ++op) { 4167 if (op) 4168 Out << ", "; 4169 writeParamOperand(II->getArgOperand(op), PAL.getParamAttrs(op)); 4170 } 4171 4172 Out << ')'; 4173 if (PAL.hasFnAttrs()) 4174 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs()); 4175 4176 writeOperandBundles(II); 4177 4178 Out << "\n to "; 4179 writeOperand(II->getNormalDest(), true); 4180 Out << " unwind "; 4181 writeOperand(II->getUnwindDest(), true); 4182 } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) { 4183 Operand = CBI->getCalledOperand(); 4184 FunctionType *FTy = CBI->getFunctionType(); 4185 Type *RetTy = FTy->getReturnType(); 4186 const AttributeList &PAL = CBI->getAttributes(); 4187 4188 // Print the calling convention being used. 4189 if (CBI->getCallingConv() != CallingConv::C) { 4190 Out << " "; 4191 PrintCallingConv(CBI->getCallingConv(), Out); 4192 } 4193 4194 if (PAL.hasRetAttrs()) 4195 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 4196 4197 // If possible, print out the short form of the callbr instruction. We can 4198 // only do this if the first argument is a pointer to a nonvararg function, 4199 // and if the return type is not a pointer to a function. 4200 // 4201 Out << ' '; 4202 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 4203 Out << ' '; 4204 writeOperand(Operand, false); 4205 Out << '('; 4206 for (unsigned op = 0, Eop = CBI->arg_size(); op < Eop; ++op) { 4207 if (op) 4208 Out << ", "; 4209 writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttrs(op)); 4210 } 4211 4212 Out << ')'; 4213 if (PAL.hasFnAttrs()) 4214 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttrs()); 4215 4216 writeOperandBundles(CBI); 4217 4218 Out << "\n to "; 4219 writeOperand(CBI->getDefaultDest(), true); 4220 Out << " ["; 4221 for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) { 4222 if (i != 0) 4223 Out << ", "; 4224 writeOperand(CBI->getIndirectDest(i), true); 4225 } 4226 Out << ']'; 4227 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 4228 Out << ' '; 4229 if (AI->isUsedWithInAlloca()) 4230 Out << "inalloca "; 4231 if (AI->isSwiftError()) 4232 Out << "swifterror "; 4233 TypePrinter.print(AI->getAllocatedType(), Out); 4234 4235 // Explicitly write the array size if the code is broken, if it's an array 4236 // allocation, or if the type is not canonical for scalar allocations. The 4237 // latter case prevents the type from mutating when round-tripping through 4238 // assembly. 4239 if (!AI->getArraySize() || AI->isArrayAllocation() || 4240 !AI->getArraySize()->getType()->isIntegerTy(32)) { 4241 Out << ", "; 4242 writeOperand(AI->getArraySize(), true); 4243 } 4244 if (MaybeAlign A = AI->getAlign()) { 4245 Out << ", align " << A->value(); 4246 } 4247 4248 unsigned AddrSpace = AI->getType()->getAddressSpace(); 4249 if (AddrSpace != 0) { 4250 Out << ", addrspace(" << AddrSpace << ')'; 4251 } 4252 } else if (isa<CastInst>(I)) { 4253 if (Operand) { 4254 Out << ' '; 4255 writeOperand(Operand, true); // Work with broken code 4256 } 4257 Out << " to "; 4258 TypePrinter.print(I.getType(), Out); 4259 } else if (isa<VAArgInst>(I)) { 4260 if (Operand) { 4261 Out << ' '; 4262 writeOperand(Operand, true); // Work with broken code 4263 } 4264 Out << ", "; 4265 TypePrinter.print(I.getType(), Out); 4266 } else if (Operand) { // Print the normal way. 4267 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 4268 Out << ' '; 4269 TypePrinter.print(GEP->getSourceElementType(), Out); 4270 Out << ','; 4271 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) { 4272 Out << ' '; 4273 TypePrinter.print(LI->getType(), Out); 4274 Out << ','; 4275 } 4276 4277 // PrintAllTypes - Instructions who have operands of all the same type 4278 // omit the type from all but the first operand. If the instruction has 4279 // different type operands (for example br), then they are all printed. 4280 bool PrintAllTypes = false; 4281 Type *TheType = Operand->getType(); 4282 4283 // Select, Store and ShuffleVector always print all types. 4284 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 4285 || isa<ReturnInst>(I)) { 4286 PrintAllTypes = true; 4287 } else { 4288 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 4289 Operand = I.getOperand(i); 4290 // note that Operand shouldn't be null, but the test helps make dump() 4291 // more tolerant of malformed IR 4292 if (Operand && Operand->getType() != TheType) { 4293 PrintAllTypes = true; // We have differing types! Print them all! 4294 break; 4295 } 4296 } 4297 } 4298 4299 if (!PrintAllTypes) { 4300 Out << ' '; 4301 TypePrinter.print(TheType, Out); 4302 } 4303 4304 Out << ' '; 4305 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 4306 if (i) Out << ", "; 4307 writeOperand(I.getOperand(i), PrintAllTypes); 4308 } 4309 } 4310 4311 // Print atomic ordering/alignment for memory operations 4312 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 4313 if (LI->isAtomic()) 4314 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID()); 4315 if (MaybeAlign A = LI->getAlign()) 4316 Out << ", align " << A->value(); 4317 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 4318 if (SI->isAtomic()) 4319 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID()); 4320 if (MaybeAlign A = SI->getAlign()) 4321 Out << ", align " << A->value(); 4322 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 4323 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(), 4324 CXI->getFailureOrdering(), CXI->getSyncScopeID()); 4325 Out << ", align " << CXI->getAlign().value(); 4326 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 4327 writeAtomic(RMWI->getContext(), RMWI->getOrdering(), 4328 RMWI->getSyncScopeID()); 4329 Out << ", align " << RMWI->getAlign().value(); 4330 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 4331 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID()); 4332 } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) { 4333 PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask()); 4334 } 4335 4336 // Print Metadata info. 4337 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD; 4338 I.getAllMetadata(InstMD); 4339 printMetadataAttachments(InstMD, ", "); 4340 4341 // Print a nice comment. 4342 printInfoComment(I); 4343 } 4344 4345 void AssemblyWriter::printMetadataAttachments( 4346 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 4347 StringRef Separator) { 4348 if (MDs.empty()) 4349 return; 4350 4351 if (MDNames.empty()) 4352 MDs[0].second->getContext().getMDKindNames(MDNames); 4353 4354 auto WriterCtx = getContext(); 4355 for (const auto &I : MDs) { 4356 unsigned Kind = I.first; 4357 Out << Separator; 4358 if (Kind < MDNames.size()) { 4359 Out << "!"; 4360 printMetadataIdentifier(MDNames[Kind], Out); 4361 } else 4362 Out << "!<unknown kind #" << Kind << ">"; 4363 Out << ' '; 4364 WriteAsOperandInternal(Out, I.second, WriterCtx); 4365 } 4366 } 4367 4368 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 4369 Out << '!' << Slot << " = "; 4370 printMDNodeBody(Node); 4371 Out << "\n"; 4372 } 4373 4374 void AssemblyWriter::writeAllMDNodes() { 4375 SmallVector<const MDNode *, 16> Nodes; 4376 Nodes.resize(Machine.mdn_size()); 4377 for (auto &I : llvm::make_range(Machine.mdn_begin(), Machine.mdn_end())) 4378 Nodes[I.second] = cast<MDNode>(I.first); 4379 4380 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 4381 writeMDNode(i, Nodes[i]); 4382 } 4383 } 4384 4385 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 4386 auto WriterCtx = getContext(); 4387 WriteMDNodeBodyInternal(Out, Node, WriterCtx); 4388 } 4389 4390 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) { 4391 if (!Attr.isTypeAttribute()) { 4392 Out << Attr.getAsString(InAttrGroup); 4393 return; 4394 } 4395 4396 Out << Attribute::getNameFromAttrKind(Attr.getKindAsEnum()); 4397 if (Type *Ty = Attr.getValueAsType()) { 4398 Out << '('; 4399 TypePrinter.print(Ty, Out); 4400 Out << ')'; 4401 } 4402 } 4403 4404 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet, 4405 bool InAttrGroup) { 4406 bool FirstAttr = true; 4407 for (const auto &Attr : AttrSet) { 4408 if (!FirstAttr) 4409 Out << ' '; 4410 writeAttribute(Attr, InAttrGroup); 4411 FirstAttr = false; 4412 } 4413 } 4414 4415 void AssemblyWriter::writeAllAttributeGroups() { 4416 std::vector<std::pair<AttributeSet, unsigned>> asVec; 4417 asVec.resize(Machine.as_size()); 4418 4419 for (auto &I : llvm::make_range(Machine.as_begin(), Machine.as_end())) 4420 asVec[I.second] = I; 4421 4422 for (const auto &I : asVec) 4423 Out << "attributes #" << I.second << " = { " 4424 << I.first.getAsString(true) << " }\n"; 4425 } 4426 4427 void AssemblyWriter::printUseListOrder(const Value *V, 4428 const std::vector<unsigned> &Shuffle) { 4429 bool IsInFunction = Machine.getFunction(); 4430 if (IsInFunction) 4431 Out << " "; 4432 4433 Out << "uselistorder"; 4434 if (const BasicBlock *BB = IsInFunction ? nullptr : dyn_cast<BasicBlock>(V)) { 4435 Out << "_bb "; 4436 writeOperand(BB->getParent(), false); 4437 Out << ", "; 4438 writeOperand(BB, false); 4439 } else { 4440 Out << " "; 4441 writeOperand(V, true); 4442 } 4443 Out << ", { "; 4444 4445 assert(Shuffle.size() >= 2 && "Shuffle too small"); 4446 Out << Shuffle[0]; 4447 for (unsigned I = 1, E = Shuffle.size(); I != E; ++I) 4448 Out << ", " << Shuffle[I]; 4449 Out << " }\n"; 4450 } 4451 4452 void AssemblyWriter::printUseLists(const Function *F) { 4453 auto It = UseListOrders.find(F); 4454 if (It == UseListOrders.end()) 4455 return; 4456 4457 Out << "\n; uselistorder directives\n"; 4458 for (const auto &Pair : It->second) 4459 printUseListOrder(Pair.first, Pair.second); 4460 } 4461 4462 //===----------------------------------------------------------------------===// 4463 // External Interface declarations 4464 //===----------------------------------------------------------------------===// 4465 4466 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4467 bool ShouldPreserveUseListOrder, 4468 bool IsForDebug) const { 4469 SlotTracker SlotTable(this->getParent()); 4470 formatted_raw_ostream OS(ROS); 4471 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW, 4472 IsForDebug, 4473 ShouldPreserveUseListOrder); 4474 W.printFunction(this); 4475 } 4476 4477 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4478 bool ShouldPreserveUseListOrder, 4479 bool IsForDebug) const { 4480 SlotTracker SlotTable(this->getParent()); 4481 formatted_raw_ostream OS(ROS); 4482 AssemblyWriter W(OS, SlotTable, this->getModule(), AAW, 4483 IsForDebug, 4484 ShouldPreserveUseListOrder); 4485 W.printBasicBlock(this); 4486 } 4487 4488 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 4489 bool ShouldPreserveUseListOrder, bool IsForDebug) const { 4490 SlotTracker SlotTable(this); 4491 formatted_raw_ostream OS(ROS); 4492 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug, 4493 ShouldPreserveUseListOrder); 4494 W.printModule(this); 4495 } 4496 4497 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const { 4498 SlotTracker SlotTable(getParent()); 4499 formatted_raw_ostream OS(ROS); 4500 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug); 4501 W.printNamedMDNode(this); 4502 } 4503 4504 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4505 bool IsForDebug) const { 4506 Optional<SlotTracker> LocalST; 4507 SlotTracker *SlotTable; 4508 if (auto *ST = MST.getMachine()) 4509 SlotTable = ST; 4510 else { 4511 LocalST.emplace(getParent()); 4512 SlotTable = &*LocalST; 4513 } 4514 4515 formatted_raw_ostream OS(ROS); 4516 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug); 4517 W.printNamedMDNode(this); 4518 } 4519 4520 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const { 4521 PrintLLVMName(ROS, getName(), ComdatPrefix); 4522 ROS << " = comdat "; 4523 4524 switch (getSelectionKind()) { 4525 case Comdat::Any: 4526 ROS << "any"; 4527 break; 4528 case Comdat::ExactMatch: 4529 ROS << "exactmatch"; 4530 break; 4531 case Comdat::Largest: 4532 ROS << "largest"; 4533 break; 4534 case Comdat::NoDeduplicate: 4535 ROS << "nodeduplicate"; 4536 break; 4537 case Comdat::SameSize: 4538 ROS << "samesize"; 4539 break; 4540 } 4541 4542 ROS << '\n'; 4543 } 4544 4545 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const { 4546 TypePrinting TP; 4547 TP.print(const_cast<Type*>(this), OS); 4548 4549 if (NoDetails) 4550 return; 4551 4552 // If the type is a named struct type, print the body as well. 4553 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 4554 if (!STy->isLiteral()) { 4555 OS << " = type "; 4556 TP.printStructBody(STy, OS); 4557 } 4558 } 4559 4560 static bool isReferencingMDNode(const Instruction &I) { 4561 if (const auto *CI = dyn_cast<CallInst>(&I)) 4562 if (Function *F = CI->getCalledFunction()) 4563 if (F->isIntrinsic()) 4564 for (auto &Op : I.operands()) 4565 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 4566 if (isa<MDNode>(V->getMetadata())) 4567 return true; 4568 return false; 4569 } 4570 4571 void Value::print(raw_ostream &ROS, bool IsForDebug) const { 4572 bool ShouldInitializeAllMetadata = false; 4573 if (auto *I = dyn_cast<Instruction>(this)) 4574 ShouldInitializeAllMetadata = isReferencingMDNode(*I); 4575 else if (isa<Function>(this) || isa<MetadataAsValue>(this)) 4576 ShouldInitializeAllMetadata = true; 4577 4578 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata); 4579 print(ROS, MST, IsForDebug); 4580 } 4581 4582 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST, 4583 bool IsForDebug) const { 4584 formatted_raw_ostream OS(ROS); 4585 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr)); 4586 SlotTracker &SlotTable = 4587 MST.getMachine() ? *MST.getMachine() : EmptySlotTable; 4588 auto incorporateFunction = [&](const Function *F) { 4589 if (F) 4590 MST.incorporateFunction(*F); 4591 }; 4592 4593 if (const Instruction *I = dyn_cast<Instruction>(this)) { 4594 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr); 4595 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug); 4596 W.printInstruction(*I); 4597 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 4598 incorporateFunction(BB->getParent()); 4599 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug); 4600 W.printBasicBlock(BB); 4601 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 4602 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug); 4603 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 4604 W.printGlobal(V); 4605 else if (const Function *F = dyn_cast<Function>(GV)) 4606 W.printFunction(F); 4607 else if (const GlobalAlias *A = dyn_cast<GlobalAlias>(GV)) 4608 W.printAlias(A); 4609 else if (const GlobalIFunc *I = dyn_cast<GlobalIFunc>(GV)) 4610 W.printIFunc(I); 4611 else 4612 llvm_unreachable("Unknown GlobalValue to print out!"); 4613 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) { 4614 V->getMetadata()->print(ROS, MST, getModuleFromVal(V)); 4615 } else if (const Constant *C = dyn_cast<Constant>(this)) { 4616 TypePrinting TypePrinter; 4617 TypePrinter.print(C->getType(), OS); 4618 OS << ' '; 4619 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine()); 4620 WriteConstantInternal(OS, C, WriterCtx); 4621 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) { 4622 this->printAsOperand(OS, /* PrintType */ true, MST); 4623 } else { 4624 llvm_unreachable("Unknown value to print out!"); 4625 } 4626 } 4627 4628 /// Print without a type, skipping the TypePrinting object. 4629 /// 4630 /// \return \c true iff printing was successful. 4631 static bool printWithoutType(const Value &V, raw_ostream &O, 4632 SlotTracker *Machine, const Module *M) { 4633 if (V.hasName() || isa<GlobalValue>(V) || 4634 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) { 4635 AsmWriterContext WriterCtx(nullptr, Machine, M); 4636 WriteAsOperandInternal(O, &V, WriterCtx); 4637 return true; 4638 } 4639 return false; 4640 } 4641 4642 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, 4643 ModuleSlotTracker &MST) { 4644 TypePrinting TypePrinter(MST.getModule()); 4645 if (PrintType) { 4646 TypePrinter.print(V.getType(), O); 4647 O << ' '; 4648 } 4649 4650 AsmWriterContext WriterCtx(&TypePrinter, MST.getMachine(), MST.getModule()); 4651 WriteAsOperandInternal(O, &V, WriterCtx); 4652 } 4653 4654 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4655 const Module *M) const { 4656 if (!M) 4657 M = getModuleFromVal(this); 4658 4659 if (!PrintType) 4660 if (printWithoutType(*this, O, nullptr, M)) 4661 return; 4662 4663 SlotTracker Machine( 4664 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this)); 4665 ModuleSlotTracker MST(Machine, M); 4666 printAsOperandImpl(*this, O, PrintType, MST); 4667 } 4668 4669 void Value::printAsOperand(raw_ostream &O, bool PrintType, 4670 ModuleSlotTracker &MST) const { 4671 if (!PrintType) 4672 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule())) 4673 return; 4674 4675 printAsOperandImpl(*this, O, PrintType, MST); 4676 } 4677 4678 /// Recursive version of printMetadataImpl. 4679 static void printMetadataImplRec(raw_ostream &ROS, const Metadata &MD, 4680 AsmWriterContext &WriterCtx) { 4681 formatted_raw_ostream OS(ROS); 4682 WriteAsOperandInternal(OS, &MD, WriterCtx, /* FromValue */ true); 4683 4684 auto *N = dyn_cast<MDNode>(&MD); 4685 if (!N || isa<DIExpression>(MD) || isa<DIArgList>(MD)) 4686 return; 4687 4688 OS << " = "; 4689 WriteMDNodeBodyInternal(OS, N, WriterCtx); 4690 } 4691 4692 namespace { 4693 struct MDTreeAsmWriterContext : public AsmWriterContext { 4694 unsigned Level; 4695 // {Level, Printed string} 4696 using EntryTy = std::pair<unsigned, std::string>; 4697 SmallVector<EntryTy, 4> Buffer; 4698 4699 // Used to break the cycle in case there is any. 4700 SmallPtrSet<const Metadata *, 4> Visited; 4701 4702 raw_ostream &MainOS; 4703 4704 MDTreeAsmWriterContext(TypePrinting *TP, SlotTracker *ST, const Module *M, 4705 raw_ostream &OS, const Metadata *InitMD) 4706 : AsmWriterContext(TP, ST, M), Level(0U), Visited({InitMD}), MainOS(OS) {} 4707 4708 void onWriteMetadataAsOperand(const Metadata *MD) override { 4709 if (Visited.count(MD)) 4710 return; 4711 Visited.insert(MD); 4712 4713 std::string Str; 4714 raw_string_ostream SS(Str); 4715 ++Level; 4716 // A placeholder entry to memorize the correct 4717 // position in buffer. 4718 Buffer.emplace_back(std::make_pair(Level, "")); 4719 unsigned InsertIdx = Buffer.size() - 1; 4720 4721 printMetadataImplRec(SS, *MD, *this); 4722 Buffer[InsertIdx].second = std::move(SS.str()); 4723 --Level; 4724 } 4725 4726 ~MDTreeAsmWriterContext() { 4727 for (const auto &Entry : Buffer) { 4728 MainOS << "\n"; 4729 unsigned NumIndent = Entry.first * 2U; 4730 MainOS.indent(NumIndent) << Entry.second; 4731 } 4732 } 4733 }; 4734 } // end anonymous namespace 4735 4736 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, 4737 ModuleSlotTracker &MST, const Module *M, 4738 bool OnlyAsOperand, bool PrintAsTree = false) { 4739 formatted_raw_ostream OS(ROS); 4740 4741 TypePrinting TypePrinter(M); 4742 4743 std::unique_ptr<AsmWriterContext> WriterCtx; 4744 if (PrintAsTree && !OnlyAsOperand) 4745 WriterCtx = std::make_unique<MDTreeAsmWriterContext>( 4746 &TypePrinter, MST.getMachine(), M, OS, &MD); 4747 else 4748 WriterCtx = 4749 std::make_unique<AsmWriterContext>(&TypePrinter, MST.getMachine(), M); 4750 4751 WriteAsOperandInternal(OS, &MD, *WriterCtx, /* FromValue */ true); 4752 4753 auto *N = dyn_cast<MDNode>(&MD); 4754 if (OnlyAsOperand || !N || isa<DIExpression>(MD) || isa<DIArgList>(MD)) 4755 return; 4756 4757 OS << " = "; 4758 WriteMDNodeBodyInternal(OS, N, *WriterCtx); 4759 } 4760 4761 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const { 4762 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4763 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4764 } 4765 4766 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, 4767 const Module *M) const { 4768 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 4769 } 4770 4771 void Metadata::print(raw_ostream &OS, const Module *M, 4772 bool /*IsForDebug*/) const { 4773 ModuleSlotTracker MST(M, isa<MDNode>(this)); 4774 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4775 } 4776 4777 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST, 4778 const Module *M, bool /*IsForDebug*/) const { 4779 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 4780 } 4781 4782 void MDNode::printTree(raw_ostream &OS, const Module *M) const { 4783 ModuleSlotTracker MST(M, true); 4784 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false, 4785 /*PrintAsTree=*/true); 4786 } 4787 4788 void MDNode::printTree(raw_ostream &OS, ModuleSlotTracker &MST, 4789 const Module *M) const { 4790 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false, 4791 /*PrintAsTree=*/true); 4792 } 4793 4794 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const { 4795 SlotTracker SlotTable(this); 4796 formatted_raw_ostream OS(ROS); 4797 AssemblyWriter W(OS, SlotTable, this, IsForDebug); 4798 W.printModuleSummaryIndex(); 4799 } 4800 4801 void ModuleSlotTracker::collectMDNodes(MachineMDNodeListType &L, unsigned LB, 4802 unsigned UB) const { 4803 SlotTracker *ST = MachineStorage.get(); 4804 if (!ST) 4805 return; 4806 4807 for (auto &I : llvm::make_range(ST->mdn_begin(), ST->mdn_end())) 4808 if (I.second >= LB && I.second < UB) 4809 L.push_back(std::make_pair(I.second, I.first)); 4810 } 4811 4812 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4813 // Value::dump - allow easy printing of Values from the debugger. 4814 LLVM_DUMP_METHOD 4815 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4816 4817 // Type::dump - allow easy printing of Types from the debugger. 4818 LLVM_DUMP_METHOD 4819 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 4820 4821 // Module::dump() - Allow printing of Modules from the debugger. 4822 LLVM_DUMP_METHOD 4823 void Module::dump() const { 4824 print(dbgs(), nullptr, 4825 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true); 4826 } 4827 4828 // Allow printing of Comdats from the debugger. 4829 LLVM_DUMP_METHOD 4830 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4831 4832 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 4833 LLVM_DUMP_METHOD 4834 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4835 4836 LLVM_DUMP_METHOD 4837 void Metadata::dump() const { dump(nullptr); } 4838 4839 LLVM_DUMP_METHOD 4840 void Metadata::dump(const Module *M) const { 4841 print(dbgs(), M, /*IsForDebug=*/true); 4842 dbgs() << '\n'; 4843 } 4844 4845 LLVM_DUMP_METHOD 4846 void MDNode::dumpTree() const { dumpTree(nullptr); } 4847 4848 LLVM_DUMP_METHOD 4849 void MDNode::dumpTree(const Module *M) const { 4850 printTree(dbgs(), M); 4851 dbgs() << '\n'; 4852 } 4853 4854 // Allow printing of ModuleSummaryIndex from the debugger. 4855 LLVM_DUMP_METHOD 4856 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); } 4857 #endif 4858