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