1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/IR/Writer.h
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.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/TypeFinder.h"
37 #include "llvm/IR/UseListOrder.h"
38 #include "llvm/IR/ValueSymbolTable.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
50 // Make virtual table appear in this compilation unit.
51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
59 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
61 unsigned size() const { return IDs.size(); }
62 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
63 std::pair<unsigned, bool> lookup(const Value *V) const {
66 void index(const Value *V) {
67 // Explicitly sequence get-size and insert-value operations to avoid UB.
68 unsigned ID = IDs.size() + 1;
74 static void orderValue(const Value *V, OrderMap &OM) {
75 if (OM.lookup(V).first)
78 if (const Constant *C = dyn_cast<Constant>(V))
79 if (C->getNumOperands() && !isa<GlobalValue>(C))
80 for (const Value *Op : C->operands())
81 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
84 // Note: we cannot cache this lookup above, since inserting into the map
85 // changes the map's size, and thus affects the other IDs.
89 static OrderMap orderModule(const Module *M) {
90 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
91 // and ValueEnumerator::incorporateFunction().
94 for (const GlobalVariable &G : M->globals()) {
95 if (G.hasInitializer())
96 if (!isa<GlobalValue>(G.getInitializer()))
97 orderValue(G.getInitializer(), OM);
100 for (const GlobalAlias &A : M->aliases()) {
101 if (!isa<GlobalValue>(A.getAliasee()))
102 orderValue(A.getAliasee(), OM);
105 for (const Function &F : *M) {
106 if (F.hasPrefixData())
107 if (!isa<GlobalValue>(F.getPrefixData()))
108 orderValue(F.getPrefixData(), OM);
110 if (F.hasPrologueData())
111 if (!isa<GlobalValue>(F.getPrologueData()))
112 orderValue(F.getPrologueData(), OM);
114 if (F.hasPersonalityFn())
115 if (!isa<GlobalValue>(F.getPersonalityFn()))
116 orderValue(F.getPersonalityFn(), OM);
120 if (F.isDeclaration())
123 for (const Argument &A : F.args())
125 for (const BasicBlock &BB : F) {
127 for (const Instruction &I : BB) {
128 for (const Value *Op : I.operands())
129 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
139 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
140 unsigned ID, const OrderMap &OM,
141 UseListOrderStack &Stack) {
142 // Predict use-list order for this one.
143 typedef std::pair<const Use *, unsigned> Entry;
144 SmallVector<Entry, 64> List;
145 for (const Use &U : V->uses())
146 // Check if this user will be serialized.
147 if (OM.lookup(U.getUser()).first)
148 List.push_back(std::make_pair(&U, List.size()));
151 // We may have lost some users.
155 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
156 if (auto *BA = dyn_cast<BlockAddress>(V))
157 ID = OM.lookup(BA->getBasicBlock()).first;
158 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
159 const Use *LU = L.first;
160 const Use *RU = R.first;
164 auto LID = OM.lookup(LU->getUser()).first;
165 auto RID = OM.lookup(RU->getUser()).first;
167 // If ID is 4, then expect: 7 6 5 1 2 3.
181 // LID and RID are equal, so we have different operands of the same user.
182 // Assume operands are added in order for all instructions.
185 return LU->getOperandNo() < RU->getOperandNo();
186 return LU->getOperandNo() > RU->getOperandNo();
190 List.begin(), List.end(),
191 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
192 // Order is already correct.
195 // Store the shuffle.
196 Stack.emplace_back(V, F, List.size());
197 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
198 for (size_t I = 0, E = List.size(); I != E; ++I)
199 Stack.back().Shuffle[I] = List[I].second;
202 static void predictValueUseListOrder(const Value *V, const Function *F,
203 OrderMap &OM, UseListOrderStack &Stack) {
204 auto &IDPair = OM[V];
205 assert(IDPair.first && "Unmapped value");
207 // Already predicted.
210 // Do the actual prediction.
211 IDPair.second = true;
212 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
213 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
215 // Recursive descent into constants.
216 if (const Constant *C = dyn_cast<Constant>(V))
217 if (C->getNumOperands()) // Visit GlobalValues.
218 for (const Value *Op : C->operands())
219 if (isa<Constant>(Op)) // Visit GlobalValues.
220 predictValueUseListOrder(Op, F, OM, Stack);
223 static UseListOrderStack predictUseListOrder(const Module *M) {
224 OrderMap OM = orderModule(M);
226 // Use-list orders need to be serialized after all the users have been added
227 // to a value, or else the shuffles will be incomplete. Store them per
228 // function in a stack.
230 // Aside from function order, the order of values doesn't matter much here.
231 UseListOrderStack Stack;
233 // We want to visit the functions backward now so we can list function-local
234 // constants in the last Function they're used in. Module-level constants
235 // have already been visited above.
236 for (const Function &F : make_range(M->rbegin(), M->rend())) {
237 if (F.isDeclaration())
239 for (const BasicBlock &BB : F)
240 predictValueUseListOrder(&BB, &F, OM, Stack);
241 for (const Argument &A : F.args())
242 predictValueUseListOrder(&A, &F, OM, Stack);
243 for (const BasicBlock &BB : F)
244 for (const Instruction &I : BB)
245 for (const Value *Op : I.operands())
246 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
247 predictValueUseListOrder(Op, &F, OM, Stack);
248 for (const BasicBlock &BB : F)
249 for (const Instruction &I : BB)
250 predictValueUseListOrder(&I, &F, OM, Stack);
253 // Visit globals last.
254 for (const GlobalVariable &G : M->globals())
255 predictValueUseListOrder(&G, nullptr, OM, Stack);
256 for (const Function &F : *M)
257 predictValueUseListOrder(&F, nullptr, OM, Stack);
258 for (const GlobalAlias &A : M->aliases())
259 predictValueUseListOrder(&A, nullptr, OM, Stack);
260 for (const GlobalVariable &G : M->globals())
261 if (G.hasInitializer())
262 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
263 for (const GlobalAlias &A : M->aliases())
264 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
265 for (const Function &F : *M)
266 if (F.hasPrefixData())
267 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
272 static const Module *getModuleFromVal(const Value *V) {
273 if (const Argument *MA = dyn_cast<Argument>(V))
274 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
276 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
277 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
279 if (const Instruction *I = dyn_cast<Instruction>(V)) {
280 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
281 return M ? M->getParent() : nullptr;
284 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
285 return GV->getParent();
287 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
288 for (const User *U : MAV->users())
289 if (isa<Instruction>(U))
290 if (const Module *M = getModuleFromVal(U))
298 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
300 default: Out << "cc" << cc; break;
301 case CallingConv::Fast: Out << "fastcc"; break;
302 case CallingConv::Cold: Out << "coldcc"; break;
303 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
304 case CallingConv::AnyReg: Out << "anyregcc"; break;
305 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
306 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
307 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
308 case CallingConv::GHC: Out << "ghccc"; break;
309 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
310 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
311 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
312 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
313 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
314 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
315 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
316 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
317 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
318 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
319 case CallingConv::PTX_Device: Out << "ptx_device"; break;
320 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
321 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
322 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
323 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
324 case CallingConv::HHVM: Out << "hhvmcc"; break;
325 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
329 // PrintEscapedString - Print each character of the specified string, escaping
330 // it if it is not printable or if it is an escape char.
331 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
332 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
333 unsigned char C = Name[i];
334 if (isprint(C) && C != '\\' && C != '"')
337 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
349 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
350 assert(!Name.empty() && "Cannot get empty name!");
352 // Scan the name to see if it needs quotes first.
353 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
355 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
356 // By making this unsigned, the value passed in to isalnum will always be
357 // in the range 0-255. This is important when building with MSVC because
358 // its implementation will assert. This situation can arise when dealing
359 // with UTF-8 multibyte characters.
360 unsigned char C = Name[i];
361 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
369 // If we didn't need any quotes, just write out the name in one blast.
375 // Okay, we need quotes. Output the quotes and escape any scary characters as
378 PrintEscapedString(Name, OS);
382 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
383 /// (if the string only contains simple characters) or is surrounded with ""'s
384 /// (if it has special chars in it). Print it out.
385 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
401 printLLVMNameWithoutPrefix(OS, Name);
404 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
405 /// (if the string only contains simple characters) or is surrounded with ""'s
406 /// (if it has special chars in it). Print it out.
407 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
408 PrintLLVMName(OS, V->getName(),
409 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
415 TypePrinting(const TypePrinting &) = delete;
416 void operator=(const TypePrinting&) = delete;
419 /// NamedTypes - The named types that are used by the current module.
420 TypeFinder NamedTypes;
422 /// NumberedTypes - The numbered types, along with their value.
423 DenseMap<StructType*, unsigned> NumberedTypes;
425 TypePrinting() = default;
427 void incorporateTypes(const Module &M);
429 void print(Type *Ty, raw_ostream &OS);
431 void printStructBody(StructType *Ty, raw_ostream &OS);
435 void TypePrinting::incorporateTypes(const Module &M) {
436 NamedTypes.run(M, false);
438 // The list of struct types we got back includes all the struct types, split
439 // the unnamed ones out to a numbering and remove the anonymous structs.
440 unsigned NextNumber = 0;
442 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
443 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
444 StructType *STy = *I;
446 // Ignore anonymous types.
447 if (STy->isLiteral())
450 if (STy->getName().empty())
451 NumberedTypes[STy] = NextNumber++;
456 NamedTypes.erase(NextToUse, NamedTypes.end());
460 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
461 /// use of type names or up references to shorten the type name where possible.
462 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
463 switch (Ty->getTypeID()) {
464 case Type::VoidTyID: OS << "void"; return;
465 case Type::HalfTyID: OS << "half"; return;
466 case Type::FloatTyID: OS << "float"; return;
467 case Type::DoubleTyID: OS << "double"; return;
468 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
469 case Type::FP128TyID: OS << "fp128"; return;
470 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
471 case Type::LabelTyID: OS << "label"; return;
472 case Type::MetadataTyID: OS << "metadata"; return;
473 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
474 case Type::TokenTyID: OS << "token"; return;
475 case Type::IntegerTyID:
476 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
479 case Type::FunctionTyID: {
480 FunctionType *FTy = cast<FunctionType>(Ty);
481 print(FTy->getReturnType(), OS);
483 for (FunctionType::param_iterator I = FTy->param_begin(),
484 E = FTy->param_end(); I != E; ++I) {
485 if (I != FTy->param_begin())
489 if (FTy->isVarArg()) {
490 if (FTy->getNumParams()) OS << ", ";
496 case Type::StructTyID: {
497 StructType *STy = cast<StructType>(Ty);
499 if (STy->isLiteral())
500 return printStructBody(STy, OS);
502 if (!STy->getName().empty())
503 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
505 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
506 if (I != NumberedTypes.end())
507 OS << '%' << I->second;
508 else // Not enumerated, print the hex address.
509 OS << "%\"type " << STy << '\"';
512 case Type::PointerTyID: {
513 PointerType *PTy = cast<PointerType>(Ty);
514 print(PTy->getElementType(), OS);
515 if (unsigned AddressSpace = PTy->getAddressSpace())
516 OS << " addrspace(" << AddressSpace << ')';
520 case Type::ArrayTyID: {
521 ArrayType *ATy = cast<ArrayType>(Ty);
522 OS << '[' << ATy->getNumElements() << " x ";
523 print(ATy->getElementType(), OS);
527 case Type::VectorTyID: {
528 VectorType *PTy = cast<VectorType>(Ty);
529 OS << "<" << PTy->getNumElements() << " x ";
530 print(PTy->getElementType(), OS);
535 llvm_unreachable("Invalid TypeID");
538 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
539 if (STy->isOpaque()) {
547 if (STy->getNumElements() == 0) {
550 StructType::element_iterator I = STy->element_begin();
553 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
565 //===----------------------------------------------------------------------===//
566 // SlotTracker Class: Enumerate slot numbers for unnamed values
567 //===----------------------------------------------------------------------===//
568 /// This class provides computation of slot numbers for LLVM Assembly writing.
572 /// ValueMap - A mapping of Values to slot numbers.
573 typedef DenseMap<const Value*, unsigned> ValueMap;
576 /// TheModule - The module for which we are holding slot numbers.
577 const Module* TheModule;
579 /// TheFunction - The function for which we are holding slot numbers.
580 const Function* TheFunction;
581 bool FunctionProcessed;
582 bool ShouldInitializeAllMetadata;
584 /// mMap - The slot map for the module level data.
588 /// fMap - The slot map for the function level data.
592 /// mdnMap - Map for MDNodes.
593 DenseMap<const MDNode*, unsigned> mdnMap;
596 /// asMap - The slot map for attribute sets.
597 DenseMap<AttributeSet, unsigned> asMap;
600 /// Construct from a module.
602 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
603 /// functions, giving correct numbering for metadata referenced only from
604 /// within a function (even if no functions have been initialized).
605 explicit SlotTracker(const Module *M,
606 bool ShouldInitializeAllMetadata = false);
607 /// Construct from a function, starting out in incorp state.
609 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
610 /// functions, giving correct numbering for metadata referenced only from
611 /// within a function (even if no functions have been initialized).
612 explicit SlotTracker(const Function *F,
613 bool ShouldInitializeAllMetadata = false);
615 /// Return the slot number of the specified value in it's type
616 /// plane. If something is not in the SlotTracker, return -1.
617 int getLocalSlot(const Value *V);
618 int getGlobalSlot(const GlobalValue *V);
619 int getMetadataSlot(const MDNode *N);
620 int getAttributeGroupSlot(AttributeSet AS);
622 /// If you'd like to deal with a function instead of just a module, use
623 /// this method to get its data into the SlotTracker.
624 void incorporateFunction(const Function *F) {
626 FunctionProcessed = false;
629 const Function *getFunction() const { return TheFunction; }
631 /// After calling incorporateFunction, use this method to remove the
632 /// most recently incorporated function from the SlotTracker. This
633 /// will reset the state of the machine back to just the module contents.
634 void purgeFunction();
636 /// MDNode map iterators.
637 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
638 mdn_iterator mdn_begin() { return mdnMap.begin(); }
639 mdn_iterator mdn_end() { return mdnMap.end(); }
640 unsigned mdn_size() const { return mdnMap.size(); }
641 bool mdn_empty() const { return mdnMap.empty(); }
643 /// AttributeSet map iterators.
644 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
645 as_iterator as_begin() { return asMap.begin(); }
646 as_iterator as_end() { return asMap.end(); }
647 unsigned as_size() const { return asMap.size(); }
648 bool as_empty() const { return asMap.empty(); }
650 /// This function does the actual initialization.
651 inline void initialize();
653 // Implementation Details
655 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
656 void CreateModuleSlot(const GlobalValue *V);
658 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
659 void CreateMetadataSlot(const MDNode *N);
661 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
662 void CreateFunctionSlot(const Value *V);
664 /// \brief Insert the specified AttributeSet into the slot table.
665 void CreateAttributeSetSlot(AttributeSet AS);
667 /// Add all of the module level global variables (and their initializers)
668 /// and function declarations, but not the contents of those functions.
669 void processModule();
671 /// Add all of the functions arguments, basic blocks, and instructions.
672 void processFunction();
674 /// Add all of the metadata from a function.
675 void processFunctionMetadata(const Function &F);
677 /// Add all of the metadata from an instruction.
678 void processInstructionMetadata(const Instruction &I);
680 SlotTracker(const SlotTracker &) = delete;
681 void operator=(const SlotTracker &) = delete;
685 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
687 : M(M), F(F), Machine(&Machine) {}
689 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
690 bool ShouldInitializeAllMetadata)
691 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
693 M(M), Machine(MachineStorage.get()) {}
695 ModuleSlotTracker::~ModuleSlotTracker() {}
697 void ModuleSlotTracker::incorporateFunction(const Function &F) {
701 // Nothing to do if this is the right function already.
705 Machine->purgeFunction();
706 Machine->incorporateFunction(&F);
710 int ModuleSlotTracker::getLocalSlot(const Value *V) {
711 assert(F && "No function incorporated");
712 return Machine->getLocalSlot(V);
715 static SlotTracker *createSlotTracker(const Value *V) {
716 if (const Argument *FA = dyn_cast<Argument>(V))
717 return new SlotTracker(FA->getParent());
719 if (const Instruction *I = dyn_cast<Instruction>(V))
721 return new SlotTracker(I->getParent()->getParent());
723 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
724 return new SlotTracker(BB->getParent());
726 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
727 return new SlotTracker(GV->getParent());
729 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
730 return new SlotTracker(GA->getParent());
732 if (const Function *Func = dyn_cast<Function>(V))
733 return new SlotTracker(Func);
739 #define ST_DEBUG(X) dbgs() << X
744 // Module level constructor. Causes the contents of the Module (sans functions)
745 // to be added to the slot table.
746 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
747 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
748 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
749 fNext(0), mdnNext(0), asNext(0) {}
751 // Function level constructor. Causes the contents of the Module and the one
752 // function provided to be added to the slot table.
753 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
754 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
755 FunctionProcessed(false),
756 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
757 fNext(0), mdnNext(0), asNext(0) {}
759 inline void SlotTracker::initialize() {
762 TheModule = nullptr; ///< Prevent re-processing next time we're called.
765 if (TheFunction && !FunctionProcessed)
769 // Iterate through all the global variables, functions, and global
770 // variable initializers and create slots for them.
771 void SlotTracker::processModule() {
772 ST_DEBUG("begin processModule!\n");
774 // Add all of the unnamed global variables to the value table.
775 for (const GlobalVariable &Var : TheModule->globals()) {
777 CreateModuleSlot(&Var);
780 for (const GlobalAlias &A : TheModule->aliases()) {
782 CreateModuleSlot(&A);
785 // Add metadata used by named metadata.
786 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
787 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
788 CreateMetadataSlot(NMD.getOperand(i));
791 for (const Function &F : *TheModule) {
793 // Add all the unnamed functions to the table.
794 CreateModuleSlot(&F);
796 if (ShouldInitializeAllMetadata)
797 processFunctionMetadata(F);
799 // Add all the function attributes to the table.
800 // FIXME: Add attributes of other objects?
801 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
802 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
803 CreateAttributeSetSlot(FnAttrs);
806 ST_DEBUG("end processModule!\n");
809 // Process the arguments, basic blocks, and instructions of a function.
810 void SlotTracker::processFunction() {
811 ST_DEBUG("begin processFunction!\n");
814 // Process function metadata if it wasn't hit at the module-level.
815 if (!ShouldInitializeAllMetadata)
816 processFunctionMetadata(*TheFunction);
818 // Add all the function arguments with no names.
819 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
820 AE = TheFunction->arg_end(); AI != AE; ++AI)
822 CreateFunctionSlot(&*AI);
824 ST_DEBUG("Inserting Instructions:\n");
826 // Add all of the basic blocks and instructions with no names.
827 for (auto &BB : *TheFunction) {
829 CreateFunctionSlot(&BB);
832 if (!I.getType()->isVoidTy() && !I.hasName())
833 CreateFunctionSlot(&I);
835 // We allow direct calls to any llvm.foo function here, because the
836 // target may not be linked into the optimizer.
837 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
838 // Add all the call attributes to the table.
839 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
840 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
841 CreateAttributeSetSlot(Attrs);
842 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
843 // Add all the call attributes to the table.
844 AttributeSet Attrs = II->getAttributes().getFnAttributes();
845 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
846 CreateAttributeSetSlot(Attrs);
851 FunctionProcessed = true;
853 ST_DEBUG("end processFunction!\n");
856 void SlotTracker::processFunctionMetadata(const Function &F) {
857 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
858 F.getAllMetadata(MDs);
860 CreateMetadataSlot(MD.second);
864 processInstructionMetadata(I);
868 void SlotTracker::processInstructionMetadata(const Instruction &I) {
869 // Process metadata used directly by intrinsics.
870 if (const CallInst *CI = dyn_cast<CallInst>(&I))
871 if (Function *F = CI->getCalledFunction())
872 if (F->isIntrinsic())
873 for (auto &Op : I.operands())
874 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
875 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
876 CreateMetadataSlot(N);
878 // Process metadata attached to this instruction.
879 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
880 I.getAllMetadata(MDs);
882 CreateMetadataSlot(MD.second);
885 /// Clean up after incorporating a function. This is the only way to get out of
886 /// the function incorporation state that affects get*Slot/Create*Slot. Function
887 /// incorporation state is indicated by TheFunction != 0.
888 void SlotTracker::purgeFunction() {
889 ST_DEBUG("begin purgeFunction!\n");
890 fMap.clear(); // Simply discard the function level map
891 TheFunction = nullptr;
892 FunctionProcessed = false;
893 ST_DEBUG("end purgeFunction!\n");
896 /// getGlobalSlot - Get the slot number of a global value.
897 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
898 // Check for uninitialized state and do lazy initialization.
901 // Find the value in the module map
902 ValueMap::iterator MI = mMap.find(V);
903 return MI == mMap.end() ? -1 : (int)MI->second;
906 /// getMetadataSlot - Get the slot number of a MDNode.
907 int SlotTracker::getMetadataSlot(const MDNode *N) {
908 // Check for uninitialized state and do lazy initialization.
911 // Find the MDNode in the module map
912 mdn_iterator MI = mdnMap.find(N);
913 return MI == mdnMap.end() ? -1 : (int)MI->second;
917 /// getLocalSlot - Get the slot number for a value that is local to a function.
918 int SlotTracker::getLocalSlot(const Value *V) {
919 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
921 // Check for uninitialized state and do lazy initialization.
924 ValueMap::iterator FI = fMap.find(V);
925 return FI == fMap.end() ? -1 : (int)FI->second;
928 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
929 // Check for uninitialized state and do lazy initialization.
932 // Find the AttributeSet in the module map.
933 as_iterator AI = asMap.find(AS);
934 return AI == asMap.end() ? -1 : (int)AI->second;
937 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
938 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
939 assert(V && "Can't insert a null Value into SlotTracker!");
940 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
941 assert(!V->hasName() && "Doesn't need a slot!");
943 unsigned DestSlot = mNext++;
946 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
948 // G = Global, F = Function, A = Alias, o = other
949 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
950 (isa<Function>(V) ? 'F' :
951 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
954 /// CreateSlot - Create a new slot for the specified value if it has no name.
955 void SlotTracker::CreateFunctionSlot(const Value *V) {
956 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
958 unsigned DestSlot = fNext++;
961 // G = Global, F = Function, o = other
962 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
963 DestSlot << " [o]\n");
966 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
967 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
968 assert(N && "Can't insert a null Value into SlotTracker!");
970 unsigned DestSlot = mdnNext;
971 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
975 // Recursively add any MDNodes referenced by operands.
976 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
977 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
978 CreateMetadataSlot(Op);
981 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
982 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
983 "Doesn't need a slot!");
985 as_iterator I = asMap.find(AS);
986 if (I != asMap.end())
989 unsigned DestSlot = asNext++;
990 asMap[AS] = DestSlot;
993 //===----------------------------------------------------------------------===//
994 // AsmWriter Implementation
995 //===----------------------------------------------------------------------===//
997 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
998 TypePrinting *TypePrinter,
999 SlotTracker *Machine,
1000 const Module *Context);
1002 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1003 TypePrinting *TypePrinter,
1004 SlotTracker *Machine, const Module *Context,
1005 bool FromValue = false);
1007 static const char *getPredicateText(unsigned predicate) {
1008 const char * pred = "unknown";
1009 switch (predicate) {
1010 case FCmpInst::FCMP_FALSE: pred = "false"; break;
1011 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
1012 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
1013 case FCmpInst::FCMP_OGE: pred = "oge"; break;
1014 case FCmpInst::FCMP_OLT: pred = "olt"; break;
1015 case FCmpInst::FCMP_OLE: pred = "ole"; break;
1016 case FCmpInst::FCMP_ONE: pred = "one"; break;
1017 case FCmpInst::FCMP_ORD: pred = "ord"; break;
1018 case FCmpInst::FCMP_UNO: pred = "uno"; break;
1019 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
1020 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
1021 case FCmpInst::FCMP_UGE: pred = "uge"; break;
1022 case FCmpInst::FCMP_ULT: pred = "ult"; break;
1023 case FCmpInst::FCMP_ULE: pred = "ule"; break;
1024 case FCmpInst::FCMP_UNE: pred = "une"; break;
1025 case FCmpInst::FCMP_TRUE: pred = "true"; break;
1026 case ICmpInst::ICMP_EQ: pred = "eq"; break;
1027 case ICmpInst::ICMP_NE: pred = "ne"; break;
1028 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
1029 case ICmpInst::ICMP_SGE: pred = "sge"; break;
1030 case ICmpInst::ICMP_SLT: pred = "slt"; break;
1031 case ICmpInst::ICMP_SLE: pred = "sle"; break;
1032 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
1033 case ICmpInst::ICMP_UGE: pred = "uge"; break;
1034 case ICmpInst::ICMP_ULT: pred = "ult"; break;
1035 case ICmpInst::ICMP_ULE: pred = "ule"; break;
1040 static void writeAtomicRMWOperation(raw_ostream &Out,
1041 AtomicRMWInst::BinOp Op) {
1043 default: Out << " <unknown operation " << Op << ">"; break;
1044 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1045 case AtomicRMWInst::Add: Out << " add"; break;
1046 case AtomicRMWInst::Sub: Out << " sub"; break;
1047 case AtomicRMWInst::And: Out << " and"; break;
1048 case AtomicRMWInst::Nand: Out << " nand"; break;
1049 case AtomicRMWInst::Or: Out << " or"; break;
1050 case AtomicRMWInst::Xor: Out << " xor"; break;
1051 case AtomicRMWInst::Max: Out << " max"; break;
1052 case AtomicRMWInst::Min: Out << " min"; break;
1053 case AtomicRMWInst::UMax: Out << " umax"; break;
1054 case AtomicRMWInst::UMin: Out << " umin"; break;
1058 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1059 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1060 // Unsafe algebra implies all the others, no need to write them all out
1061 if (FPO->hasUnsafeAlgebra())
1064 if (FPO->hasNoNaNs())
1066 if (FPO->hasNoInfs())
1068 if (FPO->hasNoSignedZeros())
1070 if (FPO->hasAllowReciprocal())
1075 if (const OverflowingBinaryOperator *OBO =
1076 dyn_cast<OverflowingBinaryOperator>(U)) {
1077 if (OBO->hasNoUnsignedWrap())
1079 if (OBO->hasNoSignedWrap())
1081 } else if (const PossiblyExactOperator *Div =
1082 dyn_cast<PossiblyExactOperator>(U)) {
1085 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1086 if (GEP->isInBounds())
1091 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1092 TypePrinting &TypePrinter,
1093 SlotTracker *Machine,
1094 const Module *Context) {
1095 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1096 if (CI->getType()->isIntegerTy(1)) {
1097 Out << (CI->getZExtValue() ? "true" : "false");
1100 Out << CI->getValue();
1104 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1105 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1106 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1107 // We would like to output the FP constant value in exponential notation,
1108 // but we cannot do this if doing so will lose precision. Check here to
1109 // make sure that we only output it in exponential format if we can parse
1110 // the value back and get the same value.
1113 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1114 bool isInf = CFP->getValueAPF().isInfinity();
1115 bool isNaN = CFP->getValueAPF().isNaN();
1116 if (!isInf && !isNaN) {
1117 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1118 CFP->getValueAPF().convertToFloat();
1119 SmallString<128> StrVal;
1120 raw_svector_ostream(StrVal) << Val;
1122 // Check to make sure that the stringized number is not some string like
1123 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1124 // that the string matches the "[-+]?[0-9]" regex.
1126 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1127 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1128 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1129 // Reparse stringized version!
1130 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1136 // Otherwise we could not reparse it to exactly the same value, so we must
1137 // output the string in hexadecimal format! Note that loading and storing
1138 // floating point types changes the bits of NaNs on some hosts, notably
1139 // x86, so we must not use these types.
1140 static_assert(sizeof(double) == sizeof(uint64_t),
1141 "assuming that double is 64 bits!");
1142 APFloat apf = CFP->getValueAPF();
1143 // Floats are represented in ASCII IR as double, convert.
1145 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1147 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1151 // Either half, or some form of long double.
1152 // These appear as a magic letter identifying the type, then a
1153 // fixed number of hex digits.
1155 APInt API = CFP->getValueAPF().bitcastToAPInt();
1156 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1158 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1160 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1163 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1165 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1167 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1169 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1171 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1173 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1175 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1177 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1180 llvm_unreachable("Unsupported floating point type");
1184 if (isa<ConstantAggregateZero>(CV)) {
1185 Out << "zeroinitializer";
1189 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1190 Out << "blockaddress(";
1191 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1194 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1200 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1201 Type *ETy = CA->getType()->getElementType();
1203 TypePrinter.print(ETy, Out);
1205 WriteAsOperandInternal(Out, CA->getOperand(0),
1206 &TypePrinter, Machine,
1208 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1210 TypePrinter.print(ETy, Out);
1212 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1219 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1220 // As a special case, print the array as a string if it is an array of
1221 // i8 with ConstantInt values.
1222 if (CA->isString()) {
1224 PrintEscapedString(CA->getAsString(), Out);
1229 Type *ETy = CA->getType()->getElementType();
1231 TypePrinter.print(ETy, Out);
1233 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1234 &TypePrinter, Machine,
1236 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1238 TypePrinter.print(ETy, Out);
1240 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1248 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1249 if (CS->getType()->isPacked())
1252 unsigned N = CS->getNumOperands();
1255 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1258 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1261 for (unsigned i = 1; i < N; i++) {
1263 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1266 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1273 if (CS->getType()->isPacked())
1278 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1279 Type *ETy = CV->getType()->getVectorElementType();
1281 TypePrinter.print(ETy, Out);
1283 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1285 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1287 TypePrinter.print(ETy, Out);
1289 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1296 if (isa<ConstantPointerNull>(CV)) {
1301 if (isa<ConstantTokenNone>(CV)) {
1306 if (isa<UndefValue>(CV)) {
1311 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1312 Out << CE->getOpcodeName();
1313 WriteOptimizationInfo(Out, CE);
1314 if (CE->isCompare())
1315 Out << ' ' << getPredicateText(CE->getPredicate());
1318 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1319 TypePrinter.print(GEP->getSourceElementType(), Out);
1323 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1324 TypePrinter.print((*OI)->getType(), Out);
1326 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1327 if (OI+1 != CE->op_end())
1331 if (CE->hasIndices()) {
1332 ArrayRef<unsigned> Indices = CE->getIndices();
1333 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1334 Out << ", " << Indices[i];
1339 TypePrinter.print(CE->getType(), Out);
1346 Out << "<placeholder or erroneous Constant>";
1349 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1350 TypePrinting *TypePrinter, SlotTracker *Machine,
1351 const Module *Context) {
1353 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1354 const Metadata *MD = Node->getOperand(mi);
1357 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1358 Value *V = MDV->getValue();
1359 TypePrinter->print(V->getType(), Out);
1361 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1363 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1373 struct FieldSeparator {
1376 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1378 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1383 return OS << FS.Sep;
1385 struct MDFieldPrinter {
1388 TypePrinting *TypePrinter;
1389 SlotTracker *Machine;
1390 const Module *Context;
1392 explicit MDFieldPrinter(raw_ostream &Out)
1393 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1394 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1395 SlotTracker *Machine, const Module *Context)
1396 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1398 void printTag(const DINode *N);
1399 void printMacinfoType(const DIMacroNode *N);
1400 void printString(StringRef Name, StringRef Value,
1401 bool ShouldSkipEmpty = true);
1402 void printMetadata(StringRef Name, const Metadata *MD,
1403 bool ShouldSkipNull = true);
1404 template <class IntTy>
1405 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1406 void printBool(StringRef Name, bool Value);
1407 void printDIFlags(StringRef Name, unsigned Flags);
1408 template <class IntTy, class Stringifier>
1409 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1410 bool ShouldSkipZero = true);
1414 void MDFieldPrinter::printTag(const DINode *N) {
1415 Out << FS << "tag: ";
1416 if (const char *Tag = dwarf::TagString(N->getTag()))
1422 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1423 Out << FS << "type: ";
1424 if (const char *Type = dwarf::MacinfoString(N->getMacinfoType()))
1427 Out << N->getMacinfoType();
1430 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1431 bool ShouldSkipEmpty) {
1432 if (ShouldSkipEmpty && Value.empty())
1435 Out << FS << Name << ": \"";
1436 PrintEscapedString(Value, Out);
1440 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1441 TypePrinting *TypePrinter,
1442 SlotTracker *Machine,
1443 const Module *Context) {
1448 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1451 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1452 bool ShouldSkipNull) {
1453 if (ShouldSkipNull && !MD)
1456 Out << FS << Name << ": ";
1457 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1460 template <class IntTy>
1461 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1462 if (ShouldSkipZero && !Int)
1465 Out << FS << Name << ": " << Int;
1468 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1469 Out << FS << Name << ": " << (Value ? "true" : "false");
1472 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1476 Out << FS << Name << ": ";
1478 SmallVector<unsigned, 8> SplitFlags;
1479 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1481 FieldSeparator FlagsFS(" | ");
1482 for (unsigned F : SplitFlags) {
1483 const char *StringF = DINode::getFlagString(F);
1484 assert(StringF && "Expected valid flag");
1485 Out << FlagsFS << StringF;
1487 if (Extra || SplitFlags.empty())
1488 Out << FlagsFS << Extra;
1491 template <class IntTy, class Stringifier>
1492 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1493 Stringifier toString, bool ShouldSkipZero) {
1497 Out << FS << Name << ": ";
1498 if (const char *S = toString(Value))
1504 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1505 TypePrinting *TypePrinter, SlotTracker *Machine,
1506 const Module *Context) {
1507 Out << "!GenericDINode(";
1508 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1509 Printer.printTag(N);
1510 Printer.printString("header", N->getHeader());
1511 if (N->getNumDwarfOperands()) {
1512 Out << Printer.FS << "operands: {";
1514 for (auto &I : N->dwarf_operands()) {
1516 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1523 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1524 TypePrinting *TypePrinter, SlotTracker *Machine,
1525 const Module *Context) {
1526 Out << "!DILocation(";
1527 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1528 // Always output the line, since 0 is a relevant and important value for it.
1529 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1530 Printer.printInt("column", DL->getColumn());
1531 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1532 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1536 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1537 TypePrinting *, SlotTracker *, const Module *) {
1538 Out << "!DISubrange(";
1539 MDFieldPrinter Printer(Out);
1540 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1541 Printer.printInt("lowerBound", N->getLowerBound());
1545 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1546 TypePrinting *, SlotTracker *, const Module *) {
1547 Out << "!DIEnumerator(";
1548 MDFieldPrinter Printer(Out);
1549 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1550 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1554 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1555 TypePrinting *, SlotTracker *, const Module *) {
1556 Out << "!DIBasicType(";
1557 MDFieldPrinter Printer(Out);
1558 if (N->getTag() != dwarf::DW_TAG_base_type)
1559 Printer.printTag(N);
1560 Printer.printString("name", N->getName());
1561 Printer.printInt("size", N->getSizeInBits());
1562 Printer.printInt("align", N->getAlignInBits());
1563 Printer.printDwarfEnum("encoding", N->getEncoding(),
1564 dwarf::AttributeEncodingString);
1568 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1569 TypePrinting *TypePrinter, SlotTracker *Machine,
1570 const Module *Context) {
1571 Out << "!DIDerivedType(";
1572 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1573 Printer.printTag(N);
1574 Printer.printString("name", N->getName());
1575 Printer.printMetadata("scope", N->getRawScope());
1576 Printer.printMetadata("file", N->getRawFile());
1577 Printer.printInt("line", N->getLine());
1578 Printer.printMetadata("baseType", N->getRawBaseType(),
1579 /* ShouldSkipNull */ false);
1580 Printer.printInt("size", N->getSizeInBits());
1581 Printer.printInt("align", N->getAlignInBits());
1582 Printer.printInt("offset", N->getOffsetInBits());
1583 Printer.printDIFlags("flags", N->getFlags());
1584 Printer.printMetadata("extraData", N->getRawExtraData());
1588 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1589 TypePrinting *TypePrinter,
1590 SlotTracker *Machine, const Module *Context) {
1591 Out << "!DICompositeType(";
1592 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1593 Printer.printTag(N);
1594 Printer.printString("name", N->getName());
1595 Printer.printMetadata("scope", N->getRawScope());
1596 Printer.printMetadata("file", N->getRawFile());
1597 Printer.printInt("line", N->getLine());
1598 Printer.printMetadata("baseType", N->getRawBaseType());
1599 Printer.printInt("size", N->getSizeInBits());
1600 Printer.printInt("align", N->getAlignInBits());
1601 Printer.printInt("offset", N->getOffsetInBits());
1602 Printer.printDIFlags("flags", N->getFlags());
1603 Printer.printMetadata("elements", N->getRawElements());
1604 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1605 dwarf::LanguageString);
1606 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1607 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1608 Printer.printString("identifier", N->getIdentifier());
1612 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1613 TypePrinting *TypePrinter,
1614 SlotTracker *Machine, const Module *Context) {
1615 Out << "!DISubroutineType(";
1616 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1617 Printer.printDIFlags("flags", N->getFlags());
1618 Printer.printMetadata("types", N->getRawTypeArray(),
1619 /* ShouldSkipNull */ false);
1623 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1624 SlotTracker *, const Module *) {
1626 MDFieldPrinter Printer(Out);
1627 Printer.printString("filename", N->getFilename(),
1628 /* ShouldSkipEmpty */ false);
1629 Printer.printString("directory", N->getDirectory(),
1630 /* ShouldSkipEmpty */ false);
1634 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1635 TypePrinting *TypePrinter, SlotTracker *Machine,
1636 const Module *Context) {
1637 Out << "!DICompileUnit(";
1638 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1639 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1640 dwarf::LanguageString, /* ShouldSkipZero */ false);
1641 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1642 Printer.printString("producer", N->getProducer());
1643 Printer.printBool("isOptimized", N->isOptimized());
1644 Printer.printString("flags", N->getFlags());
1645 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1646 /* ShouldSkipZero */ false);
1647 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1648 Printer.printInt("emissionKind", N->getEmissionKind(),
1649 /* ShouldSkipZero */ false);
1650 Printer.printMetadata("enums", N->getRawEnumTypes());
1651 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1652 Printer.printMetadata("subprograms", N->getRawSubprograms());
1653 Printer.printMetadata("globals", N->getRawGlobalVariables());
1654 Printer.printMetadata("imports", N->getRawImportedEntities());
1655 Printer.printMetadata("macros", N->getRawMacros());
1656 Printer.printInt("dwoId", N->getDWOId());
1660 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1661 TypePrinting *TypePrinter, SlotTracker *Machine,
1662 const Module *Context) {
1663 Out << "!DISubprogram(";
1664 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1665 Printer.printString("name", N->getName());
1666 Printer.printString("linkageName", N->getLinkageName());
1667 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1668 Printer.printMetadata("file", N->getRawFile());
1669 Printer.printInt("line", N->getLine());
1670 Printer.printMetadata("type", N->getRawType());
1671 Printer.printBool("isLocal", N->isLocalToUnit());
1672 Printer.printBool("isDefinition", N->isDefinition());
1673 Printer.printInt("scopeLine", N->getScopeLine());
1674 Printer.printMetadata("containingType", N->getRawContainingType());
1675 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1676 dwarf::VirtualityString);
1677 Printer.printInt("virtualIndex", N->getVirtualIndex());
1678 Printer.printDIFlags("flags", N->getFlags());
1679 Printer.printBool("isOptimized", N->isOptimized());
1680 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1681 Printer.printMetadata("declaration", N->getRawDeclaration());
1682 Printer.printMetadata("variables", N->getRawVariables());
1686 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1687 TypePrinting *TypePrinter, SlotTracker *Machine,
1688 const Module *Context) {
1689 Out << "!DILexicalBlock(";
1690 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1691 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1692 Printer.printMetadata("file", N->getRawFile());
1693 Printer.printInt("line", N->getLine());
1694 Printer.printInt("column", N->getColumn());
1698 static void writeDILexicalBlockFile(raw_ostream &Out,
1699 const DILexicalBlockFile *N,
1700 TypePrinting *TypePrinter,
1701 SlotTracker *Machine,
1702 const Module *Context) {
1703 Out << "!DILexicalBlockFile(";
1704 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1705 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1706 Printer.printMetadata("file", N->getRawFile());
1707 Printer.printInt("discriminator", N->getDiscriminator(),
1708 /* ShouldSkipZero */ false);
1712 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1713 TypePrinting *TypePrinter, SlotTracker *Machine,
1714 const Module *Context) {
1715 Out << "!DINamespace(";
1716 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1717 Printer.printString("name", N->getName());
1718 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1719 Printer.printMetadata("file", N->getRawFile());
1720 Printer.printInt("line", N->getLine());
1724 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
1725 TypePrinting *TypePrinter, SlotTracker *Machine,
1726 const Module *Context) {
1728 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1729 Printer.printMacinfoType(N);
1730 Printer.printInt("line", N->getLine());
1731 Printer.printString("name", N->getName());
1732 Printer.printString("value", N->getValue());
1736 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
1737 TypePrinting *TypePrinter, SlotTracker *Machine,
1738 const Module *Context) {
1739 Out << "!DIMacroFile(";
1740 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1741 Printer.printInt("line", N->getLine());
1742 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1743 Printer.printMetadata("nodes", N->getRawElements());
1747 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1748 TypePrinting *TypePrinter, SlotTracker *Machine,
1749 const Module *Context) {
1750 Out << "!DIModule(";
1751 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1752 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1753 Printer.printString("name", N->getName());
1754 Printer.printString("configMacros", N->getConfigurationMacros());
1755 Printer.printString("includePath", N->getIncludePath());
1756 Printer.printString("isysroot", N->getISysRoot());
1761 static void writeDITemplateTypeParameter(raw_ostream &Out,
1762 const DITemplateTypeParameter *N,
1763 TypePrinting *TypePrinter,
1764 SlotTracker *Machine,
1765 const Module *Context) {
1766 Out << "!DITemplateTypeParameter(";
1767 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1768 Printer.printString("name", N->getName());
1769 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1773 static void writeDITemplateValueParameter(raw_ostream &Out,
1774 const DITemplateValueParameter *N,
1775 TypePrinting *TypePrinter,
1776 SlotTracker *Machine,
1777 const Module *Context) {
1778 Out << "!DITemplateValueParameter(";
1779 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1780 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1781 Printer.printTag(N);
1782 Printer.printString("name", N->getName());
1783 Printer.printMetadata("type", N->getRawType());
1784 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1788 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1789 TypePrinting *TypePrinter,
1790 SlotTracker *Machine, const Module *Context) {
1791 Out << "!DIGlobalVariable(";
1792 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1793 Printer.printString("name", N->getName());
1794 Printer.printString("linkageName", N->getLinkageName());
1795 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1796 Printer.printMetadata("file", N->getRawFile());
1797 Printer.printInt("line", N->getLine());
1798 Printer.printMetadata("type", N->getRawType());
1799 Printer.printBool("isLocal", N->isLocalToUnit());
1800 Printer.printBool("isDefinition", N->isDefinition());
1801 Printer.printMetadata("variable", N->getRawVariable());
1802 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1806 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1807 TypePrinting *TypePrinter,
1808 SlotTracker *Machine, const Module *Context) {
1809 Out << "!DILocalVariable(";
1810 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1811 Printer.printString("name", N->getName());
1812 Printer.printInt("arg", N->getArg());
1813 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1814 Printer.printMetadata("file", N->getRawFile());
1815 Printer.printInt("line", N->getLine());
1816 Printer.printMetadata("type", N->getRawType());
1817 Printer.printDIFlags("flags", N->getFlags());
1821 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1822 TypePrinting *TypePrinter, SlotTracker *Machine,
1823 const Module *Context) {
1824 Out << "!DIExpression(";
1827 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1828 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1829 assert(OpStr && "Expected valid opcode");
1832 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1833 Out << FS << I->getArg(A);
1836 for (const auto &I : N->getElements())
1842 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1843 TypePrinting *TypePrinter, SlotTracker *Machine,
1844 const Module *Context) {
1845 Out << "!DIObjCProperty(";
1846 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1847 Printer.printString("name", N->getName());
1848 Printer.printMetadata("file", N->getRawFile());
1849 Printer.printInt("line", N->getLine());
1850 Printer.printString("setter", N->getSetterName());
1851 Printer.printString("getter", N->getGetterName());
1852 Printer.printInt("attributes", N->getAttributes());
1853 Printer.printMetadata("type", N->getRawType());
1857 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1858 TypePrinting *TypePrinter,
1859 SlotTracker *Machine, const Module *Context) {
1860 Out << "!DIImportedEntity(";
1861 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1862 Printer.printTag(N);
1863 Printer.printString("name", N->getName());
1864 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1865 Printer.printMetadata("entity", N->getRawEntity());
1866 Printer.printInt("line", N->getLine());
1871 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1872 TypePrinting *TypePrinter,
1873 SlotTracker *Machine,
1874 const Module *Context) {
1875 if (Node->isDistinct())
1877 else if (Node->isTemporary())
1878 Out << "<temporary!> "; // Handle broken code.
1880 switch (Node->getMetadataID()) {
1882 llvm_unreachable("Expected uniquable MDNode");
1883 #define HANDLE_MDNODE_LEAF(CLASS) \
1884 case Metadata::CLASS##Kind: \
1885 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1887 #include "llvm/IR/Metadata.def"
1891 // Full implementation of printing a Value as an operand with support for
1892 // TypePrinting, etc.
1893 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1894 TypePrinting *TypePrinter,
1895 SlotTracker *Machine,
1896 const Module *Context) {
1898 PrintLLVMName(Out, V);
1902 const Constant *CV = dyn_cast<Constant>(V);
1903 if (CV && !isa<GlobalValue>(CV)) {
1904 assert(TypePrinter && "Constants require TypePrinting!");
1905 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1909 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1911 if (IA->hasSideEffects())
1912 Out << "sideeffect ";
1913 if (IA->isAlignStack())
1914 Out << "alignstack ";
1915 // We don't emit the AD_ATT dialect as it's the assumed default.
1916 if (IA->getDialect() == InlineAsm::AD_Intel)
1917 Out << "inteldialect ";
1919 PrintEscapedString(IA->getAsmString(), Out);
1921 PrintEscapedString(IA->getConstraintString(), Out);
1926 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1927 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1928 Context, /* FromValue */ true);
1934 // If we have a SlotTracker, use it.
1936 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1937 Slot = Machine->getGlobalSlot(GV);
1940 Slot = Machine->getLocalSlot(V);
1942 // If the local value didn't succeed, then we may be referring to a value
1943 // from a different function. Translate it, as this can happen when using
1944 // address of blocks.
1946 if ((Machine = createSlotTracker(V))) {
1947 Slot = Machine->getLocalSlot(V);
1951 } else if ((Machine = createSlotTracker(V))) {
1952 // Otherwise, create one to get the # and then destroy it.
1953 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1954 Slot = Machine->getGlobalSlot(GV);
1957 Slot = Machine->getLocalSlot(V);
1966 Out << Prefix << Slot;
1971 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1972 TypePrinting *TypePrinter,
1973 SlotTracker *Machine, const Module *Context,
1975 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1976 std::unique_ptr<SlotTracker> MachineStorage;
1978 MachineStorage = make_unique<SlotTracker>(Context);
1979 Machine = MachineStorage.get();
1981 int Slot = Machine->getMetadataSlot(N);
1983 // Give the pointer value instead of "badref", since this comes up all
1984 // the time when debugging.
1985 Out << "<" << N << ">";
1991 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1993 PrintEscapedString(MDS->getString(), Out);
1998 auto *V = cast<ValueAsMetadata>(MD);
1999 assert(TypePrinter && "TypePrinter required for metadata values");
2000 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2001 "Unexpected function-local metadata outside of value argument");
2003 TypePrinter->print(V->getValue()->getType(), Out);
2005 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2009 class AssemblyWriter {
2010 formatted_raw_ostream &Out;
2011 const Module *TheModule;
2012 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2013 SlotTracker &Machine;
2014 TypePrinting TypePrinter;
2015 AssemblyAnnotationWriter *AnnotationWriter;
2016 SetVector<const Comdat *> Comdats;
2018 bool ShouldPreserveUseListOrder;
2019 UseListOrderStack UseListOrders;
2020 SmallVector<StringRef, 8> MDNames;
2023 /// Construct an AssemblyWriter with an external SlotTracker
2024 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2025 AssemblyAnnotationWriter *AAW, bool IsForDebug,
2026 bool ShouldPreserveUseListOrder = false);
2028 void printMDNodeBody(const MDNode *MD);
2029 void printNamedMDNode(const NamedMDNode *NMD);
2031 void printModule(const Module *M);
2033 void writeOperand(const Value *Op, bool PrintType);
2034 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2035 void writeOperandBundles(ImmutableCallSite CS);
2036 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2037 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2038 AtomicOrdering FailureOrdering,
2039 SynchronizationScope SynchScope);
2041 void writeAllMDNodes();
2042 void writeMDNode(unsigned Slot, const MDNode *Node);
2043 void writeAllAttributeGroups();
2045 void printTypeIdentities();
2046 void printGlobal(const GlobalVariable *GV);
2047 void printAlias(const GlobalAlias *GV);
2048 void printComdat(const Comdat *C);
2049 void printFunction(const Function *F);
2050 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2051 void printBasicBlock(const BasicBlock *BB);
2052 void printInstructionLine(const Instruction &I);
2053 void printInstruction(const Instruction &I);
2055 void printUseListOrder(const UseListOrder &Order);
2056 void printUseLists(const Function *F);
2059 /// \brief Print out metadata attachments.
2060 void printMetadataAttachments(
2061 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2062 StringRef Separator);
2064 // printInfoComment - Print a little comment after the instruction indicating
2065 // which slot it occupies.
2066 void printInfoComment(const Value &V);
2068 // printGCRelocateComment - print comment after call to the gc.relocate
2069 // intrinsic indicating base and derived pointer names.
2070 void printGCRelocateComment(const Value &V);
2074 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2075 const Module *M, AssemblyAnnotationWriter *AAW,
2076 bool IsForDebug, bool ShouldPreserveUseListOrder)
2077 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2078 IsForDebug(IsForDebug),
2079 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2082 TypePrinter.incorporateTypes(*TheModule);
2083 for (const Function &F : *TheModule)
2084 if (const Comdat *C = F.getComdat())
2086 for (const GlobalVariable &GV : TheModule->globals())
2087 if (const Comdat *C = GV.getComdat())
2091 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2093 Out << "<null operand!>";
2097 TypePrinter.print(Operand->getType(), Out);
2100 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2103 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2104 SynchronizationScope SynchScope) {
2105 if (Ordering == NotAtomic)
2108 switch (SynchScope) {
2109 case SingleThread: Out << " singlethread"; break;
2110 case CrossThread: break;
2114 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2115 case Unordered: Out << " unordered"; break;
2116 case Monotonic: Out << " monotonic"; break;
2117 case Acquire: Out << " acquire"; break;
2118 case Release: Out << " release"; break;
2119 case AcquireRelease: Out << " acq_rel"; break;
2120 case SequentiallyConsistent: Out << " seq_cst"; break;
2124 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2125 AtomicOrdering FailureOrdering,
2126 SynchronizationScope SynchScope) {
2127 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2129 switch (SynchScope) {
2130 case SingleThread: Out << " singlethread"; break;
2131 case CrossThread: break;
2134 switch (SuccessOrdering) {
2135 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2136 case Unordered: Out << " unordered"; break;
2137 case Monotonic: Out << " monotonic"; break;
2138 case Acquire: Out << " acquire"; break;
2139 case Release: Out << " release"; break;
2140 case AcquireRelease: Out << " acq_rel"; break;
2141 case SequentiallyConsistent: Out << " seq_cst"; break;
2144 switch (FailureOrdering) {
2145 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2146 case Unordered: Out << " unordered"; break;
2147 case Monotonic: Out << " monotonic"; break;
2148 case Acquire: Out << " acquire"; break;
2149 case Release: Out << " release"; break;
2150 case AcquireRelease: Out << " acq_rel"; break;
2151 case SequentiallyConsistent: Out << " seq_cst"; break;
2155 void AssemblyWriter::writeParamOperand(const Value *Operand,
2156 AttributeSet Attrs, unsigned Idx) {
2158 Out << "<null operand!>";
2163 TypePrinter.print(Operand->getType(), Out);
2164 // Print parameter attributes list
2165 if (Attrs.hasAttributes(Idx))
2166 Out << ' ' << Attrs.getAsString(Idx);
2168 // Print the operand
2169 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2172 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2173 if (!CS.hasOperandBundles())
2178 bool FirstBundle = true;
2179 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2180 OperandBundleUse BU = CS.getOperandBundleAt(i);
2184 FirstBundle = false;
2187 PrintEscapedString(BU.getTagName(), Out);
2192 bool FirstInput = true;
2193 for (const auto &Input : BU.Inputs) {
2198 TypePrinter.print(Input->getType(), Out);
2200 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2209 void AssemblyWriter::printModule(const Module *M) {
2210 Machine.initialize();
2212 if (ShouldPreserveUseListOrder)
2213 UseListOrders = predictUseListOrder(M);
2215 if (!M->getModuleIdentifier().empty() &&
2216 // Don't print the ID if it will start a new line (which would
2217 // require a comment char before it).
2218 M->getModuleIdentifier().find('\n') == std::string::npos)
2219 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2221 const std::string &DL = M->getDataLayoutStr();
2223 Out << "target datalayout = \"" << DL << "\"\n";
2224 if (!M->getTargetTriple().empty())
2225 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2227 if (!M->getModuleInlineAsm().empty()) {
2230 // Split the string into lines, to make it easier to read the .ll file.
2231 StringRef Asm = M->getModuleInlineAsm();
2234 std::tie(Front, Asm) = Asm.split('\n');
2236 // We found a newline, print the portion of the asm string from the
2237 // last newline up to this newline.
2238 Out << "module asm \"";
2239 PrintEscapedString(Front, Out);
2241 } while (!Asm.empty());
2244 printTypeIdentities();
2246 // Output all comdats.
2247 if (!Comdats.empty())
2249 for (const Comdat *C : Comdats) {
2251 if (C != Comdats.back())
2255 // Output all globals.
2256 if (!M->global_empty()) Out << '\n';
2257 for (const GlobalVariable &GV : M->globals()) {
2258 printGlobal(&GV); Out << '\n';
2261 // Output all aliases.
2262 if (!M->alias_empty()) Out << "\n";
2263 for (const GlobalAlias &GA : M->aliases())
2266 // Output global use-lists.
2267 printUseLists(nullptr);
2269 // Output all of the functions.
2270 for (const Function &F : *M)
2272 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2274 // Output all attribute groups.
2275 if (!Machine.as_empty()) {
2277 writeAllAttributeGroups();
2280 // Output named metadata.
2281 if (!M->named_metadata_empty()) Out << '\n';
2283 for (const NamedMDNode &Node : M->named_metadata())
2284 printNamedMDNode(&Node);
2287 if (!Machine.mdn_empty()) {
2293 static void printMetadataIdentifier(StringRef Name,
2294 formatted_raw_ostream &Out) {
2296 Out << "<empty name> ";
2298 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2299 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2302 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2303 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2304 unsigned char C = Name[i];
2305 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2306 C == '.' || C == '_')
2309 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2314 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2316 printMetadataIdentifier(NMD->getName(), Out);
2318 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2321 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2330 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2331 formatted_raw_ostream &Out) {
2333 case GlobalValue::ExternalLinkage: break;
2334 case GlobalValue::PrivateLinkage: Out << "private "; break;
2335 case GlobalValue::InternalLinkage: Out << "internal "; break;
2336 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2337 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2338 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2339 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2340 case GlobalValue::CommonLinkage: Out << "common "; break;
2341 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2342 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2343 case GlobalValue::AvailableExternallyLinkage:
2344 Out << "available_externally ";
2349 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2350 formatted_raw_ostream &Out) {
2352 case GlobalValue::DefaultVisibility: break;
2353 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2354 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2358 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2359 formatted_raw_ostream &Out) {
2361 case GlobalValue::DefaultStorageClass: break;
2362 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2363 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2367 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2368 formatted_raw_ostream &Out) {
2370 case GlobalVariable::NotThreadLocal:
2372 case GlobalVariable::GeneralDynamicTLSModel:
2373 Out << "thread_local ";
2375 case GlobalVariable::LocalDynamicTLSModel:
2376 Out << "thread_local(localdynamic) ";
2378 case GlobalVariable::InitialExecTLSModel:
2379 Out << "thread_local(initialexec) ";
2381 case GlobalVariable::LocalExecTLSModel:
2382 Out << "thread_local(localexec) ";
2387 static void maybePrintComdat(formatted_raw_ostream &Out,
2388 const GlobalObject &GO) {
2389 const Comdat *C = GO.getComdat();
2393 if (isa<GlobalVariable>(GO))
2397 if (GO.getName() == C->getName())
2401 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2405 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2406 if (GV->isMaterializable())
2407 Out << "; Materializable\n";
2409 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2412 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2415 PrintLinkage(GV->getLinkage(), Out);
2416 PrintVisibility(GV->getVisibility(), Out);
2417 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2418 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2419 if (GV->hasUnnamedAddr())
2420 Out << "unnamed_addr ";
2422 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2423 Out << "addrspace(" << AddressSpace << ") ";
2424 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2425 Out << (GV->isConstant() ? "constant " : "global ");
2426 TypePrinter.print(GV->getType()->getElementType(), Out);
2428 if (GV->hasInitializer()) {
2430 writeOperand(GV->getInitializer(), false);
2433 if (GV->hasSection()) {
2434 Out << ", section \"";
2435 PrintEscapedString(GV->getSection(), Out);
2438 maybePrintComdat(Out, *GV);
2439 if (GV->getAlignment())
2440 Out << ", align " << GV->getAlignment();
2442 printInfoComment(*GV);
2445 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2446 if (GA->isMaterializable())
2447 Out << "; Materializable\n";
2449 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2452 PrintLinkage(GA->getLinkage(), Out);
2453 PrintVisibility(GA->getVisibility(), Out);
2454 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2455 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2456 if (GA->hasUnnamedAddr())
2457 Out << "unnamed_addr ";
2461 TypePrinter.print(GA->getValueType(), Out);
2465 const Constant *Aliasee = GA->getAliasee();
2468 TypePrinter.print(GA->getType(), Out);
2469 Out << " <<NULL ALIASEE>>";
2471 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2474 printInfoComment(*GA);
2478 void AssemblyWriter::printComdat(const Comdat *C) {
2482 void AssemblyWriter::printTypeIdentities() {
2483 if (TypePrinter.NumberedTypes.empty() &&
2484 TypePrinter.NamedTypes.empty())
2489 // We know all the numbers that each type is used and we know that it is a
2490 // dense assignment. Convert the map to an index table.
2491 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2492 for (DenseMap<StructType*, unsigned>::iterator I =
2493 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2495 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2496 NumberedTypes[I->second] = I->first;
2499 // Emit all numbered types.
2500 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2501 Out << '%' << i << " = type ";
2503 // Make sure we print out at least one level of the type structure, so
2504 // that we do not get %2 = type %2
2505 TypePrinter.printStructBody(NumberedTypes[i], Out);
2509 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2510 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2513 // Make sure we print out at least one level of the type structure, so
2514 // that we do not get %FILE = type %FILE
2515 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2520 /// printFunction - Print all aspects of a function.
2522 void AssemblyWriter::printFunction(const Function *F) {
2523 // Print out the return type and name.
2526 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2528 if (F->isMaterializable())
2529 Out << "; Materializable\n";
2531 const AttributeSet &Attrs = F->getAttributes();
2532 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2533 AttributeSet AS = Attrs.getFnAttributes();
2534 std::string AttrStr;
2537 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2538 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2541 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2543 Attribute Attr = *I;
2544 if (!Attr.isStringAttribute()) {
2545 if (!AttrStr.empty()) AttrStr += ' ';
2546 AttrStr += Attr.getAsString();
2550 if (!AttrStr.empty())
2551 Out << "; Function Attrs: " << AttrStr << '\n';
2554 if (F->isDeclaration())
2559 PrintLinkage(F->getLinkage(), Out);
2560 PrintVisibility(F->getVisibility(), Out);
2561 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2563 // Print the calling convention.
2564 if (F->getCallingConv() != CallingConv::C) {
2565 PrintCallingConv(F->getCallingConv(), Out);
2569 FunctionType *FT = F->getFunctionType();
2570 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2571 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2572 TypePrinter.print(F->getReturnType(), Out);
2574 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2576 Machine.incorporateFunction(F);
2578 // Loop over the arguments, printing them...
2579 if (F->isDeclaration() && !IsForDebug) {
2580 // We're only interested in the type here - don't print argument names.
2581 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2582 // Insert commas as we go... the first arg doesn't get a comma
2586 TypePrinter.print(FT->getParamType(I), Out);
2588 if (Attrs.hasAttributes(I + 1))
2589 Out << ' ' << Attrs.getAsString(I + 1);
2592 // The arguments are meaningful here, print them in detail.
2594 for (const Argument &Arg : F->args()) {
2595 // Insert commas as we go... the first arg doesn't get a comma
2598 printArgument(&Arg, Attrs, Idx++);
2602 // Finish printing arguments...
2603 if (FT->isVarArg()) {
2604 if (FT->getNumParams()) Out << ", ";
2605 Out << "..."; // Output varargs portion of signature!
2608 if (F->hasUnnamedAddr())
2609 Out << " unnamed_addr";
2610 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2611 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2612 if (F->hasSection()) {
2613 Out << " section \"";
2614 PrintEscapedString(F->getSection(), Out);
2617 maybePrintComdat(Out, *F);
2618 if (F->getAlignment())
2619 Out << " align " << F->getAlignment();
2621 Out << " gc \"" << F->getGC() << '"';
2622 if (F->hasPrefixData()) {
2624 writeOperand(F->getPrefixData(), true);
2626 if (F->hasPrologueData()) {
2627 Out << " prologue ";
2628 writeOperand(F->getPrologueData(), true);
2630 if (F->hasPersonalityFn()) {
2631 Out << " personality ";
2632 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2635 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2636 F->getAllMetadata(MDs);
2637 printMetadataAttachments(MDs, " ");
2639 if (F->isDeclaration()) {
2643 // Output all of the function's basic blocks.
2644 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2645 printBasicBlock(&*I);
2647 // Output the function's use-lists.
2653 Machine.purgeFunction();
2656 /// printArgument - This member is called for every argument that is passed into
2657 /// the function. Simply print it out
2659 void AssemblyWriter::printArgument(const Argument *Arg,
2660 AttributeSet Attrs, unsigned Idx) {
2662 TypePrinter.print(Arg->getType(), Out);
2664 // Output parameter attributes list
2665 if (Attrs.hasAttributes(Idx))
2666 Out << ' ' << Attrs.getAsString(Idx);
2668 // Output name, if available...
2669 if (Arg->hasName()) {
2671 PrintLLVMName(Out, Arg);
2675 /// printBasicBlock - This member is called for each basic block in a method.
2677 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2678 if (BB->hasName()) { // Print out the label if it exists...
2680 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2682 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2683 Out << "\n; <label>:";
2684 int Slot = Machine.getLocalSlot(BB);
2691 if (!BB->getParent()) {
2692 Out.PadToColumn(50);
2693 Out << "; Error: Block without parent!";
2694 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2695 // Output predecessors for the block.
2696 Out.PadToColumn(50);
2698 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2701 Out << " No predecessors!";
2704 writeOperand(*PI, false);
2705 for (++PI; PI != PE; ++PI) {
2707 writeOperand(*PI, false);
2714 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2716 // Output all of the instructions in the basic block...
2717 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2718 printInstructionLine(*I);
2721 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2724 /// printInstructionLine - Print an instruction and a newline character.
2725 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2726 printInstruction(I);
2730 /// printGCRelocateComment - print comment after call to the gc.relocate
2731 /// intrinsic indicating base and derived pointer names.
2732 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2733 assert(isGCRelocate(&V));
2734 GCRelocateOperands GCOps(cast<Instruction>(&V));
2737 writeOperand(GCOps.getBasePtr(), false);
2739 writeOperand(GCOps.getDerivedPtr(), false);
2743 /// printInfoComment - Print a little comment after the instruction indicating
2744 /// which slot it occupies.
2746 void AssemblyWriter::printInfoComment(const Value &V) {
2747 if (isGCRelocate(&V))
2748 printGCRelocateComment(V);
2750 if (AnnotationWriter)
2751 AnnotationWriter->printInfoComment(V, Out);
2754 // This member is called for each Instruction in a function..
2755 void AssemblyWriter::printInstruction(const Instruction &I) {
2756 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2758 // Print out indentation for an instruction.
2761 // Print out name if it exists...
2763 PrintLLVMName(Out, &I);
2765 } else if (!I.getType()->isVoidTy()) {
2766 // Print out the def slot taken.
2767 int SlotNum = Machine.getLocalSlot(&I);
2769 Out << "<badref> = ";
2771 Out << '%' << SlotNum << " = ";
2774 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2775 if (CI->isMustTailCall())
2777 else if (CI->isTailCall())
2779 else if (CI->isNoTailCall())
2783 // Print out the opcode...
2784 Out << I.getOpcodeName();
2786 // If this is an atomic load or store, print out the atomic marker.
2787 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2788 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2791 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2794 // If this is a volatile operation, print out the volatile marker.
2795 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2796 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2797 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2798 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2801 // Print out optimization information.
2802 WriteOptimizationInfo(Out, &I);
2804 // Print out the compare instruction predicates
2805 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2806 Out << ' ' << getPredicateText(CI->getPredicate());
2808 // Print out the atomicrmw operation
2809 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2810 writeAtomicRMWOperation(Out, RMWI->getOperation());
2812 // Print out the type of the operands...
2813 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2815 // Special case conditional branches to swizzle the condition out to the front
2816 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2817 const BranchInst &BI(cast<BranchInst>(I));
2819 writeOperand(BI.getCondition(), true);
2821 writeOperand(BI.getSuccessor(0), true);
2823 writeOperand(BI.getSuccessor(1), true);
2825 } else if (isa<SwitchInst>(I)) {
2826 const SwitchInst& SI(cast<SwitchInst>(I));
2827 // Special case switch instruction to get formatting nice and correct.
2829 writeOperand(SI.getCondition(), true);
2831 writeOperand(SI.getDefaultDest(), true);
2833 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2836 writeOperand(i.getCaseValue(), true);
2838 writeOperand(i.getCaseSuccessor(), true);
2841 } else if (isa<IndirectBrInst>(I)) {
2842 // Special case indirectbr instruction to get formatting nice and correct.
2844 writeOperand(Operand, true);
2847 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2850 writeOperand(I.getOperand(i), true);
2853 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2855 TypePrinter.print(I.getType(), Out);
2858 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2859 if (op) Out << ", ";
2861 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2862 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2864 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2866 writeOperand(I.getOperand(0), true);
2867 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2869 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2871 writeOperand(I.getOperand(0), true); Out << ", ";
2872 writeOperand(I.getOperand(1), true);
2873 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2875 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2877 TypePrinter.print(I.getType(), Out);
2878 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2881 if (LPI->isCleanup())
2884 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2885 if (i != 0 || LPI->isCleanup()) Out << "\n";
2886 if (LPI->isCatch(i))
2891 writeOperand(LPI->getClause(i), true);
2893 } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2895 for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps;
2899 writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true);
2902 writeOperand(CPI->getNormalDest(), /*PrintType=*/true);
2904 writeOperand(CPI->getUnwindDest(), /*PrintType=*/true);
2905 } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) {
2907 for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps;
2911 writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true);
2914 if (TPI->hasUnwindDest())
2915 writeOperand(TPI->getUnwindDest(), /*PrintType=*/true);
2918 } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) {
2920 for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) {
2923 writeOperand(CPI->getOperand(Op), /*PrintType=*/true);
2926 } else if (isa<ReturnInst>(I) && !Operand) {
2928 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2930 writeOperand(CRI->getCatchPad(), /*PrintType=*/false);
2933 writeOperand(CRI->getSuccessor(), /*PrintType=*/true);
2934 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2936 writeOperand(CRI->getCleanupPad(), /*PrintType=*/false);
2939 if (CRI->hasUnwindDest())
2940 writeOperand(CRI->getUnwindDest(), /*PrintType=*/true);
2943 } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) {
2945 if (CEPI->hasUnwindDest())
2946 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2949 } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) {
2951 writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false);
2954 if (CEPI->hasUnwindDest())
2955 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2958 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2959 // Print the calling convention being used.
2960 if (CI->getCallingConv() != CallingConv::C) {
2962 PrintCallingConv(CI->getCallingConv(), Out);
2965 Operand = CI->getCalledValue();
2966 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2967 Type *RetTy = FTy->getReturnType();
2968 const AttributeSet &PAL = CI->getAttributes();
2970 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2971 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2973 // If possible, print out the short form of the call instruction. We can
2974 // only do this if the first argument is a pointer to a nonvararg function,
2975 // and if the return type is not a pointer to a function.
2978 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2980 writeOperand(Operand, false);
2982 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2985 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2988 // Emit an ellipsis if this is a musttail call in a vararg function. This
2989 // is only to aid readability, musttail calls forward varargs by default.
2990 if (CI->isMustTailCall() && CI->getParent() &&
2991 CI->getParent()->getParent() &&
2992 CI->getParent()->getParent()->isVarArg())
2996 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2997 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2999 writeOperandBundles(CI);
3001 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3002 Operand = II->getCalledValue();
3003 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
3004 Type *RetTy = FTy->getReturnType();
3005 const AttributeSet &PAL = II->getAttributes();
3007 // Print the calling convention being used.
3008 if (II->getCallingConv() != CallingConv::C) {
3010 PrintCallingConv(II->getCallingConv(), Out);
3013 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
3014 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
3016 // If possible, print out the short form of the invoke instruction. We can
3017 // only do this if the first argument is a pointer to a nonvararg function,
3018 // and if the return type is not a pointer to a function.
3021 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3023 writeOperand(Operand, false);
3025 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3028 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
3032 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
3033 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3035 writeOperandBundles(II);
3038 writeOperand(II->getNormalDest(), true);
3040 writeOperand(II->getUnwindDest(), true);
3042 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3044 if (AI->isUsedWithInAlloca())
3046 TypePrinter.print(AI->getAllocatedType(), Out);
3048 // Explicitly write the array size if the code is broken, if it's an array
3049 // allocation, or if the type is not canonical for scalar allocations. The
3050 // latter case prevents the type from mutating when round-tripping through
3052 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3053 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3055 writeOperand(AI->getArraySize(), true);
3057 if (AI->getAlignment()) {
3058 Out << ", align " << AI->getAlignment();
3060 } else if (isa<CastInst>(I)) {
3063 writeOperand(Operand, true); // Work with broken code
3066 TypePrinter.print(I.getType(), Out);
3067 } else if (isa<VAArgInst>(I)) {
3070 writeOperand(Operand, true); // Work with broken code
3073 TypePrinter.print(I.getType(), Out);
3074 } else if (Operand) { // Print the normal way.
3075 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3077 TypePrinter.print(GEP->getSourceElementType(), Out);
3079 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3081 TypePrinter.print(LI->getType(), Out);
3085 // PrintAllTypes - Instructions who have operands of all the same type
3086 // omit the type from all but the first operand. If the instruction has
3087 // different type operands (for example br), then they are all printed.
3088 bool PrintAllTypes = false;
3089 Type *TheType = Operand->getType();
3091 // Select, Store and ShuffleVector always print all types.
3092 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3093 || isa<ReturnInst>(I)) {
3094 PrintAllTypes = true;
3096 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3097 Operand = I.getOperand(i);
3098 // note that Operand shouldn't be null, but the test helps make dump()
3099 // more tolerant of malformed IR
3100 if (Operand && Operand->getType() != TheType) {
3101 PrintAllTypes = true; // We have differing types! Print them all!
3107 if (!PrintAllTypes) {
3109 TypePrinter.print(TheType, Out);
3113 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3115 writeOperand(I.getOperand(i), PrintAllTypes);
3119 // Print atomic ordering/alignment for memory operations
3120 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3122 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3123 if (LI->getAlignment())
3124 Out << ", align " << LI->getAlignment();
3125 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3127 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3128 if (SI->getAlignment())
3129 Out << ", align " << SI->getAlignment();
3130 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3131 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3132 CXI->getSynchScope());
3133 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3134 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3135 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3136 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3139 // Print Metadata info.
3140 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3141 I.getAllMetadata(InstMD);
3142 printMetadataAttachments(InstMD, ", ");
3144 // Print a nice comment.
3145 printInfoComment(I);
3148 void AssemblyWriter::printMetadataAttachments(
3149 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3150 StringRef Separator) {
3154 if (MDNames.empty())
3155 TheModule->getMDKindNames(MDNames);
3157 for (const auto &I : MDs) {
3158 unsigned Kind = I.first;
3160 if (Kind < MDNames.size()) {
3162 printMetadataIdentifier(MDNames[Kind], Out);
3164 Out << "!<unknown kind #" << Kind << ">";
3166 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3170 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3171 Out << '!' << Slot << " = ";
3172 printMDNodeBody(Node);
3176 void AssemblyWriter::writeAllMDNodes() {
3177 SmallVector<const MDNode *, 16> Nodes;
3178 Nodes.resize(Machine.mdn_size());
3179 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3181 Nodes[I->second] = cast<MDNode>(I->first);
3183 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3184 writeMDNode(i, Nodes[i]);
3188 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3189 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3192 void AssemblyWriter::writeAllAttributeGroups() {
3193 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3194 asVec.resize(Machine.as_size());
3196 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3198 asVec[I->second] = *I;
3200 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3201 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3202 Out << "attributes #" << I->second << " = { "
3203 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3206 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3207 bool IsInFunction = Machine.getFunction();
3211 Out << "uselistorder";
3212 if (const BasicBlock *BB =
3213 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3215 writeOperand(BB->getParent(), false);
3217 writeOperand(BB, false);
3220 writeOperand(Order.V, true);
3224 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3225 Out << Order.Shuffle[0];
3226 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3227 Out << ", " << Order.Shuffle[I];
3231 void AssemblyWriter::printUseLists(const Function *F) {
3233 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3238 Out << "\n; uselistorder directives\n";
3240 printUseListOrder(UseListOrders.back());
3241 UseListOrders.pop_back();
3245 //===----------------------------------------------------------------------===//
3246 // External Interface declarations
3247 //===----------------------------------------------------------------------===//
3249 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3250 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3251 SlotTracker SlotTable(this);
3252 formatted_raw_ostream OS(ROS);
3253 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3254 ShouldPreserveUseListOrder);
3255 W.printModule(this);
3258 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3259 SlotTracker SlotTable(getParent());
3260 formatted_raw_ostream OS(ROS);
3261 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3262 W.printNamedMDNode(this);
3265 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3266 PrintLLVMName(ROS, getName(), ComdatPrefix);
3267 ROS << " = comdat ";
3269 switch (getSelectionKind()) {
3273 case Comdat::ExactMatch:
3274 ROS << "exactmatch";
3276 case Comdat::Largest:
3279 case Comdat::NoDuplicates:
3280 ROS << "noduplicates";
3282 case Comdat::SameSize:
3290 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3292 TP.print(const_cast<Type*>(this), OS);
3294 // If the type is a named struct type, print the body as well.
3295 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3296 if (!STy->isLiteral()) {
3298 TP.printStructBody(STy, OS);
3302 static bool isReferencingMDNode(const Instruction &I) {
3303 if (const auto *CI = dyn_cast<CallInst>(&I))
3304 if (Function *F = CI->getCalledFunction())
3305 if (F->isIntrinsic())
3306 for (auto &Op : I.operands())
3307 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3308 if (isa<MDNode>(V->getMetadata()))
3313 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3314 bool ShouldInitializeAllMetadata = false;
3315 if (auto *I = dyn_cast<Instruction>(this))
3316 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3317 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3318 ShouldInitializeAllMetadata = true;
3320 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3321 print(ROS, MST, IsForDebug);
3324 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3325 bool IsForDebug) const {
3326 formatted_raw_ostream OS(ROS);
3327 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3328 SlotTracker &SlotTable =
3329 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3330 auto incorporateFunction = [&](const Function *F) {
3332 MST.incorporateFunction(*F);
3335 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3336 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3337 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3338 W.printInstruction(*I);
3339 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3340 incorporateFunction(BB->getParent());
3341 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3342 W.printBasicBlock(BB);
3343 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3344 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3345 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3347 else if (const Function *F = dyn_cast<Function>(GV))
3350 W.printAlias(cast<GlobalAlias>(GV));
3351 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3352 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3353 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3354 TypePrinting TypePrinter;
3355 TypePrinter.print(C->getType(), OS);
3357 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3358 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3359 this->printAsOperand(OS, /* PrintType */ true, MST);
3361 llvm_unreachable("Unknown value to print out!");
3365 /// Print without a type, skipping the TypePrinting object.
3367 /// \return \c true iff printing was successful.
3368 static bool printWithoutType(const Value &V, raw_ostream &O,
3369 SlotTracker *Machine, const Module *M) {
3370 if (V.hasName() || isa<GlobalValue>(V) ||
3371 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3372 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3378 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3379 ModuleSlotTracker &MST) {
3380 TypePrinting TypePrinter;
3381 if (const Module *M = MST.getModule())
3382 TypePrinter.incorporateTypes(*M);
3384 TypePrinter.print(V.getType(), O);
3388 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3392 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3393 const Module *M) const {
3395 M = getModuleFromVal(this);
3398 if (printWithoutType(*this, O, nullptr, M))
3401 SlotTracker Machine(
3402 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3403 ModuleSlotTracker MST(Machine, M);
3404 printAsOperandImpl(*this, O, PrintType, MST);
3407 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3408 ModuleSlotTracker &MST) const {
3410 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3413 printAsOperandImpl(*this, O, PrintType, MST);
3416 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3417 ModuleSlotTracker &MST, const Module *M,
3418 bool OnlyAsOperand) {
3419 formatted_raw_ostream OS(ROS);
3421 TypePrinting TypePrinter;
3423 TypePrinter.incorporateTypes(*M);
3425 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3426 /* FromValue */ true);
3428 auto *N = dyn_cast<MDNode>(&MD);
3429 if (OnlyAsOperand || !N)
3433 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3436 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3437 ModuleSlotTracker MST(M, isa<MDNode>(this));
3438 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3441 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3442 const Module *M) const {
3443 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3446 void Metadata::print(raw_ostream &OS, const Module *M,
3447 bool /*IsForDebug*/) const {
3448 ModuleSlotTracker MST(M, isa<MDNode>(this));
3449 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3452 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3453 const Module *M, bool /*IsForDebug*/) const {
3454 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3457 // Value::dump - allow easy printing of Values from the debugger.
3459 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3461 // Type::dump - allow easy printing of Types from the debugger.
3463 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3465 // Module::dump() - Allow printing of Modules from the debugger.
3467 void Module::dump() const {
3468 print(dbgs(), nullptr,
3469 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3472 // \brief Allow printing of Comdats from the debugger.
3474 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3476 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3478 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3481 void Metadata::dump() const { dump(nullptr); }
3484 void Metadata::dump(const Module *M) const {
3485 print(dbgs(), M, /*IsForDebug=*/true);