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 // 'Fast' is an abbreviation for all fast-math-flags. 1112 if (FPO->isFast()) 1113 Out << " fast"; 1114 else { 1115 if (FPO->hasAllowReassoc()) 1116 Out << " reassoc"; 1117 if (FPO->hasNoNaNs()) 1118 Out << " nnan"; 1119 if (FPO->hasNoInfs()) 1120 Out << " ninf"; 1121 if (FPO->hasNoSignedZeros()) 1122 Out << " nsz"; 1123 if (FPO->hasAllowReciprocal()) 1124 Out << " arcp"; 1125 if (FPO->hasAllowContract()) 1126 Out << " contract"; 1127 if (FPO->hasApproxFunc()) 1128 Out << " afn"; 1129 } 1130 } 1131 1132 if (const OverflowingBinaryOperator *OBO = 1133 dyn_cast<OverflowingBinaryOperator>(U)) { 1134 if (OBO->hasNoUnsignedWrap()) 1135 Out << " nuw"; 1136 if (OBO->hasNoSignedWrap()) 1137 Out << " nsw"; 1138 } else if (const PossiblyExactOperator *Div = 1139 dyn_cast<PossiblyExactOperator>(U)) { 1140 if (Div->isExact()) 1141 Out << " exact"; 1142 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { 1143 if (GEP->isInBounds()) 1144 Out << " inbounds"; 1145 } 1146 } 1147 1148 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV, 1149 TypePrinting &TypePrinter, 1150 SlotTracker *Machine, 1151 const Module *Context) { 1152 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1153 if (CI->getType()->isIntegerTy(1)) { 1154 Out << (CI->getZExtValue() ? "true" : "false"); 1155 return; 1156 } 1157 Out << CI->getValue(); 1158 return; 1159 } 1160 1161 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 1162 const APFloat &APF = CFP->getValueAPF(); 1163 if (&APF.getSemantics() == &APFloat::IEEEsingle() || 1164 &APF.getSemantics() == &APFloat::IEEEdouble()) { 1165 // We would like to output the FP constant value in exponential notation, 1166 // but we cannot do this if doing so will lose precision. Check here to 1167 // make sure that we only output it in exponential format if we can parse 1168 // the value back and get the same value. 1169 // 1170 bool ignored; 1171 bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble(); 1172 bool isInf = APF.isInfinity(); 1173 bool isNaN = APF.isNaN(); 1174 if (!isInf && !isNaN) { 1175 double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat(); 1176 SmallString<128> StrVal; 1177 APF.toString(StrVal, 6, 0, false); 1178 // Check to make sure that the stringized number is not some string like 1179 // "Inf" or NaN, that atof will accept, but the lexer will not. Check 1180 // that the string matches the "[-+]?[0-9]" regex. 1181 // 1182 assert(((StrVal[0] >= '0' && StrVal[0] <= '9') || 1183 ((StrVal[0] == '-' || StrVal[0] == '+') && 1184 (StrVal[1] >= '0' && StrVal[1] <= '9'))) && 1185 "[-+]?[0-9] regex does not match!"); 1186 // Reparse stringized version! 1187 if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) { 1188 Out << StrVal; 1189 return; 1190 } 1191 } 1192 // Otherwise we could not reparse it to exactly the same value, so we must 1193 // output the string in hexadecimal format! Note that loading and storing 1194 // floating point types changes the bits of NaNs on some hosts, notably 1195 // x86, so we must not use these types. 1196 static_assert(sizeof(double) == sizeof(uint64_t), 1197 "assuming that double is 64 bits!"); 1198 APFloat apf = APF; 1199 // Floats are represented in ASCII IR as double, convert. 1200 if (!isDouble) 1201 apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 1202 &ignored); 1203 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true); 1204 return; 1205 } 1206 1207 // Either half, or some form of long double. 1208 // These appear as a magic letter identifying the type, then a 1209 // fixed number of hex digits. 1210 Out << "0x"; 1211 APInt API = APF.bitcastToAPInt(); 1212 if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) { 1213 Out << 'K'; 1214 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4, 1215 /*Upper=*/true); 1216 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1217 /*Upper=*/true); 1218 return; 1219 } else if (&APF.getSemantics() == &APFloat::IEEEquad()) { 1220 Out << 'L'; 1221 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1222 /*Upper=*/true); 1223 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1224 /*Upper=*/true); 1225 } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) { 1226 Out << 'M'; 1227 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16, 1228 /*Upper=*/true); 1229 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16, 1230 /*Upper=*/true); 1231 } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) { 1232 Out << 'H'; 1233 Out << format_hex_no_prefix(API.getZExtValue(), 4, 1234 /*Upper=*/true); 1235 } else 1236 llvm_unreachable("Unsupported floating point type"); 1237 return; 1238 } 1239 1240 if (isa<ConstantAggregateZero>(CV)) { 1241 Out << "zeroinitializer"; 1242 return; 1243 } 1244 1245 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 1246 Out << "blockaddress("; 1247 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine, 1248 Context); 1249 Out << ", "; 1250 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine, 1251 Context); 1252 Out << ")"; 1253 return; 1254 } 1255 1256 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 1257 Type *ETy = CA->getType()->getElementType(); 1258 Out << '['; 1259 TypePrinter.print(ETy, Out); 1260 Out << ' '; 1261 WriteAsOperandInternal(Out, CA->getOperand(0), 1262 &TypePrinter, Machine, 1263 Context); 1264 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 1265 Out << ", "; 1266 TypePrinter.print(ETy, Out); 1267 Out << ' '; 1268 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine, 1269 Context); 1270 } 1271 Out << ']'; 1272 return; 1273 } 1274 1275 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) { 1276 // As a special case, print the array as a string if it is an array of 1277 // i8 with ConstantInt values. 1278 if (CA->isString()) { 1279 Out << "c\""; 1280 PrintEscapedString(CA->getAsString(), Out); 1281 Out << '"'; 1282 return; 1283 } 1284 1285 Type *ETy = CA->getType()->getElementType(); 1286 Out << '['; 1287 TypePrinter.print(ETy, Out); 1288 Out << ' '; 1289 WriteAsOperandInternal(Out, CA->getElementAsConstant(0), 1290 &TypePrinter, Machine, 1291 Context); 1292 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) { 1293 Out << ", "; 1294 TypePrinter.print(ETy, Out); 1295 Out << ' '; 1296 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter, 1297 Machine, Context); 1298 } 1299 Out << ']'; 1300 return; 1301 } 1302 1303 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 1304 if (CS->getType()->isPacked()) 1305 Out << '<'; 1306 Out << '{'; 1307 unsigned N = CS->getNumOperands(); 1308 if (N) { 1309 Out << ' '; 1310 TypePrinter.print(CS->getOperand(0)->getType(), Out); 1311 Out << ' '; 1312 1313 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine, 1314 Context); 1315 1316 for (unsigned i = 1; i < N; i++) { 1317 Out << ", "; 1318 TypePrinter.print(CS->getOperand(i)->getType(), Out); 1319 Out << ' '; 1320 1321 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine, 1322 Context); 1323 } 1324 Out << ' '; 1325 } 1326 1327 Out << '}'; 1328 if (CS->getType()->isPacked()) 1329 Out << '>'; 1330 return; 1331 } 1332 1333 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) { 1334 Type *ETy = CV->getType()->getVectorElementType(); 1335 Out << '<'; 1336 TypePrinter.print(ETy, Out); 1337 Out << ' '; 1338 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter, 1339 Machine, Context); 1340 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){ 1341 Out << ", "; 1342 TypePrinter.print(ETy, Out); 1343 Out << ' '; 1344 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter, 1345 Machine, Context); 1346 } 1347 Out << '>'; 1348 return; 1349 } 1350 1351 if (isa<ConstantPointerNull>(CV)) { 1352 Out << "null"; 1353 return; 1354 } 1355 1356 if (isa<ConstantTokenNone>(CV)) { 1357 Out << "none"; 1358 return; 1359 } 1360 1361 if (isa<UndefValue>(CV)) { 1362 Out << "undef"; 1363 return; 1364 } 1365 1366 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1367 Out << CE->getOpcodeName(); 1368 WriteOptimizationInfo(Out, CE); 1369 if (CE->isCompare()) 1370 Out << ' ' << CmpInst::getPredicateName( 1371 static_cast<CmpInst::Predicate>(CE->getPredicate())); 1372 Out << " ("; 1373 1374 Optional<unsigned> InRangeOp; 1375 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) { 1376 TypePrinter.print(GEP->getSourceElementType(), Out); 1377 Out << ", "; 1378 InRangeOp = GEP->getInRangeIndex(); 1379 if (InRangeOp) 1380 ++*InRangeOp; 1381 } 1382 1383 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) { 1384 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp) 1385 Out << "inrange "; 1386 TypePrinter.print((*OI)->getType(), Out); 1387 Out << ' '; 1388 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context); 1389 if (OI+1 != CE->op_end()) 1390 Out << ", "; 1391 } 1392 1393 if (CE->hasIndices()) { 1394 ArrayRef<unsigned> Indices = CE->getIndices(); 1395 for (unsigned i = 0, e = Indices.size(); i != e; ++i) 1396 Out << ", " << Indices[i]; 1397 } 1398 1399 if (CE->isCast()) { 1400 Out << " to "; 1401 TypePrinter.print(CE->getType(), Out); 1402 } 1403 1404 Out << ')'; 1405 return; 1406 } 1407 1408 Out << "<placeholder or erroneous Constant>"; 1409 } 1410 1411 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node, 1412 TypePrinting *TypePrinter, SlotTracker *Machine, 1413 const Module *Context) { 1414 Out << "!{"; 1415 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) { 1416 const Metadata *MD = Node->getOperand(mi); 1417 if (!MD) 1418 Out << "null"; 1419 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) { 1420 Value *V = MDV->getValue(); 1421 TypePrinter->print(V->getType(), Out); 1422 Out << ' '; 1423 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context); 1424 } else { 1425 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1426 } 1427 if (mi + 1 != me) 1428 Out << ", "; 1429 } 1430 1431 Out << "}"; 1432 } 1433 1434 namespace { 1435 1436 struct FieldSeparator { 1437 bool Skip = true; 1438 const char *Sep; 1439 1440 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {} 1441 }; 1442 1443 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) { 1444 if (FS.Skip) { 1445 FS.Skip = false; 1446 return OS; 1447 } 1448 return OS << FS.Sep; 1449 } 1450 1451 struct MDFieldPrinter { 1452 raw_ostream &Out; 1453 FieldSeparator FS; 1454 TypePrinting *TypePrinter = nullptr; 1455 SlotTracker *Machine = nullptr; 1456 const Module *Context = nullptr; 1457 1458 explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {} 1459 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter, 1460 SlotTracker *Machine, const Module *Context) 1461 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) { 1462 } 1463 1464 void printTag(const DINode *N); 1465 void printMacinfoType(const DIMacroNode *N); 1466 void printChecksumKind(const DIFile *N); 1467 void printString(StringRef Name, StringRef Value, 1468 bool ShouldSkipEmpty = true); 1469 void printMetadata(StringRef Name, const Metadata *MD, 1470 bool ShouldSkipNull = true); 1471 template <class IntTy> 1472 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true); 1473 void printBool(StringRef Name, bool Value, Optional<bool> Default = None); 1474 void printDIFlags(StringRef Name, DINode::DIFlags Flags); 1475 template <class IntTy, class Stringifier> 1476 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString, 1477 bool ShouldSkipZero = true); 1478 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK); 1479 }; 1480 1481 } // end anonymous namespace 1482 1483 void MDFieldPrinter::printTag(const DINode *N) { 1484 Out << FS << "tag: "; 1485 auto Tag = dwarf::TagString(N->getTag()); 1486 if (!Tag.empty()) 1487 Out << Tag; 1488 else 1489 Out << N->getTag(); 1490 } 1491 1492 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) { 1493 Out << FS << "type: "; 1494 auto Type = dwarf::MacinfoString(N->getMacinfoType()); 1495 if (!Type.empty()) 1496 Out << Type; 1497 else 1498 Out << N->getMacinfoType(); 1499 } 1500 1501 void MDFieldPrinter::printChecksumKind(const DIFile *N) { 1502 if (N->getChecksumKind() == DIFile::CSK_None) 1503 // Skip CSK_None checksum kind. 1504 return; 1505 Out << FS << "checksumkind: " << N->getChecksumKindAsString(); 1506 } 1507 1508 void MDFieldPrinter::printString(StringRef Name, StringRef Value, 1509 bool ShouldSkipEmpty) { 1510 if (ShouldSkipEmpty && Value.empty()) 1511 return; 1512 1513 Out << FS << Name << ": \""; 1514 PrintEscapedString(Value, Out); 1515 Out << "\""; 1516 } 1517 1518 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD, 1519 TypePrinting *TypePrinter, 1520 SlotTracker *Machine, 1521 const Module *Context) { 1522 if (!MD) { 1523 Out << "null"; 1524 return; 1525 } 1526 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context); 1527 } 1528 1529 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD, 1530 bool ShouldSkipNull) { 1531 if (ShouldSkipNull && !MD) 1532 return; 1533 1534 Out << FS << Name << ": "; 1535 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context); 1536 } 1537 1538 template <class IntTy> 1539 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) { 1540 if (ShouldSkipZero && !Int) 1541 return; 1542 1543 Out << FS << Name << ": " << Int; 1544 } 1545 1546 void MDFieldPrinter::printBool(StringRef Name, bool Value, 1547 Optional<bool> Default) { 1548 if (Default && Value == *Default) 1549 return; 1550 Out << FS << Name << ": " << (Value ? "true" : "false"); 1551 } 1552 1553 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) { 1554 if (!Flags) 1555 return; 1556 1557 Out << FS << Name << ": "; 1558 1559 SmallVector<DINode::DIFlags, 8> SplitFlags; 1560 auto Extra = DINode::splitFlags(Flags, SplitFlags); 1561 1562 FieldSeparator FlagsFS(" | "); 1563 for (auto F : SplitFlags) { 1564 auto StringF = DINode::getFlagString(F); 1565 assert(!StringF.empty() && "Expected valid flag"); 1566 Out << FlagsFS << StringF; 1567 } 1568 if (Extra || SplitFlags.empty()) 1569 Out << FlagsFS << Extra; 1570 } 1571 1572 void MDFieldPrinter::printEmissionKind(StringRef Name, 1573 DICompileUnit::DebugEmissionKind EK) { 1574 Out << FS << Name << ": " << DICompileUnit::EmissionKindString(EK); 1575 } 1576 1577 template <class IntTy, class Stringifier> 1578 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value, 1579 Stringifier toString, bool ShouldSkipZero) { 1580 if (!Value) 1581 return; 1582 1583 Out << FS << Name << ": "; 1584 auto S = toString(Value); 1585 if (!S.empty()) 1586 Out << S; 1587 else 1588 Out << Value; 1589 } 1590 1591 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N, 1592 TypePrinting *TypePrinter, SlotTracker *Machine, 1593 const Module *Context) { 1594 Out << "!GenericDINode("; 1595 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1596 Printer.printTag(N); 1597 Printer.printString("header", N->getHeader()); 1598 if (N->getNumDwarfOperands()) { 1599 Out << Printer.FS << "operands: {"; 1600 FieldSeparator IFS; 1601 for (auto &I : N->dwarf_operands()) { 1602 Out << IFS; 1603 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context); 1604 } 1605 Out << "}"; 1606 } 1607 Out << ")"; 1608 } 1609 1610 static void writeDILocation(raw_ostream &Out, const DILocation *DL, 1611 TypePrinting *TypePrinter, SlotTracker *Machine, 1612 const Module *Context) { 1613 Out << "!DILocation("; 1614 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1615 // Always output the line, since 0 is a relevant and important value for it. 1616 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false); 1617 Printer.printInt("column", DL->getColumn()); 1618 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false); 1619 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt()); 1620 Out << ")"; 1621 } 1622 1623 static void writeDISubrange(raw_ostream &Out, const DISubrange *N, 1624 TypePrinting *, SlotTracker *, const Module *) { 1625 Out << "!DISubrange("; 1626 MDFieldPrinter Printer(Out); 1627 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false); 1628 Printer.printInt("lowerBound", N->getLowerBound()); 1629 Out << ")"; 1630 } 1631 1632 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N, 1633 TypePrinting *, SlotTracker *, const Module *) { 1634 Out << "!DIEnumerator("; 1635 MDFieldPrinter Printer(Out); 1636 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false); 1637 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false); 1638 Out << ")"; 1639 } 1640 1641 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N, 1642 TypePrinting *, SlotTracker *, const Module *) { 1643 Out << "!DIBasicType("; 1644 MDFieldPrinter Printer(Out); 1645 if (N->getTag() != dwarf::DW_TAG_base_type) 1646 Printer.printTag(N); 1647 Printer.printString("name", N->getName()); 1648 Printer.printInt("size", N->getSizeInBits()); 1649 Printer.printInt("align", N->getAlignInBits()); 1650 Printer.printDwarfEnum("encoding", N->getEncoding(), 1651 dwarf::AttributeEncodingString); 1652 Out << ")"; 1653 } 1654 1655 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N, 1656 TypePrinting *TypePrinter, SlotTracker *Machine, 1657 const Module *Context) { 1658 Out << "!DIDerivedType("; 1659 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1660 Printer.printTag(N); 1661 Printer.printString("name", N->getName()); 1662 Printer.printMetadata("scope", N->getRawScope()); 1663 Printer.printMetadata("file", N->getRawFile()); 1664 Printer.printInt("line", N->getLine()); 1665 Printer.printMetadata("baseType", N->getRawBaseType(), 1666 /* ShouldSkipNull */ false); 1667 Printer.printInt("size", N->getSizeInBits()); 1668 Printer.printInt("align", N->getAlignInBits()); 1669 Printer.printInt("offset", N->getOffsetInBits()); 1670 Printer.printDIFlags("flags", N->getFlags()); 1671 Printer.printMetadata("extraData", N->getRawExtraData()); 1672 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace()) 1673 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace, 1674 /* ShouldSkipZero */ false); 1675 Out << ")"; 1676 } 1677 1678 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N, 1679 TypePrinting *TypePrinter, 1680 SlotTracker *Machine, const Module *Context) { 1681 Out << "!DICompositeType("; 1682 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1683 Printer.printTag(N); 1684 Printer.printString("name", N->getName()); 1685 Printer.printMetadata("scope", N->getRawScope()); 1686 Printer.printMetadata("file", N->getRawFile()); 1687 Printer.printInt("line", N->getLine()); 1688 Printer.printMetadata("baseType", N->getRawBaseType()); 1689 Printer.printInt("size", N->getSizeInBits()); 1690 Printer.printInt("align", N->getAlignInBits()); 1691 Printer.printInt("offset", N->getOffsetInBits()); 1692 Printer.printDIFlags("flags", N->getFlags()); 1693 Printer.printMetadata("elements", N->getRawElements()); 1694 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(), 1695 dwarf::LanguageString); 1696 Printer.printMetadata("vtableHolder", N->getRawVTableHolder()); 1697 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 1698 Printer.printString("identifier", N->getIdentifier()); 1699 Out << ")"; 1700 } 1701 1702 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N, 1703 TypePrinting *TypePrinter, 1704 SlotTracker *Machine, const Module *Context) { 1705 Out << "!DISubroutineType("; 1706 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1707 Printer.printDIFlags("flags", N->getFlags()); 1708 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString); 1709 Printer.printMetadata("types", N->getRawTypeArray(), 1710 /* ShouldSkipNull */ false); 1711 Out << ")"; 1712 } 1713 1714 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *, 1715 SlotTracker *, const Module *) { 1716 Out << "!DIFile("; 1717 MDFieldPrinter Printer(Out); 1718 Printer.printString("filename", N->getFilename(), 1719 /* ShouldSkipEmpty */ false); 1720 Printer.printString("directory", N->getDirectory(), 1721 /* ShouldSkipEmpty */ false); 1722 Printer.printChecksumKind(N); 1723 Printer.printString("checksum", N->getChecksum(), /* ShouldSkipEmpty */ true); 1724 Out << ")"; 1725 } 1726 1727 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N, 1728 TypePrinting *TypePrinter, SlotTracker *Machine, 1729 const Module *Context) { 1730 Out << "!DICompileUnit("; 1731 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1732 Printer.printDwarfEnum("language", N->getSourceLanguage(), 1733 dwarf::LanguageString, /* ShouldSkipZero */ false); 1734 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 1735 Printer.printString("producer", N->getProducer()); 1736 Printer.printBool("isOptimized", N->isOptimized()); 1737 Printer.printString("flags", N->getFlags()); 1738 Printer.printInt("runtimeVersion", N->getRuntimeVersion(), 1739 /* ShouldSkipZero */ false); 1740 Printer.printString("splitDebugFilename", N->getSplitDebugFilename()); 1741 Printer.printEmissionKind("emissionKind", N->getEmissionKind()); 1742 Printer.printMetadata("enums", N->getRawEnumTypes()); 1743 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes()); 1744 Printer.printMetadata("globals", N->getRawGlobalVariables()); 1745 Printer.printMetadata("imports", N->getRawImportedEntities()); 1746 Printer.printMetadata("macros", N->getRawMacros()); 1747 Printer.printInt("dwoId", N->getDWOId()); 1748 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true); 1749 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(), 1750 false); 1751 Printer.printBool("gnuPubnames", N->getGnuPubnames(), false); 1752 Out << ")"; 1753 } 1754 1755 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N, 1756 TypePrinting *TypePrinter, SlotTracker *Machine, 1757 const Module *Context) { 1758 Out << "!DISubprogram("; 1759 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1760 Printer.printString("name", N->getName()); 1761 Printer.printString("linkageName", N->getLinkageName()); 1762 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1763 Printer.printMetadata("file", N->getRawFile()); 1764 Printer.printInt("line", N->getLine()); 1765 Printer.printMetadata("type", N->getRawType()); 1766 Printer.printBool("isLocal", N->isLocalToUnit()); 1767 Printer.printBool("isDefinition", N->isDefinition()); 1768 Printer.printInt("scopeLine", N->getScopeLine()); 1769 Printer.printMetadata("containingType", N->getRawContainingType()); 1770 Printer.printDwarfEnum("virtuality", N->getVirtuality(), 1771 dwarf::VirtualityString); 1772 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none || 1773 N->getVirtualIndex() != 0) 1774 Printer.printInt("virtualIndex", N->getVirtualIndex(), false); 1775 Printer.printInt("thisAdjustment", N->getThisAdjustment()); 1776 Printer.printDIFlags("flags", N->getFlags()); 1777 Printer.printBool("isOptimized", N->isOptimized()); 1778 Printer.printMetadata("unit", N->getRawUnit()); 1779 Printer.printMetadata("templateParams", N->getRawTemplateParams()); 1780 Printer.printMetadata("declaration", N->getRawDeclaration()); 1781 Printer.printMetadata("variables", N->getRawVariables()); 1782 Printer.printMetadata("thrownTypes", N->getRawThrownTypes()); 1783 Out << ")"; 1784 } 1785 1786 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N, 1787 TypePrinting *TypePrinter, SlotTracker *Machine, 1788 const Module *Context) { 1789 Out << "!DILexicalBlock("; 1790 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1791 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1792 Printer.printMetadata("file", N->getRawFile()); 1793 Printer.printInt("line", N->getLine()); 1794 Printer.printInt("column", N->getColumn()); 1795 Out << ")"; 1796 } 1797 1798 static void writeDILexicalBlockFile(raw_ostream &Out, 1799 const DILexicalBlockFile *N, 1800 TypePrinting *TypePrinter, 1801 SlotTracker *Machine, 1802 const Module *Context) { 1803 Out << "!DILexicalBlockFile("; 1804 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1805 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1806 Printer.printMetadata("file", N->getRawFile()); 1807 Printer.printInt("discriminator", N->getDiscriminator(), 1808 /* ShouldSkipZero */ false); 1809 Out << ")"; 1810 } 1811 1812 static void writeDINamespace(raw_ostream &Out, const DINamespace *N, 1813 TypePrinting *TypePrinter, SlotTracker *Machine, 1814 const Module *Context) { 1815 Out << "!DINamespace("; 1816 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1817 Printer.printString("name", N->getName()); 1818 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1819 Printer.printBool("exportSymbols", N->getExportSymbols(), false); 1820 Out << ")"; 1821 } 1822 1823 static void writeDIMacro(raw_ostream &Out, const DIMacro *N, 1824 TypePrinting *TypePrinter, SlotTracker *Machine, 1825 const Module *Context) { 1826 Out << "!DIMacro("; 1827 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1828 Printer.printMacinfoType(N); 1829 Printer.printInt("line", N->getLine()); 1830 Printer.printString("name", N->getName()); 1831 Printer.printString("value", N->getValue()); 1832 Out << ")"; 1833 } 1834 1835 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N, 1836 TypePrinting *TypePrinter, SlotTracker *Machine, 1837 const Module *Context) { 1838 Out << "!DIMacroFile("; 1839 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1840 Printer.printInt("line", N->getLine()); 1841 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false); 1842 Printer.printMetadata("nodes", N->getRawElements()); 1843 Out << ")"; 1844 } 1845 1846 static void writeDIModule(raw_ostream &Out, const DIModule *N, 1847 TypePrinting *TypePrinter, SlotTracker *Machine, 1848 const Module *Context) { 1849 Out << "!DIModule("; 1850 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1851 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1852 Printer.printString("name", N->getName()); 1853 Printer.printString("configMacros", N->getConfigurationMacros()); 1854 Printer.printString("includePath", N->getIncludePath()); 1855 Printer.printString("isysroot", N->getISysRoot()); 1856 Out << ")"; 1857 } 1858 1859 1860 static void writeDITemplateTypeParameter(raw_ostream &Out, 1861 const DITemplateTypeParameter *N, 1862 TypePrinting *TypePrinter, 1863 SlotTracker *Machine, 1864 const Module *Context) { 1865 Out << "!DITemplateTypeParameter("; 1866 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1867 Printer.printString("name", N->getName()); 1868 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false); 1869 Out << ")"; 1870 } 1871 1872 static void writeDITemplateValueParameter(raw_ostream &Out, 1873 const DITemplateValueParameter *N, 1874 TypePrinting *TypePrinter, 1875 SlotTracker *Machine, 1876 const Module *Context) { 1877 Out << "!DITemplateValueParameter("; 1878 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1879 if (N->getTag() != dwarf::DW_TAG_template_value_parameter) 1880 Printer.printTag(N); 1881 Printer.printString("name", N->getName()); 1882 Printer.printMetadata("type", N->getRawType()); 1883 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false); 1884 Out << ")"; 1885 } 1886 1887 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N, 1888 TypePrinting *TypePrinter, 1889 SlotTracker *Machine, const Module *Context) { 1890 Out << "!DIGlobalVariable("; 1891 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1892 Printer.printString("name", N->getName()); 1893 Printer.printString("linkageName", N->getLinkageName()); 1894 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1895 Printer.printMetadata("file", N->getRawFile()); 1896 Printer.printInt("line", N->getLine()); 1897 Printer.printMetadata("type", N->getRawType()); 1898 Printer.printBool("isLocal", N->isLocalToUnit()); 1899 Printer.printBool("isDefinition", N->isDefinition()); 1900 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration()); 1901 Printer.printInt("align", N->getAlignInBits()); 1902 Out << ")"; 1903 } 1904 1905 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N, 1906 TypePrinting *TypePrinter, 1907 SlotTracker *Machine, const Module *Context) { 1908 Out << "!DILocalVariable("; 1909 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1910 Printer.printString("name", N->getName()); 1911 Printer.printInt("arg", N->getArg()); 1912 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1913 Printer.printMetadata("file", N->getRawFile()); 1914 Printer.printInt("line", N->getLine()); 1915 Printer.printMetadata("type", N->getRawType()); 1916 Printer.printDIFlags("flags", N->getFlags()); 1917 Printer.printInt("align", N->getAlignInBits()); 1918 Out << ")"; 1919 } 1920 1921 static void writeDIExpression(raw_ostream &Out, const DIExpression *N, 1922 TypePrinting *TypePrinter, SlotTracker *Machine, 1923 const Module *Context) { 1924 Out << "!DIExpression("; 1925 FieldSeparator FS; 1926 if (N->isValid()) { 1927 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) { 1928 auto OpStr = dwarf::OperationEncodingString(I->getOp()); 1929 assert(!OpStr.empty() && "Expected valid opcode"); 1930 1931 Out << FS << OpStr; 1932 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A) 1933 Out << FS << I->getArg(A); 1934 } 1935 } else { 1936 for (const auto &I : N->getElements()) 1937 Out << FS << I; 1938 } 1939 Out << ")"; 1940 } 1941 1942 static void writeDIGlobalVariableExpression(raw_ostream &Out, 1943 const DIGlobalVariableExpression *N, 1944 TypePrinting *TypePrinter, 1945 SlotTracker *Machine, 1946 const Module *Context) { 1947 Out << "!DIGlobalVariableExpression("; 1948 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1949 Printer.printMetadata("var", N->getVariable()); 1950 Printer.printMetadata("expr", N->getExpression()); 1951 Out << ")"; 1952 } 1953 1954 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N, 1955 TypePrinting *TypePrinter, SlotTracker *Machine, 1956 const Module *Context) { 1957 Out << "!DIObjCProperty("; 1958 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1959 Printer.printString("name", N->getName()); 1960 Printer.printMetadata("file", N->getRawFile()); 1961 Printer.printInt("line", N->getLine()); 1962 Printer.printString("setter", N->getSetterName()); 1963 Printer.printString("getter", N->getGetterName()); 1964 Printer.printInt("attributes", N->getAttributes()); 1965 Printer.printMetadata("type", N->getRawType()); 1966 Out << ")"; 1967 } 1968 1969 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N, 1970 TypePrinting *TypePrinter, 1971 SlotTracker *Machine, const Module *Context) { 1972 Out << "!DIImportedEntity("; 1973 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context); 1974 Printer.printTag(N); 1975 Printer.printString("name", N->getName()); 1976 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false); 1977 Printer.printMetadata("entity", N->getRawEntity()); 1978 Printer.printMetadata("file", N->getRawFile()); 1979 Printer.printInt("line", N->getLine()); 1980 Out << ")"; 1981 } 1982 1983 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node, 1984 TypePrinting *TypePrinter, 1985 SlotTracker *Machine, 1986 const Module *Context) { 1987 if (Node->isDistinct()) 1988 Out << "distinct "; 1989 else if (Node->isTemporary()) 1990 Out << "<temporary!> "; // Handle broken code. 1991 1992 switch (Node->getMetadataID()) { 1993 default: 1994 llvm_unreachable("Expected uniquable MDNode"); 1995 #define HANDLE_MDNODE_LEAF(CLASS) \ 1996 case Metadata::CLASS##Kind: \ 1997 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \ 1998 break; 1999 #include "llvm/IR/Metadata.def" 2000 } 2001 } 2002 2003 // Full implementation of printing a Value as an operand with support for 2004 // TypePrinting, etc. 2005 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V, 2006 TypePrinting *TypePrinter, 2007 SlotTracker *Machine, 2008 const Module *Context) { 2009 if (V->hasName()) { 2010 PrintLLVMName(Out, V); 2011 return; 2012 } 2013 2014 const Constant *CV = dyn_cast<Constant>(V); 2015 if (CV && !isa<GlobalValue>(CV)) { 2016 assert(TypePrinter && "Constants require TypePrinting!"); 2017 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context); 2018 return; 2019 } 2020 2021 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 2022 Out << "asm "; 2023 if (IA->hasSideEffects()) 2024 Out << "sideeffect "; 2025 if (IA->isAlignStack()) 2026 Out << "alignstack "; 2027 // We don't emit the AD_ATT dialect as it's the assumed default. 2028 if (IA->getDialect() == InlineAsm::AD_Intel) 2029 Out << "inteldialect "; 2030 Out << '"'; 2031 PrintEscapedString(IA->getAsmString(), Out); 2032 Out << "\", \""; 2033 PrintEscapedString(IA->getConstraintString(), Out); 2034 Out << '"'; 2035 return; 2036 } 2037 2038 if (auto *MD = dyn_cast<MetadataAsValue>(V)) { 2039 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine, 2040 Context, /* FromValue */ true); 2041 return; 2042 } 2043 2044 char Prefix = '%'; 2045 int Slot; 2046 // If we have a SlotTracker, use it. 2047 if (Machine) { 2048 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2049 Slot = Machine->getGlobalSlot(GV); 2050 Prefix = '@'; 2051 } else { 2052 Slot = Machine->getLocalSlot(V); 2053 2054 // If the local value didn't succeed, then we may be referring to a value 2055 // from a different function. Translate it, as this can happen when using 2056 // address of blocks. 2057 if (Slot == -1) 2058 if ((Machine = createSlotTracker(V))) { 2059 Slot = Machine->getLocalSlot(V); 2060 delete Machine; 2061 } 2062 } 2063 } else if ((Machine = createSlotTracker(V))) { 2064 // Otherwise, create one to get the # and then destroy it. 2065 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2066 Slot = Machine->getGlobalSlot(GV); 2067 Prefix = '@'; 2068 } else { 2069 Slot = Machine->getLocalSlot(V); 2070 } 2071 delete Machine; 2072 Machine = nullptr; 2073 } else { 2074 Slot = -1; 2075 } 2076 2077 if (Slot != -1) 2078 Out << Prefix << Slot; 2079 else 2080 Out << "<badref>"; 2081 } 2082 2083 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD, 2084 TypePrinting *TypePrinter, 2085 SlotTracker *Machine, const Module *Context, 2086 bool FromValue) { 2087 // Write DIExpressions inline when used as a value. Improves readability of 2088 // debug info intrinsics. 2089 if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) { 2090 writeDIExpression(Out, Expr, TypePrinter, Machine, Context); 2091 return; 2092 } 2093 2094 if (const MDNode *N = dyn_cast<MDNode>(MD)) { 2095 std::unique_ptr<SlotTracker> MachineStorage; 2096 if (!Machine) { 2097 MachineStorage = make_unique<SlotTracker>(Context); 2098 Machine = MachineStorage.get(); 2099 } 2100 int Slot = Machine->getMetadataSlot(N); 2101 if (Slot == -1) 2102 // Give the pointer value instead of "badref", since this comes up all 2103 // the time when debugging. 2104 Out << "<" << N << ">"; 2105 else 2106 Out << '!' << Slot; 2107 return; 2108 } 2109 2110 if (const MDString *MDS = dyn_cast<MDString>(MD)) { 2111 Out << "!\""; 2112 PrintEscapedString(MDS->getString(), Out); 2113 Out << '"'; 2114 return; 2115 } 2116 2117 auto *V = cast<ValueAsMetadata>(MD); 2118 assert(TypePrinter && "TypePrinter required for metadata values"); 2119 assert((FromValue || !isa<LocalAsMetadata>(V)) && 2120 "Unexpected function-local metadata outside of value argument"); 2121 2122 TypePrinter->print(V->getValue()->getType(), Out); 2123 Out << ' '; 2124 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context); 2125 } 2126 2127 namespace { 2128 2129 class AssemblyWriter { 2130 formatted_raw_ostream &Out; 2131 const Module *TheModule; 2132 std::unique_ptr<SlotTracker> SlotTrackerStorage; 2133 SlotTracker &Machine; 2134 TypePrinting TypePrinter; 2135 AssemblyAnnotationWriter *AnnotationWriter; 2136 SetVector<const Comdat *> Comdats; 2137 bool IsForDebug; 2138 bool ShouldPreserveUseListOrder; 2139 UseListOrderStack UseListOrders; 2140 SmallVector<StringRef, 8> MDNames; 2141 /// Synchronization scope names registered with LLVMContext. 2142 SmallVector<StringRef, 8> SSNs; 2143 2144 public: 2145 /// Construct an AssemblyWriter with an external SlotTracker 2146 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M, 2147 AssemblyAnnotationWriter *AAW, bool IsForDebug, 2148 bool ShouldPreserveUseListOrder = false); 2149 2150 void printMDNodeBody(const MDNode *MD); 2151 void printNamedMDNode(const NamedMDNode *NMD); 2152 2153 void printModule(const Module *M); 2154 2155 void writeOperand(const Value *Op, bool PrintType); 2156 void writeParamOperand(const Value *Operand, AttributeSet Attrs); 2157 void writeOperandBundles(ImmutableCallSite CS); 2158 void writeSyncScope(const LLVMContext &Context, 2159 SyncScope::ID SSID); 2160 void writeAtomic(const LLVMContext &Context, 2161 AtomicOrdering Ordering, 2162 SyncScope::ID SSID); 2163 void writeAtomicCmpXchg(const LLVMContext &Context, 2164 AtomicOrdering SuccessOrdering, 2165 AtomicOrdering FailureOrdering, 2166 SyncScope::ID SSID); 2167 2168 void writeAllMDNodes(); 2169 void writeMDNode(unsigned Slot, const MDNode *Node); 2170 void writeAllAttributeGroups(); 2171 2172 void printTypeIdentities(); 2173 void printGlobal(const GlobalVariable *GV); 2174 void printIndirectSymbol(const GlobalIndirectSymbol *GIS); 2175 void printComdat(const Comdat *C); 2176 void printFunction(const Function *F); 2177 void printArgument(const Argument *FA, AttributeSet Attrs); 2178 void printBasicBlock(const BasicBlock *BB); 2179 void printInstructionLine(const Instruction &I); 2180 void printInstruction(const Instruction &I); 2181 2182 void printUseListOrder(const UseListOrder &Order); 2183 void printUseLists(const Function *F); 2184 2185 private: 2186 /// \brief Print out metadata attachments. 2187 void printMetadataAttachments( 2188 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 2189 StringRef Separator); 2190 2191 // printInfoComment - Print a little comment after the instruction indicating 2192 // which slot it occupies. 2193 void printInfoComment(const Value &V); 2194 2195 // printGCRelocateComment - print comment after call to the gc.relocate 2196 // intrinsic indicating base and derived pointer names. 2197 void printGCRelocateComment(const GCRelocateInst &Relocate); 2198 }; 2199 2200 } // end anonymous namespace 2201 2202 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, 2203 const Module *M, AssemblyAnnotationWriter *AAW, 2204 bool IsForDebug, bool ShouldPreserveUseListOrder) 2205 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW), 2206 IsForDebug(IsForDebug), 2207 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 2208 if (!TheModule) 2209 return; 2210 TypePrinter.incorporateTypes(*TheModule); 2211 for (const GlobalObject &GO : TheModule->global_objects()) 2212 if (const Comdat *C = GO.getComdat()) 2213 Comdats.insert(C); 2214 } 2215 2216 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) { 2217 if (!Operand) { 2218 Out << "<null operand!>"; 2219 return; 2220 } 2221 if (PrintType) { 2222 TypePrinter.print(Operand->getType(), Out); 2223 Out << ' '; 2224 } 2225 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2226 } 2227 2228 void AssemblyWriter::writeSyncScope(const LLVMContext &Context, 2229 SyncScope::ID SSID) { 2230 switch (SSID) { 2231 case SyncScope::System: { 2232 break; 2233 } 2234 default: { 2235 if (SSNs.empty()) 2236 Context.getSyncScopeNames(SSNs); 2237 2238 Out << " syncscope(\""; 2239 PrintEscapedString(SSNs[SSID], Out); 2240 Out << "\")"; 2241 break; 2242 } 2243 } 2244 } 2245 2246 void AssemblyWriter::writeAtomic(const LLVMContext &Context, 2247 AtomicOrdering Ordering, 2248 SyncScope::ID SSID) { 2249 if (Ordering == AtomicOrdering::NotAtomic) 2250 return; 2251 2252 writeSyncScope(Context, SSID); 2253 Out << " " << toIRString(Ordering); 2254 } 2255 2256 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context, 2257 AtomicOrdering SuccessOrdering, 2258 AtomicOrdering FailureOrdering, 2259 SyncScope::ID SSID) { 2260 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 2261 FailureOrdering != AtomicOrdering::NotAtomic); 2262 2263 writeSyncScope(Context, SSID); 2264 Out << " " << toIRString(SuccessOrdering); 2265 Out << " " << toIRString(FailureOrdering); 2266 } 2267 2268 void AssemblyWriter::writeParamOperand(const Value *Operand, 2269 AttributeSet Attrs) { 2270 if (!Operand) { 2271 Out << "<null operand!>"; 2272 return; 2273 } 2274 2275 // Print the type 2276 TypePrinter.print(Operand->getType(), Out); 2277 // Print parameter attributes list 2278 if (Attrs.hasAttributes()) 2279 Out << ' ' << Attrs.getAsString(); 2280 Out << ' '; 2281 // Print the operand 2282 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule); 2283 } 2284 2285 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) { 2286 if (!CS.hasOperandBundles()) 2287 return; 2288 2289 Out << " [ "; 2290 2291 bool FirstBundle = true; 2292 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) { 2293 OperandBundleUse BU = CS.getOperandBundleAt(i); 2294 2295 if (!FirstBundle) 2296 Out << ", "; 2297 FirstBundle = false; 2298 2299 Out << '"'; 2300 PrintEscapedString(BU.getTagName(), Out); 2301 Out << '"'; 2302 2303 Out << '('; 2304 2305 bool FirstInput = true; 2306 for (const auto &Input : BU.Inputs) { 2307 if (!FirstInput) 2308 Out << ", "; 2309 FirstInput = false; 2310 2311 TypePrinter.print(Input->getType(), Out); 2312 Out << " "; 2313 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule); 2314 } 2315 2316 Out << ')'; 2317 } 2318 2319 Out << " ]"; 2320 } 2321 2322 void AssemblyWriter::printModule(const Module *M) { 2323 Machine.initialize(); 2324 2325 if (ShouldPreserveUseListOrder) 2326 UseListOrders = predictUseListOrder(M); 2327 2328 if (!M->getModuleIdentifier().empty() && 2329 // Don't print the ID if it will start a new line (which would 2330 // require a comment char before it). 2331 M->getModuleIdentifier().find('\n') == std::string::npos) 2332 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 2333 2334 if (!M->getSourceFileName().empty()) { 2335 Out << "source_filename = \""; 2336 PrintEscapedString(M->getSourceFileName(), Out); 2337 Out << "\"\n"; 2338 } 2339 2340 const std::string &DL = M->getDataLayoutStr(); 2341 if (!DL.empty()) 2342 Out << "target datalayout = \"" << DL << "\"\n"; 2343 if (!M->getTargetTriple().empty()) 2344 Out << "target triple = \"" << M->getTargetTriple() << "\"\n"; 2345 2346 if (!M->getModuleInlineAsm().empty()) { 2347 Out << '\n'; 2348 2349 // Split the string into lines, to make it easier to read the .ll file. 2350 StringRef Asm = M->getModuleInlineAsm(); 2351 do { 2352 StringRef Front; 2353 std::tie(Front, Asm) = Asm.split('\n'); 2354 2355 // We found a newline, print the portion of the asm string from the 2356 // last newline up to this newline. 2357 Out << "module asm \""; 2358 PrintEscapedString(Front, Out); 2359 Out << "\"\n"; 2360 } while (!Asm.empty()); 2361 } 2362 2363 printTypeIdentities(); 2364 2365 // Output all comdats. 2366 if (!Comdats.empty()) 2367 Out << '\n'; 2368 for (const Comdat *C : Comdats) { 2369 printComdat(C); 2370 if (C != Comdats.back()) 2371 Out << '\n'; 2372 } 2373 2374 // Output all globals. 2375 if (!M->global_empty()) Out << '\n'; 2376 for (const GlobalVariable &GV : M->globals()) { 2377 printGlobal(&GV); Out << '\n'; 2378 } 2379 2380 // Output all aliases. 2381 if (!M->alias_empty()) Out << "\n"; 2382 for (const GlobalAlias &GA : M->aliases()) 2383 printIndirectSymbol(&GA); 2384 2385 // Output all ifuncs. 2386 if (!M->ifunc_empty()) Out << "\n"; 2387 for (const GlobalIFunc &GI : M->ifuncs()) 2388 printIndirectSymbol(&GI); 2389 2390 // Output global use-lists. 2391 printUseLists(nullptr); 2392 2393 // Output all of the functions. 2394 for (const Function &F : *M) 2395 printFunction(&F); 2396 assert(UseListOrders.empty() && "All use-lists should have been consumed"); 2397 2398 // Output all attribute groups. 2399 if (!Machine.as_empty()) { 2400 Out << '\n'; 2401 writeAllAttributeGroups(); 2402 } 2403 2404 // Output named metadata. 2405 if (!M->named_metadata_empty()) Out << '\n'; 2406 2407 for (const NamedMDNode &Node : M->named_metadata()) 2408 printNamedMDNode(&Node); 2409 2410 // Output metadata. 2411 if (!Machine.mdn_empty()) { 2412 Out << '\n'; 2413 writeAllMDNodes(); 2414 } 2415 } 2416 2417 static void printMetadataIdentifier(StringRef Name, 2418 formatted_raw_ostream &Out) { 2419 if (Name.empty()) { 2420 Out << "<empty name> "; 2421 } else { 2422 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' || 2423 Name[0] == '$' || Name[0] == '.' || Name[0] == '_') 2424 Out << Name[0]; 2425 else 2426 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F); 2427 for (unsigned i = 1, e = Name.size(); i != e; ++i) { 2428 unsigned char C = Name[i]; 2429 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' || 2430 C == '.' || C == '_') 2431 Out << C; 2432 else 2433 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F); 2434 } 2435 } 2436 } 2437 2438 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) { 2439 Out << '!'; 2440 printMetadataIdentifier(NMD->getName(), Out); 2441 Out << " = !{"; 2442 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2443 if (i) 2444 Out << ", "; 2445 2446 // Write DIExpressions inline. 2447 // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose. 2448 MDNode *Op = NMD->getOperand(i); 2449 if (auto *Expr = dyn_cast<DIExpression>(Op)) { 2450 writeDIExpression(Out, Expr, nullptr, nullptr, nullptr); 2451 continue; 2452 } 2453 2454 int Slot = Machine.getMetadataSlot(Op); 2455 if (Slot == -1) 2456 Out << "<badref>"; 2457 else 2458 Out << '!' << Slot; 2459 } 2460 Out << "}\n"; 2461 } 2462 2463 static const char *getLinkagePrintName(GlobalValue::LinkageTypes LT) { 2464 switch (LT) { 2465 case GlobalValue::ExternalLinkage: 2466 return ""; 2467 case GlobalValue::PrivateLinkage: 2468 return "private "; 2469 case GlobalValue::InternalLinkage: 2470 return "internal "; 2471 case GlobalValue::LinkOnceAnyLinkage: 2472 return "linkonce "; 2473 case GlobalValue::LinkOnceODRLinkage: 2474 return "linkonce_odr "; 2475 case GlobalValue::WeakAnyLinkage: 2476 return "weak "; 2477 case GlobalValue::WeakODRLinkage: 2478 return "weak_odr "; 2479 case GlobalValue::CommonLinkage: 2480 return "common "; 2481 case GlobalValue::AppendingLinkage: 2482 return "appending "; 2483 case GlobalValue::ExternalWeakLinkage: 2484 return "extern_weak "; 2485 case GlobalValue::AvailableExternallyLinkage: 2486 return "available_externally "; 2487 } 2488 llvm_unreachable("invalid linkage"); 2489 } 2490 2491 static void PrintVisibility(GlobalValue::VisibilityTypes Vis, 2492 formatted_raw_ostream &Out) { 2493 switch (Vis) { 2494 case GlobalValue::DefaultVisibility: break; 2495 case GlobalValue::HiddenVisibility: Out << "hidden "; break; 2496 case GlobalValue::ProtectedVisibility: Out << "protected "; break; 2497 } 2498 } 2499 2500 static void PrintDSOLocation(bool IsDSOLocal, formatted_raw_ostream &Out){ 2501 if (IsDSOLocal) 2502 Out << "dso_local "; 2503 } 2504 2505 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT, 2506 formatted_raw_ostream &Out) { 2507 switch (SCT) { 2508 case GlobalValue::DefaultStorageClass: break; 2509 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break; 2510 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break; 2511 } 2512 } 2513 2514 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM, 2515 formatted_raw_ostream &Out) { 2516 switch (TLM) { 2517 case GlobalVariable::NotThreadLocal: 2518 break; 2519 case GlobalVariable::GeneralDynamicTLSModel: 2520 Out << "thread_local "; 2521 break; 2522 case GlobalVariable::LocalDynamicTLSModel: 2523 Out << "thread_local(localdynamic) "; 2524 break; 2525 case GlobalVariable::InitialExecTLSModel: 2526 Out << "thread_local(initialexec) "; 2527 break; 2528 case GlobalVariable::LocalExecTLSModel: 2529 Out << "thread_local(localexec) "; 2530 break; 2531 } 2532 } 2533 2534 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) { 2535 switch (UA) { 2536 case GlobalVariable::UnnamedAddr::None: 2537 return ""; 2538 case GlobalVariable::UnnamedAddr::Local: 2539 return "local_unnamed_addr"; 2540 case GlobalVariable::UnnamedAddr::Global: 2541 return "unnamed_addr"; 2542 } 2543 llvm_unreachable("Unknown UnnamedAddr"); 2544 } 2545 2546 static void maybePrintComdat(formatted_raw_ostream &Out, 2547 const GlobalObject &GO) { 2548 const Comdat *C = GO.getComdat(); 2549 if (!C) 2550 return; 2551 2552 if (isa<GlobalVariable>(GO)) 2553 Out << ','; 2554 Out << " comdat"; 2555 2556 if (GO.getName() == C->getName()) 2557 return; 2558 2559 Out << '('; 2560 PrintLLVMName(Out, C->getName(), ComdatPrefix); 2561 Out << ')'; 2562 } 2563 2564 void AssemblyWriter::printGlobal(const GlobalVariable *GV) { 2565 if (GV->isMaterializable()) 2566 Out << "; Materializable\n"; 2567 2568 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent()); 2569 Out << " = "; 2570 2571 if (!GV->hasInitializer() && GV->hasExternalLinkage()) 2572 Out << "external "; 2573 2574 Out << getLinkagePrintName(GV->getLinkage()); 2575 PrintDSOLocation(GV->isDSOLocal(), Out); 2576 PrintVisibility(GV->getVisibility(), Out); 2577 PrintDLLStorageClass(GV->getDLLStorageClass(), Out); 2578 PrintThreadLocalModel(GV->getThreadLocalMode(), Out); 2579 StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr()); 2580 if (!UA.empty()) 2581 Out << UA << ' '; 2582 2583 if (unsigned AddressSpace = GV->getType()->getAddressSpace()) 2584 Out << "addrspace(" << AddressSpace << ") "; 2585 if (GV->isExternallyInitialized()) Out << "externally_initialized "; 2586 Out << (GV->isConstant() ? "constant " : "global "); 2587 TypePrinter.print(GV->getValueType(), Out); 2588 2589 if (GV->hasInitializer()) { 2590 Out << ' '; 2591 writeOperand(GV->getInitializer(), false); 2592 } 2593 2594 if (GV->hasSection()) { 2595 Out << ", section \""; 2596 PrintEscapedString(GV->getSection(), Out); 2597 Out << '"'; 2598 } 2599 maybePrintComdat(Out, *GV); 2600 if (GV->getAlignment()) 2601 Out << ", align " << GV->getAlignment(); 2602 2603 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2604 GV->getAllMetadata(MDs); 2605 printMetadataAttachments(MDs, ", "); 2606 2607 auto Attrs = GV->getAttributes(); 2608 if (Attrs.hasAttributes()) 2609 Out << " #" << Machine.getAttributeGroupSlot(Attrs); 2610 2611 printInfoComment(*GV); 2612 } 2613 2614 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) { 2615 if (GIS->isMaterializable()) 2616 Out << "; Materializable\n"; 2617 2618 WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent()); 2619 Out << " = "; 2620 2621 Out << getLinkagePrintName(GIS->getLinkage()); 2622 PrintDSOLocation(GIS->isDSOLocal(), Out); 2623 PrintVisibility(GIS->getVisibility(), Out); 2624 PrintDLLStorageClass(GIS->getDLLStorageClass(), Out); 2625 PrintThreadLocalModel(GIS->getThreadLocalMode(), Out); 2626 StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr()); 2627 if (!UA.empty()) 2628 Out << UA << ' '; 2629 2630 if (isa<GlobalAlias>(GIS)) 2631 Out << "alias "; 2632 else if (isa<GlobalIFunc>(GIS)) 2633 Out << "ifunc "; 2634 else 2635 llvm_unreachable("Not an alias or ifunc!"); 2636 2637 TypePrinter.print(GIS->getValueType(), Out); 2638 2639 Out << ", "; 2640 2641 const Constant *IS = GIS->getIndirectSymbol(); 2642 2643 if (!IS) { 2644 TypePrinter.print(GIS->getType(), Out); 2645 Out << " <<NULL ALIASEE>>"; 2646 } else { 2647 writeOperand(IS, !isa<ConstantExpr>(IS)); 2648 } 2649 2650 printInfoComment(*GIS); 2651 Out << '\n'; 2652 } 2653 2654 void AssemblyWriter::printComdat(const Comdat *C) { 2655 C->print(Out); 2656 } 2657 2658 void AssemblyWriter::printTypeIdentities() { 2659 if (TypePrinter.NumberedTypes.empty() && 2660 TypePrinter.NamedTypes.empty()) 2661 return; 2662 2663 Out << '\n'; 2664 2665 // We know all the numbers that each type is used and we know that it is a 2666 // dense assignment. Convert the map to an index table. 2667 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size()); 2668 for (DenseMap<StructType*, unsigned>::iterator I = 2669 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end(); 2670 I != E; ++I) { 2671 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?"); 2672 NumberedTypes[I->second] = I->first; 2673 } 2674 2675 // Emit all numbered types. 2676 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) { 2677 Out << '%' << i << " = type "; 2678 2679 // Make sure we print out at least one level of the type structure, so 2680 // that we do not get %2 = type %2 2681 TypePrinter.printStructBody(NumberedTypes[i], Out); 2682 Out << '\n'; 2683 } 2684 2685 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) { 2686 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix); 2687 Out << " = type "; 2688 2689 // Make sure we print out at least one level of the type structure, so 2690 // that we do not get %FILE = type %FILE 2691 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out); 2692 Out << '\n'; 2693 } 2694 } 2695 2696 /// printFunction - Print all aspects of a function. 2697 void AssemblyWriter::printFunction(const Function *F) { 2698 // Print out the return type and name. 2699 Out << '\n'; 2700 2701 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out); 2702 2703 if (F->isMaterializable()) 2704 Out << "; Materializable\n"; 2705 2706 const AttributeList &Attrs = F->getAttributes(); 2707 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) { 2708 AttributeSet AS = Attrs.getFnAttributes(); 2709 std::string AttrStr; 2710 2711 for (const Attribute &Attr : AS) { 2712 if (!Attr.isStringAttribute()) { 2713 if (!AttrStr.empty()) AttrStr += ' '; 2714 AttrStr += Attr.getAsString(); 2715 } 2716 } 2717 2718 if (!AttrStr.empty()) 2719 Out << "; Function Attrs: " << AttrStr << '\n'; 2720 } 2721 2722 Machine.incorporateFunction(F); 2723 2724 if (F->isDeclaration()) { 2725 Out << "declare"; 2726 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2727 F->getAllMetadata(MDs); 2728 printMetadataAttachments(MDs, " "); 2729 Out << ' '; 2730 } else 2731 Out << "define "; 2732 2733 Out << getLinkagePrintName(F->getLinkage()); 2734 PrintDSOLocation(F->isDSOLocal(), Out); 2735 PrintVisibility(F->getVisibility(), Out); 2736 PrintDLLStorageClass(F->getDLLStorageClass(), Out); 2737 2738 // Print the calling convention. 2739 if (F->getCallingConv() != CallingConv::C) { 2740 PrintCallingConv(F->getCallingConv(), Out); 2741 Out << " "; 2742 } 2743 2744 FunctionType *FT = F->getFunctionType(); 2745 if (Attrs.hasAttributes(AttributeList::ReturnIndex)) 2746 Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' '; 2747 TypePrinter.print(F->getReturnType(), Out); 2748 Out << ' '; 2749 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent()); 2750 Out << '('; 2751 2752 // Loop over the arguments, printing them... 2753 if (F->isDeclaration() && !IsForDebug) { 2754 // We're only interested in the type here - don't print argument names. 2755 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) { 2756 // Insert commas as we go... the first arg doesn't get a comma 2757 if (I) 2758 Out << ", "; 2759 // Output type... 2760 TypePrinter.print(FT->getParamType(I), Out); 2761 2762 AttributeSet ArgAttrs = Attrs.getParamAttributes(I); 2763 if (ArgAttrs.hasAttributes()) 2764 Out << ' ' << ArgAttrs.getAsString(); 2765 } 2766 } else { 2767 // The arguments are meaningful here, print them in detail. 2768 for (const Argument &Arg : F->args()) { 2769 // Insert commas as we go... the first arg doesn't get a comma 2770 if (Arg.getArgNo() != 0) 2771 Out << ", "; 2772 printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo())); 2773 } 2774 } 2775 2776 // Finish printing arguments... 2777 if (FT->isVarArg()) { 2778 if (FT->getNumParams()) Out << ", "; 2779 Out << "..."; // Output varargs portion of signature! 2780 } 2781 Out << ')'; 2782 StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr()); 2783 if (!UA.empty()) 2784 Out << ' ' << UA; 2785 if (Attrs.hasAttributes(AttributeList::FunctionIndex)) 2786 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes()); 2787 if (F->hasSection()) { 2788 Out << " section \""; 2789 PrintEscapedString(F->getSection(), Out); 2790 Out << '"'; 2791 } 2792 maybePrintComdat(Out, *F); 2793 if (F->getAlignment()) 2794 Out << " align " << F->getAlignment(); 2795 if (F->hasGC()) 2796 Out << " gc \"" << F->getGC() << '"'; 2797 if (F->hasPrefixData()) { 2798 Out << " prefix "; 2799 writeOperand(F->getPrefixData(), true); 2800 } 2801 if (F->hasPrologueData()) { 2802 Out << " prologue "; 2803 writeOperand(F->getPrologueData(), true); 2804 } 2805 if (F->hasPersonalityFn()) { 2806 Out << " personality "; 2807 writeOperand(F->getPersonalityFn(), /*PrintType=*/true); 2808 } 2809 2810 if (F->isDeclaration()) { 2811 Out << '\n'; 2812 } else { 2813 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2814 F->getAllMetadata(MDs); 2815 printMetadataAttachments(MDs, " "); 2816 2817 Out << " {"; 2818 // Output all of the function's basic blocks. 2819 for (const BasicBlock &BB : *F) 2820 printBasicBlock(&BB); 2821 2822 // Output the function's use-lists. 2823 printUseLists(F); 2824 2825 Out << "}\n"; 2826 } 2827 2828 Machine.purgeFunction(); 2829 } 2830 2831 /// printArgument - This member is called for every argument that is passed into 2832 /// the function. Simply print it out 2833 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) { 2834 // Output type... 2835 TypePrinter.print(Arg->getType(), Out); 2836 2837 // Output parameter attributes list 2838 if (Attrs.hasAttributes()) 2839 Out << ' ' << Attrs.getAsString(); 2840 2841 // Output name, if available... 2842 if (Arg->hasName()) { 2843 Out << ' '; 2844 PrintLLVMName(Out, Arg); 2845 } 2846 } 2847 2848 /// printBasicBlock - This member is called for each basic block in a method. 2849 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) { 2850 if (BB->hasName()) { // Print out the label if it exists... 2851 Out << "\n"; 2852 PrintLLVMName(Out, BB->getName(), LabelPrefix); 2853 Out << ':'; 2854 } else if (!BB->use_empty()) { // Don't print block # of no uses... 2855 Out << "\n; <label>:"; 2856 int Slot = Machine.getLocalSlot(BB); 2857 if (Slot != -1) 2858 Out << Slot << ":"; 2859 else 2860 Out << "<badref>"; 2861 } 2862 2863 if (!BB->getParent()) { 2864 Out.PadToColumn(50); 2865 Out << "; Error: Block without parent!"; 2866 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block? 2867 // Output predecessors for the block. 2868 Out.PadToColumn(50); 2869 Out << ";"; 2870 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB); 2871 2872 if (PI == PE) { 2873 Out << " No predecessors!"; 2874 } else { 2875 Out << " preds = "; 2876 writeOperand(*PI, false); 2877 for (++PI; PI != PE; ++PI) { 2878 Out << ", "; 2879 writeOperand(*PI, false); 2880 } 2881 } 2882 } 2883 2884 Out << "\n"; 2885 2886 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out); 2887 2888 // Output all of the instructions in the basic block... 2889 for (const Instruction &I : *BB) { 2890 printInstructionLine(I); 2891 } 2892 2893 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out); 2894 } 2895 2896 /// printInstructionLine - Print an instruction and a newline character. 2897 void AssemblyWriter::printInstructionLine(const Instruction &I) { 2898 printInstruction(I); 2899 Out << '\n'; 2900 } 2901 2902 /// printGCRelocateComment - print comment after call to the gc.relocate 2903 /// intrinsic indicating base and derived pointer names. 2904 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) { 2905 Out << " ; ("; 2906 writeOperand(Relocate.getBasePtr(), false); 2907 Out << ", "; 2908 writeOperand(Relocate.getDerivedPtr(), false); 2909 Out << ")"; 2910 } 2911 2912 /// printInfoComment - Print a little comment after the instruction indicating 2913 /// which slot it occupies. 2914 void AssemblyWriter::printInfoComment(const Value &V) { 2915 if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V)) 2916 printGCRelocateComment(*Relocate); 2917 2918 if (AnnotationWriter) 2919 AnnotationWriter->printInfoComment(V, Out); 2920 } 2921 2922 // This member is called for each Instruction in a function.. 2923 void AssemblyWriter::printInstruction(const Instruction &I) { 2924 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out); 2925 2926 // Print out indentation for an instruction. 2927 Out << " "; 2928 2929 // Print out name if it exists... 2930 if (I.hasName()) { 2931 PrintLLVMName(Out, &I); 2932 Out << " = "; 2933 } else if (!I.getType()->isVoidTy()) { 2934 // Print out the def slot taken. 2935 int SlotNum = Machine.getLocalSlot(&I); 2936 if (SlotNum == -1) 2937 Out << "<badref> = "; 2938 else 2939 Out << '%' << SlotNum << " = "; 2940 } 2941 2942 if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 2943 if (CI->isMustTailCall()) 2944 Out << "musttail "; 2945 else if (CI->isTailCall()) 2946 Out << "tail "; 2947 else if (CI->isNoTailCall()) 2948 Out << "notail "; 2949 } 2950 2951 // Print out the opcode... 2952 Out << I.getOpcodeName(); 2953 2954 // If this is an atomic load or store, print out the atomic marker. 2955 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) || 2956 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic())) 2957 Out << " atomic"; 2958 2959 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak()) 2960 Out << " weak"; 2961 2962 // If this is a volatile operation, print out the volatile marker. 2963 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) || 2964 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) || 2965 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) || 2966 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile())) 2967 Out << " volatile"; 2968 2969 // Print out optimization information. 2970 WriteOptimizationInfo(Out, &I); 2971 2972 // Print out the compare instruction predicates 2973 if (const CmpInst *CI = dyn_cast<CmpInst>(&I)) 2974 Out << ' ' << CmpInst::getPredicateName(CI->getPredicate()); 2975 2976 // Print out the atomicrmw operation 2977 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) 2978 writeAtomicRMWOperation(Out, RMWI->getOperation()); 2979 2980 // Print out the type of the operands... 2981 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr; 2982 2983 // Special case conditional branches to swizzle the condition out to the front 2984 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) { 2985 const BranchInst &BI(cast<BranchInst>(I)); 2986 Out << ' '; 2987 writeOperand(BI.getCondition(), true); 2988 Out << ", "; 2989 writeOperand(BI.getSuccessor(0), true); 2990 Out << ", "; 2991 writeOperand(BI.getSuccessor(1), true); 2992 2993 } else if (isa<SwitchInst>(I)) { 2994 const SwitchInst& SI(cast<SwitchInst>(I)); 2995 // Special case switch instruction to get formatting nice and correct. 2996 Out << ' '; 2997 writeOperand(SI.getCondition(), true); 2998 Out << ", "; 2999 writeOperand(SI.getDefaultDest(), true); 3000 Out << " ["; 3001 for (auto Case : SI.cases()) { 3002 Out << "\n "; 3003 writeOperand(Case.getCaseValue(), true); 3004 Out << ", "; 3005 writeOperand(Case.getCaseSuccessor(), true); 3006 } 3007 Out << "\n ]"; 3008 } else if (isa<IndirectBrInst>(I)) { 3009 // Special case indirectbr instruction to get formatting nice and correct. 3010 Out << ' '; 3011 writeOperand(Operand, true); 3012 Out << ", ["; 3013 3014 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 3015 if (i != 1) 3016 Out << ", "; 3017 writeOperand(I.getOperand(i), true); 3018 } 3019 Out << ']'; 3020 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) { 3021 Out << ' '; 3022 TypePrinter.print(I.getType(), Out); 3023 Out << ' '; 3024 3025 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) { 3026 if (op) Out << ", "; 3027 Out << "[ "; 3028 writeOperand(PN->getIncomingValue(op), false); Out << ", "; 3029 writeOperand(PN->getIncomingBlock(op), false); Out << " ]"; 3030 } 3031 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) { 3032 Out << ' '; 3033 writeOperand(I.getOperand(0), true); 3034 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 3035 Out << ", " << *i; 3036 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) { 3037 Out << ' '; 3038 writeOperand(I.getOperand(0), true); Out << ", "; 3039 writeOperand(I.getOperand(1), true); 3040 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 3041 Out << ", " << *i; 3042 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) { 3043 Out << ' '; 3044 TypePrinter.print(I.getType(), Out); 3045 if (LPI->isCleanup() || LPI->getNumClauses() != 0) 3046 Out << '\n'; 3047 3048 if (LPI->isCleanup()) 3049 Out << " cleanup"; 3050 3051 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) { 3052 if (i != 0 || LPI->isCleanup()) Out << "\n"; 3053 if (LPI->isCatch(i)) 3054 Out << " catch "; 3055 else 3056 Out << " filter "; 3057 3058 writeOperand(LPI->getClause(i), true); 3059 } 3060 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) { 3061 Out << " within "; 3062 writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false); 3063 Out << " ["; 3064 unsigned Op = 0; 3065 for (const BasicBlock *PadBB : CatchSwitch->handlers()) { 3066 if (Op > 0) 3067 Out << ", "; 3068 writeOperand(PadBB, /*PrintType=*/true); 3069 ++Op; 3070 } 3071 Out << "] unwind "; 3072 if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest()) 3073 writeOperand(UnwindDest, /*PrintType=*/true); 3074 else 3075 Out << "to caller"; 3076 } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) { 3077 Out << " within "; 3078 writeOperand(FPI->getParentPad(), /*PrintType=*/false); 3079 Out << " ["; 3080 for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps; 3081 ++Op) { 3082 if (Op > 0) 3083 Out << ", "; 3084 writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true); 3085 } 3086 Out << ']'; 3087 } else if (isa<ReturnInst>(I) && !Operand) { 3088 Out << " void"; 3089 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) { 3090 Out << " from "; 3091 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 3092 3093 Out << " to "; 3094 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 3095 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) { 3096 Out << " from "; 3097 writeOperand(CRI->getOperand(0), /*PrintType=*/false); 3098 3099 Out << " unwind "; 3100 if (CRI->hasUnwindDest()) 3101 writeOperand(CRI->getOperand(1), /*PrintType=*/true); 3102 else 3103 Out << "to caller"; 3104 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) { 3105 // Print the calling convention being used. 3106 if (CI->getCallingConv() != CallingConv::C) { 3107 Out << " "; 3108 PrintCallingConv(CI->getCallingConv(), Out); 3109 } 3110 3111 Operand = CI->getCalledValue(); 3112 FunctionType *FTy = CI->getFunctionType(); 3113 Type *RetTy = FTy->getReturnType(); 3114 const AttributeList &PAL = CI->getAttributes(); 3115 3116 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 3117 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 3118 3119 // If possible, print out the short form of the call instruction. We can 3120 // only do this if the first argument is a pointer to a nonvararg function, 3121 // and if the return type is not a pointer to a function. 3122 // 3123 Out << ' '; 3124 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 3125 Out << ' '; 3126 writeOperand(Operand, false); 3127 Out << '('; 3128 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) { 3129 if (op > 0) 3130 Out << ", "; 3131 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op)); 3132 } 3133 3134 // Emit an ellipsis if this is a musttail call in a vararg function. This 3135 // is only to aid readability, musttail calls forward varargs by default. 3136 if (CI->isMustTailCall() && CI->getParent() && 3137 CI->getParent()->getParent() && 3138 CI->getParent()->getParent()->isVarArg()) 3139 Out << ", ..."; 3140 3141 Out << ')'; 3142 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 3143 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 3144 3145 writeOperandBundles(CI); 3146 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) { 3147 Operand = II->getCalledValue(); 3148 FunctionType *FTy = II->getFunctionType(); 3149 Type *RetTy = FTy->getReturnType(); 3150 const AttributeList &PAL = II->getAttributes(); 3151 3152 // Print the calling convention being used. 3153 if (II->getCallingConv() != CallingConv::C) { 3154 Out << " "; 3155 PrintCallingConv(II->getCallingConv(), Out); 3156 } 3157 3158 if (PAL.hasAttributes(AttributeList::ReturnIndex)) 3159 Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex); 3160 3161 // If possible, print out the short form of the invoke instruction. We can 3162 // only do this if the first argument is a pointer to a nonvararg function, 3163 // and if the return type is not a pointer to a function. 3164 // 3165 Out << ' '; 3166 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out); 3167 Out << ' '; 3168 writeOperand(Operand, false); 3169 Out << '('; 3170 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) { 3171 if (op) 3172 Out << ", "; 3173 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op)); 3174 } 3175 3176 Out << ')'; 3177 if (PAL.hasAttributes(AttributeList::FunctionIndex)) 3178 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes()); 3179 3180 writeOperandBundles(II); 3181 3182 Out << "\n to "; 3183 writeOperand(II->getNormalDest(), true); 3184 Out << " unwind "; 3185 writeOperand(II->getUnwindDest(), true); 3186 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) { 3187 Out << ' '; 3188 if (AI->isUsedWithInAlloca()) 3189 Out << "inalloca "; 3190 if (AI->isSwiftError()) 3191 Out << "swifterror "; 3192 TypePrinter.print(AI->getAllocatedType(), Out); 3193 3194 // Explicitly write the array size if the code is broken, if it's an array 3195 // allocation, or if the type is not canonical for scalar allocations. The 3196 // latter case prevents the type from mutating when round-tripping through 3197 // assembly. 3198 if (!AI->getArraySize() || AI->isArrayAllocation() || 3199 !AI->getArraySize()->getType()->isIntegerTy(32)) { 3200 Out << ", "; 3201 writeOperand(AI->getArraySize(), true); 3202 } 3203 if (AI->getAlignment()) { 3204 Out << ", align " << AI->getAlignment(); 3205 } 3206 3207 unsigned AddrSpace = AI->getType()->getAddressSpace(); 3208 if (AddrSpace != 0) { 3209 Out << ", addrspace(" << AddrSpace << ')'; 3210 } 3211 } else if (isa<CastInst>(I)) { 3212 if (Operand) { 3213 Out << ' '; 3214 writeOperand(Operand, true); // Work with broken code 3215 } 3216 Out << " to "; 3217 TypePrinter.print(I.getType(), Out); 3218 } else if (isa<VAArgInst>(I)) { 3219 if (Operand) { 3220 Out << ' '; 3221 writeOperand(Operand, true); // Work with broken code 3222 } 3223 Out << ", "; 3224 TypePrinter.print(I.getType(), Out); 3225 } else if (Operand) { // Print the normal way. 3226 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 3227 Out << ' '; 3228 TypePrinter.print(GEP->getSourceElementType(), Out); 3229 Out << ','; 3230 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) { 3231 Out << ' '; 3232 TypePrinter.print(LI->getType(), Out); 3233 Out << ','; 3234 } 3235 3236 // PrintAllTypes - Instructions who have operands of all the same type 3237 // omit the type from all but the first operand. If the instruction has 3238 // different type operands (for example br), then they are all printed. 3239 bool PrintAllTypes = false; 3240 Type *TheType = Operand->getType(); 3241 3242 // Select, Store and ShuffleVector always print all types. 3243 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I) 3244 || isa<ReturnInst>(I)) { 3245 PrintAllTypes = true; 3246 } else { 3247 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) { 3248 Operand = I.getOperand(i); 3249 // note that Operand shouldn't be null, but the test helps make dump() 3250 // more tolerant of malformed IR 3251 if (Operand && Operand->getType() != TheType) { 3252 PrintAllTypes = true; // We have differing types! Print them all! 3253 break; 3254 } 3255 } 3256 } 3257 3258 if (!PrintAllTypes) { 3259 Out << ' '; 3260 TypePrinter.print(TheType, Out); 3261 } 3262 3263 Out << ' '; 3264 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) { 3265 if (i) Out << ", "; 3266 writeOperand(I.getOperand(i), PrintAllTypes); 3267 } 3268 } 3269 3270 // Print atomic ordering/alignment for memory operations 3271 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 3272 if (LI->isAtomic()) 3273 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID()); 3274 if (LI->getAlignment()) 3275 Out << ", align " << LI->getAlignment(); 3276 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 3277 if (SI->isAtomic()) 3278 writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID()); 3279 if (SI->getAlignment()) 3280 Out << ", align " << SI->getAlignment(); 3281 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) { 3282 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(), 3283 CXI->getFailureOrdering(), CXI->getSyncScopeID()); 3284 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) { 3285 writeAtomic(RMWI->getContext(), RMWI->getOrdering(), 3286 RMWI->getSyncScopeID()); 3287 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) { 3288 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID()); 3289 } 3290 3291 // Print Metadata info. 3292 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD; 3293 I.getAllMetadata(InstMD); 3294 printMetadataAttachments(InstMD, ", "); 3295 3296 // Print a nice comment. 3297 printInfoComment(I); 3298 } 3299 3300 void AssemblyWriter::printMetadataAttachments( 3301 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs, 3302 StringRef Separator) { 3303 if (MDs.empty()) 3304 return; 3305 3306 if (MDNames.empty()) 3307 MDs[0].second->getContext().getMDKindNames(MDNames); 3308 3309 for (const auto &I : MDs) { 3310 unsigned Kind = I.first; 3311 Out << Separator; 3312 if (Kind < MDNames.size()) { 3313 Out << "!"; 3314 printMetadataIdentifier(MDNames[Kind], Out); 3315 } else 3316 Out << "!<unknown kind #" << Kind << ">"; 3317 Out << ' '; 3318 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule); 3319 } 3320 } 3321 3322 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) { 3323 Out << '!' << Slot << " = "; 3324 printMDNodeBody(Node); 3325 Out << "\n"; 3326 } 3327 3328 void AssemblyWriter::writeAllMDNodes() { 3329 SmallVector<const MDNode *, 16> Nodes; 3330 Nodes.resize(Machine.mdn_size()); 3331 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end(); 3332 I != E; ++I) 3333 Nodes[I->second] = cast<MDNode>(I->first); 3334 3335 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) { 3336 writeMDNode(i, Nodes[i]); 3337 } 3338 } 3339 3340 void AssemblyWriter::printMDNodeBody(const MDNode *Node) { 3341 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule); 3342 } 3343 3344 void AssemblyWriter::writeAllAttributeGroups() { 3345 std::vector<std::pair<AttributeSet, unsigned>> asVec; 3346 asVec.resize(Machine.as_size()); 3347 3348 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end(); 3349 I != E; ++I) 3350 asVec[I->second] = *I; 3351 3352 for (const auto &I : asVec) 3353 Out << "attributes #" << I.second << " = { " 3354 << I.first.getAsString(true) << " }\n"; 3355 } 3356 3357 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) { 3358 bool IsInFunction = Machine.getFunction(); 3359 if (IsInFunction) 3360 Out << " "; 3361 3362 Out << "uselistorder"; 3363 if (const BasicBlock *BB = 3364 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) { 3365 Out << "_bb "; 3366 writeOperand(BB->getParent(), false); 3367 Out << ", "; 3368 writeOperand(BB, false); 3369 } else { 3370 Out << " "; 3371 writeOperand(Order.V, true); 3372 } 3373 Out << ", { "; 3374 3375 assert(Order.Shuffle.size() >= 2 && "Shuffle too small"); 3376 Out << Order.Shuffle[0]; 3377 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I) 3378 Out << ", " << Order.Shuffle[I]; 3379 Out << " }\n"; 3380 } 3381 3382 void AssemblyWriter::printUseLists(const Function *F) { 3383 auto hasMore = 3384 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; }; 3385 if (!hasMore()) 3386 // Nothing to do. 3387 return; 3388 3389 Out << "\n; uselistorder directives\n"; 3390 while (hasMore()) { 3391 printUseListOrder(UseListOrders.back()); 3392 UseListOrders.pop_back(); 3393 } 3394 } 3395 3396 //===----------------------------------------------------------------------===// 3397 // External Interface declarations 3398 //===----------------------------------------------------------------------===// 3399 3400 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 3401 bool ShouldPreserveUseListOrder, 3402 bool IsForDebug) const { 3403 SlotTracker SlotTable(this->getParent()); 3404 formatted_raw_ostream OS(ROS); 3405 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW, 3406 IsForDebug, 3407 ShouldPreserveUseListOrder); 3408 W.printFunction(this); 3409 } 3410 3411 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW, 3412 bool ShouldPreserveUseListOrder, bool IsForDebug) const { 3413 SlotTracker SlotTable(this); 3414 formatted_raw_ostream OS(ROS); 3415 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug, 3416 ShouldPreserveUseListOrder); 3417 W.printModule(this); 3418 } 3419 3420 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const { 3421 SlotTracker SlotTable(getParent()); 3422 formatted_raw_ostream OS(ROS); 3423 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug); 3424 W.printNamedMDNode(this); 3425 } 3426 3427 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST, 3428 bool IsForDebug) const { 3429 Optional<SlotTracker> LocalST; 3430 SlotTracker *SlotTable; 3431 if (auto *ST = MST.getMachine()) 3432 SlotTable = ST; 3433 else { 3434 LocalST.emplace(getParent()); 3435 SlotTable = &*LocalST; 3436 } 3437 3438 formatted_raw_ostream OS(ROS); 3439 AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug); 3440 W.printNamedMDNode(this); 3441 } 3442 3443 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const { 3444 PrintLLVMName(ROS, getName(), ComdatPrefix); 3445 ROS << " = comdat "; 3446 3447 switch (getSelectionKind()) { 3448 case Comdat::Any: 3449 ROS << "any"; 3450 break; 3451 case Comdat::ExactMatch: 3452 ROS << "exactmatch"; 3453 break; 3454 case Comdat::Largest: 3455 ROS << "largest"; 3456 break; 3457 case Comdat::NoDuplicates: 3458 ROS << "noduplicates"; 3459 break; 3460 case Comdat::SameSize: 3461 ROS << "samesize"; 3462 break; 3463 } 3464 3465 ROS << '\n'; 3466 } 3467 3468 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const { 3469 TypePrinting TP; 3470 TP.print(const_cast<Type*>(this), OS); 3471 3472 if (NoDetails) 3473 return; 3474 3475 // If the type is a named struct type, print the body as well. 3476 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this))) 3477 if (!STy->isLiteral()) { 3478 OS << " = type "; 3479 TP.printStructBody(STy, OS); 3480 } 3481 } 3482 3483 static bool isReferencingMDNode(const Instruction &I) { 3484 if (const auto *CI = dyn_cast<CallInst>(&I)) 3485 if (Function *F = CI->getCalledFunction()) 3486 if (F->isIntrinsic()) 3487 for (auto &Op : I.operands()) 3488 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op)) 3489 if (isa<MDNode>(V->getMetadata())) 3490 return true; 3491 return false; 3492 } 3493 3494 void Value::print(raw_ostream &ROS, bool IsForDebug) const { 3495 bool ShouldInitializeAllMetadata = false; 3496 if (auto *I = dyn_cast<Instruction>(this)) 3497 ShouldInitializeAllMetadata = isReferencingMDNode(*I); 3498 else if (isa<Function>(this) || isa<MetadataAsValue>(this)) 3499 ShouldInitializeAllMetadata = true; 3500 3501 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata); 3502 print(ROS, MST, IsForDebug); 3503 } 3504 3505 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST, 3506 bool IsForDebug) const { 3507 formatted_raw_ostream OS(ROS); 3508 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr)); 3509 SlotTracker &SlotTable = 3510 MST.getMachine() ? *MST.getMachine() : EmptySlotTable; 3511 auto incorporateFunction = [&](const Function *F) { 3512 if (F) 3513 MST.incorporateFunction(*F); 3514 }; 3515 3516 if (const Instruction *I = dyn_cast<Instruction>(this)) { 3517 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr); 3518 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug); 3519 W.printInstruction(*I); 3520 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) { 3521 incorporateFunction(BB->getParent()); 3522 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug); 3523 W.printBasicBlock(BB); 3524 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 3525 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug); 3526 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV)) 3527 W.printGlobal(V); 3528 else if (const Function *F = dyn_cast<Function>(GV)) 3529 W.printFunction(F); 3530 else 3531 W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV)); 3532 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) { 3533 V->getMetadata()->print(ROS, MST, getModuleFromVal(V)); 3534 } else if (const Constant *C = dyn_cast<Constant>(this)) { 3535 TypePrinting TypePrinter; 3536 TypePrinter.print(C->getType(), OS); 3537 OS << ' '; 3538 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr); 3539 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) { 3540 this->printAsOperand(OS, /* PrintType */ true, MST); 3541 } else { 3542 llvm_unreachable("Unknown value to print out!"); 3543 } 3544 } 3545 3546 /// Print without a type, skipping the TypePrinting object. 3547 /// 3548 /// \return \c true iff printing was successful. 3549 static bool printWithoutType(const Value &V, raw_ostream &O, 3550 SlotTracker *Machine, const Module *M) { 3551 if (V.hasName() || isa<GlobalValue>(V) || 3552 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) { 3553 WriteAsOperandInternal(O, &V, nullptr, Machine, M); 3554 return true; 3555 } 3556 return false; 3557 } 3558 3559 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType, 3560 ModuleSlotTracker &MST) { 3561 TypePrinting TypePrinter; 3562 if (const Module *M = MST.getModule()) 3563 TypePrinter.incorporateTypes(*M); 3564 if (PrintType) { 3565 TypePrinter.print(V.getType(), O); 3566 O << ' '; 3567 } 3568 3569 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(), 3570 MST.getModule()); 3571 } 3572 3573 void Value::printAsOperand(raw_ostream &O, bool PrintType, 3574 const Module *M) const { 3575 if (!M) 3576 M = getModuleFromVal(this); 3577 3578 if (!PrintType) 3579 if (printWithoutType(*this, O, nullptr, M)) 3580 return; 3581 3582 SlotTracker Machine( 3583 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this)); 3584 ModuleSlotTracker MST(Machine, M); 3585 printAsOperandImpl(*this, O, PrintType, MST); 3586 } 3587 3588 void Value::printAsOperand(raw_ostream &O, bool PrintType, 3589 ModuleSlotTracker &MST) const { 3590 if (!PrintType) 3591 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule())) 3592 return; 3593 3594 printAsOperandImpl(*this, O, PrintType, MST); 3595 } 3596 3597 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD, 3598 ModuleSlotTracker &MST, const Module *M, 3599 bool OnlyAsOperand) { 3600 formatted_raw_ostream OS(ROS); 3601 3602 TypePrinting TypePrinter; 3603 if (M) 3604 TypePrinter.incorporateTypes(*M); 3605 3606 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M, 3607 /* FromValue */ true); 3608 3609 auto *N = dyn_cast<MDNode>(&MD); 3610 if (OnlyAsOperand || !N || isa<DIExpression>(MD)) 3611 return; 3612 3613 OS << " = "; 3614 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M); 3615 } 3616 3617 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const { 3618 ModuleSlotTracker MST(M, isa<MDNode>(this)); 3619 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 3620 } 3621 3622 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST, 3623 const Module *M) const { 3624 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true); 3625 } 3626 3627 void Metadata::print(raw_ostream &OS, const Module *M, 3628 bool /*IsForDebug*/) const { 3629 ModuleSlotTracker MST(M, isa<MDNode>(this)); 3630 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 3631 } 3632 3633 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST, 3634 const Module *M, bool /*IsForDebug*/) const { 3635 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false); 3636 } 3637 3638 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3639 // Value::dump - allow easy printing of Values from the debugger. 3640 LLVM_DUMP_METHOD 3641 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 3642 3643 // Type::dump - allow easy printing of Types from the debugger. 3644 LLVM_DUMP_METHOD 3645 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; } 3646 3647 // Module::dump() - Allow printing of Modules from the debugger. 3648 LLVM_DUMP_METHOD 3649 void Module::dump() const { 3650 print(dbgs(), nullptr, 3651 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true); 3652 } 3653 3654 // \brief Allow printing of Comdats from the debugger. 3655 LLVM_DUMP_METHOD 3656 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); } 3657 3658 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger. 3659 LLVM_DUMP_METHOD 3660 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); } 3661 3662 LLVM_DUMP_METHOD 3663 void Metadata::dump() const { dump(nullptr); } 3664 3665 LLVM_DUMP_METHOD 3666 void Metadata::dump(const Module *M) const { 3667 print(dbgs(), M, /*IsForDebug=*/true); 3668 dbgs() << '\n'; 3669 } 3670 #endif 3671