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 the functionality defined in llvm/IR/Writer.h 11 // 12 // Note that these routines must be extremely tolerant of various errors in the 13 // LLVM code, because it can be used for debugging transformations. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/IR/AssemblyAnnotationWriter.h" 23 #include "llvm/IR/CFG.h" 24 #include "llvm/IR/CallingConv.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/IRPrintingPasses.h" 29 #include "llvm/IR/InlineAsm.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ModuleSlotTracker.h" 34 #include "llvm/IR/Operator.h" 35 #include "llvm/IR/Statepoint.h" 36 #include "llvm/IR/TypeFinder.h" 37 #include "llvm/IR/UseListOrder.h" 38 #include "llvm/IR/ValueSymbolTable.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/Dwarf.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/Format.h" 43 #include "llvm/Support/FormattedStream.h" 44 #include "llvm/Support/MathExtras.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include <algorithm> 47 #include <cctype> 48 using namespace llvm; 49 50 // Make virtual table appear in this compilation unit. 51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {} 52 53 //===----------------------------------------------------------------------===// 54 // Helper Functions 55 //===----------------------------------------------------------------------===// 56 57 namespace { 58 struct OrderMap { 59 DenseMap<const Value *, std::pair<unsigned, bool>> IDs; 60 61 unsigned size() const { return IDs.size(); } 62 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; } 63 std::pair<unsigned, bool> lookup(const Value *V) const { 64 return IDs.lookup(V); 65 } 66 void index(const Value *V) { 67 // Explicitly sequence get-size and insert-value operations to avoid UB. 68 unsigned ID = IDs.size() + 1; 69 IDs[V].first = ID; 70 } 71 }; 72 } 73 74 static void orderValue(const Value *V, OrderMap &OM) { 75 if (OM.lookup(V).first) 76 return; 77 78 if (const Constant *C = dyn_cast<Constant>(V)) 79 if (C->getNumOperands() && !isa<GlobalValue>(C)) 80 for (const Value *Op : C->operands()) 81 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op)) 82 orderValue(Op, OM); 83 84 // Note: we cannot cache this lookup above, since inserting into the map 85 // changes the map's size, and thus affects the other IDs. 86 OM.index(V); 87 } 88 89 static OrderMap orderModule(const Module *M) { 90 // This needs to match the order used by ValueEnumerator::ValueEnumerator() 91 // and ValueEnumerator::incorporateFunction(). 92 OrderMap OM; 93 94 for (const GlobalVariable &G : M->globals()) { 95 if (G.hasInitializer()) 96 if (!isa<GlobalValue>(G.getInitializer())) 97 orderValue(G.getInitializer(), OM); 98 orderValue(&G, OM); 99 } 100 for (const GlobalAlias &A : M->aliases()) { 101 if (!isa<GlobalValue>(A.getAliasee())) 102 orderValue(A.getAliasee(), OM); 103 orderValue(&A, OM); 104 } 105 for (const Function &F : *M) { 106 if (F.hasPrefixData()) 107 if (!isa<GlobalValue>(F.getPrefixData())) 108 orderValue(F.getPrefixData(), OM); 109 110 if (F.hasPrologueData()) 111 if (!isa<GlobalValue>(F.getPrologueData())) 112 orderValue(F.getPrologueData(), OM); 113 114 if (F.hasPersonalityFn()) 115 if (!isa<GlobalValue>(F.getPersonalityFn())) 116 orderValue(F.getPersonalityFn(), OM); 117 118 orderValue(&F, OM); 119 120 if (F.isDeclaration()) 121 continue; 122 123 for (const Argument &A : F.args()) 124 orderValue(&A, OM); 125 for (const BasicBlock &BB : F) { 126 orderValue(&BB, OM); 127 for (const Instruction &I : BB) { 128 for (const Value *Op : I.operands()) 129 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) || 130 isa<InlineAsm>(*Op)) 131 orderValue(Op, OM); 132 orderValue(&I, OM); 133 } 134 } 135 } 136 return OM; 137 } 138 139 static void predictValueUseListOrderImpl(const Value *V, const Function *F, 140 unsigned ID, const OrderMap &OM, 141 UseListOrderStack &Stack) { 142 // Predict use-list order for this one. 143 typedef std::pair<const Use *, unsigned> Entry; 144 SmallVector<Entry, 64> List; 145 for (const Use &U : V->uses()) 146 // Check if this user will be serialized. 147 if (OM.lookup(U.getUser()).first) 148 List.push_back(std::make_pair(&U, List.size())); 149 150 if (List.size() < 2) 151 // We may have lost some users. 152 return; 153 154 bool GetsReversed = 155 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V); 156 if (auto *BA = dyn_cast<BlockAddress>(V)) 157 ID = OM.lookup(BA->getBasicBlock()).first; 158 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) { 159 const Use *LU = L.first; 160 const Use *RU = R.first; 161 if (LU == RU) 162 return false; 163 164 auto LID = OM.lookup(LU->getUser()).first; 165 auto RID = OM.lookup(RU->getUser()).first; 166 167 // If ID is 4, then expect: 7 6 5 1 2 3. 168 if (LID < RID) { 169 if (GetsReversed) 170 if (RID <= ID) 171 return true; 172 return false; 173 } 174 if (RID < LID) { 175 if (GetsReversed) 176 if (LID <= ID) 177 return false; 178 return true; 179 } 180 181 // LID and RID are equal, so we have different operands of the same user. 182 // Assume operands are added in order for all instructions. 183 if (GetsReversed) 184 if (LID <= ID) 185 return LU->getOperandNo() < RU->getOperandNo(); 186 return LU->getOperandNo() > RU->getOperandNo(); 187 }); 188 189 if (std::is_sorted( 190 List.begin(), List.end(), 191 [](const Entry &L, const Entry &R) { return L.second < R.second; })) 192 // Order is already correct. 193 return; 194 195 // Store the shuffle. 196 Stack.emplace_back(V, F, List.size()); 197 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size"); 198 for (size_t I = 0, E = List.size(); I != E; ++I) 199 Stack.back().Shuffle[I] = List[I].second; 200 } 201 202 static void predictValueUseListOrder(const Value *V, const Function *F, 203 OrderMap &OM, UseListOrderStack &Stack) { 204 auto &IDPair = OM[V]; 205 assert(IDPair.first && "Unmapped value"); 206 if (IDPair.second) 207 // Already predicted. 208 return; 209 210 // Do the actual prediction. 211 IDPair.second = true; 212 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end()) 213 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack); 214 215 // Recursive descent into constants. 216 if (const Constant *C = dyn_cast<Constant>(V)) 217 if (C->getNumOperands()) // Visit GlobalValues. 218 for (const Value *Op : C->operands()) 219 if (isa<Constant>(Op)) // Visit GlobalValues. 220 predictValueUseListOrder(Op, F, OM, Stack); 221 } 222 223 static UseListOrderStack predictUseListOrder(const Module *M) { 224 OrderMap OM = orderModule(M); 225 226 // Use-list orders need to be serialized after all the users have been added 227 // to a value, or else the shuffles will be incomplete. Store them per 228 // function in a stack. 229 // 230 // Aside from function order, the order of values doesn't matter much here. 231 UseListOrderStack Stack; 232 233 // We want to visit the functions backward now so we can list function-local 234 // constants in the last Function they're used in. Module-level constants 235 // have already been visited above. 236 for (const Function &F : make_range(M->rbegin(), M->rend())) { 237 if (F.isDeclaration()) 238 continue; 239 for (const BasicBlock &BB : F) 240 predictValueUseListOrder(&BB, &F, OM, Stack); 241 for (const Argument &A : F.args()) 242 predictValueUseListOrder(&A, &F, OM, Stack); 243 for (const BasicBlock &BB : F) 244 for (const Instruction &I : BB) 245 for (const Value *Op : I.operands()) 246 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues. 247 predictValueUseListOrder(Op, &F, OM, Stack); 248 for (const BasicBlock &BB : F) 249 for (const Instruction &I : BB) 250 predictValueUseListOrder(&I, &F, OM, Stack); 251 } 252 253 // Visit globals last. 254 for (const GlobalVariable &G : M->globals()) 255 predictValueUseListOrder(&G, nullptr, OM, Stack); 256 for (const Function &F : *M) 257 predictValueUseListOrder(&F, nullptr, OM, Stack); 258 for (const GlobalAlias &A : M->aliases()) 259 predictValueUseListOrder(&A, nullptr, OM, Stack); 260 for (const GlobalVariable &G : M->globals()) 261 if (G.hasInitializer()) 262 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack); 263 for (const GlobalAlias &A : M->aliases()) 264 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack); 265 for (const Function &F : *M) 266 if (F.hasPrefixData()) 267 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack); 268 269 return Stack; 270 } 271 272 static const Module *getModuleFromVal(const Value *V) { 273 if (const Argument *MA = dyn_cast<Argument>(V)) 274 return MA->getParent() ? MA->getParent()->getParent() : nullptr; 275 276 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 277 return BB->getParent() ? BB->getParent()->getParent() : nullptr; 278 279 if (const Instruction *I = dyn_cast<Instruction>(V)) { 280 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr; 281 return M ? M->getParent() : nullptr; 282 } 283 284 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 285 return GV->getParent(); 286 287 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) { 288 for (const User *U : MAV->users()) 289 if (isa<Instruction>(U)) 290 if (const Module *M = getModuleFromVal(U)) 291 return M; 292 return nullptr; 293 } 294 295 return nullptr; 296 } 297 298 static void PrintCallingConv(unsigned cc, raw_ostream &Out) { 299 switch (cc) { 300 default: Out << "cc" << cc; break; 301 case CallingConv::Fast: Out << "fastcc"; break; 302 case CallingConv::Cold: Out << "coldcc"; break; 303 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break; 304 case CallingConv::AnyReg: Out << "anyregcc"; break; 305 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break; 306 case CallingConv::PreserveAll: Out << "preserve_allcc"; break; 307 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break; 308 case CallingConv::GHC: Out << "ghccc"; break; 309 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break; 310 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break; 311 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break; 312 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break; 313 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break; 314 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break; 315 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break; 316 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break; 317 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break; 318 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break; 319 case CallingConv::PTX_Device: Out << "ptx_device"; break; 320 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break; 321 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break; 322 case CallingConv::SPIR_FUNC: Out << "spir_func"; break; 323 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break; 324 case CallingConv::HHVM: Out << "hhvmcc"; break; 325 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break; 326 } 327 } 328 329 // PrintEscapedString - Print each character of the specified string, escaping 330 // it if it is not printable or if it is an escape char. 331 static void PrintEscapedString(StringRef Name, raw_ostream &Out) { 332 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 333 unsigned char C = Name[i]; 334 if (isprint(C) && C != '\\' && C != '"') 335 Out << C; 336 else 337 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 338 } 339 } 340 341 enum PrefixType { 342 GlobalPrefix, 343 ComdatPrefix, 344 LabelPrefix, 345 LocalPrefix, 346 NoPrefix 347 }; 348 349 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) { 350 assert(!Name.empty() && "Cannot get empty name!"); 351 352 // Scan the name to see if it needs quotes first. 353 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0])); 354 if (!NeedsQuotes) { 355 for (unsigned i = 0, e = Name.size(); i != e; ++i) { 356 // By making this unsigned, the value passed in to isalnum will always be 357 // in the range 0-255. This is important when building with MSVC because 358 // its implementation will assert. This situation can arise when dealing 359 // with UTF-8 multibyte characters. 360 unsigned char C = Name[i]; 361 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' && 362 C != '_') { 363 NeedsQuotes = true; 364 break; 365 } 366 } 367 } 368 369 // If we didn't need any quotes, just write out the name in one blast. 370 if (!NeedsQuotes) { 371 OS << Name; 372 return; 373 } 374 375 // Okay, we need quotes. Output the quotes and escape any scary characters as 376 // needed. 377 OS << '"'; 378 PrintEscapedString(Name, OS); 379 OS << '"'; 380 } 381 382 /// Turn the specified name into an 'LLVM name', which is either prefixed with % 383 /// (if the string only contains simple characters) or is surrounded with ""'s 384 /// (if it has special chars in it). Print it out. 385 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) { 386 switch (Prefix) { 387 case NoPrefix: 388 break; 389 case GlobalPrefix: 390 OS << '@'; 391 break; 392 case ComdatPrefix: 393 OS << '$'; 394 break; 395 case LabelPrefix: 396 break; 397 case LocalPrefix: 398 OS << '%'; 399 break; 400 } 401 printLLVMNameWithoutPrefix(OS, Name); 402 } 403 404 /// Turn the specified name into an 'LLVM name', which is either prefixed with % 405 /// (if the string only contains simple characters) or is surrounded with ""'s 406 /// (if it has special chars in it). Print it out. 407 static void PrintLLVMName(raw_ostream &OS, const Value *V) { 408 PrintLLVMName(OS, V->getName(), 409 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix); 410 } 411 412 413 namespace { 414 class TypePrinting { 415 TypePrinting(const TypePrinting &) = delete; 416 void operator=(const TypePrinting&) = delete; 417 public: 418 419 /// NamedTypes - The named types that are used by the current module. 420 TypeFinder NamedTypes; 421 422 /// NumberedTypes - The numbered types, along with their value. 423 DenseMap<StructType*, unsigned> NumberedTypes; 424 425 TypePrinting() = default; 426 427 void incorporateTypes(const Module &M); 428 429 void print(Type *Ty, raw_ostream &OS); 430 431 void printStructBody(StructType *Ty, raw_ostream &OS); 432 }; 433 } // namespace 434 435 void TypePrinting::incorporateTypes(const Module &M) { 436 NamedTypes.run(M, false); 437 438 // The list of struct types we got back includes all the struct types, split 439 // the unnamed ones out to a numbering and remove the anonymous structs. 440 unsigned NextNumber = 0; 441 442 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E; 443 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) { 444 StructType *STy = *I; 445 446 // Ignore anonymous types. 447 if (STy->isLiteral()) 448 continue; 449 450 if (STy->getName().empty()) 451 NumberedTypes[STy] = NextNumber++; 452 else 453 *NextToUse++ = STy; 454 } 455 456 NamedTypes.erase(NextToUse, NamedTypes.end()); 457 } 458 459 460 /// CalcTypeName - Write the specified type to the specified raw_ostream, making 461 /// use of type names or up references to shorten the type name where possible. 462 void TypePrinting::print(Type *Ty, raw_ostream &OS) { 463 switch (Ty->getTypeID()) { 464 case Type::VoidTyID: OS << "void"; return; 465 case Type::HalfTyID: OS << "half"; return; 466 case Type::FloatTyID: OS << "float"; return; 467 case Type::DoubleTyID: OS << "double"; return; 468 case Type::X86_FP80TyID: OS << "x86_fp80"; return; 469 case Type::FP128TyID: OS << "fp128"; return; 470 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return; 471 case Type::LabelTyID: OS << "label"; return; 472 case Type::MetadataTyID: OS << "metadata"; return; 473 case Type::X86_MMXTyID: OS << "x86_mmx"; return; 474 case Type::TokenTyID: OS << "token"; return; 475 case Type::IntegerTyID: 476 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth(); 477 return; 478 479 case Type::FunctionTyID: { 480 FunctionType *FTy = cast<FunctionType>(Ty); 481 print(FTy->getReturnType(), OS); 482 OS << " ("; 483 for (FunctionType::param_iterator I = FTy->param_begin(), 484 E = FTy->param_end(); I != E; ++I) { 485 if (I != FTy->param_begin()) 486 OS << ", "; 487 print(*I, OS); 488 } 489 if (FTy->isVarArg()) { 490 if (FTy->getNumParams()) OS << ", "; 491 OS << "..."; 492 } 493 OS << ')'; 494 return; 495 } 496 case Type::StructTyID: { 497 StructType *STy = cast<StructType>(Ty); 498 499 if (STy->isLiteral()) 500 return printStructBody(STy, OS); 501 502 if (!STy->getName().empty()) 503 return PrintLLVMName(OS, STy->getName(), LocalPrefix); 504 505 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy); 506 if (I != NumberedTypes.end()) 507 OS << '%' << I->second; 508 else // Not enumerated, print the hex address. 509 OS << "%\"type " << STy << '\"'; 510 return; 511 } 512 case Type::PointerTyID: { 513 PointerType *PTy = cast<PointerType>(Ty); 514 print(PTy->getElementType(), OS); 515 if (unsigned AddressSpace = PTy->getAddressSpace()) 516 OS << " addrspace(" << AddressSpace << ')'; 517 OS << '*'; 518 return; 519 } 520 case Type::ArrayTyID: { 521 ArrayType *ATy = cast<ArrayType>(Ty); 522 OS << '[' << ATy->getNumElements() << " x "; 523 print(ATy->getElementType(), OS); 524 OS << ']'; 525 return; 526 } 527 case Type::VectorTyID: { 528 VectorType *PTy = cast<VectorType>(Ty); 529 OS << "<" << PTy->getNumElements() << " x "; 530 print(PTy->getElementType(), OS); 531 OS << '>'; 532 return; 533 } 534 } 535 llvm_unreachable("Invalid TypeID"); 536 } 537 538 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) { 539 if (STy->isOpaque()) { 540 OS << "opaque"; 541 return; 542 } 543 544 if (STy->isPacked()) 545 OS << '<'; 546 547 if (STy->getNumElements() == 0) { 548 OS << "{}"; 549 } else { 550 StructType::element_iterator I = STy->element_begin(); 551 OS << "{ "; 552 print(*I++, OS); 553 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) { 554 OS << ", "; 555 print(*I, OS); 556 } 557 558 OS << " }"; 559 } 560 if (STy->isPacked()) 561 OS << '>'; 562 } 563 564 namespace llvm { 565 //===----------------------------------------------------------------------===// 566 // SlotTracker Class: Enumerate slot numbers for unnamed values 567 //===----------------------------------------------------------------------===// 568 /// This class provides computation of slot numbers for LLVM Assembly writing. 569 /// 570 class SlotTracker { 571 public: 572 /// ValueMap - A mapping of Values to slot numbers. 573 typedef DenseMap<const Value*, unsigned> ValueMap; 574 575 private: 576 /// TheModule - The module for which we are holding slot numbers. 577 const Module* TheModule; 578 579 /// TheFunction - The function for which we are holding slot numbers. 580 const Function* TheFunction; 581 bool FunctionProcessed; 582 bool ShouldInitializeAllMetadata; 583 584 /// mMap - The slot map for the module level data. 585 ValueMap mMap; 586 unsigned mNext; 587 588 /// fMap - The slot map for the function level data. 589 ValueMap fMap; 590 unsigned fNext; 591 592 /// mdnMap - Map for MDNodes. 593 DenseMap<const MDNode*, unsigned> mdnMap; 594 unsigned mdnNext; 595 596 /// asMap - The slot map for attribute sets. 597 DenseMap<AttributeSet, unsigned> asMap; 598 unsigned asNext; 599 public: 600 /// Construct from a module. 601 /// 602 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all 603 /// functions, giving correct numbering for metadata referenced only from 604 /// within a function (even if no functions have been initialized). 605 explicit SlotTracker(const Module *M, 606 bool ShouldInitializeAllMetadata = false); 607 /// Construct from a function, starting out in incorp state. 608 /// 609 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all 610 /// functions, giving correct numbering for metadata referenced only from 611 /// within a function (even if no functions have been initialized). 612 explicit SlotTracker(const Function *F, 613 bool ShouldInitializeAllMetadata = false); 614 615 /// Return the slot number of the specified value in it's type 616 /// plane. If something is not in the SlotTracker, return -1. 617 int getLocalSlot(const Value *V); 618 int getGlobalSlot(const GlobalValue *V); 619 int getMetadataSlot(const MDNode *N); 620 int getAttributeGroupSlot(AttributeSet AS); 621 622 /// If you'd like to deal with a function instead of just a module, use 623 /// this method to get its data into the SlotTracker. 624 void incorporateFunction(const Function *F) { 625 TheFunction = F; 626 FunctionProcessed = false; 627 } 628 629 const Function *getFunction() const { return TheFunction; } 630 631 /// After calling incorporateFunction, use this method to remove the 632 /// most recently incorporated function from the SlotTracker. This 633 /// will reset the state of the machine back to just the module contents. 634 void purgeFunction(); 635 636 /// MDNode map iterators. 637 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator; 638 mdn_iterator mdn_begin() { return mdnMap.begin(); } 639 mdn_iterator mdn_end() { return mdnMap.end(); } 640 unsigned mdn_size() const { return mdnMap.size(); } 641 bool mdn_empty() const { return mdnMap.empty(); } 642 643 /// AttributeSet map iterators. 644 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator; 645 as_iterator as_begin() { return asMap.begin(); } 646 as_iterator as_end() { return asMap.end(); } 647 unsigned as_size() const { return asMap.size(); } 648 bool as_empty() const { return asMap.empty(); } 649 650 /// This function does the actual initialization. 651 inline void initialize(); 652 653 // Implementation Details 654 private: 655 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 656 void CreateModuleSlot(const GlobalValue *V); 657 658 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table. 659 void CreateMetadataSlot(const MDNode *N); 660 661 /// CreateFunctionSlot - Insert the specified Value* into the slot table. 662 void CreateFunctionSlot(const Value *V); 663 664 /// \brief Insert the specified AttributeSet into the slot table. 665 void CreateAttributeSetSlot(AttributeSet AS); 666 667 /// Add all of the module level global variables (and their initializers) 668 /// and function declarations, but not the contents of those functions. 669 void processModule(); 670 671 /// Add all of the functions arguments, basic blocks, and instructions. 672 void processFunction(); 673 674 /// Add all of the metadata from a function. 675 void processFunctionMetadata(const Function &F); 676 677 /// Add all of the metadata from an instruction. 678 void processInstructionMetadata(const Instruction &I); 679 680 SlotTracker(const SlotTracker &) = delete; 681 void operator=(const SlotTracker &) = delete; 682 }; 683 } // namespace llvm 684 685 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M, 686 const Function *F) 687 : M(M), F(F), Machine(&Machine) {} 688 689 ModuleSlotTracker::ModuleSlotTracker(const Module *M, 690 bool ShouldInitializeAllMetadata) 691 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata) 692 : nullptr), 693 M(M), Machine(MachineStorage.get()) {} 694 695 ModuleSlotTracker::~ModuleSlotTracker() {} 696 697 void ModuleSlotTracker::incorporateFunction(const Function &F) { 698 if (!Machine) 699 return; 700 701 // Nothing to do if this is the right function already. 702 if (this->F == &F) 703 return; 704 if (this->F) 705 Machine->purgeFunction(); 706 Machine->incorporateFunction(&F); 707 this->F = &F; 708 } 709 710 int ModuleSlotTracker::getLocalSlot(const Value *V) { 711 assert(F && "No function incorporated"); 712 return Machine->getLocalSlot(V); 713 } 714 715 static SlotTracker *createSlotTracker(const Value *V) { 716 if (const Argument *FA = dyn_cast<Argument>(V)) 717 return new SlotTracker(FA->getParent()); 718 719 if (const Instruction *I = dyn_cast<Instruction>(V)) 720 if (I->getParent()) 721 return new SlotTracker(I->getParent()->getParent()); 722 723 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) 724 return new SlotTracker(BB->getParent()); 725 726 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 727 return new SlotTracker(GV->getParent()); 728 729 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 730 return new SlotTracker(GA->getParent()); 731 732 if (const Function *Func = dyn_cast<Function>(V)) 733 return new SlotTracker(Func); 734 735 return nullptr; 736 } 737 738 #if 0 739 #define ST_DEBUG(X) dbgs() << X 740 #else 741 #define ST_DEBUG(X) 742 #endif 743 744 // Module level constructor. Causes the contents of the Module (sans functions) 745 // to be added to the slot table. 746 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata) 747 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false), 748 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0), 749 fNext(0), mdnNext(0), asNext(0) {} 750 751 // Function level constructor. Causes the contents of the Module and the one 752 // function provided to be added to the slot table. 753 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata) 754 : TheModule(F ? F->getParent() : nullptr), TheFunction(F), 755 FunctionProcessed(false), 756 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0), 757 fNext(0), mdnNext(0), asNext(0) {} 758 759 inline void SlotTracker::initialize() { 760 if (TheModule) { 761 processModule(); 762 TheModule = nullptr; ///< Prevent re-processing next time we're called. 763 } 764 765 if (TheFunction && !FunctionProcessed) 766 processFunction(); 767 } 768 769 // Iterate through all the global variables, functions, and global 770 // variable initializers and create slots for them. 771 void SlotTracker::processModule() { 772 ST_DEBUG("begin processModule!\n"); 773 774 // Add all of the unnamed global variables to the value table. 775 for (const GlobalVariable &Var : TheModule->globals()) { 776 if (!Var.hasName()) 777 CreateModuleSlot(&Var); 778 } 779 780 for (const GlobalAlias &A : TheModule->aliases()) { 781 if (!A.hasName()) 782 CreateModuleSlot(&A); 783 } 784 785 // Add metadata used by named metadata. 786 for (const NamedMDNode &NMD : TheModule->named_metadata()) { 787 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) 788 CreateMetadataSlot(NMD.getOperand(i)); 789 } 790 791 for (const Function &F : *TheModule) { 792 if (!F.hasName()) 793 // Add all the unnamed functions to the table. 794 CreateModuleSlot(&F); 795 796 if (ShouldInitializeAllMetadata) 797 processFunctionMetadata(F); 798 799 // Add all the function attributes to the table. 800 // FIXME: Add attributes of other objects? 801 AttributeSet FnAttrs = F.getAttributes().getFnAttributes(); 802 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex)) 803 CreateAttributeSetSlot(FnAttrs); 804 } 805 806 ST_DEBUG("end processModule!\n"); 807 } 808 809 // Process the arguments, basic blocks, and instructions of a function. 810 void SlotTracker::processFunction() { 811 ST_DEBUG("begin processFunction!\n"); 812 fNext = 0; 813 814 // Process function metadata if it wasn't hit at the module-level. 815 if (!ShouldInitializeAllMetadata) 816 processFunctionMetadata(*TheFunction); 817 818 // Add all the function arguments with no names. 819 for(Function::const_arg_iterator AI = TheFunction->arg_begin(), 820 AE = TheFunction->arg_end(); AI != AE; ++AI) 821 if (!AI->hasName()) 822 CreateFunctionSlot(&*AI); 823 824 ST_DEBUG("Inserting Instructions:\n"); 825 826 // Add all of the basic blocks and instructions with no names. 827 for (auto &BB : *TheFunction) { 828 if (!BB.hasName()) 829 CreateFunctionSlot(&BB); 830 831 for (auto &I : BB) { 832 if (!I.getType()->isVoidTy() && !I.hasName()) 833 CreateFunctionSlot(&I); 834 835 // We allow direct calls to any llvm.foo function here, because the 836 // target may not be linked into the optimizer. 837 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 838 // Add all the call attributes to the table. 839 AttributeSet Attrs = CI->getAttributes().getFnAttributes(); 840 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 841 CreateAttributeSetSlot(Attrs); 842 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 843 // Add all the call attributes to the table. 844 AttributeSet Attrs = II->getAttributes().getFnAttributes(); 845 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 846 CreateAttributeSetSlot(Attrs); 847 } 848 } 849 } 850 851 FunctionProcessed = true; 852 853 ST_DEBUG("end processFunction!\n"); 854 } 855 856 void SlotTracker::processFunctionMetadata(const Function &F) { 857 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 858 F.getAllMetadata(MDs); 859 for (auto &MD : MDs) 860 CreateMetadataSlot(MD.second); 861 862 for (auto &BB : F) { 863 for (auto &I : BB) 864 processInstructionMetadata(I); 865 } 866 } 867 868 void SlotTracker::processInstructionMetadata(const Instruction &I) { 869 // Process metadata used directly by intrinsics. 870 if (const CallInst *CI = dyn_cast<CallInst>(&I)) 871 if (Function *F = CI->getCalledFunction()) 872 if (F->isIntrinsic()) 873 for (auto &Op : I.operands()) 874 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 875 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata())) 876 CreateMetadataSlot(N); 877 878 // Process metadata attached to this instruction. 879 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 880 I.getAllMetadata(MDs); 881 for (auto &MD : MDs) 882 CreateMetadataSlot(MD.second); 883 } 884 885 /// Clean up after incorporating a function. This is the only way to get out of 886 /// the function incorporation state that affects get*Slot/Create*Slot. Function 887 /// incorporation state is indicated by TheFunction != 0. 888 void SlotTracker::purgeFunction() { 889 ST_DEBUG("begin purgeFunction!\n"); 890 fMap.clear(); // Simply discard the function level map 891 TheFunction = nullptr; 892 FunctionProcessed = false; 893 ST_DEBUG("end purgeFunction!\n"); 894 } 895 896 /// getGlobalSlot - Get the slot number of a global value. 897 int SlotTracker::getGlobalSlot(const GlobalValue *V) { 898 // Check for uninitialized state and do lazy initialization. 899 initialize(); 900 901 // Find the value in the module map 902 ValueMap::iterator MI = mMap.find(V); 903 return MI == mMap.end() ? -1 : (int)MI->second; 904 } 905 906 /// getMetadataSlot - Get the slot number of a MDNode. 907 int SlotTracker::getMetadataSlot(const MDNode *N) { 908 // Check for uninitialized state and do lazy initialization. 909 initialize(); 910 911 // Find the MDNode in the module map 912 mdn_iterator MI = mdnMap.find(N); 913 return MI == mdnMap.end() ? -1 : (int)MI->second; 914 } 915 916 917 /// getLocalSlot - Get the slot number for a value that is local to a function. 918 int SlotTracker::getLocalSlot(const Value *V) { 919 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!"); 920 921 // Check for uninitialized state and do lazy initialization. 922 initialize(); 923 924 ValueMap::iterator FI = fMap.find(V); 925 return FI == fMap.end() ? -1 : (int)FI->second; 926 } 927 928 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) { 929 // Check for uninitialized state and do lazy initialization. 930 initialize(); 931 932 // Find the AttributeSet in the module map. 933 as_iterator AI = asMap.find(AS); 934 return AI == asMap.end() ? -1 : (int)AI->second; 935 } 936 937 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table. 938 void SlotTracker::CreateModuleSlot(const GlobalValue *V) { 939 assert(V && "Can't insert a null Value into SlotTracker!"); 940 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!"); 941 assert(!V->hasName() && "Doesn't need a slot!"); 942 943 unsigned DestSlot = mNext++; 944 mMap[V] = DestSlot; 945 946 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 947 DestSlot << " ["); 948 // G = Global, F = Function, A = Alias, o = other 949 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' : 950 (isa<Function>(V) ? 'F' : 951 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n"); 952 } 953 954 /// CreateSlot - Create a new slot for the specified value if it has no name. 955 void SlotTracker::CreateFunctionSlot(const Value *V) { 956 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!"); 957 958 unsigned DestSlot = fNext++; 959 fMap[V] = DestSlot; 960 961 // G = Global, F = Function, o = other 962 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" << 963 DestSlot << " [o]\n"); 964 } 965 966 /// CreateModuleSlot - Insert the specified MDNode* into the slot table. 967 void SlotTracker::CreateMetadataSlot(const MDNode *N) { 968 assert(N && "Can't insert a null Value into SlotTracker!"); 969 970 unsigned DestSlot = mdnNext; 971 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second) 972 return; 973 ++mdnNext; 974 975 // Recursively add any MDNodes referenced by operands. 976 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 977 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i))) 978 CreateMetadataSlot(Op); 979 } 980 981 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) { 982 assert(AS.hasAttributes(AttributeSet::FunctionIndex) && 983 "Doesn't need a slot!"); 984 985 as_iterator I = asMap.find(AS); 986 if (I != asMap.end()) 987 return; 988 989 unsigned DestSlot = asNext++; 990 asMap[AS] = DestSlot; 991 } 992 993 //===----------------------------------------------------------------------===// 994 // AsmWriter Implementation 995 //===----------------------------------------------------------------------===// 996 997 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 998 TypePrinting *TypePrinter, 999 SlotTracker *Machine, 1000 const Module *Context); 1001 1002 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 1003 TypePrinting *TypePrinter, 1004 SlotTracker *Machine, const Module *Context, 1005 bool FromValue = false); 1006 1007 static const char *getPredicateText(unsigned predicate) { 1008 const char * pred = "unknown"; 1009 switch (predicate) { 1010 case FCmpInst::FCMP_FALSE: pred = "false"; break; 1011 case FCmpInst::FCMP_OEQ: pred = "oeq"; break; 1012 case FCmpInst::FCMP_OGT: pred = "ogt"; break; 1013 case FCmpInst::FCMP_OGE: pred = "oge"; break; 1014 case FCmpInst::FCMP_OLT: pred = "olt"; break; 1015 case FCmpInst::FCMP_OLE: pred = "ole"; break; 1016 case FCmpInst::FCMP_ONE: pred = "one"; break; 1017 case FCmpInst::FCMP_ORD: pred = "ord"; break; 1018 case FCmpInst::FCMP_UNO: pred = "uno"; break; 1019 case FCmpInst::FCMP_UEQ: pred = "ueq"; break; 1020 case FCmpInst::FCMP_UGT: pred = "ugt"; break; 1021 case FCmpInst::FCMP_UGE: pred = "uge"; break; 1022 case FCmpInst::FCMP_ULT: pred = "ult"; break; 1023 case FCmpInst::FCMP_ULE: pred = "ule"; break; 1024 case FCmpInst::FCMP_UNE: pred = "une"; break; 1025 case FCmpInst::FCMP_TRUE: pred = "true"; break; 1026 case ICmpInst::ICMP_EQ: pred = "eq"; break; 1027 case ICmpInst::ICMP_NE: pred = "ne"; break; 1028 case ICmpInst::ICMP_SGT: pred = "sgt"; break; 1029 case ICmpInst::ICMP_SGE: pred = "sge"; break; 1030 case ICmpInst::ICMP_SLT: pred = "slt"; break; 1031 case ICmpInst::ICMP_SLE: pred = "sle"; break; 1032 case ICmpInst::ICMP_UGT: pred = "ugt"; break; 1033 case ICmpInst::ICMP_UGE: pred = "uge"; break; 1034 case ICmpInst::ICMP_ULT: pred = "ult"; break; 1035 case ICmpInst::ICMP_ULE: pred = "ule"; break; 1036 } 1037 return pred; 1038 } 1039 1040 static void writeAtomicRMWOperation(raw_ostream &Out, 1041 AtomicRMWInst::BinOp Op) { 1042 switch (Op) { 1043 default: Out << " <unknown operation " << Op << ">"; break; 1044 case AtomicRMWInst::Xchg: Out << " xchg"; break; 1045 case AtomicRMWInst::Add: Out << " add"; break; 1046 case AtomicRMWInst::Sub: Out << " sub"; break; 1047 case AtomicRMWInst::And: Out << " and"; break; 1048 case AtomicRMWInst::Nand: Out << " nand"; break; 1049 case AtomicRMWInst::Or: Out << " or"; break; 1050 case AtomicRMWInst::Xor: Out << " xor"; break; 1051 case AtomicRMWInst::Max: Out << " max"; break; 1052 case AtomicRMWInst::Min: Out << " min"; break; 1053 case AtomicRMWInst::UMax: Out << " umax"; break; 1054 case AtomicRMWInst::UMin: Out << " umin"; break; 1055 } 1056 } 1057 1058 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) { 1059 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) { 1060 // Unsafe algebra implies all the others, no need to write them all out 1061 if (FPO->hasUnsafeAlgebra()) 1062 Out << " fast"; 1063 else { 1064 if (FPO->hasNoNaNs()) 1065 Out << " nnan"; 1066 if (FPO->hasNoInfs()) 1067 Out << " ninf"; 1068 if (FPO->hasNoSignedZeros()) 1069 Out << " nsz"; 1070 if (FPO->hasAllowReciprocal()) 1071 Out << " arcp"; 1072 } 1073 } 1074 1075 if (const OverflowingBinaryOperator *OBO = 1076 dyn_cast<OverflowingBinaryOperator>(U)) { 1077 if (OBO->hasNoUnsignedWrap()) 1078 Out << " nuw"; 1079 if (OBO->hasNoSignedWrap()) 1080 Out << " nsw"; 1081 } else if (const PossiblyExactOperator *Div = 1082 dyn_cast<PossiblyExactOperator>(U)) { 1083 if (Div->isExact()) 1084 Out << " exact"; 1085 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 1086 if (GEP->isInBounds()) 1087 Out << " inbounds"; 1088 } 1089 } 1090 1091 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, 1092 TypePrinting &TypePrinter, 1093 SlotTracker *Machine, 1094 const Module *Context) { 1095 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1096 if (CI->getType()->isIntegerTy(1)) { 1097 Out << (CI->getZExtValue() ? "true" : "false"); 1098 return; 1099 } 1100 Out << CI->getValue(); 1101 return; 1102 } 1103 1104 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 1105 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle || 1106 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) { 1107 // We would like to output the FP constant value in exponential notation, 1108 // but we cannot do this if doing so will lose precision. Check here to 1109 // make sure that we only output it in exponential format if we can parse 1110 // the value back and get the same value. 1111 // 1112 bool ignored; 1113 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble; 1114 bool isInf = CFP->getValueAPF().isInfinity(); 1115 bool isNaN = CFP->getValueAPF().isNaN(); 1116 if (!isInf && !isNaN) { 1117 double Val = isDouble ? CFP->getValueAPF().convertToDouble() : 1118 CFP->getValueAPF().convertToFloat(); 1119 SmallString<128> StrVal; 1120 raw_svector_ostream(StrVal) << Val; 1121 1122 // Check to make sure that the stringized number is not some string like 1123 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 1124 // that the string matches the "[-+]?[0-9]" regex. 1125 // 1126 if ((StrVal[0] >= '0' && StrVal[0] <= '9') || 1127 ((StrVal[0] == '-' || StrVal[0] == '+') && 1128 (StrVal[1] >= '0' && StrVal[1] <= '9'))) { 1129 // Reparse stringized version! 1130 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) { 1131 Out << StrVal; 1132 return; 1133 } 1134 } 1135 } 1136 // Otherwise we could not reparse it to exactly the same value, so we must 1137 // output the string in hexadecimal format! Note that loading and storing 1138 // floating point types changes the bits of NaNs on some hosts, notably 1139 // x86, so we must not use these types. 1140 static_assert(sizeof(double) == sizeof(uint64_t), 1141 "assuming that double is 64 bits!"); 1142 APFloat apf = CFP->getValueAPF(); 1143 // Floats are represented in ASCII IR as double, convert. 1144 if (!isDouble) 1145 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1146 &ignored); 1147 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true); 1148 return; 1149 } 1150 1151 // Either half, or some form of long double. 1152 // These appear as a magic letter identifying the type, then a 1153 // fixed number of hex digits. 1154 Out << "0x"; 1155 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1156 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) { 1157 Out << 'K'; 1158 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4, 1159 /*Upper=*/true); 1160 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1161 /*Upper=*/true); 1162 return; 1163 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) { 1164 Out << 'L'; 1165 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1166 /*Upper=*/true); 1167 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1168 /*Upper=*/true); 1169 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) { 1170 Out << 'M'; 1171 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1172 /*Upper=*/true); 1173 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1174 /*Upper=*/true); 1175 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) { 1176 Out << 'H'; 1177 Out << format_hex_no_prefix(API.getZExtValue(), 4, 1178 /*Upper=*/true); 1179 } else 1180 llvm_unreachable("Unsupported floating point type"); 1181 return; 1182 } 1183 1184 if (isa<ConstantAggregateZero>(CV)) { 1185 Out << "zeroinitializer"; 1186 return; 1187 } 1188 1189 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 1190 Out << "blockaddress("; 1191 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine, 1192 Context); 1193 Out << ", "; 1194 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine, 1195 Context); 1196 Out << ")"; 1197 return; 1198 } 1199 1200 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 1201 Type *ETy = CA->getType()->getElementType(); 1202 Out << '['; 1203 TypePrinter.print(ETy, Out); 1204 Out << ' '; 1205 WriteAsOperandInternal(Out, CA->getOperand(0), 1206 &TypePrinter, Machine, 1207 Context); 1208 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 1209 Out << ", "; 1210 TypePrinter.print(ETy, Out); 1211 Out << ' '; 1212 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine, 1213 Context); 1214 } 1215 Out << ']'; 1216 return; 1217 } 1218 1219 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) { 1220 // As a special case, print the array as a string if it is an array of 1221 // i8 with ConstantInt values. 1222 if (CA->isString()) { 1223 Out << "c\""; 1224 PrintEscapedString(CA->getAsString(), Out); 1225 Out << '"'; 1226 return; 1227 } 1228 1229 Type *ETy = CA->getType()->getElementType(); 1230 Out << '['; 1231 TypePrinter.print(ETy, Out); 1232 Out << ' '; 1233 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), 1234 &TypePrinter, Machine, 1235 Context); 1236 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) { 1237 Out << ", "; 1238 TypePrinter.print(ETy, Out); 1239 Out << ' '; 1240 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter, 1241 Machine, Context); 1242 } 1243 Out << ']'; 1244 return; 1245 } 1246 1247 1248 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 1249 if (CS->getType()->isPacked()) 1250 Out << '<'; 1251 Out << '{'; 1252 unsigned N = CS->getNumOperands(); 1253 if (N) { 1254 Out << ' '; 1255 TypePrinter.print(CS->getOperand(0)->getType(), Out); 1256 Out << ' '; 1257 1258 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine, 1259 Context); 1260 1261 for (unsigned i = 1; i < N; i++) { 1262 Out << ", "; 1263 TypePrinter.print(CS->getOperand(i)->getType(), Out); 1264 Out << ' '; 1265 1266 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine, 1267 Context); 1268 } 1269 Out << ' '; 1270 } 1271 1272 Out << '}'; 1273 if (CS->getType()->isPacked()) 1274 Out << '>'; 1275 return; 1276 } 1277 1278 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) { 1279 Type *ETy = CV->getType()->getVectorElementType(); 1280 Out << '<'; 1281 TypePrinter.print(ETy, Out); 1282 Out << ' '; 1283 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter, 1284 Machine, Context); 1285 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){ 1286 Out << ", "; 1287 TypePrinter.print(ETy, Out); 1288 Out << ' '; 1289 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter, 1290 Machine, Context); 1291 } 1292 Out << '>'; 1293 return; 1294 } 1295 1296 if (isa<ConstantPointerNull>(CV)) { 1297 Out << "null"; 1298 return; 1299 } 1300 1301 if (isa<ConstantTokenNone>(CV)) { 1302 Out << "none"; 1303 return; 1304 } 1305 1306 if (isa<UndefValue>(CV)) { 1307 Out << "undef"; 1308 return; 1309 } 1310 1311 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1312 Out << CE->getOpcodeName(); 1313 WriteOptimizationInfo(Out, CE); 1314 if (CE->isCompare()) 1315 Out << ' ' << getPredicateText(CE->getPredicate()); 1316 Out << " ("; 1317 1318 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) { 1319 TypePrinter.print(GEP->getSourceElementType(), Out); 1320 Out << ", "; 1321 } 1322 1323 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 1324 TypePrinter.print((*OI)->getType(), Out); 1325 Out << ' '; 1326 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context); 1327 if (OI+1 != CE->op_end()) 1328 Out << ", "; 1329 } 1330 1331 if (CE->hasIndices()) { 1332 ArrayRef<unsigned> Indices = CE->getIndices(); 1333 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 1334 Out << ", " << Indices[i]; 1335 } 1336 1337 if (CE->isCast()) { 1338 Out << " to "; 1339 TypePrinter.print(CE->getType(), Out); 1340 } 1341 1342 Out << ')'; 1343 return; 1344 } 1345 1346 Out << "<placeholder or erroneous Constant>"; 1347 } 1348 1349 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, 1350 TypePrinting *TypePrinter, SlotTracker *Machine, 1351 const Module *Context) { 1352 Out << "!{"; 1353 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1354 const Metadata *MD = Node->getOperand(mi); 1355 if (!MD) 1356 Out << "null"; 1357 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) { 1358 Value *V = MDV->getValue(); 1359 TypePrinter->print(V->getType(), Out); 1360 Out << ' '; 1361 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context); 1362 } else { 1363 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1364 } 1365 if (mi + 1 != me) 1366 Out << ", "; 1367 } 1368 1369 Out << "}"; 1370 } 1371 1372 namespace { 1373 struct FieldSeparator { 1374 bool Skip; 1375 const char *Sep; 1376 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {} 1377 }; 1378 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) { 1379 if (FS.Skip) { 1380 FS.Skip = false; 1381 return OS; 1382 } 1383 return OS << FS.Sep; 1384 } 1385 struct MDFieldPrinter { 1386 raw_ostream &Out; 1387 FieldSeparator FS; 1388 TypePrinting *TypePrinter; 1389 SlotTracker *Machine; 1390 const Module *Context; 1391 1392 explicit MDFieldPrinter(raw_ostream &Out) 1393 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {} 1394 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter, 1395 SlotTracker *Machine, const Module *Context) 1396 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) { 1397 } 1398 void printTag(const DINode *N); 1399 void printString(StringRef Name, StringRef Value, 1400 bool ShouldSkipEmpty = true); 1401 void printMetadata(StringRef Name, const Metadata *MD, 1402 bool ShouldSkipNull = true); 1403 template <class IntTy> 1404 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true); 1405 void printBool(StringRef Name, bool Value); 1406 void printDIFlags(StringRef Name, unsigned Flags); 1407 template <class IntTy, class Stringifier> 1408 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString, 1409 bool ShouldSkipZero = true); 1410 }; 1411 } // end namespace 1412 1413 void MDFieldPrinter::printTag(const DINode *N) { 1414 Out << FS << "tag: "; 1415 if (const char *Tag = dwarf::TagString(N->getTag())) 1416 Out << Tag; 1417 else 1418 Out << N->getTag(); 1419 } 1420 1421 void MDFieldPrinter::printString(StringRef Name, StringRef Value, 1422 bool ShouldSkipEmpty) { 1423 if (ShouldSkipEmpty && Value.empty()) 1424 return; 1425 1426 Out << FS << Name << ": \""; 1427 PrintEscapedString(Value, Out); 1428 Out << "\""; 1429 } 1430 1431 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD, 1432 TypePrinting *TypePrinter, 1433 SlotTracker *Machine, 1434 const Module *Context) { 1435 if (!MD) { 1436 Out << "null"; 1437 return; 1438 } 1439 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1440 } 1441 1442 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD, 1443 bool ShouldSkipNull) { 1444 if (ShouldSkipNull && !MD) 1445 return; 1446 1447 Out << FS << Name << ": "; 1448 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context); 1449 } 1450 1451 template <class IntTy> 1452 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) { 1453 if (ShouldSkipZero && !Int) 1454 return; 1455 1456 Out << FS << Name << ": " << Int; 1457 } 1458 1459 void MDFieldPrinter::printBool(StringRef Name, bool Value) { 1460 Out << FS << Name << ": " << (Value ? "true" : "false"); 1461 } 1462 1463 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) { 1464 if (!Flags) 1465 return; 1466 1467 Out << FS << Name << ": "; 1468 1469 SmallVector<unsigned, 8> SplitFlags; 1470 unsigned Extra = DINode::splitFlags(Flags, SplitFlags); 1471 1472 FieldSeparator FlagsFS(" | "); 1473 for (unsigned F : SplitFlags) { 1474 const char *StringF = DINode::getFlagString(F); 1475 assert(StringF && "Expected valid flag"); 1476 Out << FlagsFS << StringF; 1477 } 1478 if (Extra || SplitFlags.empty()) 1479 Out << FlagsFS << Extra; 1480 } 1481 1482 template <class IntTy, class Stringifier> 1483 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value, 1484 Stringifier toString, bool ShouldSkipZero) { 1485 if (!Value) 1486 return; 1487 1488 Out << FS << Name << ": "; 1489 if (const char *S = toString(Value)) 1490 Out << S; 1491 else 1492 Out << Value; 1493 } 1494 1495 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, 1496 TypePrinting *TypePrinter, SlotTracker *Machine, 1497 const Module *Context) { 1498 Out << "!GenericDINode("; 1499 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1500 Printer.printTag(N); 1501 Printer.printString("header", N->getHeader()); 1502 if (N->getNumDwarfOperands()) { 1503 Out << Printer.FS << "operands: {"; 1504 FieldSeparator IFS; 1505 for (auto &I : N->dwarf_operands()) { 1506 Out << IFS; 1507 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context); 1508 } 1509 Out << "}"; 1510 } 1511 Out << ")"; 1512 } 1513 1514 static void writeDILocation(raw_ostream &Out, const DILocation *DL, 1515 TypePrinting *TypePrinter, SlotTracker *Machine, 1516 const Module *Context) { 1517 Out << "!DILocation("; 1518 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1519 // Always output the line, since 0 is a relevant and important value for it. 1520 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false); 1521 Printer.printInt("column", DL->getColumn()); 1522 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false); 1523 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt()); 1524 Out << ")"; 1525 } 1526 1527 static void writeDISubrange(raw_ostream &Out, const DISubrange *N, 1528 TypePrinting *, SlotTracker *, const Module *) { 1529 Out << "!DISubrange("; 1530 MDFieldPrinter Printer(Out); 1531 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false); 1532 Printer.printInt("lowerBound", N->getLowerBound()); 1533 Out << ")"; 1534 } 1535 1536 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, 1537 TypePrinting *, SlotTracker *, const Module *) { 1538 Out << "!DIEnumerator("; 1539 MDFieldPrinter Printer(Out); 1540 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false); 1541 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false); 1542 Out << ")"; 1543 } 1544 1545 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, 1546 TypePrinting *, SlotTracker *, const Module *) { 1547 Out << "!DIBasicType("; 1548 MDFieldPrinter Printer(Out); 1549 if (N->getTag() != dwarf::DW_TAG_base_type) 1550 Printer.printTag(N); 1551 Printer.printString("name", N->getName()); 1552 Printer.printInt("size", N->getSizeInBits()); 1553 Printer.printInt("align", N->getAlignInBits()); 1554 Printer.printDwarfEnum("encoding", N->getEncoding(), 1555 dwarf::AttributeEncodingString); 1556 Out << ")"; 1557 } 1558 1559 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, 1560 TypePrinting *TypePrinter, SlotTracker *Machine, 1561 const Module *Context) { 1562 Out << "!DIDerivedType("; 1563 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1564 Printer.printTag(N); 1565 Printer.printString("name", N->getName()); 1566 Printer.printMetadata("scope", N->getRawScope()); 1567 Printer.printMetadata("file", N->getRawFile()); 1568 Printer.printInt("line", N->getLine()); 1569 Printer.printMetadata("baseType", N->getRawBaseType(), 1570 /* ShouldSkipNull */ false); 1571 Printer.printInt("size", N->getSizeInBits()); 1572 Printer.printInt("align", N->getAlignInBits()); 1573 Printer.printInt("offset", N->getOffsetInBits()); 1574 Printer.printDIFlags("flags", N->getFlags()); 1575 Printer.printMetadata("extraData", N->getRawExtraData()); 1576 Out << ")"; 1577 } 1578 1579 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, 1580 TypePrinting *TypePrinter, 1581 SlotTracker *Machine, const Module *Context) { 1582 Out << "!DICompositeType("; 1583 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1584 Printer.printTag(N); 1585 Printer.printString("name", N->getName()); 1586 Printer.printMetadata("scope", N->getRawScope()); 1587 Printer.printMetadata("file", N->getRawFile()); 1588 Printer.printInt("line", N->getLine()); 1589 Printer.printMetadata("baseType", N->getRawBaseType()); 1590 Printer.printInt("size", N->getSizeInBits()); 1591 Printer.printInt("align", N->getAlignInBits()); 1592 Printer.printInt("offset", N->getOffsetInBits()); 1593 Printer.printDIFlags("flags", N->getFlags()); 1594 Printer.printMetadata("elements", N->getRawElements()); 1595 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(), 1596 dwarf::LanguageString); 1597 Printer.printMetadata("vtableHolder", N->getRawVTableHolder()); 1598 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 1599 Printer.printString("identifier", N->getIdentifier()); 1600 Out << ")"; 1601 } 1602 1603 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, 1604 TypePrinting *TypePrinter, 1605 SlotTracker *Machine, const Module *Context) { 1606 Out << "!DISubroutineType("; 1607 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1608 Printer.printDIFlags("flags", N->getFlags()); 1609 Printer.printMetadata("types", N->getRawTypeArray(), 1610 /* ShouldSkipNull */ false); 1611 Out << ")"; 1612 } 1613 1614 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *, 1615 SlotTracker *, const Module *) { 1616 Out << "!DIFile("; 1617 MDFieldPrinter Printer(Out); 1618 Printer.printString("filename", N->getFilename(), 1619 /* ShouldSkipEmpty */ false); 1620 Printer.printString("directory", N->getDirectory(), 1621 /* ShouldSkipEmpty */ false); 1622 Out << ")"; 1623 } 1624 1625 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, 1626 TypePrinting *TypePrinter, SlotTracker *Machine, 1627 const Module *Context) { 1628 Out << "!DICompileUnit("; 1629 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1630 Printer.printDwarfEnum("language", N->getSourceLanguage(), 1631 dwarf::LanguageString, /* ShouldSkipZero */ false); 1632 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 1633 Printer.printString("producer", N->getProducer()); 1634 Printer.printBool("isOptimized", N->isOptimized()); 1635 Printer.printString("flags", N->getFlags()); 1636 Printer.printInt("runtimeVersion", N->getRuntimeVersion(), 1637 /* ShouldSkipZero */ false); 1638 Printer.printString("splitDebugFilename", N->getSplitDebugFilename()); 1639 Printer.printInt("emissionKind", N->getEmissionKind(), 1640 /* ShouldSkipZero */ false); 1641 Printer.printMetadata("enums", N->getRawEnumTypes()); 1642 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes()); 1643 Printer.printMetadata("subprograms", N->getRawSubprograms()); 1644 Printer.printMetadata("globals", N->getRawGlobalVariables()); 1645 Printer.printMetadata("imports", N->getRawImportedEntities()); 1646 Printer.printInt("dwoId", N->getDWOId()); 1647 Out << ")"; 1648 } 1649 1650 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, 1651 TypePrinting *TypePrinter, SlotTracker *Machine, 1652 const Module *Context) { 1653 Out << "!DISubprogram("; 1654 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1655 Printer.printString("name", N->getName()); 1656 Printer.printString("linkageName", N->getLinkageName()); 1657 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1658 Printer.printMetadata("file", N->getRawFile()); 1659 Printer.printInt("line", N->getLine()); 1660 Printer.printMetadata("type", N->getRawType()); 1661 Printer.printBool("isLocal", N->isLocalToUnit()); 1662 Printer.printBool("isDefinition", N->isDefinition()); 1663 Printer.printInt("scopeLine", N->getScopeLine()); 1664 Printer.printMetadata("containingType", N->getRawContainingType()); 1665 Printer.printDwarfEnum("virtuality", N->getVirtuality(), 1666 dwarf::VirtualityString); 1667 Printer.printInt("virtualIndex", N->getVirtualIndex()); 1668 Printer.printDIFlags("flags", N->getFlags()); 1669 Printer.printBool("isOptimized", N->isOptimized()); 1670 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 1671 Printer.printMetadata("declaration", N->getRawDeclaration()); 1672 Printer.printMetadata("variables", N->getRawVariables()); 1673 Out << ")"; 1674 } 1675 1676 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, 1677 TypePrinting *TypePrinter, SlotTracker *Machine, 1678 const Module *Context) { 1679 Out << "!DILexicalBlock("; 1680 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1681 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1682 Printer.printMetadata("file", N->getRawFile()); 1683 Printer.printInt("line", N->getLine()); 1684 Printer.printInt("column", N->getColumn()); 1685 Out << ")"; 1686 } 1687 1688 static void writeDILexicalBlockFile(raw_ostream &Out, 1689 const DILexicalBlockFile *N, 1690 TypePrinting *TypePrinter, 1691 SlotTracker *Machine, 1692 const Module *Context) { 1693 Out << "!DILexicalBlockFile("; 1694 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1695 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1696 Printer.printMetadata("file", N->getRawFile()); 1697 Printer.printInt("discriminator", N->getDiscriminator(), 1698 /* ShouldSkipZero */ false); 1699 Out << ")"; 1700 } 1701 1702 static void writeDINamespace(raw_ostream &Out, const DINamespace *N, 1703 TypePrinting *TypePrinter, SlotTracker *Machine, 1704 const Module *Context) { 1705 Out << "!DINamespace("; 1706 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1707 Printer.printString("name", N->getName()); 1708 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1709 Printer.printMetadata("file", N->getRawFile()); 1710 Printer.printInt("line", N->getLine()); 1711 Out << ")"; 1712 } 1713 1714 static void writeDIModule(raw_ostream &Out, const DIModule *N, 1715 TypePrinting *TypePrinter, SlotTracker *Machine, 1716 const Module *Context) { 1717 Out << "!DIModule("; 1718 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1719 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1720 Printer.printString("name", N->getName()); 1721 Printer.printString("configMacros", N->getConfigurationMacros()); 1722 Printer.printString("includePath", N->getIncludePath()); 1723 Printer.printString("isysroot", N->getISysRoot()); 1724 Out << ")"; 1725 } 1726 1727 1728 static void writeDITemplateTypeParameter(raw_ostream &Out, 1729 const DITemplateTypeParameter *N, 1730 TypePrinting *TypePrinter, 1731 SlotTracker *Machine, 1732 const Module *Context) { 1733 Out << "!DITemplateTypeParameter("; 1734 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1735 Printer.printString("name", N->getName()); 1736 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false); 1737 Out << ")"; 1738 } 1739 1740 static void writeDITemplateValueParameter(raw_ostream &Out, 1741 const DITemplateValueParameter *N, 1742 TypePrinting *TypePrinter, 1743 SlotTracker *Machine, 1744 const Module *Context) { 1745 Out << "!DITemplateValueParameter("; 1746 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1747 if (N->getTag() != dwarf::DW_TAG_template_value_parameter) 1748 Printer.printTag(N); 1749 Printer.printString("name", N->getName()); 1750 Printer.printMetadata("type", N->getRawType()); 1751 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false); 1752 Out << ")"; 1753 } 1754 1755 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, 1756 TypePrinting *TypePrinter, 1757 SlotTracker *Machine, const Module *Context) { 1758 Out << "!DIGlobalVariable("; 1759 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1760 Printer.printString("name", N->getName()); 1761 Printer.printString("linkageName", N->getLinkageName()); 1762 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1763 Printer.printMetadata("file", N->getRawFile()); 1764 Printer.printInt("line", N->getLine()); 1765 Printer.printMetadata("type", N->getRawType()); 1766 Printer.printBool("isLocal", N->isLocalToUnit()); 1767 Printer.printBool("isDefinition", N->isDefinition()); 1768 Printer.printMetadata("variable", N->getRawVariable()); 1769 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration()); 1770 Out << ")"; 1771 } 1772 1773 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, 1774 TypePrinting *TypePrinter, 1775 SlotTracker *Machine, const Module *Context) { 1776 Out << "!DILocalVariable("; 1777 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1778 Printer.printString("name", N->getName()); 1779 Printer.printInt("arg", N->getArg()); 1780 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1781 Printer.printMetadata("file", N->getRawFile()); 1782 Printer.printInt("line", N->getLine()); 1783 Printer.printMetadata("type", N->getRawType()); 1784 Printer.printDIFlags("flags", N->getFlags()); 1785 Out << ")"; 1786 } 1787 1788 static void writeDIExpression(raw_ostream &Out, const DIExpression *N, 1789 TypePrinting *TypePrinter, SlotTracker *Machine, 1790 const Module *Context) { 1791 Out << "!DIExpression("; 1792 FieldSeparator FS; 1793 if (N->isValid()) { 1794 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) { 1795 const char *OpStr = dwarf::OperationEncodingString(I->getOp()); 1796 assert(OpStr && "Expected valid opcode"); 1797 1798 Out << FS << OpStr; 1799 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A) 1800 Out << FS << I->getArg(A); 1801 } 1802 } else { 1803 for (const auto &I : N->getElements()) 1804 Out << FS << I; 1805 } 1806 Out << ")"; 1807 } 1808 1809 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, 1810 TypePrinting *TypePrinter, SlotTracker *Machine, 1811 const Module *Context) { 1812 Out << "!DIObjCProperty("; 1813 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1814 Printer.printString("name", N->getName()); 1815 Printer.printMetadata("file", N->getRawFile()); 1816 Printer.printInt("line", N->getLine()); 1817 Printer.printString("setter", N->getSetterName()); 1818 Printer.printString("getter", N->getGetterName()); 1819 Printer.printInt("attributes", N->getAttributes()); 1820 Printer.printMetadata("type", N->getRawType()); 1821 Out << ")"; 1822 } 1823 1824 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, 1825 TypePrinting *TypePrinter, 1826 SlotTracker *Machine, const Module *Context) { 1827 Out << "!DIImportedEntity("; 1828 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1829 Printer.printTag(N); 1830 Printer.printString("name", N->getName()); 1831 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1832 Printer.printMetadata("entity", N->getRawEntity()); 1833 Printer.printInt("line", N->getLine()); 1834 Out << ")"; 1835 } 1836 1837 1838 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 1839 TypePrinting *TypePrinter, 1840 SlotTracker *Machine, 1841 const Module *Context) { 1842 if (Node->isDistinct()) 1843 Out << "distinct "; 1844 else if (Node->isTemporary()) 1845 Out << "<temporary!> "; // Handle broken code. 1846 1847 switch (Node->getMetadataID()) { 1848 default: 1849 llvm_unreachable("Expected uniquable MDNode"); 1850 #define HANDLE_MDNODE_LEAF(CLASS) \ 1851 case Metadata::CLASS##Kind: \ 1852 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \ 1853 break; 1854 #include "llvm/IR/Metadata.def" 1855 } 1856 } 1857 1858 // Full implementation of printing a Value as an operand with support for 1859 // TypePrinting, etc. 1860 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 1861 TypePrinting *TypePrinter, 1862 SlotTracker *Machine, 1863 const Module *Context) { 1864 if (V->hasName()) { 1865 PrintLLVMName(Out, V); 1866 return; 1867 } 1868 1869 const Constant *CV = dyn_cast<Constant>(V); 1870 if (CV && !isa<GlobalValue>(CV)) { 1871 assert(TypePrinter && "Constants require TypePrinting!"); 1872 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context); 1873 return; 1874 } 1875 1876 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 1877 Out << "asm "; 1878 if (IA->hasSideEffects()) 1879 Out << "sideeffect "; 1880 if (IA->isAlignStack()) 1881 Out << "alignstack "; 1882 // We don't emit the AD_ATT dialect as it's the assumed default. 1883 if (IA->getDialect() == InlineAsm::AD_Intel) 1884 Out << "inteldialect "; 1885 Out << '"'; 1886 PrintEscapedString(IA->getAsmString(), Out); 1887 Out << "\", \""; 1888 PrintEscapedString(IA->getConstraintString(), Out); 1889 Out << '"'; 1890 return; 1891 } 1892 1893 if (auto *MD = dyn_cast<MetadataAsValue>(V)) { 1894 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine, 1895 Context, /* FromValue */ true); 1896 return; 1897 } 1898 1899 char Prefix = '%'; 1900 int Slot; 1901 // If we have a SlotTracker, use it. 1902 if (Machine) { 1903 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1904 Slot = Machine->getGlobalSlot(GV); 1905 Prefix = '@'; 1906 } else { 1907 Slot = Machine->getLocalSlot(V); 1908 1909 // If the local value didn't succeed, then we may be referring to a value 1910 // from a different function. Translate it, as this can happen when using 1911 // address of blocks. 1912 if (Slot == -1) 1913 if ((Machine = createSlotTracker(V))) { 1914 Slot = Machine->getLocalSlot(V); 1915 delete Machine; 1916 } 1917 } 1918 } else if ((Machine = createSlotTracker(V))) { 1919 // Otherwise, create one to get the # and then destroy it. 1920 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1921 Slot = Machine->getGlobalSlot(GV); 1922 Prefix = '@'; 1923 } else { 1924 Slot = Machine->getLocalSlot(V); 1925 } 1926 delete Machine; 1927 Machine = nullptr; 1928 } else { 1929 Slot = -1; 1930 } 1931 1932 if (Slot != -1) 1933 Out << Prefix << Slot; 1934 else 1935 Out << "<badref>"; 1936 } 1937 1938 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 1939 TypePrinting *TypePrinter, 1940 SlotTracker *Machine, const Module *Context, 1941 bool FromValue) { 1942 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 1943 std::unique_ptr<SlotTracker> MachineStorage; 1944 if (!Machine) { 1945 MachineStorage = make_unique<SlotTracker>(Context); 1946 Machine = MachineStorage.get(); 1947 } 1948 int Slot = Machine->getMetadataSlot(N); 1949 if (Slot == -1) 1950 // Give the pointer value instead of "badref", since this comes up all 1951 // the time when debugging. 1952 Out << "<" << N << ">"; 1953 else 1954 Out << '!' << Slot; 1955 return; 1956 } 1957 1958 if (const MDString *MDS = dyn_cast<MDString>(MD)) { 1959 Out << "!\""; 1960 PrintEscapedString(MDS->getString(), Out); 1961 Out << '"'; 1962 return; 1963 } 1964 1965 auto *V = cast<ValueAsMetadata>(MD); 1966 assert(TypePrinter && "TypePrinter required for metadata values"); 1967 assert((FromValue || !isa<LocalAsMetadata>(V)) && 1968 "Unexpected function-local metadata outside of value argument"); 1969 1970 TypePrinter->print(V->getValue()->getType(), Out); 1971 Out << ' '; 1972 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context); 1973 } 1974 1975 namespace { 1976 class AssemblyWriter { 1977 formatted_raw_ostream &Out; 1978 const Module *TheModule; 1979 std::unique_ptr<SlotTracker> SlotTrackerStorage; 1980 SlotTracker &Machine; 1981 TypePrinting TypePrinter; 1982 AssemblyAnnotationWriter *AnnotationWriter; 1983 SetVector<const Comdat *> Comdats; 1984 bool IsForDebug; 1985 bool ShouldPreserveUseListOrder; 1986 UseListOrderStack UseListOrders; 1987 SmallVector<StringRef, 8> MDNames; 1988 1989 public: 1990 /// Construct an AssemblyWriter with an external SlotTracker 1991 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, 1992 AssemblyAnnotationWriter *AAW, bool IsForDebug, 1993 bool ShouldPreserveUseListOrder = false); 1994 1995 void printMDNodeBody(const MDNode *MD); 1996 void printNamedMDNode(const NamedMDNode *NMD); 1997 1998 void printModule(const Module *M); 1999 2000 void writeOperand(const Value *Op, bool PrintType); 2001 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx); 2002 void writeOperandBundles(ImmutableCallSite CS); 2003 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope); 2004 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering, 2005 AtomicOrdering FailureOrdering, 2006 SynchronizationScope SynchScope); 2007 2008 void writeAllMDNodes(); 2009 void writeMDNode(unsigned Slot, const MDNode *Node); 2010 void writeAllAttributeGroups(); 2011 2012 void printTypeIdentities(); 2013 void printGlobal(const GlobalVariable *GV); 2014 void printAlias(const GlobalAlias *GV); 2015 void printComdat(const Comdat *C); 2016 void printFunction(const Function *F); 2017 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx); 2018 void printBasicBlock(const BasicBlock *BB); 2019 void printInstructionLine(const Instruction &I); 2020 void printInstruction(const Instruction &I); 2021 2022 void printUseListOrder(const UseListOrder &Order); 2023 void printUseLists(const Function *F); 2024 2025 private: 2026 /// \brief Print out metadata attachments. 2027 void printMetadataAttachments( 2028 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 2029 StringRef Separator); 2030 2031 // printInfoComment - Print a little comment after the instruction indicating 2032 // which slot it occupies. 2033 void printInfoComment(const Value &V); 2034 2035 // printGCRelocateComment - print comment after call to the gc.relocate 2036 // intrinsic indicating base and derived pointer names. 2037 void printGCRelocateComment(const Value &V); 2038 }; 2039 } // namespace 2040 2041 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2042 const Module *M, AssemblyAnnotationWriter *AAW, 2043 bool IsForDebug, bool ShouldPreserveUseListOrder) 2044 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW), 2045 IsForDebug(IsForDebug), 2046 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 2047 if (!TheModule) 2048 return; 2049 TypePrinter.incorporateTypes(*TheModule); 2050 for (const Function &F : *TheModule) 2051 if (const Comdat *C = F.getComdat()) 2052 Comdats.insert(C); 2053 for (const GlobalVariable &GV : TheModule->globals()) 2054 if (const Comdat *C = GV.getComdat()) 2055 Comdats.insert(C); 2056 } 2057 2058 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 2059 if (!Operand) { 2060 Out << "<null operand!>"; 2061 return; 2062 } 2063 if (PrintType) { 2064 TypePrinter.print(Operand->getType(), Out); 2065 Out << ' '; 2066 } 2067 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2068 } 2069 2070 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering, 2071 SynchronizationScope SynchScope) { 2072 if (Ordering == NotAtomic) 2073 return; 2074 2075 switch (SynchScope) { 2076 case SingleThread: Out << " singlethread"; break; 2077 case CrossThread: break; 2078 } 2079 2080 switch (Ordering) { 2081 default: Out << " <bad ordering " << int(Ordering) << ">"; break; 2082 case Unordered: Out << " unordered"; break; 2083 case Monotonic: Out << " monotonic"; break; 2084 case Acquire: Out << " acquire"; break; 2085 case Release: Out << " release"; break; 2086 case AcquireRelease: Out << " acq_rel"; break; 2087 case SequentiallyConsistent: Out << " seq_cst"; break; 2088 } 2089 } 2090 2091 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering, 2092 AtomicOrdering FailureOrdering, 2093 SynchronizationScope SynchScope) { 2094 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic); 2095 2096 switch (SynchScope) { 2097 case SingleThread: Out << " singlethread"; break; 2098 case CrossThread: break; 2099 } 2100 2101 switch (SuccessOrdering) { 2102 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break; 2103 case Unordered: Out << " unordered"; break; 2104 case Monotonic: Out << " monotonic"; break; 2105 case Acquire: Out << " acquire"; break; 2106 case Release: Out << " release"; break; 2107 case AcquireRelease: Out << " acq_rel"; break; 2108 case SequentiallyConsistent: Out << " seq_cst"; break; 2109 } 2110 2111 switch (FailureOrdering) { 2112 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break; 2113 case Unordered: Out << " unordered"; break; 2114 case Monotonic: Out << " monotonic"; break; 2115 case Acquire: Out << " acquire"; break; 2116 case Release: Out << " release"; break; 2117 case AcquireRelease: Out << " acq_rel"; break; 2118 case SequentiallyConsistent: Out << " seq_cst"; break; 2119 } 2120 } 2121 2122 void AssemblyWriter::writeParamOperand(const Value *Operand, 2123 AttributeSet Attrs, unsigned Idx) { 2124 if (!Operand) { 2125 Out << "<null operand!>"; 2126 return; 2127 } 2128 2129 // Print the type 2130 TypePrinter.print(Operand->getType(), Out); 2131 // Print parameter attributes list 2132 if (Attrs.hasAttributes(Idx)) 2133 Out << ' ' << Attrs.getAsString(Idx); 2134 Out << ' '; 2135 // Print the operand 2136 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2137 } 2138 2139 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) { 2140 if (!CS.hasOperandBundles()) 2141 return; 2142 2143 Out << " [ "; 2144 2145 bool FirstBundle = true; 2146 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2147 OperandBundleUse BU = CS.getOperandBundleAt(i); 2148 2149 if (!FirstBundle) 2150 Out << ", "; 2151 FirstBundle = false; 2152 2153 Out << '"'; 2154 PrintEscapedString(BU.getTagName(), Out); 2155 Out << '"'; 2156 2157 Out << '('; 2158 2159 bool FirstInput = true; 2160 for (const auto &Input : BU.Inputs) { 2161 if (!FirstInput) 2162 Out << ", "; 2163 FirstInput = false; 2164 2165 TypePrinter.print(Input->getType(), Out); 2166 Out << " "; 2167 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule); 2168 } 2169 2170 Out << ')'; 2171 } 2172 2173 Out << " ]"; 2174 } 2175 2176 void AssemblyWriter::printModule(const Module *M) { 2177 Machine.initialize(); 2178 2179 if (ShouldPreserveUseListOrder) 2180 UseListOrders = predictUseListOrder(M); 2181 2182 if (!M->getModuleIdentifier().empty() && 2183 // Don't print the ID if it will start a new line (which would 2184 // require a comment char before it). 2185 M->getModuleIdentifier().find('\n') == std::string::npos) 2186 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 2187 2188 const std::string &DL = M->getDataLayoutStr(); 2189 if (!DL.empty()) 2190 Out << "target datalayout = \"" << DL << "\"\n"; 2191 if (!M->getTargetTriple().empty()) 2192 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 2193 2194 if (!M->getModuleInlineAsm().empty()) { 2195 Out << '\n'; 2196 2197 // Split the string into lines, to make it easier to read the .ll file. 2198 StringRef Asm = M->getModuleInlineAsm(); 2199 do { 2200 StringRef Front; 2201 std::tie(Front, Asm) = Asm.split('\n'); 2202 2203 // We found a newline, print the portion of the asm string from the 2204 // last newline up to this newline. 2205 Out << "module asm \""; 2206 PrintEscapedString(Front, Out); 2207 Out << "\"\n"; 2208 } while (!Asm.empty()); 2209 } 2210 2211 printTypeIdentities(); 2212 2213 // Output all comdats. 2214 if (!Comdats.empty()) 2215 Out << '\n'; 2216 for (const Comdat *C : Comdats) { 2217 printComdat(C); 2218 if (C != Comdats.back()) 2219 Out << '\n'; 2220 } 2221 2222 // Output all globals. 2223 if (!M->global_empty()) Out << '\n'; 2224 for (const GlobalVariable &GV : M->globals()) { 2225 printGlobal(&GV); Out << '\n'; 2226 } 2227 2228 // Output all aliases. 2229 if (!M->alias_empty()) Out << "\n"; 2230 for (const GlobalAlias &GA : M->aliases()) 2231 printAlias(&GA); 2232 2233 // Output global use-lists. 2234 printUseLists(nullptr); 2235 2236 // Output all of the functions. 2237 for (const Function &F : *M) 2238 printFunction(&F); 2239 assert(UseListOrders.empty() && "All use-lists should have been consumed"); 2240 2241 // Output all attribute groups. 2242 if (!Machine.as_empty()) { 2243 Out << '\n'; 2244 writeAllAttributeGroups(); 2245 } 2246 2247 // Output named metadata. 2248 if (!M->named_metadata_empty()) Out << '\n'; 2249 2250 for (const NamedMDNode &Node : M->named_metadata()) 2251 printNamedMDNode(&Node); 2252 2253 // Output metadata. 2254 if (!Machine.mdn_empty()) { 2255 Out << '\n'; 2256 writeAllMDNodes(); 2257 } 2258 } 2259 2260 static void printMetadataIdentifier(StringRef Name, 2261 formatted_raw_ostream &Out) { 2262 if (Name.empty()) { 2263 Out << "<empty name> "; 2264 } else { 2265 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' || 2266 Name[0] == '$' || Name[0] == '.' || Name[0] == '_') 2267 Out << Name[0]; 2268 else 2269 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 2270 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 2271 unsigned char C = Name[i]; 2272 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 2273 C == '.' || C == '_') 2274 Out << C; 2275 else 2276 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 2277 } 2278 } 2279 } 2280 2281 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 2282 Out << '!'; 2283 printMetadataIdentifier(NMD->getName(), Out); 2284 Out << " = !{"; 2285 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2286 if (i) 2287 Out << ", "; 2288 int Slot = Machine.getMetadataSlot(NMD->getOperand(i)); 2289 if (Slot == -1) 2290 Out << "<badref>"; 2291 else 2292 Out << '!' << Slot; 2293 } 2294 Out << "}\n"; 2295 } 2296 2297 static void PrintLinkage(GlobalValue::LinkageTypes LT, 2298 formatted_raw_ostream &Out) { 2299 switch (LT) { 2300 case GlobalValue::ExternalLinkage: break; 2301 case GlobalValue::PrivateLinkage: Out << "private "; break; 2302 case GlobalValue::InternalLinkage: Out << "internal "; break; 2303 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break; 2304 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break; 2305 case GlobalValue::WeakAnyLinkage: Out << "weak "; break; 2306 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break; 2307 case GlobalValue::CommonLinkage: Out << "common "; break; 2308 case GlobalValue::AppendingLinkage: Out << "appending "; break; 2309 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break; 2310 case GlobalValue::AvailableExternallyLinkage: 2311 Out << "available_externally "; 2312 break; 2313 } 2314 } 2315 2316 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 2317 formatted_raw_ostream &Out) { 2318 switch (Vis) { 2319 case GlobalValue::DefaultVisibility: break; 2320 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 2321 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 2322 } 2323 } 2324 2325 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 2326 formatted_raw_ostream &Out) { 2327 switch (SCT) { 2328 case GlobalValue::DefaultStorageClass: break; 2329 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 2330 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 2331 } 2332 } 2333 2334 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 2335 formatted_raw_ostream &Out) { 2336 switch (TLM) { 2337 case GlobalVariable::NotThreadLocal: 2338 break; 2339 case GlobalVariable::GeneralDynamicTLSModel: 2340 Out << "thread_local "; 2341 break; 2342 case GlobalVariable::LocalDynamicTLSModel: 2343 Out << "thread_local(localdynamic) "; 2344 break; 2345 case GlobalVariable::InitialExecTLSModel: 2346 Out << "thread_local(initialexec) "; 2347 break; 2348 case GlobalVariable::LocalExecTLSModel: 2349 Out << "thread_local(localexec) "; 2350 break; 2351 } 2352 } 2353 2354 static void maybePrintComdat(formatted_raw_ostream &Out, 2355 const GlobalObject &GO) { 2356 const Comdat *C = GO.getComdat(); 2357 if (!C) 2358 return; 2359 2360 if (isa<GlobalVariable>(GO)) 2361 Out << ','; 2362 Out << " comdat"; 2363 2364 if (GO.getName() == C->getName()) 2365 return; 2366 2367 Out << '('; 2368 PrintLLVMName(Out, C->getName(), ComdatPrefix); 2369 Out << ')'; 2370 } 2371 2372 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 2373 if (GV->isMaterializable()) 2374 Out << "; Materializable\n"; 2375 2376 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent()); 2377 Out << " = "; 2378 2379 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 2380 Out << "external "; 2381 2382 PrintLinkage(GV->getLinkage(), Out); 2383 PrintVisibility(GV->getVisibility(), Out); 2384 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 2385 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 2386 if (GV->hasUnnamedAddr()) 2387 Out << "unnamed_addr "; 2388 2389 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 2390 Out << "addrspace(" << AddressSpace << ") "; 2391 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 2392 Out << (GV->isConstant() ? "constant " : "global "); 2393 TypePrinter.print(GV->getType()->getElementType(), Out); 2394 2395 if (GV->hasInitializer()) { 2396 Out << ' '; 2397 writeOperand(GV->getInitializer(), false); 2398 } 2399 2400 if (GV->hasSection()) { 2401 Out << ", section \""; 2402 PrintEscapedString(GV->getSection(), Out); 2403 Out << '"'; 2404 } 2405 maybePrintComdat(Out, *GV); 2406 if (GV->getAlignment()) 2407 Out << ", align " << GV->getAlignment(); 2408 2409 printInfoComment(*GV); 2410 } 2411 2412 void AssemblyWriter::printAlias(const GlobalAlias *GA) { 2413 if (GA->isMaterializable()) 2414 Out << "; Materializable\n"; 2415 2416 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent()); 2417 Out << " = "; 2418 2419 PrintLinkage(GA->getLinkage(), Out); 2420 PrintVisibility(GA->getVisibility(), Out); 2421 PrintDLLStorageClass(GA->getDLLStorageClass(), Out); 2422 PrintThreadLocalModel(GA->getThreadLocalMode(), Out); 2423 if (GA->hasUnnamedAddr()) 2424 Out << "unnamed_addr "; 2425 2426 Out << "alias "; 2427 2428 TypePrinter.print(GA->getValueType(), Out); 2429 2430 Out << ", "; 2431 2432 const Constant *Aliasee = GA->getAliasee(); 2433 2434 if (!Aliasee) { 2435 TypePrinter.print(GA->getType(), Out); 2436 Out << " <<NULL ALIASEE>>"; 2437 } else { 2438 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee)); 2439 } 2440 2441 printInfoComment(*GA); 2442 Out << '\n'; 2443 } 2444 2445 void AssemblyWriter::printComdat(const Comdat *C) { 2446 C->print(Out); 2447 } 2448 2449 void AssemblyWriter::printTypeIdentities() { 2450 if (TypePrinter.NumberedTypes.empty() && 2451 TypePrinter.NamedTypes.empty()) 2452 return; 2453 2454 Out << '\n'; 2455 2456 // We know all the numbers that each type is used and we know that it is a 2457 // dense assignment. Convert the map to an index table. 2458 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size()); 2459 for (DenseMap<StructType*, unsigned>::iterator I = 2460 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end(); 2461 I != E; ++I) { 2462 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?"); 2463 NumberedTypes[I->second] = I->first; 2464 } 2465 2466 // Emit all numbered types. 2467 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 2468 Out << '%' << i << " = type "; 2469 2470 // Make sure we print out at least one level of the type structure, so 2471 // that we do not get %2 = type %2 2472 TypePrinter.printStructBody(NumberedTypes[i], Out); 2473 Out << '\n'; 2474 } 2475 2476 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) { 2477 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix); 2478 Out << " = type "; 2479 2480 // Make sure we print out at least one level of the type structure, so 2481 // that we do not get %FILE = type %FILE 2482 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out); 2483 Out << '\n'; 2484 } 2485 } 2486 2487 /// printFunction - Print all aspects of a function. 2488 /// 2489 void AssemblyWriter::printFunction(const Function *F) { 2490 // Print out the return type and name. 2491 Out << '\n'; 2492 2493 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 2494 2495 if (F->isMaterializable()) 2496 Out << "; Materializable\n"; 2497 2498 const AttributeSet &Attrs = F->getAttributes(); 2499 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) { 2500 AttributeSet AS = Attrs.getFnAttributes(); 2501 std::string AttrStr; 2502 2503 unsigned Idx = 0; 2504 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx) 2505 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex) 2506 break; 2507 2508 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx); 2509 I != E; ++I) { 2510 Attribute Attr = *I; 2511 if (!Attr.isStringAttribute()) { 2512 if (!AttrStr.empty()) AttrStr += ' '; 2513 AttrStr += Attr.getAsString(); 2514 } 2515 } 2516 2517 if (!AttrStr.empty()) 2518 Out << "; Function Attrs: " << AttrStr << '\n'; 2519 } 2520 2521 if (F->isDeclaration()) 2522 Out << "declare "; 2523 else 2524 Out << "define "; 2525 2526 PrintLinkage(F->getLinkage(), Out); 2527 PrintVisibility(F->getVisibility(), Out); 2528 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 2529 2530 // Print the calling convention. 2531 if (F->getCallingConv() != CallingConv::C) { 2532 PrintCallingConv(F->getCallingConv(), Out); 2533 Out << " "; 2534 } 2535 2536 FunctionType *FT = F->getFunctionType(); 2537 if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) 2538 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' '; 2539 TypePrinter.print(F->getReturnType(), Out); 2540 Out << ' '; 2541 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 2542 Out << '('; 2543 Machine.incorporateFunction(F); 2544 2545 // Loop over the arguments, printing them... 2546 if (F->isDeclaration() && !IsForDebug) { 2547 // We're only interested in the type here - don't print argument names. 2548 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) { 2549 // Insert commas as we go... the first arg doesn't get a comma 2550 if (I) 2551 Out << ", "; 2552 // Output type... 2553 TypePrinter.print(FT->getParamType(I), Out); 2554 2555 if (Attrs.hasAttributes(I + 1)) 2556 Out << ' ' << Attrs.getAsString(I + 1); 2557 } 2558 } else { 2559 // The arguments are meaningful here, print them in detail. 2560 unsigned Idx = 1; 2561 for (const Argument &Arg : F->args()) { 2562 // Insert commas as we go... the first arg doesn't get a comma 2563 if (Idx != 1) 2564 Out << ", "; 2565 printArgument(&Arg, Attrs, Idx++); 2566 } 2567 } 2568 2569 // Finish printing arguments... 2570 if (FT->isVarArg()) { 2571 if (FT->getNumParams()) Out << ", "; 2572 Out << "..."; // Output varargs portion of signature! 2573 } 2574 Out << ')'; 2575 if (F->hasUnnamedAddr()) 2576 Out << " unnamed_addr"; 2577 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 2578 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes()); 2579 if (F->hasSection()) { 2580 Out << " section \""; 2581 PrintEscapedString(F->getSection(), Out); 2582 Out << '"'; 2583 } 2584 maybePrintComdat(Out, *F); 2585 if (F->getAlignment()) 2586 Out << " align " << F->getAlignment(); 2587 if (F->hasGC()) 2588 Out << " gc \"" << F->getGC() << '"'; 2589 if (F->hasPrefixData()) { 2590 Out << " prefix "; 2591 writeOperand(F->getPrefixData(), true); 2592 } 2593 if (F->hasPrologueData()) { 2594 Out << " prologue "; 2595 writeOperand(F->getPrologueData(), true); 2596 } 2597 if (F->hasPersonalityFn()) { 2598 Out << " personality "; 2599 writeOperand(F->getPersonalityFn(), /*PrintType=*/true); 2600 } 2601 2602 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2603 F->getAllMetadata(MDs); 2604 printMetadataAttachments(MDs, " "); 2605 2606 if (F->isDeclaration()) { 2607 Out << '\n'; 2608 } else { 2609 Out << " {"; 2610 // Output all of the function's basic blocks. 2611 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I) 2612 printBasicBlock(&*I); 2613 2614 // Output the function's use-lists. 2615 printUseLists(F); 2616 2617 Out << "}\n"; 2618 } 2619 2620 Machine.purgeFunction(); 2621 } 2622 2623 /// printArgument - This member is called for every argument that is passed into 2624 /// the function. Simply print it out 2625 /// 2626 void AssemblyWriter::printArgument(const Argument *Arg, 2627 AttributeSet Attrs, unsigned Idx) { 2628 // Output type... 2629 TypePrinter.print(Arg->getType(), Out); 2630 2631 // Output parameter attributes list 2632 if (Attrs.hasAttributes(Idx)) 2633 Out << ' ' << Attrs.getAsString(Idx); 2634 2635 // Output name, if available... 2636 if (Arg->hasName()) { 2637 Out << ' '; 2638 PrintLLVMName(Out, Arg); 2639 } 2640 } 2641 2642 /// printBasicBlock - This member is called for each basic block in a method. 2643 /// 2644 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 2645 if (BB->hasName()) { // Print out the label if it exists... 2646 Out << "\n"; 2647 PrintLLVMName(Out, BB->getName(), LabelPrefix); 2648 Out << ':'; 2649 } else if (!BB->use_empty()) { // Don't print block # of no uses... 2650 Out << "\n; <label>:"; 2651 int Slot = Machine.getLocalSlot(BB); 2652 if (Slot != -1) 2653 Out << Slot; 2654 else 2655 Out << "<badref>"; 2656 } 2657 2658 if (!BB->getParent()) { 2659 Out.PadToColumn(50); 2660 Out << "; Error: Block without parent!"; 2661 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 2662 // Output predecessors for the block. 2663 Out.PadToColumn(50); 2664 Out << ";"; 2665 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 2666 2667 if (PI == PE) { 2668 Out << " No predecessors!"; 2669 } else { 2670 Out << " preds = "; 2671 writeOperand(*PI, false); 2672 for (++PI; PI != PE; ++PI) { 2673 Out << ", "; 2674 writeOperand(*PI, false); 2675 } 2676 } 2677 } 2678 2679 Out << "\n"; 2680 2681 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 2682 2683 // Output all of the instructions in the basic block... 2684 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 2685 printInstructionLine(*I); 2686 } 2687 2688 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 2689 } 2690 2691 /// printInstructionLine - Print an instruction and a newline character. 2692 void AssemblyWriter::printInstructionLine(const Instruction &I) { 2693 printInstruction(I); 2694 Out << '\n'; 2695 } 2696 2697 /// printGCRelocateComment - print comment after call to the gc.relocate 2698 /// intrinsic indicating base and derived pointer names. 2699 void AssemblyWriter::printGCRelocateComment(const Value &V) { 2700 assert(isGCRelocate(&V)); 2701 GCRelocateOperands GCOps(cast<Instruction>(&V)); 2702 2703 Out << " ; ("; 2704 writeOperand(GCOps.getBasePtr(), false); 2705 Out << ", "; 2706 writeOperand(GCOps.getDerivedPtr(), false); 2707 Out << ")"; 2708 } 2709 2710 /// printInfoComment - Print a little comment after the instruction indicating 2711 /// which slot it occupies. 2712 /// 2713 void AssemblyWriter::printInfoComment(const Value &V) { 2714 if (isGCRelocate(&V)) 2715 printGCRelocateComment(V); 2716 2717 if (AnnotationWriter) 2718 AnnotationWriter->printInfoComment(V, Out); 2719 } 2720 2721 // This member is called for each Instruction in a function.. 2722 void AssemblyWriter::printInstruction(const Instruction &I) { 2723 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 2724 2725 // Print out indentation for an instruction. 2726 Out << " "; 2727 2728 // Print out name if it exists... 2729 if (I.hasName()) { 2730 PrintLLVMName(Out, &I); 2731 Out << " = "; 2732 } else if (!I.getType()->isVoidTy()) { 2733 // Print out the def slot taken. 2734 int SlotNum = Machine.getLocalSlot(&I); 2735 if (SlotNum == -1) 2736 Out << "<badref> = "; 2737 else 2738 Out << '%' << SlotNum << " = "; 2739 } 2740 2741 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 2742 if (CI->isMustTailCall()) 2743 Out << "musttail "; 2744 else if (CI->isTailCall()) 2745 Out << "tail "; 2746 else if (CI->isNoTailCall()) 2747 Out << "notail "; 2748 } 2749 2750 // Print out the opcode... 2751 Out << I.getOpcodeName(); 2752 2753 // If this is an atomic load or store, print out the atomic marker. 2754 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 2755 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 2756 Out << " atomic"; 2757 2758 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 2759 Out << " weak"; 2760 2761 // If this is a volatile operation, print out the volatile marker. 2762 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 2763 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 2764 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 2765 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 2766 Out << " volatile"; 2767 2768 // Print out optimization information. 2769 WriteOptimizationInfo(Out, &I); 2770 2771 // Print out the compare instruction predicates 2772 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 2773 Out << ' ' << getPredicateText(CI->getPredicate()); 2774 2775 // Print out the atomicrmw operation 2776 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 2777 writeAtomicRMWOperation(Out, RMWI->getOperation()); 2778 2779 // Print out the type of the operands... 2780 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 2781 2782 // Special case conditional branches to swizzle the condition out to the front 2783 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 2784 const BranchInst &BI(cast<BranchInst>(I)); 2785 Out << ' '; 2786 writeOperand(BI.getCondition(), true); 2787 Out << ", "; 2788 writeOperand(BI.getSuccessor(0), true); 2789 Out << ", "; 2790 writeOperand(BI.getSuccessor(1), true); 2791 2792 } else if (isa<SwitchInst>(I)) { 2793 const SwitchInst& SI(cast<SwitchInst>(I)); 2794 // Special case switch instruction to get formatting nice and correct. 2795 Out << ' '; 2796 writeOperand(SI.getCondition(), true); 2797 Out << ", "; 2798 writeOperand(SI.getDefaultDest(), true); 2799 Out << " ["; 2800 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end(); 2801 i != e; ++i) { 2802 Out << "\n "; 2803 writeOperand(i.getCaseValue(), true); 2804 Out << ", "; 2805 writeOperand(i.getCaseSuccessor(), true); 2806 } 2807 Out << "\n ]"; 2808 } else if (isa<IndirectBrInst>(I)) { 2809 // Special case indirectbr instruction to get formatting nice and correct. 2810 Out << ' '; 2811 writeOperand(Operand, true); 2812 Out << ", ["; 2813 2814 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 2815 if (i != 1) 2816 Out << ", "; 2817 writeOperand(I.getOperand(i), true); 2818 } 2819 Out << ']'; 2820 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 2821 Out << ' '; 2822 TypePrinter.print(I.getType(), Out); 2823 Out << ' '; 2824 2825 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 2826 if (op) Out << ", "; 2827 Out << "[ "; 2828 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 2829 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 2830 } 2831 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 2832 Out << ' '; 2833 writeOperand(I.getOperand(0), true); 2834 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 2835 Out << ", " << *i; 2836 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 2837 Out << ' '; 2838 writeOperand(I.getOperand(0), true); Out << ", "; 2839 writeOperand(I.getOperand(1), true); 2840 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 2841 Out << ", " << *i; 2842 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 2843 Out << ' '; 2844 TypePrinter.print(I.getType(), Out); 2845 if (LPI->isCleanup() || LPI->getNumClauses() != 0) 2846 Out << '\n'; 2847 2848 if (LPI->isCleanup()) 2849 Out << " cleanup"; 2850 2851 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 2852 if (i != 0 || LPI->isCleanup()) Out << "\n"; 2853 if (LPI->isCatch(i)) 2854 Out << " catch "; 2855 else 2856 Out << " filter "; 2857 2858 writeOperand(LPI->getClause(i), true); 2859 } 2860 } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) { 2861 Out << " ["; 2862 for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps; 2863 ++Op) { 2864 if (Op > 0) 2865 Out << ", "; 2866 writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true); 2867 } 2868 Out << "]\n to "; 2869 writeOperand(CPI->getNormalDest(), /*PrintType=*/true); 2870 Out << " unwind "; 2871 writeOperand(CPI->getUnwindDest(), /*PrintType=*/true); 2872 } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) { 2873 Out << " ["; 2874 for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps; 2875 ++Op) { 2876 if (Op > 0) 2877 Out << ", "; 2878 writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true); 2879 } 2880 Out << "] unwind "; 2881 if (TPI->hasUnwindDest()) 2882 writeOperand(TPI->getUnwindDest(), /*PrintType=*/true); 2883 else 2884 Out << "to caller"; 2885 } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) { 2886 Out << " ["; 2887 for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) { 2888 if (Op > 0) 2889 Out << ", "; 2890 writeOperand(CPI->getOperand(Op), /*PrintType=*/true); 2891 } 2892 Out << "]"; 2893 } else if (isa<ReturnInst>(I) && !Operand) { 2894 Out << " void"; 2895 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) { 2896 Out << ' '; 2897 writeOperand(CRI->getCatchPad(), /*PrintType=*/false); 2898 2899 Out << " to "; 2900 writeOperand(CRI->getSuccessor(), /*PrintType=*/true); 2901 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) { 2902 Out << ' '; 2903 writeOperand(CRI->getCleanupPad(), /*PrintType=*/false); 2904 2905 Out << " unwind "; 2906 if (CRI->hasUnwindDest()) 2907 writeOperand(CRI->getUnwindDest(), /*PrintType=*/true); 2908 else 2909 Out << "to caller"; 2910 } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) { 2911 Out << " unwind "; 2912 if (CEPI->hasUnwindDest()) 2913 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true); 2914 else 2915 Out << "to caller"; 2916 } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) { 2917 Out << ' '; 2918 writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false); 2919 2920 Out << " unwind "; 2921 if (CEPI->hasUnwindDest()) 2922 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true); 2923 else 2924 Out << "to caller"; 2925 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 2926 // Print the calling convention being used. 2927 if (CI->getCallingConv() != CallingConv::C) { 2928 Out << " "; 2929 PrintCallingConv(CI->getCallingConv(), Out); 2930 } 2931 2932 Operand = CI->getCalledValue(); 2933 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType()); 2934 Type *RetTy = FTy->getReturnType(); 2935 const AttributeSet &PAL = CI->getAttributes(); 2936 2937 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 2938 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex); 2939 2940 // If possible, print out the short form of the call instruction. We can 2941 // only do this if the first argument is a pointer to a nonvararg function, 2942 // and if the return type is not a pointer to a function. 2943 // 2944 Out << ' '; 2945 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 2946 Out << ' '; 2947 writeOperand(Operand, false); 2948 Out << '('; 2949 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 2950 if (op > 0) 2951 Out << ", "; 2952 writeParamOperand(CI->getArgOperand(op), PAL, op + 1); 2953 } 2954 2955 // Emit an ellipsis if this is a musttail call in a vararg function. This 2956 // is only to aid readability, musttail calls forward varargs by default. 2957 if (CI->isMustTailCall() && CI->getParent() && 2958 CI->getParent()->getParent() && 2959 CI->getParent()->getParent()->isVarArg()) 2960 Out << ", ..."; 2961 2962 Out << ')'; 2963 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 2964 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 2965 2966 writeOperandBundles(CI); 2967 2968 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 2969 Operand = II->getCalledValue(); 2970 FunctionType *FTy = cast<FunctionType>(II->getFunctionType()); 2971 Type *RetTy = FTy->getReturnType(); 2972 const AttributeSet &PAL = II->getAttributes(); 2973 2974 // Print the calling convention being used. 2975 if (II->getCallingConv() != CallingConv::C) { 2976 Out << " "; 2977 PrintCallingConv(II->getCallingConv(), Out); 2978 } 2979 2980 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 2981 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex); 2982 2983 // If possible, print out the short form of the invoke instruction. We can 2984 // only do this if the first argument is a pointer to a nonvararg function, 2985 // and if the return type is not a pointer to a function. 2986 // 2987 Out << ' '; 2988 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 2989 Out << ' '; 2990 writeOperand(Operand, false); 2991 Out << '('; 2992 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 2993 if (op) 2994 Out << ", "; 2995 writeParamOperand(II->getArgOperand(op), PAL, op + 1); 2996 } 2997 2998 Out << ')'; 2999 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 3000 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 3001 3002 writeOperandBundles(II); 3003 3004 Out << "\n to "; 3005 writeOperand(II->getNormalDest(), true); 3006 Out << " unwind "; 3007 writeOperand(II->getUnwindDest(), true); 3008 3009 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 3010 Out << ' '; 3011 if (AI->isUsedWithInAlloca()) 3012 Out << "inalloca "; 3013 TypePrinter.print(AI->getAllocatedType(), Out); 3014 3015 // Explicitly write the array size if the code is broken, if it's an array 3016 // allocation, or if the type is not canonical for scalar allocations. The 3017 // latter case prevents the type from mutating when round-tripping through 3018 // assembly. 3019 if (!AI->getArraySize() || AI->isArrayAllocation() || 3020 !AI->getArraySize()->getType()->isIntegerTy(32)) { 3021 Out << ", "; 3022 writeOperand(AI->getArraySize(), true); 3023 } 3024 if (AI->getAlignment()) { 3025 Out << ", align " << AI->getAlignment(); 3026 } 3027 } else if (isa<CastInst>(I)) { 3028 if (Operand) { 3029 Out << ' '; 3030 writeOperand(Operand, true); // Work with broken code 3031 } 3032 Out << " to "; 3033 TypePrinter.print(I.getType(), Out); 3034 } else if (isa<VAArgInst>(I)) { 3035 if (Operand) { 3036 Out << ' '; 3037 writeOperand(Operand, true); // Work with broken code 3038 } 3039 Out << ", "; 3040 TypePrinter.print(I.getType(), Out); 3041 } else if (Operand) { // Print the normal way. 3042 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 3043 Out << ' '; 3044 TypePrinter.print(GEP->getSourceElementType(), Out); 3045 Out << ','; 3046 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) { 3047 Out << ' '; 3048 TypePrinter.print(LI->getType(), Out); 3049 Out << ','; 3050 } 3051 3052 // PrintAllTypes - Instructions who have operands of all the same type 3053 // omit the type from all but the first operand. If the instruction has 3054 // different type operands (for example br), then they are all printed. 3055 bool PrintAllTypes = false; 3056 Type *TheType = Operand->getType(); 3057 3058 // Select, Store and ShuffleVector always print all types. 3059 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 3060 || isa<ReturnInst>(I)) { 3061 PrintAllTypes = true; 3062 } else { 3063 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 3064 Operand = I.getOperand(i); 3065 // note that Operand shouldn't be null, but the test helps make dump() 3066 // more tolerant of malformed IR 3067 if (Operand && Operand->getType() != TheType) { 3068 PrintAllTypes = true; // We have differing types! Print them all! 3069 break; 3070 } 3071 } 3072 } 3073 3074 if (!PrintAllTypes) { 3075 Out << ' '; 3076 TypePrinter.print(TheType, Out); 3077 } 3078 3079 Out << ' '; 3080 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 3081 if (i) Out << ", "; 3082 writeOperand(I.getOperand(i), PrintAllTypes); 3083 } 3084 } 3085 3086 // Print atomic ordering/alignment for memory operations 3087 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 3088 if (LI->isAtomic()) 3089 writeAtomic(LI->getOrdering(), LI->getSynchScope()); 3090 if (LI->getAlignment()) 3091 Out << ", align " << LI->getAlignment(); 3092 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 3093 if (SI->isAtomic()) 3094 writeAtomic(SI->getOrdering(), SI->getSynchScope()); 3095 if (SI->getAlignment()) 3096 Out << ", align " << SI->getAlignment(); 3097 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 3098 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(), 3099 CXI->getSynchScope()); 3100 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 3101 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope()); 3102 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 3103 writeAtomic(FI->getOrdering(), FI->getSynchScope()); 3104 } 3105 3106 // Print Metadata info. 3107 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD; 3108 I.getAllMetadata(InstMD); 3109 printMetadataAttachments(InstMD, ", "); 3110 3111 // Print a nice comment. 3112 printInfoComment(I); 3113 } 3114 3115 void AssemblyWriter::printMetadataAttachments( 3116 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 3117 StringRef Separator) { 3118 if (MDs.empty()) 3119 return; 3120 3121 if (MDNames.empty()) 3122 TheModule->getMDKindNames(MDNames); 3123 3124 for (const auto &I : MDs) { 3125 unsigned Kind = I.first; 3126 Out << Separator; 3127 if (Kind < MDNames.size()) { 3128 Out << "!"; 3129 printMetadataIdentifier(MDNames[Kind], Out); 3130 } else 3131 Out << "!<unknown kind #" << Kind << ">"; 3132 Out << ' '; 3133 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule); 3134 } 3135 } 3136 3137 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 3138 Out << '!' << Slot << " = "; 3139 printMDNodeBody(Node); 3140 Out << "\n"; 3141 } 3142 3143 void AssemblyWriter::writeAllMDNodes() { 3144 SmallVector<const MDNode *, 16> Nodes; 3145 Nodes.resize(Machine.mdn_size()); 3146 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 3147 I != E; ++I) 3148 Nodes[I->second] = cast<MDNode>(I->first); 3149 3150 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 3151 writeMDNode(i, Nodes[i]); 3152 } 3153 } 3154 3155 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 3156 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 3157 } 3158 3159 void AssemblyWriter::writeAllAttributeGroups() { 3160 std::vector<std::pair<AttributeSet, unsigned> > asVec; 3161 asVec.resize(Machine.as_size()); 3162 3163 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end(); 3164 I != E; ++I) 3165 asVec[I->second] = *I; 3166 3167 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator 3168 I = asVec.begin(), E = asVec.end(); I != E; ++I) 3169 Out << "attributes #" << I->second << " = { " 3170 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n"; 3171 } 3172 3173 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) { 3174 bool IsInFunction = Machine.getFunction(); 3175 if (IsInFunction) 3176 Out << " "; 3177 3178 Out << "uselistorder"; 3179 if (const BasicBlock *BB = 3180 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) { 3181 Out << "_bb "; 3182 writeOperand(BB->getParent(), false); 3183 Out << ", "; 3184 writeOperand(BB, false); 3185 } else { 3186 Out << " "; 3187 writeOperand(Order.V, true); 3188 } 3189 Out << ", { "; 3190 3191 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3192 Out << Order.Shuffle[0]; 3193 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I) 3194 Out << ", " << Order.Shuffle[I]; 3195 Out << " }\n"; 3196 } 3197 3198 void AssemblyWriter::printUseLists(const Function *F) { 3199 auto hasMore = 3200 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; }; 3201 if (!hasMore()) 3202 // Nothing to do. 3203 return; 3204 3205 Out << "\n; uselistorder directives\n"; 3206 while (hasMore()) { 3207 printUseListOrder(UseListOrders.back()); 3208 UseListOrders.pop_back(); 3209 } 3210 } 3211 3212 //===----------------------------------------------------------------------===// 3213 // External Interface declarations 3214 //===----------------------------------------------------------------------===// 3215 3216 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 3217 bool ShouldPreserveUseListOrder, bool IsForDebug) const { 3218 SlotTracker SlotTable(this); 3219 formatted_raw_ostream OS(ROS); 3220 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug, 3221 ShouldPreserveUseListOrder); 3222 W.printModule(this); 3223 } 3224 3225 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const { 3226 SlotTracker SlotTable(getParent()); 3227 formatted_raw_ostream OS(ROS); 3228 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug); 3229 W.printNamedMDNode(this); 3230 } 3231 3232 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const { 3233 PrintLLVMName(ROS, getName(), ComdatPrefix); 3234 ROS << " = comdat "; 3235 3236 switch (getSelectionKind()) { 3237 case Comdat::Any: 3238 ROS << "any"; 3239 break; 3240 case Comdat::ExactMatch: 3241 ROS << "exactmatch"; 3242 break; 3243 case Comdat::Largest: 3244 ROS << "largest"; 3245 break; 3246 case Comdat::NoDuplicates: 3247 ROS << "noduplicates"; 3248 break; 3249 case Comdat::SameSize: 3250 ROS << "samesize"; 3251 break; 3252 } 3253 3254 ROS << '\n'; 3255 } 3256 3257 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const { 3258 TypePrinting TP; 3259 TP.print(const_cast<Type*>(this), OS); 3260 3261 // If the type is a named struct type, print the body as well. 3262 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 3263 if (!STy->isLiteral()) { 3264 OS << " = type "; 3265 TP.printStructBody(STy, OS); 3266 } 3267 } 3268 3269 static bool isReferencingMDNode(const Instruction &I) { 3270 if (const auto *CI = dyn_cast<CallInst>(&I)) 3271 if (Function *F = CI->getCalledFunction()) 3272 if (F->isIntrinsic()) 3273 for (auto &Op : I.operands()) 3274 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 3275 if (isa<MDNode>(V->getMetadata())) 3276 return true; 3277 return false; 3278 } 3279 3280 void Value::print(raw_ostream &ROS, bool IsForDebug) const { 3281 bool ShouldInitializeAllMetadata = false; 3282 if (auto *I = dyn_cast<Instruction>(this)) 3283 ShouldInitializeAllMetadata = isReferencingMDNode(*I); 3284 else if (isa<Function>(this) || isa<MetadataAsValue>(this)) 3285 ShouldInitializeAllMetadata = true; 3286 3287 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata); 3288 print(ROS, MST, IsForDebug); 3289 } 3290 3291 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST, 3292 bool IsForDebug) const { 3293 formatted_raw_ostream OS(ROS); 3294 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr)); 3295 SlotTracker &SlotTable = 3296 MST.getMachine() ? *MST.getMachine() : EmptySlotTable; 3297 auto incorporateFunction = [&](const Function *F) { 3298 if (F) 3299 MST.incorporateFunction(*F); 3300 }; 3301 3302 if (const Instruction *I = dyn_cast<Instruction>(this)) { 3303 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr); 3304 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug); 3305 W.printInstruction(*I); 3306 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 3307 incorporateFunction(BB->getParent()); 3308 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug); 3309 W.printBasicBlock(BB); 3310 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 3311 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug); 3312 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 3313 W.printGlobal(V); 3314 else if (const Function *F = dyn_cast<Function>(GV)) 3315 W.printFunction(F); 3316 else 3317 W.printAlias(cast<GlobalAlias>(GV)); 3318 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) { 3319 V->getMetadata()->print(ROS, MST, getModuleFromVal(V)); 3320 } else if (const Constant *C = dyn_cast<Constant>(this)) { 3321 TypePrinting TypePrinter; 3322 TypePrinter.print(C->getType(), OS); 3323 OS << ' '; 3324 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr); 3325 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) { 3326 this->printAsOperand(OS, /* PrintType */ true, MST); 3327 } else { 3328 llvm_unreachable("Unknown value to print out!"); 3329 } 3330 } 3331 3332 /// Print without a type, skipping the TypePrinting object. 3333 /// 3334 /// \return \c true iff printing was successful. 3335 static bool printWithoutType(const Value &V, raw_ostream &O, 3336 SlotTracker *Machine, const Module *M) { 3337 if (V.hasName() || isa<GlobalValue>(V) || 3338 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) { 3339 WriteAsOperandInternal(O, &V, nullptr, Machine, M); 3340 return true; 3341 } 3342 return false; 3343 } 3344 3345 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, 3346 ModuleSlotTracker &MST) { 3347 TypePrinting TypePrinter; 3348 if (const Module *M = MST.getModule()) 3349 TypePrinter.incorporateTypes(*M); 3350 if (PrintType) { 3351 TypePrinter.print(V.getType(), O); 3352 O << ' '; 3353 } 3354 3355 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(), 3356 MST.getModule()); 3357 } 3358 3359 void Value::printAsOperand(raw_ostream &O, bool PrintType, 3360 const Module *M) const { 3361 if (!M) 3362 M = getModuleFromVal(this); 3363 3364 if (!PrintType) 3365 if (printWithoutType(*this, O, nullptr, M)) 3366 return; 3367 3368 SlotTracker Machine( 3369 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this)); 3370 ModuleSlotTracker MST(Machine, M); 3371 printAsOperandImpl(*this, O, PrintType, MST); 3372 } 3373 3374 void Value::printAsOperand(raw_ostream &O, bool PrintType, 3375 ModuleSlotTracker &MST) const { 3376 if (!PrintType) 3377 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule())) 3378 return; 3379 3380 printAsOperandImpl(*this, O, PrintType, MST); 3381 } 3382 3383 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, 3384 ModuleSlotTracker &MST, const Module *M, 3385 bool OnlyAsOperand) { 3386 formatted_raw_ostream OS(ROS); 3387 3388 TypePrinting TypePrinter; 3389 if (M) 3390 TypePrinter.incorporateTypes(*M); 3391 3392 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M, 3393 /* FromValue */ true); 3394 3395 auto *N = dyn_cast<MDNode>(&MD); 3396 if (OnlyAsOperand || !N) 3397 return; 3398 3399 OS << " = "; 3400 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M); 3401 } 3402 3403 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const { 3404 ModuleSlotTracker MST(M, isa<MDNode>(this)); 3405 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 3406 } 3407 3408 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, 3409 const Module *M) const { 3410 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 3411 } 3412 3413 void Metadata::print(raw_ostream &OS, const Module *M, 3414 bool /*IsForDebug*/) const { 3415 ModuleSlotTracker MST(M, isa<MDNode>(this)); 3416 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 3417 } 3418 3419 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST, 3420 const Module *M, bool /*IsForDebug*/) const { 3421 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 3422 } 3423 3424 // Value::dump - allow easy printing of Values from the debugger. 3425 LLVM_DUMP_METHOD 3426 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 3427 3428 // Type::dump - allow easy printing of Types from the debugger. 3429 LLVM_DUMP_METHOD 3430 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 3431 3432 // Module::dump() - Allow printing of Modules from the debugger. 3433 LLVM_DUMP_METHOD 3434 void Module::dump() const { 3435 print(dbgs(), nullptr, 3436 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true); 3437 } 3438 3439 // \brief Allow printing of Comdats from the debugger. 3440 LLVM_DUMP_METHOD 3441 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); } 3442 3443 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 3444 LLVM_DUMP_METHOD 3445 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); } 3446 3447 LLVM_DUMP_METHOD 3448 void Metadata::dump() const { dump(nullptr); } 3449 3450 LLVM_DUMP_METHOD 3451 void Metadata::dump(const Module *M) const { 3452 print(dbgs(), M, /*IsForDebug=*/true); 3453 dbgs() << '\n'; 3454 } 3455