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