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/FormattedStream.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
49 // Make virtual table appear in this compilation unit.
50 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
58 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
60 unsigned size() const { return IDs.size(); }
61 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
62 std::pair<unsigned, bool> lookup(const Value *V) const {
65 void index(const Value *V) {
66 // Explicitly sequence get-size and insert-value operations to avoid UB.
67 unsigned ID = IDs.size() + 1;
73 static void orderValue(const Value *V, OrderMap &OM) {
74 if (OM.lookup(V).first)
77 if (const Constant *C = dyn_cast<Constant>(V))
78 if (C->getNumOperands() && !isa<GlobalValue>(C))
79 for (const Value *Op : C->operands())
80 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
83 // Note: we cannot cache this lookup above, since inserting into the map
84 // changes the map's size, and thus affects the other IDs.
88 static OrderMap orderModule(const Module *M) {
89 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
90 // and ValueEnumerator::incorporateFunction().
93 for (const GlobalVariable &G : M->globals()) {
94 if (G.hasInitializer())
95 if (!isa<GlobalValue>(G.getInitializer()))
96 orderValue(G.getInitializer(), OM);
99 for (const GlobalAlias &A : M->aliases()) {
100 if (!isa<GlobalValue>(A.getAliasee()))
101 orderValue(A.getAliasee(), OM);
104 for (const Function &F : *M) {
105 if (F.hasPrefixData())
106 if (!isa<GlobalValue>(F.getPrefixData()))
107 orderValue(F.getPrefixData(), OM);
109 if (F.hasPrologueData())
110 if (!isa<GlobalValue>(F.getPrologueData()))
111 orderValue(F.getPrologueData(), OM);
113 if (F.hasPersonalityFn())
114 if (!isa<GlobalValue>(F.getPersonalityFn()))
115 orderValue(F.getPersonalityFn(), OM);
119 if (F.isDeclaration())
122 for (const Argument &A : F.args())
124 for (const BasicBlock &BB : F) {
126 for (const Instruction &I : BB) {
127 for (const Value *Op : I.operands())
128 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
138 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
139 unsigned ID, const OrderMap &OM,
140 UseListOrderStack &Stack) {
141 // Predict use-list order for this one.
142 typedef std::pair<const Use *, unsigned> Entry;
143 SmallVector<Entry, 64> List;
144 for (const Use &U : V->uses())
145 // Check if this user will be serialized.
146 if (OM.lookup(U.getUser()).first)
147 List.push_back(std::make_pair(&U, List.size()));
150 // We may have lost some users.
154 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
155 if (auto *BA = dyn_cast<BlockAddress>(V))
156 ID = OM.lookup(BA->getBasicBlock()).first;
157 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
158 const Use *LU = L.first;
159 const Use *RU = R.first;
163 auto LID = OM.lookup(LU->getUser()).first;
164 auto RID = OM.lookup(RU->getUser()).first;
166 // If ID is 4, then expect: 7 6 5 1 2 3.
180 // LID and RID are equal, so we have different operands of the same user.
181 // Assume operands are added in order for all instructions.
184 return LU->getOperandNo() < RU->getOperandNo();
185 return LU->getOperandNo() > RU->getOperandNo();
189 List.begin(), List.end(),
190 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
191 // Order is already correct.
194 // Store the shuffle.
195 Stack.emplace_back(V, F, List.size());
196 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
197 for (size_t I = 0, E = List.size(); I != E; ++I)
198 Stack.back().Shuffle[I] = List[I].second;
201 static void predictValueUseListOrder(const Value *V, const Function *F,
202 OrderMap &OM, UseListOrderStack &Stack) {
203 auto &IDPair = OM[V];
204 assert(IDPair.first && "Unmapped value");
206 // Already predicted.
209 // Do the actual prediction.
210 IDPair.second = true;
211 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
212 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
214 // Recursive descent into constants.
215 if (const Constant *C = dyn_cast<Constant>(V))
216 if (C->getNumOperands()) // Visit GlobalValues.
217 for (const Value *Op : C->operands())
218 if (isa<Constant>(Op)) // Visit GlobalValues.
219 predictValueUseListOrder(Op, F, OM, Stack);
222 static UseListOrderStack predictUseListOrder(const Module *M) {
223 OrderMap OM = orderModule(M);
225 // Use-list orders need to be serialized after all the users have been added
226 // to a value, or else the shuffles will be incomplete. Store them per
227 // function in a stack.
229 // Aside from function order, the order of values doesn't matter much here.
230 UseListOrderStack Stack;
232 // We want to visit the functions backward now so we can list function-local
233 // constants in the last Function they're used in. Module-level constants
234 // have already been visited above.
235 for (const Function &F : make_range(M->rbegin(), M->rend())) {
236 if (F.isDeclaration())
238 for (const BasicBlock &BB : F)
239 predictValueUseListOrder(&BB, &F, OM, Stack);
240 for (const Argument &A : F.args())
241 predictValueUseListOrder(&A, &F, OM, Stack);
242 for (const BasicBlock &BB : F)
243 for (const Instruction &I : BB)
244 for (const Value *Op : I.operands())
245 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
246 predictValueUseListOrder(Op, &F, OM, Stack);
247 for (const BasicBlock &BB : F)
248 for (const Instruction &I : BB)
249 predictValueUseListOrder(&I, &F, OM, Stack);
252 // Visit globals last.
253 for (const GlobalVariable &G : M->globals())
254 predictValueUseListOrder(&G, nullptr, OM, Stack);
255 for (const Function &F : *M)
256 predictValueUseListOrder(&F, nullptr, OM, Stack);
257 for (const GlobalAlias &A : M->aliases())
258 predictValueUseListOrder(&A, nullptr, OM, Stack);
259 for (const GlobalVariable &G : M->globals())
260 if (G.hasInitializer())
261 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
262 for (const GlobalAlias &A : M->aliases())
263 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
264 for (const Function &F : *M)
265 if (F.hasPrefixData())
266 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
271 static const Module *getModuleFromVal(const Value *V) {
272 if (const Argument *MA = dyn_cast<Argument>(V))
273 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
275 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
276 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
278 if (const Instruction *I = dyn_cast<Instruction>(V)) {
279 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
280 return M ? M->getParent() : nullptr;
283 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
284 return GV->getParent();
286 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
287 for (const User *U : MAV->users())
288 if (isa<Instruction>(U))
289 if (const Module *M = getModuleFromVal(U))
297 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
299 default: Out << "cc" << cc; break;
300 case CallingConv::Fast: Out << "fastcc"; break;
301 case CallingConv::Cold: Out << "coldcc"; break;
302 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
303 case CallingConv::AnyReg: Out << "anyregcc"; break;
304 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
305 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
306 case CallingConv::GHC: Out << "ghccc"; break;
307 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
308 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
309 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
310 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
311 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
312 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
313 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
314 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
315 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
316 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
317 case CallingConv::PTX_Device: Out << "ptx_device"; break;
318 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
319 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
320 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
321 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
325 // PrintEscapedString - Print each character of the specified string, escaping
326 // it if it is not printable or if it is an escape char.
327 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
328 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
329 unsigned char C = Name[i];
330 if (isprint(C) && C != '\\' && C != '"')
333 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
345 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
346 assert(!Name.empty() && "Cannot get empty name!");
348 // Scan the name to see if it needs quotes first.
349 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
351 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
352 // By making this unsigned, the value passed in to isalnum will always be
353 // in the range 0-255. This is important when building with MSVC because
354 // its implementation will assert. This situation can arise when dealing
355 // with UTF-8 multibyte characters.
356 unsigned char C = Name[i];
357 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
365 // If we didn't need any quotes, just write out the name in one blast.
371 // Okay, we need quotes. Output the quotes and escape any scary characters as
374 PrintEscapedString(Name, OS);
378 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
379 /// (if the string only contains simple characters) or is surrounded with ""'s
380 /// (if it has special chars in it). Print it out.
381 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
397 printLLVMNameWithoutPrefix(OS, Name);
400 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
401 /// (if the string only contains simple characters) or is surrounded with ""'s
402 /// (if it has special chars in it). Print it out.
403 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
404 PrintLLVMName(OS, V->getName(),
405 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
411 TypePrinting(const TypePrinting &) = delete;
412 void operator=(const TypePrinting&) = delete;
415 /// NamedTypes - The named types that are used by the current module.
416 TypeFinder NamedTypes;
418 /// NumberedTypes - The numbered types, along with their value.
419 DenseMap<StructType*, unsigned> NumberedTypes;
421 TypePrinting() = default;
423 void incorporateTypes(const Module &M);
425 void print(Type *Ty, raw_ostream &OS);
427 void printStructBody(StructType *Ty, raw_ostream &OS);
431 void TypePrinting::incorporateTypes(const Module &M) {
432 NamedTypes.run(M, false);
434 // The list of struct types we got back includes all the struct types, split
435 // the unnamed ones out to a numbering and remove the anonymous structs.
436 unsigned NextNumber = 0;
438 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
439 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
440 StructType *STy = *I;
442 // Ignore anonymous types.
443 if (STy->isLiteral())
446 if (STy->getName().empty())
447 NumberedTypes[STy] = NextNumber++;
452 NamedTypes.erase(NextToUse, NamedTypes.end());
456 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
457 /// use of type names or up references to shorten the type name where possible.
458 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
459 switch (Ty->getTypeID()) {
460 case Type::VoidTyID: OS << "void"; return;
461 case Type::HalfTyID: OS << "half"; return;
462 case Type::FloatTyID: OS << "float"; return;
463 case Type::DoubleTyID: OS << "double"; return;
464 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
465 case Type::FP128TyID: OS << "fp128"; return;
466 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
467 case Type::LabelTyID: OS << "label"; return;
468 case Type::MetadataTyID: OS << "metadata"; return;
469 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
470 case Type::IntegerTyID:
471 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
474 case Type::FunctionTyID: {
475 FunctionType *FTy = cast<FunctionType>(Ty);
476 print(FTy->getReturnType(), OS);
478 for (FunctionType::param_iterator I = FTy->param_begin(),
479 E = FTy->param_end(); I != E; ++I) {
480 if (I != FTy->param_begin())
484 if (FTy->isVarArg()) {
485 if (FTy->getNumParams()) OS << ", ";
491 case Type::StructTyID: {
492 StructType *STy = cast<StructType>(Ty);
494 if (STy->isLiteral())
495 return printStructBody(STy, OS);
497 if (!STy->getName().empty())
498 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
500 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
501 if (I != NumberedTypes.end())
502 OS << '%' << I->second;
503 else // Not enumerated, print the hex address.
504 OS << "%\"type " << STy << '\"';
507 case Type::PointerTyID: {
508 PointerType *PTy = cast<PointerType>(Ty);
509 print(PTy->getElementType(), OS);
510 if (unsigned AddressSpace = PTy->getAddressSpace())
511 OS << " addrspace(" << AddressSpace << ')';
515 case Type::ArrayTyID: {
516 ArrayType *ATy = cast<ArrayType>(Ty);
517 OS << '[' << ATy->getNumElements() << " x ";
518 print(ATy->getElementType(), OS);
522 case Type::VectorTyID: {
523 VectorType *PTy = cast<VectorType>(Ty);
524 OS << "<" << PTy->getNumElements() << " x ";
525 print(PTy->getElementType(), OS);
530 llvm_unreachable("Invalid TypeID");
533 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
534 if (STy->isOpaque()) {
542 if (STy->getNumElements() == 0) {
545 StructType::element_iterator I = STy->element_begin();
548 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
560 //===----------------------------------------------------------------------===//
561 // SlotTracker Class: Enumerate slot numbers for unnamed values
562 //===----------------------------------------------------------------------===//
563 /// This class provides computation of slot numbers for LLVM Assembly writing.
567 /// ValueMap - A mapping of Values to slot numbers.
568 typedef DenseMap<const Value*, unsigned> ValueMap;
571 /// TheModule - The module for which we are holding slot numbers.
572 const Module* TheModule;
574 /// TheFunction - The function for which we are holding slot numbers.
575 const Function* TheFunction;
576 bool FunctionProcessed;
577 bool ShouldInitializeAllMetadata;
579 /// mMap - The slot map for the module level data.
583 /// fMap - The slot map for the function level data.
587 /// mdnMap - Map for MDNodes.
588 DenseMap<const MDNode*, unsigned> mdnMap;
591 /// asMap - The slot map for attribute sets.
592 DenseMap<AttributeSet, unsigned> asMap;
595 /// Construct from a module.
597 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
598 /// functions, giving correct numbering for metadata referenced only from
599 /// within a function (even if no functions have been initialized).
600 explicit SlotTracker(const Module *M,
601 bool ShouldInitializeAllMetadata = false);
602 /// Construct from a function, starting out in incorp state.
604 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
605 /// functions, giving correct numbering for metadata referenced only from
606 /// within a function (even if no functions have been initialized).
607 explicit SlotTracker(const Function *F,
608 bool ShouldInitializeAllMetadata = false);
610 /// Return the slot number of the specified value in it's type
611 /// plane. If something is not in the SlotTracker, return -1.
612 int getLocalSlot(const Value *V);
613 int getGlobalSlot(const GlobalValue *V);
614 int getMetadataSlot(const MDNode *N);
615 int getAttributeGroupSlot(AttributeSet AS);
617 /// If you'd like to deal with a function instead of just a module, use
618 /// this method to get its data into the SlotTracker.
619 void incorporateFunction(const Function *F) {
621 FunctionProcessed = false;
624 const Function *getFunction() const { return TheFunction; }
626 /// After calling incorporateFunction, use this method to remove the
627 /// most recently incorporated function from the SlotTracker. This
628 /// will reset the state of the machine back to just the module contents.
629 void purgeFunction();
631 /// MDNode map iterators.
632 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
633 mdn_iterator mdn_begin() { return mdnMap.begin(); }
634 mdn_iterator mdn_end() { return mdnMap.end(); }
635 unsigned mdn_size() const { return mdnMap.size(); }
636 bool mdn_empty() const { return mdnMap.empty(); }
638 /// AttributeSet map iterators.
639 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
640 as_iterator as_begin() { return asMap.begin(); }
641 as_iterator as_end() { return asMap.end(); }
642 unsigned as_size() const { return asMap.size(); }
643 bool as_empty() const { return asMap.empty(); }
645 /// This function does the actual initialization.
646 inline void initialize();
648 // Implementation Details
650 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
651 void CreateModuleSlot(const GlobalValue *V);
653 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
654 void CreateMetadataSlot(const MDNode *N);
656 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
657 void CreateFunctionSlot(const Value *V);
659 /// \brief Insert the specified AttributeSet into the slot table.
660 void CreateAttributeSetSlot(AttributeSet AS);
662 /// Add all of the module level global variables (and their initializers)
663 /// and function declarations, but not the contents of those functions.
664 void processModule();
666 /// Add all of the functions arguments, basic blocks, and instructions.
667 void processFunction();
669 /// Add all of the metadata from a function.
670 void processFunctionMetadata(const Function &F);
672 /// Add all of the metadata from an instruction.
673 void processInstructionMetadata(const Instruction &I);
675 SlotTracker(const SlotTracker &) = delete;
676 void operator=(const SlotTracker &) = delete;
680 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
682 : M(M), F(F), Machine(&Machine) {}
684 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
685 bool ShouldInitializeAllMetadata)
686 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
688 M(M), Machine(MachineStorage.get()) {}
690 ModuleSlotTracker::~ModuleSlotTracker() {}
692 void ModuleSlotTracker::incorporateFunction(const Function &F) {
696 // Nothing to do if this is the right function already.
700 Machine->purgeFunction();
701 Machine->incorporateFunction(&F);
705 int ModuleSlotTracker::getLocalSlot(const Value *V) {
706 assert(F && "No function incorporated");
707 return Machine->getLocalSlot(V);
710 static SlotTracker *createSlotTracker(const Module *M) {
711 return new SlotTracker(M);
714 static SlotTracker *createSlotTracker(const Value *V) {
715 if (const Argument *FA = dyn_cast<Argument>(V))
716 return new SlotTracker(FA->getParent());
718 if (const Instruction *I = dyn_cast<Instruction>(V))
720 return new SlotTracker(I->getParent()->getParent());
722 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
723 return new SlotTracker(BB->getParent());
725 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
726 return new SlotTracker(GV->getParent());
728 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
729 return new SlotTracker(GA->getParent());
731 if (const Function *Func = dyn_cast<Function>(V))
732 return new SlotTracker(Func);
738 #define ST_DEBUG(X) dbgs() << X
743 // Module level constructor. Causes the contents of the Module (sans functions)
744 // to be added to the slot table.
745 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
746 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
747 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
748 fNext(0), mdnNext(0), asNext(0) {}
750 // Function level constructor. Causes the contents of the Module and the one
751 // function provided to be added to the slot table.
752 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
753 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
754 FunctionProcessed(false),
755 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
756 fNext(0), mdnNext(0), asNext(0) {}
758 inline void SlotTracker::initialize() {
761 TheModule = nullptr; ///< Prevent re-processing next time we're called.
764 if (TheFunction && !FunctionProcessed)
768 // Iterate through all the global variables, functions, and global
769 // variable initializers and create slots for them.
770 void SlotTracker::processModule() {
771 ST_DEBUG("begin processModule!\n");
773 // Add all of the unnamed global variables to the value table.
774 for (const GlobalVariable &Var : TheModule->globals()) {
776 CreateModuleSlot(&Var);
779 for (const GlobalAlias &A : TheModule->aliases()) {
781 CreateModuleSlot(&A);
784 // Add metadata used by named metadata.
785 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
786 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
787 CreateMetadataSlot(NMD.getOperand(i));
790 for (const Function &F : *TheModule) {
792 // Add all the unnamed functions to the table.
793 CreateModuleSlot(&F);
795 if (ShouldInitializeAllMetadata)
796 processFunctionMetadata(F);
798 // Add all the function attributes to the table.
799 // FIXME: Add attributes of other objects?
800 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
801 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
802 CreateAttributeSetSlot(FnAttrs);
805 ST_DEBUG("end processModule!\n");
808 // Process the arguments, basic blocks, and instructions of a function.
809 void SlotTracker::processFunction() {
810 ST_DEBUG("begin processFunction!\n");
813 // Add all the function arguments with no names.
814 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
815 AE = TheFunction->arg_end(); AI != AE; ++AI)
817 CreateFunctionSlot(AI);
819 ST_DEBUG("Inserting Instructions:\n");
821 // Add all of the basic blocks and instructions with no names.
822 for (auto &BB : *TheFunction) {
824 CreateFunctionSlot(&BB);
826 processFunctionMetadata(*TheFunction);
829 if (!I.getType()->isVoidTy() && !I.hasName())
830 CreateFunctionSlot(&I);
832 // We allow direct calls to any llvm.foo function here, because the
833 // target may not be linked into the optimizer.
834 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
835 // Add all the call attributes to the table.
836 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
837 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
838 CreateAttributeSetSlot(Attrs);
839 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
840 // Add all the call attributes to the table.
841 AttributeSet Attrs = II->getAttributes().getFnAttributes();
842 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
843 CreateAttributeSetSlot(Attrs);
848 FunctionProcessed = true;
850 ST_DEBUG("end processFunction!\n");
853 void SlotTracker::processFunctionMetadata(const Function &F) {
854 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
856 F.getAllMetadata(MDs);
858 CreateMetadataSlot(MD.second);
861 processInstructionMetadata(I);
865 void SlotTracker::processInstructionMetadata(const Instruction &I) {
866 // Process metadata used directly by intrinsics.
867 if (const CallInst *CI = dyn_cast<CallInst>(&I))
868 if (Function *F = CI->getCalledFunction())
869 if (F->isIntrinsic())
870 for (auto &Op : I.operands())
871 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
872 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
873 CreateMetadataSlot(N);
875 // Process metadata attached to this instruction.
876 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
877 I.getAllMetadata(MDs);
879 CreateMetadataSlot(MD.second);
882 /// Clean up after incorporating a function. This is the only way to get out of
883 /// the function incorporation state that affects get*Slot/Create*Slot. Function
884 /// incorporation state is indicated by TheFunction != 0.
885 void SlotTracker::purgeFunction() {
886 ST_DEBUG("begin purgeFunction!\n");
887 fMap.clear(); // Simply discard the function level map
888 TheFunction = nullptr;
889 FunctionProcessed = false;
890 ST_DEBUG("end purgeFunction!\n");
893 /// getGlobalSlot - Get the slot number of a global value.
894 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
895 // Check for uninitialized state and do lazy initialization.
898 // Find the value in the module map
899 ValueMap::iterator MI = mMap.find(V);
900 return MI == mMap.end() ? -1 : (int)MI->second;
903 /// getMetadataSlot - Get the slot number of a MDNode.
904 int SlotTracker::getMetadataSlot(const MDNode *N) {
905 // Check for uninitialized state and do lazy initialization.
908 // Find the MDNode in the module map
909 mdn_iterator MI = mdnMap.find(N);
910 return MI == mdnMap.end() ? -1 : (int)MI->second;
914 /// getLocalSlot - Get the slot number for a value that is local to a function.
915 int SlotTracker::getLocalSlot(const Value *V) {
916 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
918 // Check for uninitialized state and do lazy initialization.
921 ValueMap::iterator FI = fMap.find(V);
922 return FI == fMap.end() ? -1 : (int)FI->second;
925 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
926 // Check for uninitialized state and do lazy initialization.
929 // Find the AttributeSet in the module map.
930 as_iterator AI = asMap.find(AS);
931 return AI == asMap.end() ? -1 : (int)AI->second;
934 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
935 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
936 assert(V && "Can't insert a null Value into SlotTracker!");
937 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
938 assert(!V->hasName() && "Doesn't need a slot!");
940 unsigned DestSlot = mNext++;
943 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
945 // G = Global, F = Function, A = Alias, o = other
946 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
947 (isa<Function>(V) ? 'F' :
948 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
951 /// CreateSlot - Create a new slot for the specified value if it has no name.
952 void SlotTracker::CreateFunctionSlot(const Value *V) {
953 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
955 unsigned DestSlot = fNext++;
958 // G = Global, F = Function, o = other
959 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
960 DestSlot << " [o]\n");
963 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
964 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
965 assert(N && "Can't insert a null Value into SlotTracker!");
967 unsigned DestSlot = mdnNext;
968 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
972 // Recursively add any MDNodes referenced by operands.
973 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
974 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
975 CreateMetadataSlot(Op);
978 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
979 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
980 "Doesn't need a slot!");
982 as_iterator I = asMap.find(AS);
983 if (I != asMap.end())
986 unsigned DestSlot = asNext++;
987 asMap[AS] = DestSlot;
990 //===----------------------------------------------------------------------===//
991 // AsmWriter Implementation
992 //===----------------------------------------------------------------------===//
994 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
995 TypePrinting *TypePrinter,
996 SlotTracker *Machine,
997 const Module *Context);
999 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1000 TypePrinting *TypePrinter,
1001 SlotTracker *Machine, const Module *Context,
1002 bool FromValue = false);
1004 static const char *getPredicateText(unsigned predicate) {
1005 const char * pred = "unknown";
1006 switch (predicate) {
1007 case FCmpInst::FCMP_FALSE: pred = "false"; break;
1008 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
1009 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
1010 case FCmpInst::FCMP_OGE: pred = "oge"; break;
1011 case FCmpInst::FCMP_OLT: pred = "olt"; break;
1012 case FCmpInst::FCMP_OLE: pred = "ole"; break;
1013 case FCmpInst::FCMP_ONE: pred = "one"; break;
1014 case FCmpInst::FCMP_ORD: pred = "ord"; break;
1015 case FCmpInst::FCMP_UNO: pred = "uno"; break;
1016 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
1017 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
1018 case FCmpInst::FCMP_UGE: pred = "uge"; break;
1019 case FCmpInst::FCMP_ULT: pred = "ult"; break;
1020 case FCmpInst::FCMP_ULE: pred = "ule"; break;
1021 case FCmpInst::FCMP_UNE: pred = "une"; break;
1022 case FCmpInst::FCMP_TRUE: pred = "true"; break;
1023 case ICmpInst::ICMP_EQ: pred = "eq"; break;
1024 case ICmpInst::ICMP_NE: pred = "ne"; break;
1025 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
1026 case ICmpInst::ICMP_SGE: pred = "sge"; break;
1027 case ICmpInst::ICMP_SLT: pred = "slt"; break;
1028 case ICmpInst::ICMP_SLE: pred = "sle"; break;
1029 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
1030 case ICmpInst::ICMP_UGE: pred = "uge"; break;
1031 case ICmpInst::ICMP_ULT: pred = "ult"; break;
1032 case ICmpInst::ICMP_ULE: pred = "ule"; break;
1037 static void writeAtomicRMWOperation(raw_ostream &Out,
1038 AtomicRMWInst::BinOp Op) {
1040 default: Out << " <unknown operation " << Op << ">"; break;
1041 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1042 case AtomicRMWInst::Add: Out << " add"; break;
1043 case AtomicRMWInst::Sub: Out << " sub"; break;
1044 case AtomicRMWInst::And: Out << " and"; break;
1045 case AtomicRMWInst::Nand: Out << " nand"; break;
1046 case AtomicRMWInst::Or: Out << " or"; break;
1047 case AtomicRMWInst::Xor: Out << " xor"; break;
1048 case AtomicRMWInst::Max: Out << " max"; break;
1049 case AtomicRMWInst::Min: Out << " min"; break;
1050 case AtomicRMWInst::UMax: Out << " umax"; break;
1051 case AtomicRMWInst::UMin: Out << " umin"; break;
1055 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1056 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1057 // Unsafe algebra implies all the others, no need to write them all out
1058 if (FPO->hasUnsafeAlgebra())
1061 if (FPO->hasNoNaNs())
1063 if (FPO->hasNoInfs())
1065 if (FPO->hasNoSignedZeros())
1067 if (FPO->hasAllowReciprocal())
1072 if (const OverflowingBinaryOperator *OBO =
1073 dyn_cast<OverflowingBinaryOperator>(U)) {
1074 if (OBO->hasNoUnsignedWrap())
1076 if (OBO->hasNoSignedWrap())
1078 } else if (const PossiblyExactOperator *Div =
1079 dyn_cast<PossiblyExactOperator>(U)) {
1082 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1083 if (GEP->isInBounds())
1088 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1089 TypePrinting &TypePrinter,
1090 SlotTracker *Machine,
1091 const Module *Context) {
1092 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1093 if (CI->getType()->isIntegerTy(1)) {
1094 Out << (CI->getZExtValue() ? "true" : "false");
1097 Out << CI->getValue();
1101 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1102 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1103 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1104 // We would like to output the FP constant value in exponential notation,
1105 // but we cannot do this if doing so will lose precision. Check here to
1106 // make sure that we only output it in exponential format if we can parse
1107 // the value back and get the same value.
1110 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
1111 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1112 bool isInf = CFP->getValueAPF().isInfinity();
1113 bool isNaN = CFP->getValueAPF().isNaN();
1114 if (!isHalf && !isInf && !isNaN) {
1115 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1116 CFP->getValueAPF().convertToFloat();
1117 SmallString<128> StrVal;
1118 raw_svector_ostream(StrVal) << Val;
1120 // Check to make sure that the stringized number is not some string like
1121 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1122 // that the string matches the "[-+]?[0-9]" regex.
1124 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1125 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1126 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1127 // Reparse stringized version!
1128 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1134 // Otherwise we could not reparse it to exactly the same value, so we must
1135 // output the string in hexadecimal format! Note that loading and storing
1136 // floating point types changes the bits of NaNs on some hosts, notably
1137 // x86, so we must not use these types.
1138 static_assert(sizeof(double) == sizeof(uint64_t),
1139 "assuming that double is 64 bits!");
1141 APFloat apf = CFP->getValueAPF();
1142 // Halves and floats are represented in ASCII IR as double, convert.
1144 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1147 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1152 // Either half, or some form of long double.
1153 // These appear as a magic letter identifying the type, then a
1154 // fixed number of hex digits.
1156 // Bit position, in the current word, of the next nibble to print.
1159 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1161 // api needed to prevent premature destruction
1162 APInt api = CFP->getValueAPF().bitcastToAPInt();
1163 const uint64_t* p = api.getRawData();
1164 uint64_t word = p[1];
1166 int width = api.getBitWidth();
1167 for (int j=0; j<width; j+=4, shiftcount-=4) {
1168 unsigned int nibble = (word>>shiftcount) & 15;
1170 Out << (unsigned char)(nibble + '0');
1172 Out << (unsigned char)(nibble - 10 + 'A');
1173 if (shiftcount == 0 && j+4 < width) {
1177 shiftcount = width-j-4;
1181 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1184 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1187 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1191 llvm_unreachable("Unsupported floating point type");
1192 // api needed to prevent premature destruction
1193 APInt api = CFP->getValueAPF().bitcastToAPInt();
1194 const uint64_t* p = api.getRawData();
1196 int width = api.getBitWidth();
1197 for (int j=0; j<width; j+=4, shiftcount-=4) {
1198 unsigned int nibble = (word>>shiftcount) & 15;
1200 Out << (unsigned char)(nibble + '0');
1202 Out << (unsigned char)(nibble - 10 + 'A');
1203 if (shiftcount == 0 && j+4 < width) {
1207 shiftcount = width-j-4;
1213 if (isa<ConstantAggregateZero>(CV)) {
1214 Out << "zeroinitializer";
1218 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1219 Out << "blockaddress(";
1220 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1223 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1229 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1230 Type *ETy = CA->getType()->getElementType();
1232 TypePrinter.print(ETy, Out);
1234 WriteAsOperandInternal(Out, CA->getOperand(0),
1235 &TypePrinter, Machine,
1237 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1239 TypePrinter.print(ETy, Out);
1241 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1248 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1249 // As a special case, print the array as a string if it is an array of
1250 // i8 with ConstantInt values.
1251 if (CA->isString()) {
1253 PrintEscapedString(CA->getAsString(), Out);
1258 Type *ETy = CA->getType()->getElementType();
1260 TypePrinter.print(ETy, Out);
1262 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1263 &TypePrinter, Machine,
1265 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1267 TypePrinter.print(ETy, Out);
1269 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1277 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1278 if (CS->getType()->isPacked())
1281 unsigned N = CS->getNumOperands();
1284 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1287 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1290 for (unsigned i = 1; i < N; i++) {
1292 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1295 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1302 if (CS->getType()->isPacked())
1307 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1308 Type *ETy = CV->getType()->getVectorElementType();
1310 TypePrinter.print(ETy, Out);
1312 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1314 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1316 TypePrinter.print(ETy, Out);
1318 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1325 if (isa<ConstantPointerNull>(CV)) {
1330 if (isa<UndefValue>(CV)) {
1335 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1336 Out << CE->getOpcodeName();
1337 WriteOptimizationInfo(Out, CE);
1338 if (CE->isCompare())
1339 Out << ' ' << getPredicateText(CE->getPredicate());
1342 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1344 cast<PointerType>(GEP->getPointerOperandType()->getScalarType())
1350 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1351 TypePrinter.print((*OI)->getType(), Out);
1353 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1354 if (OI+1 != CE->op_end())
1358 if (CE->hasIndices()) {
1359 ArrayRef<unsigned> Indices = CE->getIndices();
1360 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1361 Out << ", " << Indices[i];
1366 TypePrinter.print(CE->getType(), Out);
1373 Out << "<placeholder or erroneous Constant>";
1376 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1377 TypePrinting *TypePrinter, SlotTracker *Machine,
1378 const Module *Context) {
1380 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1381 const Metadata *MD = Node->getOperand(mi);
1384 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1385 Value *V = MDV->getValue();
1386 TypePrinter->print(V->getType(), Out);
1388 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1390 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1400 struct FieldSeparator {
1403 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1405 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1410 return OS << FS.Sep;
1412 struct MDFieldPrinter {
1415 TypePrinting *TypePrinter;
1416 SlotTracker *Machine;
1417 const Module *Context;
1419 explicit MDFieldPrinter(raw_ostream &Out)
1420 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1421 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1422 SlotTracker *Machine, const Module *Context)
1423 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1425 void printTag(const DINode *N);
1426 void printString(StringRef Name, StringRef Value,
1427 bool ShouldSkipEmpty = true);
1428 void printMetadata(StringRef Name, const Metadata *MD,
1429 bool ShouldSkipNull = true);
1430 template <class IntTy>
1431 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1432 void printBool(StringRef Name, bool Value);
1433 void printDIFlags(StringRef Name, unsigned Flags);
1434 template <class IntTy, class Stringifier>
1435 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1436 bool ShouldSkipZero = true);
1440 void MDFieldPrinter::printTag(const DINode *N) {
1441 Out << FS << "tag: ";
1442 if (const char *Tag = dwarf::TagString(N->getTag()))
1448 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1449 bool ShouldSkipEmpty) {
1450 if (ShouldSkipEmpty && Value.empty())
1453 Out << FS << Name << ": \"";
1454 PrintEscapedString(Value, Out);
1458 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1459 TypePrinting *TypePrinter,
1460 SlotTracker *Machine,
1461 const Module *Context) {
1466 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1469 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1470 bool ShouldSkipNull) {
1471 if (ShouldSkipNull && !MD)
1474 Out << FS << Name << ": ";
1475 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1478 template <class IntTy>
1479 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1480 if (ShouldSkipZero && !Int)
1483 Out << FS << Name << ": " << Int;
1486 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1487 Out << FS << Name << ": " << (Value ? "true" : "false");
1490 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1494 Out << FS << Name << ": ";
1496 SmallVector<unsigned, 8> SplitFlags;
1497 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1499 FieldSeparator FlagsFS(" | ");
1500 for (unsigned F : SplitFlags) {
1501 const char *StringF = DINode::getFlagString(F);
1502 assert(StringF && "Expected valid flag");
1503 Out << FlagsFS << StringF;
1505 if (Extra || SplitFlags.empty())
1506 Out << FlagsFS << Extra;
1509 template <class IntTy, class Stringifier>
1510 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1511 Stringifier toString, bool ShouldSkipZero) {
1515 Out << FS << Name << ": ";
1516 if (const char *S = toString(Value))
1522 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1523 TypePrinting *TypePrinter, SlotTracker *Machine,
1524 const Module *Context) {
1525 Out << "!GenericDINode(";
1526 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1527 Printer.printTag(N);
1528 Printer.printString("header", N->getHeader());
1529 if (N->getNumDwarfOperands()) {
1530 Out << Printer.FS << "operands: {";
1532 for (auto &I : N->dwarf_operands()) {
1534 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1541 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1542 TypePrinting *TypePrinter, SlotTracker *Machine,
1543 const Module *Context) {
1544 Out << "!DILocation(";
1545 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1546 // Always output the line, since 0 is a relevant and important value for it.
1547 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1548 Printer.printInt("column", DL->getColumn());
1549 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1550 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1554 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1555 TypePrinting *, SlotTracker *, const Module *) {
1556 Out << "!DISubrange(";
1557 MDFieldPrinter Printer(Out);
1558 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1559 Printer.printInt("lowerBound", N->getLowerBound());
1563 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1564 TypePrinting *, SlotTracker *, const Module *) {
1565 Out << "!DIEnumerator(";
1566 MDFieldPrinter Printer(Out);
1567 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1568 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1572 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1573 TypePrinting *, SlotTracker *, const Module *) {
1574 Out << "!DIBasicType(";
1575 MDFieldPrinter Printer(Out);
1576 if (N->getTag() != dwarf::DW_TAG_base_type)
1577 Printer.printTag(N);
1578 Printer.printString("name", N->getName());
1579 Printer.printInt("size", N->getSizeInBits());
1580 Printer.printInt("align", N->getAlignInBits());
1581 Printer.printDwarfEnum("encoding", N->getEncoding(),
1582 dwarf::AttributeEncodingString);
1586 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1587 TypePrinting *TypePrinter, SlotTracker *Machine,
1588 const Module *Context) {
1589 Out << "!DIDerivedType(";
1590 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1591 Printer.printTag(N);
1592 Printer.printString("name", N->getName());
1593 Printer.printMetadata("scope", N->getRawScope());
1594 Printer.printMetadata("file", N->getRawFile());
1595 Printer.printInt("line", N->getLine());
1596 Printer.printMetadata("baseType", N->getRawBaseType(),
1597 /* ShouldSkipNull */ false);
1598 Printer.printInt("size", N->getSizeInBits());
1599 Printer.printInt("align", N->getAlignInBits());
1600 Printer.printInt("offset", N->getOffsetInBits());
1601 Printer.printDIFlags("flags", N->getFlags());
1602 Printer.printMetadata("extraData", N->getRawExtraData());
1606 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1607 TypePrinting *TypePrinter,
1608 SlotTracker *Machine, const Module *Context) {
1609 Out << "!DICompositeType(";
1610 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1611 Printer.printTag(N);
1612 Printer.printString("name", N->getName());
1613 Printer.printMetadata("scope", N->getRawScope());
1614 Printer.printMetadata("file", N->getRawFile());
1615 Printer.printInt("line", N->getLine());
1616 Printer.printMetadata("baseType", N->getRawBaseType());
1617 Printer.printInt("size", N->getSizeInBits());
1618 Printer.printInt("align", N->getAlignInBits());
1619 Printer.printInt("offset", N->getOffsetInBits());
1620 Printer.printDIFlags("flags", N->getFlags());
1621 Printer.printMetadata("elements", N->getRawElements());
1622 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1623 dwarf::LanguageString);
1624 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1625 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1626 Printer.printString("identifier", N->getIdentifier());
1630 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1631 TypePrinting *TypePrinter,
1632 SlotTracker *Machine, const Module *Context) {
1633 Out << "!DISubroutineType(";
1634 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1635 Printer.printDIFlags("flags", N->getFlags());
1636 Printer.printMetadata("types", N->getRawTypeArray(),
1637 /* ShouldSkipNull */ false);
1641 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1642 SlotTracker *, const Module *) {
1644 MDFieldPrinter Printer(Out);
1645 Printer.printString("filename", N->getFilename(),
1646 /* ShouldSkipEmpty */ false);
1647 Printer.printString("directory", N->getDirectory(),
1648 /* ShouldSkipEmpty */ false);
1652 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1653 TypePrinting *TypePrinter, SlotTracker *Machine,
1654 const Module *Context) {
1655 Out << "!DICompileUnit(";
1656 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1657 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1658 dwarf::LanguageString, /* ShouldSkipZero */ false);
1659 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1660 Printer.printString("producer", N->getProducer());
1661 Printer.printBool("isOptimized", N->isOptimized());
1662 Printer.printString("flags", N->getFlags());
1663 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1664 /* ShouldSkipZero */ false);
1665 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1666 Printer.printInt("emissionKind", N->getEmissionKind(),
1667 /* ShouldSkipZero */ false);
1668 Printer.printMetadata("enums", N->getRawEnumTypes());
1669 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1670 Printer.printMetadata("subprograms", N->getRawSubprograms());
1671 Printer.printMetadata("globals", N->getRawGlobalVariables());
1672 Printer.printMetadata("imports", N->getRawImportedEntities());
1673 Printer.printInt("dwoId", N->getDWOId());
1677 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1678 TypePrinting *TypePrinter, SlotTracker *Machine,
1679 const Module *Context) {
1680 Out << "!DISubprogram(";
1681 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1682 Printer.printString("name", N->getName());
1683 Printer.printString("linkageName", N->getLinkageName());
1684 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1685 Printer.printMetadata("file", N->getRawFile());
1686 Printer.printInt("line", N->getLine());
1687 Printer.printMetadata("type", N->getRawType());
1688 Printer.printBool("isLocal", N->isLocalToUnit());
1689 Printer.printBool("isDefinition", N->isDefinition());
1690 Printer.printInt("scopeLine", N->getScopeLine());
1691 Printer.printMetadata("containingType", N->getRawContainingType());
1692 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1693 dwarf::VirtualityString);
1694 Printer.printInt("virtualIndex", N->getVirtualIndex());
1695 Printer.printDIFlags("flags", N->getFlags());
1696 Printer.printBool("isOptimized", N->isOptimized());
1697 Printer.printMetadata("function", N->getRawFunction());
1698 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1699 Printer.printMetadata("declaration", N->getRawDeclaration());
1700 Printer.printMetadata("variables", N->getRawVariables());
1704 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1705 TypePrinting *TypePrinter, SlotTracker *Machine,
1706 const Module *Context) {
1707 Out << "!DILexicalBlock(";
1708 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1709 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1710 Printer.printMetadata("file", N->getRawFile());
1711 Printer.printInt("line", N->getLine());
1712 Printer.printInt("column", N->getColumn());
1716 static void writeDILexicalBlockFile(raw_ostream &Out,
1717 const DILexicalBlockFile *N,
1718 TypePrinting *TypePrinter,
1719 SlotTracker *Machine,
1720 const Module *Context) {
1721 Out << "!DILexicalBlockFile(";
1722 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1723 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1724 Printer.printMetadata("file", N->getRawFile());
1725 Printer.printInt("discriminator", N->getDiscriminator(),
1726 /* ShouldSkipZero */ false);
1730 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1731 TypePrinting *TypePrinter, SlotTracker *Machine,
1732 const Module *Context) {
1733 Out << "!DINamespace(";
1734 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1735 Printer.printString("name", N->getName());
1736 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1737 Printer.printMetadata("file", N->getRawFile());
1738 Printer.printInt("line", N->getLine());
1742 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1743 TypePrinting *TypePrinter, SlotTracker *Machine,
1744 const Module *Context) {
1745 Out << "!DIModule(";
1746 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1747 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1748 Printer.printString("name", N->getName());
1749 Printer.printString("configMacros", N->getConfigurationMacros());
1750 Printer.printString("includePath", N->getIncludePath());
1751 Printer.printString("isysroot", N->getISysRoot());
1756 static void writeDITemplateTypeParameter(raw_ostream &Out,
1757 const DITemplateTypeParameter *N,
1758 TypePrinting *TypePrinter,
1759 SlotTracker *Machine,
1760 const Module *Context) {
1761 Out << "!DITemplateTypeParameter(";
1762 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1763 Printer.printString("name", N->getName());
1764 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1768 static void writeDITemplateValueParameter(raw_ostream &Out,
1769 const DITemplateValueParameter *N,
1770 TypePrinting *TypePrinter,
1771 SlotTracker *Machine,
1772 const Module *Context) {
1773 Out << "!DITemplateValueParameter(";
1774 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1775 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1776 Printer.printTag(N);
1777 Printer.printString("name", N->getName());
1778 Printer.printMetadata("type", N->getRawType());
1779 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1783 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1784 TypePrinting *TypePrinter,
1785 SlotTracker *Machine, const Module *Context) {
1786 Out << "!DIGlobalVariable(";
1787 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1788 Printer.printString("name", N->getName());
1789 Printer.printString("linkageName", N->getLinkageName());
1790 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1791 Printer.printMetadata("file", N->getRawFile());
1792 Printer.printInt("line", N->getLine());
1793 Printer.printMetadata("type", N->getRawType());
1794 Printer.printBool("isLocal", N->isLocalToUnit());
1795 Printer.printBool("isDefinition", N->isDefinition());
1796 Printer.printMetadata("variable", N->getRawVariable());
1797 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1801 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1802 TypePrinting *TypePrinter,
1803 SlotTracker *Machine, const Module *Context) {
1804 Out << "!DILocalVariable(";
1805 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1806 Printer.printTag(N);
1807 Printer.printString("name", N->getName());
1808 Printer.printInt("arg", N->getArg(),
1809 /* ShouldSkipZero */
1810 N->getTag() == dwarf::DW_TAG_auto_variable);
1811 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1812 Printer.printMetadata("file", N->getRawFile());
1813 Printer.printInt("line", N->getLine());
1814 Printer.printMetadata("type", N->getRawType());
1815 Printer.printDIFlags("flags", N->getFlags());
1819 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1820 TypePrinting *TypePrinter, SlotTracker *Machine,
1821 const Module *Context) {
1822 Out << "!DIExpression(";
1825 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1826 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1827 assert(OpStr && "Expected valid opcode");
1830 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1831 Out << FS << I->getArg(A);
1834 for (const auto &I : N->getElements())
1840 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1841 TypePrinting *TypePrinter, SlotTracker *Machine,
1842 const Module *Context) {
1843 Out << "!DIObjCProperty(";
1844 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1845 Printer.printString("name", N->getName());
1846 Printer.printMetadata("file", N->getRawFile());
1847 Printer.printInt("line", N->getLine());
1848 Printer.printString("setter", N->getSetterName());
1849 Printer.printString("getter", N->getGetterName());
1850 Printer.printInt("attributes", N->getAttributes());
1851 Printer.printMetadata("type", N->getRawType());
1855 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1856 TypePrinting *TypePrinter,
1857 SlotTracker *Machine, const Module *Context) {
1858 Out << "!DIImportedEntity(";
1859 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1860 Printer.printTag(N);
1861 Printer.printString("name", N->getName());
1862 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1863 Printer.printMetadata("entity", N->getRawEntity());
1864 Printer.printInt("line", N->getLine());
1869 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1870 TypePrinting *TypePrinter,
1871 SlotTracker *Machine,
1872 const Module *Context) {
1873 if (Node->isDistinct())
1875 else if (Node->isTemporary())
1876 Out << "<temporary!> "; // Handle broken code.
1878 switch (Node->getMetadataID()) {
1880 llvm_unreachable("Expected uniquable MDNode");
1881 #define HANDLE_MDNODE_LEAF(CLASS) \
1882 case Metadata::CLASS##Kind: \
1883 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1885 #include "llvm/IR/Metadata.def"
1889 // Full implementation of printing a Value as an operand with support for
1890 // TypePrinting, etc.
1891 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1892 TypePrinting *TypePrinter,
1893 SlotTracker *Machine,
1894 const Module *Context) {
1896 PrintLLVMName(Out, V);
1900 const Constant *CV = dyn_cast<Constant>(V);
1901 if (CV && !isa<GlobalValue>(CV)) {
1902 assert(TypePrinter && "Constants require TypePrinting!");
1903 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1907 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1909 if (IA->hasSideEffects())
1910 Out << "sideeffect ";
1911 if (IA->isAlignStack())
1912 Out << "alignstack ";
1913 // We don't emit the AD_ATT dialect as it's the assumed default.
1914 if (IA->getDialect() == InlineAsm::AD_Intel)
1915 Out << "inteldialect ";
1917 PrintEscapedString(IA->getAsmString(), Out);
1919 PrintEscapedString(IA->getConstraintString(), Out);
1924 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1925 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1926 Context, /* FromValue */ true);
1932 // If we have a SlotTracker, use it.
1934 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1935 Slot = Machine->getGlobalSlot(GV);
1938 Slot = Machine->getLocalSlot(V);
1940 // If the local value didn't succeed, then we may be referring to a value
1941 // from a different function. Translate it, as this can happen when using
1942 // address of blocks.
1944 if ((Machine = createSlotTracker(V))) {
1945 Slot = Machine->getLocalSlot(V);
1949 } else if ((Machine = createSlotTracker(V))) {
1950 // Otherwise, create one to get the # and then destroy it.
1951 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1952 Slot = Machine->getGlobalSlot(GV);
1955 Slot = Machine->getLocalSlot(V);
1964 Out << Prefix << Slot;
1969 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1970 TypePrinting *TypePrinter,
1971 SlotTracker *Machine, const Module *Context,
1973 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1974 std::unique_ptr<SlotTracker> MachineStorage;
1976 MachineStorage = make_unique<SlotTracker>(Context);
1977 Machine = MachineStorage.get();
1979 int Slot = Machine->getMetadataSlot(N);
1981 // Give the pointer value instead of "badref", since this comes up all
1982 // the time when debugging.
1983 Out << "<" << N << ">";
1989 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1991 PrintEscapedString(MDS->getString(), Out);
1996 auto *V = cast<ValueAsMetadata>(MD);
1997 assert(TypePrinter && "TypePrinter required for metadata values");
1998 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1999 "Unexpected function-local metadata outside of value argument");
2001 TypePrinter->print(V->getValue()->getType(), Out);
2003 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2007 class AssemblyWriter {
2008 formatted_raw_ostream &Out;
2009 const Module *TheModule;
2010 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2011 SlotTracker &Machine;
2012 TypePrinting TypePrinter;
2013 AssemblyAnnotationWriter *AnnotationWriter;
2014 SetVector<const Comdat *> Comdats;
2015 bool ShouldPreserveUseListOrder;
2016 UseListOrderStack UseListOrders;
2017 SmallVector<StringRef, 8> MDNames;
2020 /// Construct an AssemblyWriter with an external SlotTracker
2021 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2022 AssemblyAnnotationWriter *AAW,
2023 bool ShouldPreserveUseListOrder = false);
2025 /// Construct an AssemblyWriter with an internally allocated SlotTracker
2026 AssemblyWriter(formatted_raw_ostream &o, const Module *M,
2027 AssemblyAnnotationWriter *AAW,
2028 bool ShouldPreserveUseListOrder = false);
2030 void printMDNodeBody(const MDNode *MD);
2031 void printNamedMDNode(const NamedMDNode *NMD);
2033 void printModule(const Module *M);
2035 void writeOperand(const Value *Op, bool PrintType);
2036 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2037 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2038 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2039 AtomicOrdering FailureOrdering,
2040 SynchronizationScope SynchScope);
2042 void writeAllMDNodes();
2043 void writeMDNode(unsigned Slot, const MDNode *Node);
2044 void writeAllAttributeGroups();
2046 void printTypeIdentities();
2047 void printGlobal(const GlobalVariable *GV);
2048 void printAlias(const GlobalAlias *GV);
2049 void printComdat(const Comdat *C);
2050 void printFunction(const Function *F);
2051 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2052 void printBasicBlock(const BasicBlock *BB);
2053 void printInstructionLine(const Instruction &I);
2054 void printInstruction(const Instruction &I);
2056 void printUseListOrder(const UseListOrder &Order);
2057 void printUseLists(const Function *F);
2062 /// \brief Print out metadata attachments.
2063 void printMetadataAttachments(
2064 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2065 StringRef Separator);
2067 // printInfoComment - Print a little comment after the instruction indicating
2068 // which slot it occupies.
2069 void printInfoComment(const Value &V);
2071 // printGCRelocateComment - print comment after call to the gc.relocate
2072 // intrinsic indicating base and derived pointer names.
2073 void printGCRelocateComment(const Value &V);
2077 void AssemblyWriter::init() {
2080 TypePrinter.incorporateTypes(*TheModule);
2081 for (const Function &F : *TheModule)
2082 if (const Comdat *C = F.getComdat())
2084 for (const GlobalVariable &GV : TheModule->globals())
2085 if (const Comdat *C = GV.getComdat())
2089 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2090 const Module *M, AssemblyAnnotationWriter *AAW,
2091 bool ShouldPreserveUseListOrder)
2092 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2093 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2097 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
2098 AssemblyAnnotationWriter *AAW,
2099 bool ShouldPreserveUseListOrder)
2100 : Out(o), TheModule(M), SlotTrackerStorage(createSlotTracker(M)),
2101 Machine(*SlotTrackerStorage), AnnotationWriter(AAW),
2102 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2106 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2108 Out << "<null operand!>";
2112 TypePrinter.print(Operand->getType(), Out);
2115 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2118 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2119 SynchronizationScope SynchScope) {
2120 if (Ordering == NotAtomic)
2123 switch (SynchScope) {
2124 case SingleThread: Out << " singlethread"; break;
2125 case CrossThread: break;
2129 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2130 case Unordered: Out << " unordered"; break;
2131 case Monotonic: Out << " monotonic"; break;
2132 case Acquire: Out << " acquire"; break;
2133 case Release: Out << " release"; break;
2134 case AcquireRelease: Out << " acq_rel"; break;
2135 case SequentiallyConsistent: Out << " seq_cst"; break;
2139 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2140 AtomicOrdering FailureOrdering,
2141 SynchronizationScope SynchScope) {
2142 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2144 switch (SynchScope) {
2145 case SingleThread: Out << " singlethread"; break;
2146 case CrossThread: break;
2149 switch (SuccessOrdering) {
2150 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2151 case Unordered: Out << " unordered"; break;
2152 case Monotonic: Out << " monotonic"; break;
2153 case Acquire: Out << " acquire"; break;
2154 case Release: Out << " release"; break;
2155 case AcquireRelease: Out << " acq_rel"; break;
2156 case SequentiallyConsistent: Out << " seq_cst"; break;
2159 switch (FailureOrdering) {
2160 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2161 case Unordered: Out << " unordered"; break;
2162 case Monotonic: Out << " monotonic"; break;
2163 case Acquire: Out << " acquire"; break;
2164 case Release: Out << " release"; break;
2165 case AcquireRelease: Out << " acq_rel"; break;
2166 case SequentiallyConsistent: Out << " seq_cst"; break;
2170 void AssemblyWriter::writeParamOperand(const Value *Operand,
2171 AttributeSet Attrs, unsigned Idx) {
2173 Out << "<null operand!>";
2178 TypePrinter.print(Operand->getType(), Out);
2179 // Print parameter attributes list
2180 if (Attrs.hasAttributes(Idx))
2181 Out << ' ' << Attrs.getAsString(Idx);
2183 // Print the operand
2184 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2187 void AssemblyWriter::printModule(const Module *M) {
2188 Machine.initialize();
2190 if (ShouldPreserveUseListOrder)
2191 UseListOrders = predictUseListOrder(M);
2193 if (!M->getModuleIdentifier().empty() &&
2194 // Don't print the ID if it will start a new line (which would
2195 // require a comment char before it).
2196 M->getModuleIdentifier().find('\n') == std::string::npos)
2197 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2199 const std::string &DL = M->getDataLayoutStr();
2201 Out << "target datalayout = \"" << DL << "\"\n";
2202 if (!M->getTargetTriple().empty())
2203 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2205 if (!M->getModuleInlineAsm().empty()) {
2208 // Split the string into lines, to make it easier to read the .ll file.
2209 StringRef Asm = M->getModuleInlineAsm();
2212 std::tie(Front, Asm) = Asm.split('\n');
2214 // We found a newline, print the portion of the asm string from the
2215 // last newline up to this newline.
2216 Out << "module asm \"";
2217 PrintEscapedString(Front, Out);
2219 } while (!Asm.empty());
2222 printTypeIdentities();
2224 // Output all comdats.
2225 if (!Comdats.empty())
2227 for (const Comdat *C : Comdats) {
2229 if (C != Comdats.back())
2233 // Output all globals.
2234 if (!M->global_empty()) Out << '\n';
2235 for (const GlobalVariable &GV : M->globals()) {
2236 printGlobal(&GV); Out << '\n';
2239 // Output all aliases.
2240 if (!M->alias_empty()) Out << "\n";
2241 for (const GlobalAlias &GA : M->aliases())
2244 // Output global use-lists.
2245 printUseLists(nullptr);
2247 // Output all of the functions.
2248 for (const Function &F : *M)
2250 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2252 // Output all attribute groups.
2253 if (!Machine.as_empty()) {
2255 writeAllAttributeGroups();
2258 // Output named metadata.
2259 if (!M->named_metadata_empty()) Out << '\n';
2261 for (const NamedMDNode &Node : M->named_metadata())
2262 printNamedMDNode(&Node);
2265 if (!Machine.mdn_empty()) {
2271 static void printMetadataIdentifier(StringRef Name,
2272 formatted_raw_ostream &Out) {
2274 Out << "<empty name> ";
2276 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2277 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2280 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2281 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2282 unsigned char C = Name[i];
2283 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2284 C == '.' || C == '_')
2287 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2292 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2294 printMetadataIdentifier(NMD->getName(), Out);
2296 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2299 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2308 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2309 formatted_raw_ostream &Out) {
2311 case GlobalValue::ExternalLinkage: break;
2312 case GlobalValue::PrivateLinkage: Out << "private "; break;
2313 case GlobalValue::InternalLinkage: Out << "internal "; break;
2314 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2315 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2316 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2317 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2318 case GlobalValue::CommonLinkage: Out << "common "; break;
2319 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2320 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2321 case GlobalValue::AvailableExternallyLinkage:
2322 Out << "available_externally ";
2327 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2328 formatted_raw_ostream &Out) {
2330 case GlobalValue::DefaultVisibility: break;
2331 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2332 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2336 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2337 formatted_raw_ostream &Out) {
2339 case GlobalValue::DefaultStorageClass: break;
2340 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2341 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2345 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2346 formatted_raw_ostream &Out) {
2348 case GlobalVariable::NotThreadLocal:
2350 case GlobalVariable::GeneralDynamicTLSModel:
2351 Out << "thread_local ";
2353 case GlobalVariable::LocalDynamicTLSModel:
2354 Out << "thread_local(localdynamic) ";
2356 case GlobalVariable::InitialExecTLSModel:
2357 Out << "thread_local(initialexec) ";
2359 case GlobalVariable::LocalExecTLSModel:
2360 Out << "thread_local(localexec) ";
2365 static void maybePrintComdat(formatted_raw_ostream &Out,
2366 const GlobalObject &GO) {
2367 const Comdat *C = GO.getComdat();
2371 if (isa<GlobalVariable>(GO))
2375 if (GO.getName() == C->getName())
2379 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2383 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2384 if (GV->isMaterializable())
2385 Out << "; Materializable\n";
2387 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2390 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2393 PrintLinkage(GV->getLinkage(), Out);
2394 PrintVisibility(GV->getVisibility(), Out);
2395 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2396 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2397 if (GV->hasUnnamedAddr())
2398 Out << "unnamed_addr ";
2400 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2401 Out << "addrspace(" << AddressSpace << ") ";
2402 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2403 Out << (GV->isConstant() ? "constant " : "global ");
2404 TypePrinter.print(GV->getType()->getElementType(), Out);
2406 if (GV->hasInitializer()) {
2408 writeOperand(GV->getInitializer(), false);
2411 if (GV->hasSection()) {
2412 Out << ", section \"";
2413 PrintEscapedString(GV->getSection(), Out);
2416 maybePrintComdat(Out, *GV);
2417 if (GV->getAlignment())
2418 Out << ", align " << GV->getAlignment();
2420 printInfoComment(*GV);
2423 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2424 if (GA->isMaterializable())
2425 Out << "; Materializable\n";
2427 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2430 PrintLinkage(GA->getLinkage(), Out);
2431 PrintVisibility(GA->getVisibility(), Out);
2432 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2433 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2434 if (GA->hasUnnamedAddr())
2435 Out << "unnamed_addr ";
2439 const Constant *Aliasee = GA->getAliasee();
2442 TypePrinter.print(GA->getType(), Out);
2443 Out << " <<NULL ALIASEE>>";
2445 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2448 printInfoComment(*GA);
2452 void AssemblyWriter::printComdat(const Comdat *C) {
2456 void AssemblyWriter::printTypeIdentities() {
2457 if (TypePrinter.NumberedTypes.empty() &&
2458 TypePrinter.NamedTypes.empty())
2463 // We know all the numbers that each type is used and we know that it is a
2464 // dense assignment. Convert the map to an index table.
2465 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2466 for (DenseMap<StructType*, unsigned>::iterator I =
2467 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2469 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2470 NumberedTypes[I->second] = I->first;
2473 // Emit all numbered types.
2474 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2475 Out << '%' << i << " = type ";
2477 // Make sure we print out at least one level of the type structure, so
2478 // that we do not get %2 = type %2
2479 TypePrinter.printStructBody(NumberedTypes[i], Out);
2483 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2484 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2487 // Make sure we print out at least one level of the type structure, so
2488 // that we do not get %FILE = type %FILE
2489 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2494 /// printFunction - Print all aspects of a function.
2496 void AssemblyWriter::printFunction(const Function *F) {
2497 // Print out the return type and name.
2500 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2502 if (F->isMaterializable())
2503 Out << "; Materializable\n";
2505 const AttributeSet &Attrs = F->getAttributes();
2506 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2507 AttributeSet AS = Attrs.getFnAttributes();
2508 std::string AttrStr;
2511 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2512 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2515 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2517 Attribute Attr = *I;
2518 if (!Attr.isStringAttribute()) {
2519 if (!AttrStr.empty()) AttrStr += ' ';
2520 AttrStr += Attr.getAsString();
2524 if (!AttrStr.empty())
2525 Out << "; Function Attrs: " << AttrStr << '\n';
2528 if (F->isDeclaration())
2533 PrintLinkage(F->getLinkage(), Out);
2534 PrintVisibility(F->getVisibility(), Out);
2535 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2537 // Print the calling convention.
2538 if (F->getCallingConv() != CallingConv::C) {
2539 PrintCallingConv(F->getCallingConv(), Out);
2543 FunctionType *FT = F->getFunctionType();
2544 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2545 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2546 TypePrinter.print(F->getReturnType(), Out);
2548 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2550 Machine.incorporateFunction(F);
2552 // Loop over the arguments, printing them...
2555 if (!F->isDeclaration()) {
2556 // If this isn't a declaration, print the argument names as well.
2557 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2559 // Insert commas as we go... the first arg doesn't get a comma
2560 if (I != F->arg_begin()) Out << ", ";
2561 printArgument(I, Attrs, Idx);
2565 // Otherwise, print the types from the function type.
2566 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2567 // Insert commas as we go... the first arg doesn't get a comma
2571 TypePrinter.print(FT->getParamType(i), Out);
2573 if (Attrs.hasAttributes(i+1))
2574 Out << ' ' << Attrs.getAsString(i+1);
2578 // Finish printing arguments...
2579 if (FT->isVarArg()) {
2580 if (FT->getNumParams()) Out << ", ";
2581 Out << "..."; // Output varargs portion of signature!
2584 if (F->hasUnnamedAddr())
2585 Out << " unnamed_addr";
2586 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2587 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2588 if (F->hasSection()) {
2589 Out << " section \"";
2590 PrintEscapedString(F->getSection(), Out);
2593 maybePrintComdat(Out, *F);
2594 if (F->getAlignment())
2595 Out << " align " << F->getAlignment();
2597 Out << " gc \"" << F->getGC() << '"';
2598 if (F->hasPrefixData()) {
2600 writeOperand(F->getPrefixData(), true);
2602 if (F->hasPrologueData()) {
2603 Out << " prologue ";
2604 writeOperand(F->getPrologueData(), true);
2606 if (F->hasPersonalityFn()) {
2607 Out << " personality ";
2608 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2611 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2612 F->getAllMetadata(MDs);
2613 printMetadataAttachments(MDs, " ");
2615 if (F->isDeclaration()) {
2619 // Output all of the function's basic blocks.
2620 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2623 // Output the function's use-lists.
2629 Machine.purgeFunction();
2632 /// printArgument - This member is called for every argument that is passed into
2633 /// the function. Simply print it out
2635 void AssemblyWriter::printArgument(const Argument *Arg,
2636 AttributeSet Attrs, unsigned Idx) {
2638 TypePrinter.print(Arg->getType(), Out);
2640 // Output parameter attributes list
2641 if (Attrs.hasAttributes(Idx))
2642 Out << ' ' << Attrs.getAsString(Idx);
2644 // Output name, if available...
2645 if (Arg->hasName()) {
2647 PrintLLVMName(Out, Arg);
2651 /// printBasicBlock - This member is called for each basic block in a method.
2653 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2654 if (BB->hasName()) { // Print out the label if it exists...
2656 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2658 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2659 Out << "\n; <label>:";
2660 int Slot = Machine.getLocalSlot(BB);
2667 if (!BB->getParent()) {
2668 Out.PadToColumn(50);
2669 Out << "; Error: Block without parent!";
2670 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2671 // Output predecessors for the block.
2672 Out.PadToColumn(50);
2674 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2677 Out << " No predecessors!";
2680 writeOperand(*PI, false);
2681 for (++PI; PI != PE; ++PI) {
2683 writeOperand(*PI, false);
2690 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2692 // Output all of the instructions in the basic block...
2693 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2694 printInstructionLine(*I);
2697 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2700 /// printInstructionLine - Print an instruction and a newline character.
2701 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2702 printInstruction(I);
2706 /// printGCRelocateComment - print comment after call to the gc.relocate
2707 /// intrinsic indicating base and derived pointer names.
2708 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2709 assert(isGCRelocate(&V));
2710 GCRelocateOperands GCOps(cast<Instruction>(&V));
2713 writeOperand(GCOps.getBasePtr(), false);
2715 writeOperand(GCOps.getDerivedPtr(), false);
2719 /// printInfoComment - Print a little comment after the instruction indicating
2720 /// which slot it occupies.
2722 void AssemblyWriter::printInfoComment(const Value &V) {
2723 if (isGCRelocate(&V))
2724 printGCRelocateComment(V);
2726 if (AnnotationWriter)
2727 AnnotationWriter->printInfoComment(V, Out);
2730 // This member is called for each Instruction in a function..
2731 void AssemblyWriter::printInstruction(const Instruction &I) {
2732 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2734 // Print out indentation for an instruction.
2737 // Print out name if it exists...
2739 PrintLLVMName(Out, &I);
2741 } else if (!I.getType()->isVoidTy()) {
2742 // Print out the def slot taken.
2743 int SlotNum = Machine.getLocalSlot(&I);
2745 Out << "<badref> = ";
2747 Out << '%' << SlotNum << " = ";
2750 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2751 if (CI->isMustTailCall())
2753 else if (CI->isTailCall())
2757 // Print out the opcode...
2758 Out << I.getOpcodeName();
2760 // If this is an atomic load or store, print out the atomic marker.
2761 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2762 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2765 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2768 // If this is a volatile operation, print out the volatile marker.
2769 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2770 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2771 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2772 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2775 // Print out optimization information.
2776 WriteOptimizationInfo(Out, &I);
2778 // Print out the compare instruction predicates
2779 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2780 Out << ' ' << getPredicateText(CI->getPredicate());
2782 // Print out the atomicrmw operation
2783 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2784 writeAtomicRMWOperation(Out, RMWI->getOperation());
2786 // Print out the type of the operands...
2787 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2789 // Special case conditional branches to swizzle the condition out to the front
2790 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2791 const BranchInst &BI(cast<BranchInst>(I));
2793 writeOperand(BI.getCondition(), true);
2795 writeOperand(BI.getSuccessor(0), true);
2797 writeOperand(BI.getSuccessor(1), true);
2799 } else if (isa<SwitchInst>(I)) {
2800 const SwitchInst& SI(cast<SwitchInst>(I));
2801 // Special case switch instruction to get formatting nice and correct.
2803 writeOperand(SI.getCondition(), true);
2805 writeOperand(SI.getDefaultDest(), true);
2807 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2810 writeOperand(i.getCaseValue(), true);
2812 writeOperand(i.getCaseSuccessor(), true);
2815 } else if (isa<IndirectBrInst>(I)) {
2816 // Special case indirectbr instruction to get formatting nice and correct.
2818 writeOperand(Operand, true);
2821 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2824 writeOperand(I.getOperand(i), true);
2827 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2829 TypePrinter.print(I.getType(), Out);
2832 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2833 if (op) Out << ", ";
2835 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2836 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2838 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2840 writeOperand(I.getOperand(0), true);
2841 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2843 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2845 writeOperand(I.getOperand(0), true); Out << ", ";
2846 writeOperand(I.getOperand(1), true);
2847 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2849 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2851 TypePrinter.print(I.getType(), Out);
2852 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2855 if (LPI->isCleanup())
2858 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2859 if (i != 0 || LPI->isCleanup()) Out << "\n";
2860 if (LPI->isCatch(i))
2865 writeOperand(LPI->getClause(i), true);
2867 } else if (isa<ReturnInst>(I) && !Operand) {
2869 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2870 // Print the calling convention being used.
2871 if (CI->getCallingConv() != CallingConv::C) {
2873 PrintCallingConv(CI->getCallingConv(), Out);
2876 Operand = CI->getCalledValue();
2877 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2878 Type *RetTy = FTy->getReturnType();
2879 const AttributeSet &PAL = CI->getAttributes();
2881 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2882 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2884 // If possible, print out the short form of the call instruction. We can
2885 // only do this if the first argument is a pointer to a nonvararg function,
2886 // and if the return type is not a pointer to a function.
2889 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2891 writeOperand(Operand, false);
2893 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2896 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2899 // Emit an ellipsis if this is a musttail call in a vararg function. This
2900 // is only to aid readability, musttail calls forward varargs by default.
2901 if (CI->isMustTailCall() && CI->getParent() &&
2902 CI->getParent()->getParent() &&
2903 CI->getParent()->getParent()->isVarArg())
2907 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2908 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2909 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2910 Operand = II->getCalledValue();
2911 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
2912 Type *RetTy = FTy->getReturnType();
2913 const AttributeSet &PAL = II->getAttributes();
2915 // Print the calling convention being used.
2916 if (II->getCallingConv() != CallingConv::C) {
2918 PrintCallingConv(II->getCallingConv(), Out);
2921 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2922 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2924 // If possible, print out the short form of the invoke instruction. We can
2925 // only do this if the first argument is a pointer to a nonvararg function,
2926 // and if the return type is not a pointer to a function.
2929 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2931 writeOperand(Operand, false);
2933 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2936 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
2940 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2941 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2944 writeOperand(II->getNormalDest(), true);
2946 writeOperand(II->getUnwindDest(), true);
2948 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
2950 if (AI->isUsedWithInAlloca())
2952 TypePrinter.print(AI->getAllocatedType(), Out);
2954 // Explicitly write the array size if the code is broken, if it's an array
2955 // allocation, or if the type is not canonical for scalar allocations. The
2956 // latter case prevents the type from mutating when round-tripping through
2958 if (!AI->getArraySize() || AI->isArrayAllocation() ||
2959 !AI->getArraySize()->getType()->isIntegerTy(32)) {
2961 writeOperand(AI->getArraySize(), true);
2963 if (AI->getAlignment()) {
2964 Out << ", align " << AI->getAlignment();
2966 } else if (isa<CastInst>(I)) {
2969 writeOperand(Operand, true); // Work with broken code
2972 TypePrinter.print(I.getType(), Out);
2973 } else if (isa<VAArgInst>(I)) {
2976 writeOperand(Operand, true); // Work with broken code
2979 TypePrinter.print(I.getType(), Out);
2980 } else if (Operand) { // Print the normal way.
2981 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
2983 TypePrinter.print(GEP->getSourceElementType(), Out);
2985 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
2987 TypePrinter.print(LI->getType(), Out);
2991 // PrintAllTypes - Instructions who have operands of all the same type
2992 // omit the type from all but the first operand. If the instruction has
2993 // different type operands (for example br), then they are all printed.
2994 bool PrintAllTypes = false;
2995 Type *TheType = Operand->getType();
2997 // Select, Store and ShuffleVector always print all types.
2998 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2999 || isa<ReturnInst>(I)) {
3000 PrintAllTypes = true;
3002 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3003 Operand = I.getOperand(i);
3004 // note that Operand shouldn't be null, but the test helps make dump()
3005 // more tolerant of malformed IR
3006 if (Operand && Operand->getType() != TheType) {
3007 PrintAllTypes = true; // We have differing types! Print them all!
3013 if (!PrintAllTypes) {
3015 TypePrinter.print(TheType, Out);
3019 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3021 writeOperand(I.getOperand(i), PrintAllTypes);
3025 // Print atomic ordering/alignment for memory operations
3026 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3028 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3029 if (LI->getAlignment())
3030 Out << ", align " << LI->getAlignment();
3031 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3033 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3034 if (SI->getAlignment())
3035 Out << ", align " << SI->getAlignment();
3036 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3037 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3038 CXI->getSynchScope());
3039 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3040 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3041 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3042 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3045 // Print Metadata info.
3046 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3047 I.getAllMetadata(InstMD);
3048 printMetadataAttachments(InstMD, ", ");
3050 // Print a nice comment.
3051 printInfoComment(I);
3054 void AssemblyWriter::printMetadataAttachments(
3055 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3056 StringRef Separator) {
3060 if (MDNames.empty())
3061 TheModule->getMDKindNames(MDNames);
3063 for (const auto &I : MDs) {
3064 unsigned Kind = I.first;
3066 if (Kind < MDNames.size()) {
3068 printMetadataIdentifier(MDNames[Kind], Out);
3070 Out << "!<unknown kind #" << Kind << ">";
3072 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3076 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3077 Out << '!' << Slot << " = ";
3078 printMDNodeBody(Node);
3082 void AssemblyWriter::writeAllMDNodes() {
3083 SmallVector<const MDNode *, 16> Nodes;
3084 Nodes.resize(Machine.mdn_size());
3085 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3087 Nodes[I->second] = cast<MDNode>(I->first);
3089 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3090 writeMDNode(i, Nodes[i]);
3094 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3095 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3098 void AssemblyWriter::writeAllAttributeGroups() {
3099 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3100 asVec.resize(Machine.as_size());
3102 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3104 asVec[I->second] = *I;
3106 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3107 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3108 Out << "attributes #" << I->second << " = { "
3109 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3112 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3113 bool IsInFunction = Machine.getFunction();
3117 Out << "uselistorder";
3118 if (const BasicBlock *BB =
3119 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3121 writeOperand(BB->getParent(), false);
3123 writeOperand(BB, false);
3126 writeOperand(Order.V, true);
3130 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3131 Out << Order.Shuffle[0];
3132 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3133 Out << ", " << Order.Shuffle[I];
3137 void AssemblyWriter::printUseLists(const Function *F) {
3139 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3144 Out << "\n; uselistorder directives\n";
3146 printUseListOrder(UseListOrders.back());
3147 UseListOrders.pop_back();
3151 //===----------------------------------------------------------------------===//
3152 // External Interface declarations
3153 //===----------------------------------------------------------------------===//
3155 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
3156 SlotTracker SlotTable(this->getParent());
3157 formatted_raw_ostream OS(ROS);
3158 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW);
3159 W.printFunction(this);
3162 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3163 bool ShouldPreserveUseListOrder) const {
3164 SlotTracker SlotTable(this);
3165 formatted_raw_ostream OS(ROS);
3166 AssemblyWriter W(OS, SlotTable, this, AAW, ShouldPreserveUseListOrder);
3167 W.printModule(this);
3170 void NamedMDNode::print(raw_ostream &ROS) const {
3171 SlotTracker SlotTable(getParent());
3172 formatted_raw_ostream OS(ROS);
3173 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
3174 W.printNamedMDNode(this);
3177 void Comdat::print(raw_ostream &ROS) const {
3178 PrintLLVMName(ROS, getName(), ComdatPrefix);
3179 ROS << " = comdat ";
3181 switch (getSelectionKind()) {
3185 case Comdat::ExactMatch:
3186 ROS << "exactmatch";
3188 case Comdat::Largest:
3191 case Comdat::NoDuplicates:
3192 ROS << "noduplicates";
3194 case Comdat::SameSize:
3202 void Type::print(raw_ostream &OS) const {
3204 TP.print(const_cast<Type*>(this), OS);
3206 // If the type is a named struct type, print the body as well.
3207 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3208 if (!STy->isLiteral()) {
3210 TP.printStructBody(STy, OS);
3214 static bool isReferencingMDNode(const Instruction &I) {
3215 if (const auto *CI = dyn_cast<CallInst>(&I))
3216 if (Function *F = CI->getCalledFunction())
3217 if (F->isIntrinsic())
3218 for (auto &Op : I.operands())
3219 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3220 if (isa<MDNode>(V->getMetadata()))
3225 void Value::print(raw_ostream &ROS) const {
3226 bool ShouldInitializeAllMetadata = false;
3227 if (auto *I = dyn_cast<Instruction>(this))
3228 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3229 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3230 ShouldInitializeAllMetadata = true;
3232 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3236 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST) const {
3237 formatted_raw_ostream OS(ROS);
3238 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3239 SlotTracker &SlotTable =
3240 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3241 auto incorporateFunction = [&](const Function *F) {
3243 MST.incorporateFunction(*F);
3246 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3247 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3248 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
3249 W.printInstruction(*I);
3250 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3251 incorporateFunction(BB->getParent());
3252 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
3253 W.printBasicBlock(BB);
3254 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3255 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
3256 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3258 else if (const Function *F = dyn_cast<Function>(GV))
3261 W.printAlias(cast<GlobalAlias>(GV));
3262 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3263 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3264 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3265 TypePrinting TypePrinter;
3266 TypePrinter.print(C->getType(), OS);
3268 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3269 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3270 this->printAsOperand(OS, /* PrintType */ true, MST);
3272 llvm_unreachable("Unknown value to print out!");
3276 /// Print without a type, skipping the TypePrinting object.
3278 /// \return \c true iff printing was succesful.
3279 static bool printWithoutType(const Value &V, raw_ostream &O,
3280 SlotTracker *Machine, const Module *M) {
3281 if (V.hasName() || isa<GlobalValue>(V) ||
3282 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3283 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3289 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3290 ModuleSlotTracker &MST) {
3291 TypePrinting TypePrinter;
3292 if (const Module *M = MST.getModule())
3293 TypePrinter.incorporateTypes(*M);
3295 TypePrinter.print(V.getType(), O);
3299 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3303 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3304 const Module *M) const {
3306 M = getModuleFromVal(this);
3309 if (printWithoutType(*this, O, nullptr, M))
3312 SlotTracker Machine(
3313 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3314 ModuleSlotTracker MST(Machine, M);
3315 printAsOperandImpl(*this, O, PrintType, MST);
3318 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3319 ModuleSlotTracker &MST) const {
3321 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3324 printAsOperandImpl(*this, O, PrintType, MST);
3327 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3328 ModuleSlotTracker &MST, const Module *M,
3329 bool OnlyAsOperand) {
3330 formatted_raw_ostream OS(ROS);
3332 TypePrinting TypePrinter;
3334 TypePrinter.incorporateTypes(*M);
3336 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3337 /* FromValue */ true);
3339 auto *N = dyn_cast<MDNode>(&MD);
3340 if (OnlyAsOperand || !N)
3344 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3347 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3348 ModuleSlotTracker MST(M, isa<MDNode>(this));
3349 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3352 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3353 const Module *M) const {
3354 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3357 void Metadata::print(raw_ostream &OS, const Module *M) const {
3358 ModuleSlotTracker MST(M, isa<MDNode>(this));
3359 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3362 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3363 const Module *M) const {
3364 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3367 // Value::dump - allow easy printing of Values from the debugger.
3369 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
3371 // Type::dump - allow easy printing of Types from the debugger.
3373 void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
3375 // Module::dump() - Allow printing of Modules from the debugger.
3377 void Module::dump() const { print(dbgs(), nullptr); }
3379 // \brief Allow printing of Comdats from the debugger.
3381 void Comdat::dump() const { print(dbgs()); }
3383 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3385 void NamedMDNode::dump() const { print(dbgs()); }
3388 void Metadata::dump() const { dump(nullptr); }
3391 void Metadata::dump(const Module *M) const {