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