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