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