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