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