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