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