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