1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/IR/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/TypeFinder.h"
37 #include "llvm/IR/UseListOrder.h"
38 #include "llvm/IR/ValueSymbolTable.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
50 // Make virtual table appear in this compilation unit.
51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
59 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
61 unsigned size() const { return IDs.size(); }
62 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
63 std::pair<unsigned, bool> lookup(const Value *V) const {
66 void index(const Value *V) {
67 // Explicitly sequence get-size and insert-value operations to avoid UB.
68 unsigned ID = IDs.size() + 1;
74 static void orderValue(const Value *V, OrderMap &OM) {
75 if (OM.lookup(V).first)
78 if (const Constant *C = dyn_cast<Constant>(V))
79 if (C->getNumOperands() && !isa<GlobalValue>(C))
80 for (const Value *Op : C->operands())
81 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
84 // Note: we cannot cache this lookup above, since inserting into the map
85 // changes the map's size, and thus affects the other IDs.
89 static OrderMap orderModule(const Module *M) {
90 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
91 // and ValueEnumerator::incorporateFunction().
94 for (const GlobalVariable &G : M->globals()) {
95 if (G.hasInitializer())
96 if (!isa<GlobalValue>(G.getInitializer()))
97 orderValue(G.getInitializer(), OM);
100 for (const GlobalAlias &A : M->aliases()) {
101 if (!isa<GlobalValue>(A.getAliasee()))
102 orderValue(A.getAliasee(), OM);
105 for (const Function &F : *M) {
106 if (F.hasPrefixData())
107 if (!isa<GlobalValue>(F.getPrefixData()))
108 orderValue(F.getPrefixData(), OM);
110 if (F.hasPrologueData())
111 if (!isa<GlobalValue>(F.getPrologueData()))
112 orderValue(F.getPrologueData(), OM);
114 if (F.hasPersonalityFn())
115 if (!isa<GlobalValue>(F.getPersonalityFn()))
116 orderValue(F.getPersonalityFn(), OM);
120 if (F.isDeclaration())
123 for (const Argument &A : F.args())
125 for (const BasicBlock &BB : F) {
127 for (const Instruction &I : BB) {
128 for (const Value *Op : I.operands())
129 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
139 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
140 unsigned ID, const OrderMap &OM,
141 UseListOrderStack &Stack) {
142 // Predict use-list order for this one.
143 typedef std::pair<const Use *, unsigned> Entry;
144 SmallVector<Entry, 64> List;
145 for (const Use &U : V->uses())
146 // Check if this user will be serialized.
147 if (OM.lookup(U.getUser()).first)
148 List.push_back(std::make_pair(&U, List.size()));
151 // We may have lost some users.
155 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
156 if (auto *BA = dyn_cast<BlockAddress>(V))
157 ID = OM.lookup(BA->getBasicBlock()).first;
158 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
159 const Use *LU = L.first;
160 const Use *RU = R.first;
164 auto LID = OM.lookup(LU->getUser()).first;
165 auto RID = OM.lookup(RU->getUser()).first;
167 // If ID is 4, then expect: 7 6 5 1 2 3.
181 // LID and RID are equal, so we have different operands of the same user.
182 // Assume operands are added in order for all instructions.
185 return LU->getOperandNo() < RU->getOperandNo();
186 return LU->getOperandNo() > RU->getOperandNo();
190 List.begin(), List.end(),
191 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
192 // Order is already correct.
195 // Store the shuffle.
196 Stack.emplace_back(V, F, List.size());
197 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
198 for (size_t I = 0, E = List.size(); I != E; ++I)
199 Stack.back().Shuffle[I] = List[I].second;
202 static void predictValueUseListOrder(const Value *V, const Function *F,
203 OrderMap &OM, UseListOrderStack &Stack) {
204 auto &IDPair = OM[V];
205 assert(IDPair.first && "Unmapped value");
207 // Already predicted.
210 // Do the actual prediction.
211 IDPair.second = true;
212 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
213 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
215 // Recursive descent into constants.
216 if (const Constant *C = dyn_cast<Constant>(V))
217 if (C->getNumOperands()) // Visit GlobalValues.
218 for (const Value *Op : C->operands())
219 if (isa<Constant>(Op)) // Visit GlobalValues.
220 predictValueUseListOrder(Op, F, OM, Stack);
223 static UseListOrderStack predictUseListOrder(const Module *M) {
224 OrderMap OM = orderModule(M);
226 // Use-list orders need to be serialized after all the users have been added
227 // to a value, or else the shuffles will be incomplete. Store them per
228 // function in a stack.
230 // Aside from function order, the order of values doesn't matter much here.
231 UseListOrderStack Stack;
233 // We want to visit the functions backward now so we can list function-local
234 // constants in the last Function they're used in. Module-level constants
235 // have already been visited above.
236 for (const Function &F : make_range(M->rbegin(), M->rend())) {
237 if (F.isDeclaration())
239 for (const BasicBlock &BB : F)
240 predictValueUseListOrder(&BB, &F, OM, Stack);
241 for (const Argument &A : F.args())
242 predictValueUseListOrder(&A, &F, OM, Stack);
243 for (const BasicBlock &BB : F)
244 for (const Instruction &I : BB)
245 for (const Value *Op : I.operands())
246 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
247 predictValueUseListOrder(Op, &F, OM, Stack);
248 for (const BasicBlock &BB : F)
249 for (const Instruction &I : BB)
250 predictValueUseListOrder(&I, &F, OM, Stack);
253 // Visit globals last.
254 for (const GlobalVariable &G : M->globals())
255 predictValueUseListOrder(&G, nullptr, OM, Stack);
256 for (const Function &F : *M)
257 predictValueUseListOrder(&F, nullptr, OM, Stack);
258 for (const GlobalAlias &A : M->aliases())
259 predictValueUseListOrder(&A, nullptr, OM, Stack);
260 for (const GlobalVariable &G : M->globals())
261 if (G.hasInitializer())
262 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
263 for (const GlobalAlias &A : M->aliases())
264 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
265 for (const Function &F : *M)
266 if (F.hasPrefixData())
267 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
272 static const Module *getModuleFromVal(const Value *V) {
273 if (const Argument *MA = dyn_cast<Argument>(V))
274 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
276 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
277 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
279 if (const Instruction *I = dyn_cast<Instruction>(V)) {
280 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
281 return M ? M->getParent() : nullptr;
284 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
285 return GV->getParent();
287 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
288 for (const User *U : MAV->users())
289 if (isa<Instruction>(U))
290 if (const Module *M = getModuleFromVal(U))
298 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
300 default: Out << "cc" << cc; break;
301 case CallingConv::Fast: Out << "fastcc"; break;
302 case CallingConv::Cold: Out << "coldcc"; break;
303 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
304 case CallingConv::AnyReg: Out << "anyregcc"; break;
305 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
306 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
307 case CallingConv::GHC: Out << "ghccc"; break;
308 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
309 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
310 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
311 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
312 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
313 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
314 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
315 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
316 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
317 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
318 case CallingConv::PTX_Device: Out << "ptx_device"; break;
319 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
320 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
321 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
322 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
323 case CallingConv::HHVM: Out << "hhvmcc"; break;
324 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
328 // PrintEscapedString - Print each character of the specified string, escaping
329 // it if it is not printable or if it is an escape char.
330 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
331 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
332 unsigned char C = Name[i];
333 if (isprint(C) && C != '\\' && C != '"')
336 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
348 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
349 assert(!Name.empty() && "Cannot get empty name!");
351 // Scan the name to see if it needs quotes first.
352 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
354 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
355 // By making this unsigned, the value passed in to isalnum will always be
356 // in the range 0-255. This is important when building with MSVC because
357 // its implementation will assert. This situation can arise when dealing
358 // with UTF-8 multibyte characters.
359 unsigned char C = Name[i];
360 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
368 // If we didn't need any quotes, just write out the name in one blast.
374 // Okay, we need quotes. Output the quotes and escape any scary characters as
377 PrintEscapedString(Name, OS);
381 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
382 /// (if the string only contains simple characters) or is surrounded with ""'s
383 /// (if it has special chars in it). Print it out.
384 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
400 printLLVMNameWithoutPrefix(OS, Name);
403 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
404 /// (if the string only contains simple characters) or is surrounded with ""'s
405 /// (if it has special chars in it). Print it out.
406 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
407 PrintLLVMName(OS, V->getName(),
408 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
414 TypePrinting(const TypePrinting &) = delete;
415 void operator=(const TypePrinting&) = delete;
418 /// NamedTypes - The named types that are used by the current module.
419 TypeFinder NamedTypes;
421 /// NumberedTypes - The numbered types, along with their value.
422 DenseMap<StructType*, unsigned> NumberedTypes;
424 TypePrinting() = default;
426 void incorporateTypes(const Module &M);
428 void print(Type *Ty, raw_ostream &OS);
430 void printStructBody(StructType *Ty, raw_ostream &OS);
434 void TypePrinting::incorporateTypes(const Module &M) {
435 NamedTypes.run(M, false);
437 // The list of struct types we got back includes all the struct types, split
438 // the unnamed ones out to a numbering and remove the anonymous structs.
439 unsigned NextNumber = 0;
441 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
442 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
443 StructType *STy = *I;
445 // Ignore anonymous types.
446 if (STy->isLiteral())
449 if (STy->getName().empty())
450 NumberedTypes[STy] = NextNumber++;
455 NamedTypes.erase(NextToUse, NamedTypes.end());
459 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
460 /// use of type names or up references to shorten the type name where possible.
461 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
462 switch (Ty->getTypeID()) {
463 case Type::VoidTyID: OS << "void"; return;
464 case Type::HalfTyID: OS << "half"; return;
465 case Type::FloatTyID: OS << "float"; return;
466 case Type::DoubleTyID: OS << "double"; return;
467 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
468 case Type::FP128TyID: OS << "fp128"; return;
469 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
470 case Type::LabelTyID: OS << "label"; return;
471 case Type::MetadataTyID: OS << "metadata"; return;
472 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
473 case Type::TokenTyID: OS << "token"; return;
474 case Type::IntegerTyID:
475 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
478 case Type::FunctionTyID: {
479 FunctionType *FTy = cast<FunctionType>(Ty);
480 print(FTy->getReturnType(), OS);
482 for (FunctionType::param_iterator I = FTy->param_begin(),
483 E = FTy->param_end(); I != E; ++I) {
484 if (I != FTy->param_begin())
488 if (FTy->isVarArg()) {
489 if (FTy->getNumParams()) OS << ", ";
495 case Type::StructTyID: {
496 StructType *STy = cast<StructType>(Ty);
498 if (STy->isLiteral())
499 return printStructBody(STy, OS);
501 if (!STy->getName().empty())
502 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
504 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
505 if (I != NumberedTypes.end())
506 OS << '%' << I->second;
507 else // Not enumerated, print the hex address.
508 OS << "%\"type " << STy << '\"';
511 case Type::PointerTyID: {
512 PointerType *PTy = cast<PointerType>(Ty);
513 print(PTy->getElementType(), OS);
514 if (unsigned AddressSpace = PTy->getAddressSpace())
515 OS << " addrspace(" << AddressSpace << ')';
519 case Type::ArrayTyID: {
520 ArrayType *ATy = cast<ArrayType>(Ty);
521 OS << '[' << ATy->getNumElements() << " x ";
522 print(ATy->getElementType(), OS);
526 case Type::VectorTyID: {
527 VectorType *PTy = cast<VectorType>(Ty);
528 OS << "<" << PTy->getNumElements() << " x ";
529 print(PTy->getElementType(), OS);
534 llvm_unreachable("Invalid TypeID");
537 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
538 if (STy->isOpaque()) {
546 if (STy->getNumElements() == 0) {
549 StructType::element_iterator I = STy->element_begin();
552 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
564 //===----------------------------------------------------------------------===//
565 // SlotTracker Class: Enumerate slot numbers for unnamed values
566 //===----------------------------------------------------------------------===//
567 /// This class provides computation of slot numbers for LLVM Assembly writing.
571 /// ValueMap - A mapping of Values to slot numbers.
572 typedef DenseMap<const Value*, unsigned> ValueMap;
575 /// TheModule - The module for which we are holding slot numbers.
576 const Module* TheModule;
578 /// TheFunction - The function for which we are holding slot numbers.
579 const Function* TheFunction;
580 bool FunctionProcessed;
581 bool ShouldInitializeAllMetadata;
583 /// mMap - The slot map for the module level data.
587 /// fMap - The slot map for the function level data.
591 /// mdnMap - Map for MDNodes.
592 DenseMap<const MDNode*, unsigned> mdnMap;
595 /// asMap - The slot map for attribute sets.
596 DenseMap<AttributeSet, unsigned> asMap;
599 /// Construct from a module.
601 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
602 /// functions, giving correct numbering for metadata referenced only from
603 /// within a function (even if no functions have been initialized).
604 explicit SlotTracker(const Module *M,
605 bool ShouldInitializeAllMetadata = false);
606 /// Construct from a function, starting out in incorp state.
608 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
609 /// functions, giving correct numbering for metadata referenced only from
610 /// within a function (even if no functions have been initialized).
611 explicit SlotTracker(const Function *F,
612 bool ShouldInitializeAllMetadata = false);
614 /// Return the slot number of the specified value in it's type
615 /// plane. If something is not in the SlotTracker, return -1.
616 int getLocalSlot(const Value *V);
617 int getGlobalSlot(const GlobalValue *V);
618 int getMetadataSlot(const MDNode *N);
619 int getAttributeGroupSlot(AttributeSet AS);
621 /// If you'd like to deal with a function instead of just a module, use
622 /// this method to get its data into the SlotTracker.
623 void incorporateFunction(const Function *F) {
625 FunctionProcessed = false;
628 const Function *getFunction() const { return TheFunction; }
630 /// After calling incorporateFunction, use this method to remove the
631 /// most recently incorporated function from the SlotTracker. This
632 /// will reset the state of the machine back to just the module contents.
633 void purgeFunction();
635 /// MDNode map iterators.
636 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
637 mdn_iterator mdn_begin() { return mdnMap.begin(); }
638 mdn_iterator mdn_end() { return mdnMap.end(); }
639 unsigned mdn_size() const { return mdnMap.size(); }
640 bool mdn_empty() const { return mdnMap.empty(); }
642 /// AttributeSet map iterators.
643 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
644 as_iterator as_begin() { return asMap.begin(); }
645 as_iterator as_end() { return asMap.end(); }
646 unsigned as_size() const { return asMap.size(); }
647 bool as_empty() const { return asMap.empty(); }
649 /// This function does the actual initialization.
650 inline void initialize();
652 // Implementation Details
654 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
655 void CreateModuleSlot(const GlobalValue *V);
657 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
658 void CreateMetadataSlot(const MDNode *N);
660 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
661 void CreateFunctionSlot(const Value *V);
663 /// \brief Insert the specified AttributeSet into the slot table.
664 void CreateAttributeSetSlot(AttributeSet AS);
666 /// Add all of the module level global variables (and their initializers)
667 /// and function declarations, but not the contents of those functions.
668 void processModule();
670 /// Add all of the functions arguments, basic blocks, and instructions.
671 void processFunction();
673 /// Add all of the metadata from a function.
674 void processFunctionMetadata(const Function &F);
676 /// Add all of the metadata from an instruction.
677 void processInstructionMetadata(const Instruction &I);
679 SlotTracker(const SlotTracker &) = delete;
680 void operator=(const SlotTracker &) = delete;
684 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
686 : M(M), F(F), Machine(&Machine) {}
688 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
689 bool ShouldInitializeAllMetadata)
690 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
692 M(M), Machine(MachineStorage.get()) {}
694 ModuleSlotTracker::~ModuleSlotTracker() {}
696 void ModuleSlotTracker::incorporateFunction(const Function &F) {
700 // Nothing to do if this is the right function already.
704 Machine->purgeFunction();
705 Machine->incorporateFunction(&F);
709 int ModuleSlotTracker::getLocalSlot(const Value *V) {
710 assert(F && "No function incorporated");
711 return Machine->getLocalSlot(V);
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 // Process function metadata if it wasn't hit at the module-level.
814 if (!ShouldInitializeAllMetadata)
815 processFunctionMetadata(*TheFunction);
817 // Add all the function arguments with no names.
818 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
819 AE = TheFunction->arg_end(); AI != AE; ++AI)
821 CreateFunctionSlot(&*AI);
823 ST_DEBUG("Inserting Instructions:\n");
825 // Add all of the basic blocks and instructions with no names.
826 for (auto &BB : *TheFunction) {
828 CreateFunctionSlot(&BB);
831 if (!I.getType()->isVoidTy() && !I.hasName())
832 CreateFunctionSlot(&I);
834 // We allow direct calls to any llvm.foo function here, because the
835 // target may not be linked into the optimizer.
836 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
837 // Add all the call attributes to the table.
838 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
839 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
840 CreateAttributeSetSlot(Attrs);
841 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
842 // Add all the call attributes to the table.
843 AttributeSet Attrs = II->getAttributes().getFnAttributes();
844 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
845 CreateAttributeSetSlot(Attrs);
850 FunctionProcessed = true;
852 ST_DEBUG("end processFunction!\n");
855 void SlotTracker::processFunctionMetadata(const Function &F) {
856 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
857 F.getAllMetadata(MDs);
859 CreateMetadataSlot(MD.second);
863 processInstructionMetadata(I);
867 void SlotTracker::processInstructionMetadata(const Instruction &I) {
868 // Process metadata used directly by intrinsics.
869 if (const CallInst *CI = dyn_cast<CallInst>(&I))
870 if (Function *F = CI->getCalledFunction())
871 if (F->isIntrinsic())
872 for (auto &Op : I.operands())
873 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
874 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
875 CreateMetadataSlot(N);
877 // Process metadata attached to this instruction.
878 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
879 I.getAllMetadata(MDs);
881 CreateMetadataSlot(MD.second);
884 /// Clean up after incorporating a function. This is the only way to get out of
885 /// the function incorporation state that affects get*Slot/Create*Slot. Function
886 /// incorporation state is indicated by TheFunction != 0.
887 void SlotTracker::purgeFunction() {
888 ST_DEBUG("begin purgeFunction!\n");
889 fMap.clear(); // Simply discard the function level map
890 TheFunction = nullptr;
891 FunctionProcessed = false;
892 ST_DEBUG("end purgeFunction!\n");
895 /// getGlobalSlot - Get the slot number of a global value.
896 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
897 // Check for uninitialized state and do lazy initialization.
900 // Find the value in the module map
901 ValueMap::iterator MI = mMap.find(V);
902 return MI == mMap.end() ? -1 : (int)MI->second;
905 /// getMetadataSlot - Get the slot number of a MDNode.
906 int SlotTracker::getMetadataSlot(const MDNode *N) {
907 // Check for uninitialized state and do lazy initialization.
910 // Find the MDNode in the module map
911 mdn_iterator MI = mdnMap.find(N);
912 return MI == mdnMap.end() ? -1 : (int)MI->second;
916 /// getLocalSlot - Get the slot number for a value that is local to a function.
917 int SlotTracker::getLocalSlot(const Value *V) {
918 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
920 // Check for uninitialized state and do lazy initialization.
923 ValueMap::iterator FI = fMap.find(V);
924 return FI == fMap.end() ? -1 : (int)FI->second;
927 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
928 // Check for uninitialized state and do lazy initialization.
931 // Find the AttributeSet in the module map.
932 as_iterator AI = asMap.find(AS);
933 return AI == asMap.end() ? -1 : (int)AI->second;
936 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
937 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
938 assert(V && "Can't insert a null Value into SlotTracker!");
939 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
940 assert(!V->hasName() && "Doesn't need a slot!");
942 unsigned DestSlot = mNext++;
945 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
947 // G = Global, F = Function, A = Alias, o = other
948 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
949 (isa<Function>(V) ? 'F' :
950 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
953 /// CreateSlot - Create a new slot for the specified value if it has no name.
954 void SlotTracker::CreateFunctionSlot(const Value *V) {
955 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
957 unsigned DestSlot = fNext++;
960 // G = Global, F = Function, o = other
961 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
962 DestSlot << " [o]\n");
965 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
966 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
967 assert(N && "Can't insert a null Value into SlotTracker!");
969 unsigned DestSlot = mdnNext;
970 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
974 // Recursively add any MDNodes referenced by operands.
975 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
976 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
977 CreateMetadataSlot(Op);
980 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
981 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
982 "Doesn't need a slot!");
984 as_iterator I = asMap.find(AS);
985 if (I != asMap.end())
988 unsigned DestSlot = asNext++;
989 asMap[AS] = DestSlot;
992 //===----------------------------------------------------------------------===//
993 // AsmWriter Implementation
994 //===----------------------------------------------------------------------===//
996 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
997 TypePrinting *TypePrinter,
998 SlotTracker *Machine,
999 const Module *Context);
1001 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1002 TypePrinting *TypePrinter,
1003 SlotTracker *Machine, const Module *Context,
1004 bool FromValue = false);
1006 static const char *getPredicateText(unsigned predicate) {
1007 const char * pred = "unknown";
1008 switch (predicate) {
1009 case FCmpInst::FCMP_FALSE: pred = "false"; break;
1010 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
1011 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
1012 case FCmpInst::FCMP_OGE: pred = "oge"; break;
1013 case FCmpInst::FCMP_OLT: pred = "olt"; break;
1014 case FCmpInst::FCMP_OLE: pred = "ole"; break;
1015 case FCmpInst::FCMP_ONE: pred = "one"; break;
1016 case FCmpInst::FCMP_ORD: pred = "ord"; break;
1017 case FCmpInst::FCMP_UNO: pred = "uno"; break;
1018 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
1019 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
1020 case FCmpInst::FCMP_UGE: pred = "uge"; break;
1021 case FCmpInst::FCMP_ULT: pred = "ult"; break;
1022 case FCmpInst::FCMP_ULE: pred = "ule"; break;
1023 case FCmpInst::FCMP_UNE: pred = "une"; break;
1024 case FCmpInst::FCMP_TRUE: pred = "true"; break;
1025 case ICmpInst::ICMP_EQ: pred = "eq"; break;
1026 case ICmpInst::ICMP_NE: pred = "ne"; break;
1027 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
1028 case ICmpInst::ICMP_SGE: pred = "sge"; break;
1029 case ICmpInst::ICMP_SLT: pred = "slt"; break;
1030 case ICmpInst::ICMP_SLE: pred = "sle"; break;
1031 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
1032 case ICmpInst::ICMP_UGE: pred = "uge"; break;
1033 case ICmpInst::ICMP_ULT: pred = "ult"; break;
1034 case ICmpInst::ICMP_ULE: pred = "ule"; break;
1039 static void writeAtomicRMWOperation(raw_ostream &Out,
1040 AtomicRMWInst::BinOp Op) {
1042 default: Out << " <unknown operation " << Op << ">"; break;
1043 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1044 case AtomicRMWInst::Add: Out << " add"; break;
1045 case AtomicRMWInst::Sub: Out << " sub"; break;
1046 case AtomicRMWInst::And: Out << " and"; break;
1047 case AtomicRMWInst::Nand: Out << " nand"; break;
1048 case AtomicRMWInst::Or: Out << " or"; break;
1049 case AtomicRMWInst::Xor: Out << " xor"; break;
1050 case AtomicRMWInst::Max: Out << " max"; break;
1051 case AtomicRMWInst::Min: Out << " min"; break;
1052 case AtomicRMWInst::UMax: Out << " umax"; break;
1053 case AtomicRMWInst::UMin: Out << " umin"; break;
1057 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1058 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1059 // Unsafe algebra implies all the others, no need to write them all out
1060 if (FPO->hasUnsafeAlgebra())
1063 if (FPO->hasNoNaNs())
1065 if (FPO->hasNoInfs())
1067 if (FPO->hasNoSignedZeros())
1069 if (FPO->hasAllowReciprocal())
1074 if (const OverflowingBinaryOperator *OBO =
1075 dyn_cast<OverflowingBinaryOperator>(U)) {
1076 if (OBO->hasNoUnsignedWrap())
1078 if (OBO->hasNoSignedWrap())
1080 } else if (const PossiblyExactOperator *Div =
1081 dyn_cast<PossiblyExactOperator>(U)) {
1084 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1085 if (GEP->isInBounds())
1090 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1091 TypePrinting &TypePrinter,
1092 SlotTracker *Machine,
1093 const Module *Context) {
1094 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1095 if (CI->getType()->isIntegerTy(1)) {
1096 Out << (CI->getZExtValue() ? "true" : "false");
1099 Out << CI->getValue();
1103 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1104 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1105 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1106 // We would like to output the FP constant value in exponential notation,
1107 // but we cannot do this if doing so will lose precision. Check here to
1108 // make sure that we only output it in exponential format if we can parse
1109 // the value back and get the same value.
1112 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1113 bool isInf = CFP->getValueAPF().isInfinity();
1114 bool isNaN = CFP->getValueAPF().isNaN();
1115 if (!isInf && !isNaN) {
1116 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1117 CFP->getValueAPF().convertToFloat();
1118 SmallString<128> StrVal;
1119 raw_svector_ostream(StrVal) << Val;
1121 // Check to make sure that the stringized number is not some string like
1122 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1123 // that the string matches the "[-+]?[0-9]" regex.
1125 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1126 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1127 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1128 // Reparse stringized version!
1129 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1135 // Otherwise we could not reparse it to exactly the same value, so we must
1136 // output the string in hexadecimal format! Note that loading and storing
1137 // floating point types changes the bits of NaNs on some hosts, notably
1138 // x86, so we must not use these types.
1139 static_assert(sizeof(double) == sizeof(uint64_t),
1140 "assuming that double is 64 bits!");
1141 APFloat apf = CFP->getValueAPF();
1142 // Floats are represented in ASCII IR as double, convert.
1144 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1146 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1150 // Either half, or some form of long double.
1151 // These appear as a magic letter identifying the type, then a
1152 // fixed number of hex digits.
1154 APInt API = CFP->getValueAPF().bitcastToAPInt();
1155 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1157 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1159 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1162 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1164 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1166 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1168 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1170 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1172 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1174 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1176 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1179 llvm_unreachable("Unsupported floating point type");
1183 if (isa<ConstantAggregateZero>(CV)) {
1184 Out << "zeroinitializer";
1188 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1189 Out << "blockaddress(";
1190 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1193 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1199 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1200 Type *ETy = CA->getType()->getElementType();
1202 TypePrinter.print(ETy, Out);
1204 WriteAsOperandInternal(Out, CA->getOperand(0),
1205 &TypePrinter, Machine,
1207 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1209 TypePrinter.print(ETy, Out);
1211 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1218 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1219 // As a special case, print the array as a string if it is an array of
1220 // i8 with ConstantInt values.
1221 if (CA->isString()) {
1223 PrintEscapedString(CA->getAsString(), Out);
1228 Type *ETy = CA->getType()->getElementType();
1230 TypePrinter.print(ETy, Out);
1232 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1233 &TypePrinter, Machine,
1235 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1237 TypePrinter.print(ETy, Out);
1239 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1247 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1248 if (CS->getType()->isPacked())
1251 unsigned N = CS->getNumOperands();
1254 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1257 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1260 for (unsigned i = 1; i < N; i++) {
1262 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1265 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1272 if (CS->getType()->isPacked())
1277 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1278 Type *ETy = CV->getType()->getVectorElementType();
1280 TypePrinter.print(ETy, Out);
1282 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1284 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1286 TypePrinter.print(ETy, Out);
1288 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1295 if (isa<ConstantPointerNull>(CV)) {
1300 if (isa<ConstantTokenNone>(CV)) {
1305 if (isa<UndefValue>(CV)) {
1310 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1311 Out << CE->getOpcodeName();
1312 WriteOptimizationInfo(Out, CE);
1313 if (CE->isCompare())
1314 Out << ' ' << getPredicateText(CE->getPredicate());
1317 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1318 TypePrinter.print(GEP->getSourceElementType(), Out);
1322 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1323 TypePrinter.print((*OI)->getType(), Out);
1325 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1326 if (OI+1 != CE->op_end())
1330 if (CE->hasIndices()) {
1331 ArrayRef<unsigned> Indices = CE->getIndices();
1332 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1333 Out << ", " << Indices[i];
1338 TypePrinter.print(CE->getType(), Out);
1345 Out << "<placeholder or erroneous Constant>";
1348 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1349 TypePrinting *TypePrinter, SlotTracker *Machine,
1350 const Module *Context) {
1352 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1353 const Metadata *MD = Node->getOperand(mi);
1356 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1357 Value *V = MDV->getValue();
1358 TypePrinter->print(V->getType(), Out);
1360 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1362 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1372 struct FieldSeparator {
1375 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1377 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1382 return OS << FS.Sep;
1384 struct MDFieldPrinter {
1387 TypePrinting *TypePrinter;
1388 SlotTracker *Machine;
1389 const Module *Context;
1391 explicit MDFieldPrinter(raw_ostream &Out)
1392 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1393 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1394 SlotTracker *Machine, const Module *Context)
1395 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1397 void printTag(const DINode *N);
1398 void printString(StringRef Name, StringRef Value,
1399 bool ShouldSkipEmpty = true);
1400 void printMetadata(StringRef Name, const Metadata *MD,
1401 bool ShouldSkipNull = true);
1402 template <class IntTy>
1403 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1404 void printBool(StringRef Name, bool Value);
1405 void printDIFlags(StringRef Name, unsigned Flags);
1406 template <class IntTy, class Stringifier>
1407 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1408 bool ShouldSkipZero = true);
1412 void MDFieldPrinter::printTag(const DINode *N) {
1413 Out << FS << "tag: ";
1414 if (const char *Tag = dwarf::TagString(N->getTag()))
1420 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1421 bool ShouldSkipEmpty) {
1422 if (ShouldSkipEmpty && Value.empty())
1425 Out << FS << Name << ": \"";
1426 PrintEscapedString(Value, Out);
1430 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1431 TypePrinting *TypePrinter,
1432 SlotTracker *Machine,
1433 const Module *Context) {
1438 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1441 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1442 bool ShouldSkipNull) {
1443 if (ShouldSkipNull && !MD)
1446 Out << FS << Name << ": ";
1447 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1450 template <class IntTy>
1451 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1452 if (ShouldSkipZero && !Int)
1455 Out << FS << Name << ": " << Int;
1458 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1459 Out << FS << Name << ": " << (Value ? "true" : "false");
1462 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1466 Out << FS << Name << ": ";
1468 SmallVector<unsigned, 8> SplitFlags;
1469 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1471 FieldSeparator FlagsFS(" | ");
1472 for (unsigned F : SplitFlags) {
1473 const char *StringF = DINode::getFlagString(F);
1474 assert(StringF && "Expected valid flag");
1475 Out << FlagsFS << StringF;
1477 if (Extra || SplitFlags.empty())
1478 Out << FlagsFS << Extra;
1481 template <class IntTy, class Stringifier>
1482 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1483 Stringifier toString, bool ShouldSkipZero) {
1487 Out << FS << Name << ": ";
1488 if (const char *S = toString(Value))
1494 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1495 TypePrinting *TypePrinter, SlotTracker *Machine,
1496 const Module *Context) {
1497 Out << "!GenericDINode(";
1498 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1499 Printer.printTag(N);
1500 Printer.printString("header", N->getHeader());
1501 if (N->getNumDwarfOperands()) {
1502 Out << Printer.FS << "operands: {";
1504 for (auto &I : N->dwarf_operands()) {
1506 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1513 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1514 TypePrinting *TypePrinter, SlotTracker *Machine,
1515 const Module *Context) {
1516 Out << "!DILocation(";
1517 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1518 // Always output the line, since 0 is a relevant and important value for it.
1519 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1520 Printer.printInt("column", DL->getColumn());
1521 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1522 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1526 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1527 TypePrinting *, SlotTracker *, const Module *) {
1528 Out << "!DISubrange(";
1529 MDFieldPrinter Printer(Out);
1530 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1531 Printer.printInt("lowerBound", N->getLowerBound());
1535 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1536 TypePrinting *, SlotTracker *, const Module *) {
1537 Out << "!DIEnumerator(";
1538 MDFieldPrinter Printer(Out);
1539 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1540 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1544 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1545 TypePrinting *, SlotTracker *, const Module *) {
1546 Out << "!DIBasicType(";
1547 MDFieldPrinter Printer(Out);
1548 if (N->getTag() != dwarf::DW_TAG_base_type)
1549 Printer.printTag(N);
1550 Printer.printString("name", N->getName());
1551 Printer.printInt("size", N->getSizeInBits());
1552 Printer.printInt("align", N->getAlignInBits());
1553 Printer.printDwarfEnum("encoding", N->getEncoding(),
1554 dwarf::AttributeEncodingString);
1558 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1559 TypePrinting *TypePrinter, SlotTracker *Machine,
1560 const Module *Context) {
1561 Out << "!DIDerivedType(";
1562 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1563 Printer.printTag(N);
1564 Printer.printString("name", N->getName());
1565 Printer.printMetadata("scope", N->getRawScope());
1566 Printer.printMetadata("file", N->getRawFile());
1567 Printer.printInt("line", N->getLine());
1568 Printer.printMetadata("baseType", N->getRawBaseType(),
1569 /* ShouldSkipNull */ false);
1570 Printer.printInt("size", N->getSizeInBits());
1571 Printer.printInt("align", N->getAlignInBits());
1572 Printer.printInt("offset", N->getOffsetInBits());
1573 Printer.printDIFlags("flags", N->getFlags());
1574 Printer.printMetadata("extraData", N->getRawExtraData());
1578 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1579 TypePrinting *TypePrinter,
1580 SlotTracker *Machine, const Module *Context) {
1581 Out << "!DICompositeType(";
1582 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1583 Printer.printTag(N);
1584 Printer.printString("name", N->getName());
1585 Printer.printMetadata("scope", N->getRawScope());
1586 Printer.printMetadata("file", N->getRawFile());
1587 Printer.printInt("line", N->getLine());
1588 Printer.printMetadata("baseType", N->getRawBaseType());
1589 Printer.printInt("size", N->getSizeInBits());
1590 Printer.printInt("align", N->getAlignInBits());
1591 Printer.printInt("offset", N->getOffsetInBits());
1592 Printer.printDIFlags("flags", N->getFlags());
1593 Printer.printMetadata("elements", N->getRawElements());
1594 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1595 dwarf::LanguageString);
1596 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1597 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1598 Printer.printString("identifier", N->getIdentifier());
1602 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1603 TypePrinting *TypePrinter,
1604 SlotTracker *Machine, const Module *Context) {
1605 Out << "!DISubroutineType(";
1606 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1607 Printer.printDIFlags("flags", N->getFlags());
1608 Printer.printMetadata("types", N->getRawTypeArray(),
1609 /* ShouldSkipNull */ false);
1613 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1614 SlotTracker *, const Module *) {
1616 MDFieldPrinter Printer(Out);
1617 Printer.printString("filename", N->getFilename(),
1618 /* ShouldSkipEmpty */ false);
1619 Printer.printString("directory", N->getDirectory(),
1620 /* ShouldSkipEmpty */ false);
1624 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1625 TypePrinting *TypePrinter, SlotTracker *Machine,
1626 const Module *Context) {
1627 Out << "!DICompileUnit(";
1628 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1629 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1630 dwarf::LanguageString, /* ShouldSkipZero */ false);
1631 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1632 Printer.printString("producer", N->getProducer());
1633 Printer.printBool("isOptimized", N->isOptimized());
1634 Printer.printString("flags", N->getFlags());
1635 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1636 /* ShouldSkipZero */ false);
1637 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1638 Printer.printInt("emissionKind", N->getEmissionKind(),
1639 /* ShouldSkipZero */ false);
1640 Printer.printMetadata("enums", N->getRawEnumTypes());
1641 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1642 Printer.printMetadata("subprograms", N->getRawSubprograms());
1643 Printer.printMetadata("globals", N->getRawGlobalVariables());
1644 Printer.printMetadata("imports", N->getRawImportedEntities());
1645 Printer.printInt("dwoId", N->getDWOId());
1649 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1650 TypePrinting *TypePrinter, SlotTracker *Machine,
1651 const Module *Context) {
1652 Out << "!DISubprogram(";
1653 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1654 Printer.printString("name", N->getName());
1655 Printer.printString("linkageName", N->getLinkageName());
1656 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1657 Printer.printMetadata("file", N->getRawFile());
1658 Printer.printInt("line", N->getLine());
1659 Printer.printMetadata("type", N->getRawType());
1660 Printer.printBool("isLocal", N->isLocalToUnit());
1661 Printer.printBool("isDefinition", N->isDefinition());
1662 Printer.printInt("scopeLine", N->getScopeLine());
1663 Printer.printMetadata("containingType", N->getRawContainingType());
1664 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1665 dwarf::VirtualityString);
1666 Printer.printInt("virtualIndex", N->getVirtualIndex());
1667 Printer.printDIFlags("flags", N->getFlags());
1668 Printer.printBool("isOptimized", N->isOptimized());
1669 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1670 Printer.printMetadata("declaration", N->getRawDeclaration());
1671 Printer.printMetadata("variables", N->getRawVariables());
1675 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1676 TypePrinting *TypePrinter, SlotTracker *Machine,
1677 const Module *Context) {
1678 Out << "!DILexicalBlock(";
1679 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1680 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1681 Printer.printMetadata("file", N->getRawFile());
1682 Printer.printInt("line", N->getLine());
1683 Printer.printInt("column", N->getColumn());
1687 static void writeDILexicalBlockFile(raw_ostream &Out,
1688 const DILexicalBlockFile *N,
1689 TypePrinting *TypePrinter,
1690 SlotTracker *Machine,
1691 const Module *Context) {
1692 Out << "!DILexicalBlockFile(";
1693 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1694 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1695 Printer.printMetadata("file", N->getRawFile());
1696 Printer.printInt("discriminator", N->getDiscriminator(),
1697 /* ShouldSkipZero */ false);
1701 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1702 TypePrinting *TypePrinter, SlotTracker *Machine,
1703 const Module *Context) {
1704 Out << "!DINamespace(";
1705 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1706 Printer.printString("name", N->getName());
1707 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1708 Printer.printMetadata("file", N->getRawFile());
1709 Printer.printInt("line", N->getLine());
1713 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1714 TypePrinting *TypePrinter, SlotTracker *Machine,
1715 const Module *Context) {
1716 Out << "!DIModule(";
1717 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1718 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1719 Printer.printString("name", N->getName());
1720 Printer.printString("configMacros", N->getConfigurationMacros());
1721 Printer.printString("includePath", N->getIncludePath());
1722 Printer.printString("isysroot", N->getISysRoot());
1727 static void writeDITemplateTypeParameter(raw_ostream &Out,
1728 const DITemplateTypeParameter *N,
1729 TypePrinting *TypePrinter,
1730 SlotTracker *Machine,
1731 const Module *Context) {
1732 Out << "!DITemplateTypeParameter(";
1733 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1734 Printer.printString("name", N->getName());
1735 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1739 static void writeDITemplateValueParameter(raw_ostream &Out,
1740 const DITemplateValueParameter *N,
1741 TypePrinting *TypePrinter,
1742 SlotTracker *Machine,
1743 const Module *Context) {
1744 Out << "!DITemplateValueParameter(";
1745 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1746 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1747 Printer.printTag(N);
1748 Printer.printString("name", N->getName());
1749 Printer.printMetadata("type", N->getRawType());
1750 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1754 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1755 TypePrinting *TypePrinter,
1756 SlotTracker *Machine, const Module *Context) {
1757 Out << "!DIGlobalVariable(";
1758 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1759 Printer.printString("name", N->getName());
1760 Printer.printString("linkageName", N->getLinkageName());
1761 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1762 Printer.printMetadata("file", N->getRawFile());
1763 Printer.printInt("line", N->getLine());
1764 Printer.printMetadata("type", N->getRawType());
1765 Printer.printBool("isLocal", N->isLocalToUnit());
1766 Printer.printBool("isDefinition", N->isDefinition());
1767 Printer.printMetadata("variable", N->getRawVariable());
1768 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1772 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1773 TypePrinting *TypePrinter,
1774 SlotTracker *Machine, const Module *Context) {
1775 Out << "!DILocalVariable(";
1776 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1777 Printer.printString("name", N->getName());
1778 Printer.printInt("arg", N->getArg());
1779 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1780 Printer.printMetadata("file", N->getRawFile());
1781 Printer.printInt("line", N->getLine());
1782 Printer.printMetadata("type", N->getRawType());
1783 Printer.printDIFlags("flags", N->getFlags());
1787 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1788 TypePrinting *TypePrinter, SlotTracker *Machine,
1789 const Module *Context) {
1790 Out << "!DIExpression(";
1793 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1794 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1795 assert(OpStr && "Expected valid opcode");
1798 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1799 Out << FS << I->getArg(A);
1802 for (const auto &I : N->getElements())
1808 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1809 TypePrinting *TypePrinter, SlotTracker *Machine,
1810 const Module *Context) {
1811 Out << "!DIObjCProperty(";
1812 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1813 Printer.printString("name", N->getName());
1814 Printer.printMetadata("file", N->getRawFile());
1815 Printer.printInt("line", N->getLine());
1816 Printer.printString("setter", N->getSetterName());
1817 Printer.printString("getter", N->getGetterName());
1818 Printer.printInt("attributes", N->getAttributes());
1819 Printer.printMetadata("type", N->getRawType());
1823 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1824 TypePrinting *TypePrinter,
1825 SlotTracker *Machine, const Module *Context) {
1826 Out << "!DIImportedEntity(";
1827 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1828 Printer.printTag(N);
1829 Printer.printString("name", N->getName());
1830 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1831 Printer.printMetadata("entity", N->getRawEntity());
1832 Printer.printInt("line", N->getLine());
1837 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1838 TypePrinting *TypePrinter,
1839 SlotTracker *Machine,
1840 const Module *Context) {
1841 if (Node->isDistinct())
1843 else if (Node->isTemporary())
1844 Out << "<temporary!> "; // Handle broken code.
1846 switch (Node->getMetadataID()) {
1848 llvm_unreachable("Expected uniquable MDNode");
1849 #define HANDLE_MDNODE_LEAF(CLASS) \
1850 case Metadata::CLASS##Kind: \
1851 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1853 #include "llvm/IR/Metadata.def"
1857 // Full implementation of printing a Value as an operand with support for
1858 // TypePrinting, etc.
1859 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1860 TypePrinting *TypePrinter,
1861 SlotTracker *Machine,
1862 const Module *Context) {
1864 PrintLLVMName(Out, V);
1868 const Constant *CV = dyn_cast<Constant>(V);
1869 if (CV && !isa<GlobalValue>(CV)) {
1870 assert(TypePrinter && "Constants require TypePrinting!");
1871 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1875 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1877 if (IA->hasSideEffects())
1878 Out << "sideeffect ";
1879 if (IA->isAlignStack())
1880 Out << "alignstack ";
1881 // We don't emit the AD_ATT dialect as it's the assumed default.
1882 if (IA->getDialect() == InlineAsm::AD_Intel)
1883 Out << "inteldialect ";
1885 PrintEscapedString(IA->getAsmString(), Out);
1887 PrintEscapedString(IA->getConstraintString(), Out);
1892 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1893 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1894 Context, /* FromValue */ true);
1900 // If we have a SlotTracker, use it.
1902 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1903 Slot = Machine->getGlobalSlot(GV);
1906 Slot = Machine->getLocalSlot(V);
1908 // If the local value didn't succeed, then we may be referring to a value
1909 // from a different function. Translate it, as this can happen when using
1910 // address of blocks.
1912 if ((Machine = createSlotTracker(V))) {
1913 Slot = Machine->getLocalSlot(V);
1917 } else if ((Machine = createSlotTracker(V))) {
1918 // Otherwise, create one to get the # and then destroy it.
1919 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1920 Slot = Machine->getGlobalSlot(GV);
1923 Slot = Machine->getLocalSlot(V);
1932 Out << Prefix << Slot;
1937 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1938 TypePrinting *TypePrinter,
1939 SlotTracker *Machine, const Module *Context,
1941 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1942 std::unique_ptr<SlotTracker> MachineStorage;
1944 MachineStorage = make_unique<SlotTracker>(Context);
1945 Machine = MachineStorage.get();
1947 int Slot = Machine->getMetadataSlot(N);
1949 // Give the pointer value instead of "badref", since this comes up all
1950 // the time when debugging.
1951 Out << "<" << N << ">";
1957 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1959 PrintEscapedString(MDS->getString(), Out);
1964 auto *V = cast<ValueAsMetadata>(MD);
1965 assert(TypePrinter && "TypePrinter required for metadata values");
1966 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1967 "Unexpected function-local metadata outside of value argument");
1969 TypePrinter->print(V->getValue()->getType(), Out);
1971 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
1975 class AssemblyWriter {
1976 formatted_raw_ostream &Out;
1977 const Module *TheModule;
1978 std::unique_ptr<SlotTracker> SlotTrackerStorage;
1979 SlotTracker &Machine;
1980 TypePrinting TypePrinter;
1981 AssemblyAnnotationWriter *AnnotationWriter;
1982 SetVector<const Comdat *> Comdats;
1984 bool ShouldPreserveUseListOrder;
1985 UseListOrderStack UseListOrders;
1986 SmallVector<StringRef, 8> MDNames;
1989 /// Construct an AssemblyWriter with an external SlotTracker
1990 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
1991 AssemblyAnnotationWriter *AAW, bool IsForDebug,
1992 bool ShouldPreserveUseListOrder = false);
1994 void printMDNodeBody(const MDNode *MD);
1995 void printNamedMDNode(const NamedMDNode *NMD);
1997 void printModule(const Module *M);
1999 void writeOperand(const Value *Op, bool PrintType);
2000 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2001 void writeOperandBundles(ImmutableCallSite CS);
2002 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2003 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2004 AtomicOrdering FailureOrdering,
2005 SynchronizationScope SynchScope);
2007 void writeAllMDNodes();
2008 void writeMDNode(unsigned Slot, const MDNode *Node);
2009 void writeAllAttributeGroups();
2011 void printTypeIdentities();
2012 void printGlobal(const GlobalVariable *GV);
2013 void printAlias(const GlobalAlias *GV);
2014 void printComdat(const Comdat *C);
2015 void printFunction(const Function *F);
2016 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2017 void printBasicBlock(const BasicBlock *BB);
2018 void printInstructionLine(const Instruction &I);
2019 void printInstruction(const Instruction &I);
2021 void printUseListOrder(const UseListOrder &Order);
2022 void printUseLists(const Function *F);
2025 /// \brief Print out metadata attachments.
2026 void printMetadataAttachments(
2027 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2028 StringRef Separator);
2030 // printInfoComment - Print a little comment after the instruction indicating
2031 // which slot it occupies.
2032 void printInfoComment(const Value &V);
2034 // printGCRelocateComment - print comment after call to the gc.relocate
2035 // intrinsic indicating base and derived pointer names.
2036 void printGCRelocateComment(const Value &V);
2040 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2041 const Module *M, AssemblyAnnotationWriter *AAW,
2042 bool IsForDebug, bool ShouldPreserveUseListOrder)
2043 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2044 IsForDebug(IsForDebug),
2045 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2048 TypePrinter.incorporateTypes(*TheModule);
2049 for (const Function &F : *TheModule)
2050 if (const Comdat *C = F.getComdat())
2052 for (const GlobalVariable &GV : TheModule->globals())
2053 if (const Comdat *C = GV.getComdat())
2057 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2059 Out << "<null operand!>";
2063 TypePrinter.print(Operand->getType(), Out);
2066 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2069 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2070 SynchronizationScope SynchScope) {
2071 if (Ordering == NotAtomic)
2074 switch (SynchScope) {
2075 case SingleThread: Out << " singlethread"; break;
2076 case CrossThread: break;
2080 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2081 case Unordered: Out << " unordered"; break;
2082 case Monotonic: Out << " monotonic"; break;
2083 case Acquire: Out << " acquire"; break;
2084 case Release: Out << " release"; break;
2085 case AcquireRelease: Out << " acq_rel"; break;
2086 case SequentiallyConsistent: Out << " seq_cst"; break;
2090 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2091 AtomicOrdering FailureOrdering,
2092 SynchronizationScope SynchScope) {
2093 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2095 switch (SynchScope) {
2096 case SingleThread: Out << " singlethread"; break;
2097 case CrossThread: break;
2100 switch (SuccessOrdering) {
2101 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2102 case Unordered: Out << " unordered"; break;
2103 case Monotonic: Out << " monotonic"; break;
2104 case Acquire: Out << " acquire"; break;
2105 case Release: Out << " release"; break;
2106 case AcquireRelease: Out << " acq_rel"; break;
2107 case SequentiallyConsistent: Out << " seq_cst"; break;
2110 switch (FailureOrdering) {
2111 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2112 case Unordered: Out << " unordered"; break;
2113 case Monotonic: Out << " monotonic"; break;
2114 case Acquire: Out << " acquire"; break;
2115 case Release: Out << " release"; break;
2116 case AcquireRelease: Out << " acq_rel"; break;
2117 case SequentiallyConsistent: Out << " seq_cst"; break;
2121 void AssemblyWriter::writeParamOperand(const Value *Operand,
2122 AttributeSet Attrs, unsigned Idx) {
2124 Out << "<null operand!>";
2129 TypePrinter.print(Operand->getType(), Out);
2130 // Print parameter attributes list
2131 if (Attrs.hasAttributes(Idx))
2132 Out << ' ' << Attrs.getAsString(Idx);
2134 // Print the operand
2135 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2138 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2139 if (!CS.hasOperandBundles())
2144 bool FirstBundle = true;
2145 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2146 OperandBundleUse BU = CS.getOperandBundleAt(i);
2150 FirstBundle = false;
2153 PrintEscapedString(BU.getTagName(), Out);
2158 bool FirstInput = true;
2159 for (const auto &Input : BU.Inputs) {
2164 TypePrinter.print(Input->getType(), Out);
2166 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2175 void AssemblyWriter::printModule(const Module *M) {
2176 Machine.initialize();
2178 if (ShouldPreserveUseListOrder)
2179 UseListOrders = predictUseListOrder(M);
2181 if (!M->getModuleIdentifier().empty() &&
2182 // Don't print the ID if it will start a new line (which would
2183 // require a comment char before it).
2184 M->getModuleIdentifier().find('\n') == std::string::npos)
2185 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2187 const std::string &DL = M->getDataLayoutStr();
2189 Out << "target datalayout = \"" << DL << "\"\n";
2190 if (!M->getTargetTriple().empty())
2191 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2193 if (!M->getModuleInlineAsm().empty()) {
2196 // Split the string into lines, to make it easier to read the .ll file.
2197 StringRef Asm = M->getModuleInlineAsm();
2200 std::tie(Front, Asm) = Asm.split('\n');
2202 // We found a newline, print the portion of the asm string from the
2203 // last newline up to this newline.
2204 Out << "module asm \"";
2205 PrintEscapedString(Front, Out);
2207 } while (!Asm.empty());
2210 printTypeIdentities();
2212 // Output all comdats.
2213 if (!Comdats.empty())
2215 for (const Comdat *C : Comdats) {
2217 if (C != Comdats.back())
2221 // Output all globals.
2222 if (!M->global_empty()) Out << '\n';
2223 for (const GlobalVariable &GV : M->globals()) {
2224 printGlobal(&GV); Out << '\n';
2227 // Output all aliases.
2228 if (!M->alias_empty()) Out << "\n";
2229 for (const GlobalAlias &GA : M->aliases())
2232 // Output global use-lists.
2233 printUseLists(nullptr);
2235 // Output all of the functions.
2236 for (const Function &F : *M)
2238 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2240 // Output all attribute groups.
2241 if (!Machine.as_empty()) {
2243 writeAllAttributeGroups();
2246 // Output named metadata.
2247 if (!M->named_metadata_empty()) Out << '\n';
2249 for (const NamedMDNode &Node : M->named_metadata())
2250 printNamedMDNode(&Node);
2253 if (!Machine.mdn_empty()) {
2259 static void printMetadataIdentifier(StringRef Name,
2260 formatted_raw_ostream &Out) {
2262 Out << "<empty name> ";
2264 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2265 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2268 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2269 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2270 unsigned char C = Name[i];
2271 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2272 C == '.' || C == '_')
2275 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2280 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2282 printMetadataIdentifier(NMD->getName(), Out);
2284 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2287 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2296 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2297 formatted_raw_ostream &Out) {
2299 case GlobalValue::ExternalLinkage: break;
2300 case GlobalValue::PrivateLinkage: Out << "private "; break;
2301 case GlobalValue::InternalLinkage: Out << "internal "; break;
2302 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2303 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2304 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2305 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2306 case GlobalValue::CommonLinkage: Out << "common "; break;
2307 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2308 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2309 case GlobalValue::AvailableExternallyLinkage:
2310 Out << "available_externally ";
2315 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2316 formatted_raw_ostream &Out) {
2318 case GlobalValue::DefaultVisibility: break;
2319 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2320 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2324 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2325 formatted_raw_ostream &Out) {
2327 case GlobalValue::DefaultStorageClass: break;
2328 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2329 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2333 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2334 formatted_raw_ostream &Out) {
2336 case GlobalVariable::NotThreadLocal:
2338 case GlobalVariable::GeneralDynamicTLSModel:
2339 Out << "thread_local ";
2341 case GlobalVariable::LocalDynamicTLSModel:
2342 Out << "thread_local(localdynamic) ";
2344 case GlobalVariable::InitialExecTLSModel:
2345 Out << "thread_local(initialexec) ";
2347 case GlobalVariable::LocalExecTLSModel:
2348 Out << "thread_local(localexec) ";
2353 static void maybePrintComdat(formatted_raw_ostream &Out,
2354 const GlobalObject &GO) {
2355 const Comdat *C = GO.getComdat();
2359 if (isa<GlobalVariable>(GO))
2363 if (GO.getName() == C->getName())
2367 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2371 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2372 if (GV->isMaterializable())
2373 Out << "; Materializable\n";
2375 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2378 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2381 PrintLinkage(GV->getLinkage(), Out);
2382 PrintVisibility(GV->getVisibility(), Out);
2383 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2384 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2385 if (GV->hasUnnamedAddr())
2386 Out << "unnamed_addr ";
2388 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2389 Out << "addrspace(" << AddressSpace << ") ";
2390 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2391 Out << (GV->isConstant() ? "constant " : "global ");
2392 TypePrinter.print(GV->getType()->getElementType(), Out);
2394 if (GV->hasInitializer()) {
2396 writeOperand(GV->getInitializer(), false);
2399 if (GV->hasSection()) {
2400 Out << ", section \"";
2401 PrintEscapedString(GV->getSection(), Out);
2404 maybePrintComdat(Out, *GV);
2405 if (GV->getAlignment())
2406 Out << ", align " << GV->getAlignment();
2408 printInfoComment(*GV);
2411 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2412 if (GA->isMaterializable())
2413 Out << "; Materializable\n";
2415 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2418 PrintLinkage(GA->getLinkage(), Out);
2419 PrintVisibility(GA->getVisibility(), Out);
2420 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2421 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2422 if (GA->hasUnnamedAddr())
2423 Out << "unnamed_addr ";
2427 TypePrinter.print(GA->getValueType(), Out);
2431 const Constant *Aliasee = GA->getAliasee();
2434 TypePrinter.print(GA->getType(), Out);
2435 Out << " <<NULL ALIASEE>>";
2437 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2440 printInfoComment(*GA);
2444 void AssemblyWriter::printComdat(const Comdat *C) {
2448 void AssemblyWriter::printTypeIdentities() {
2449 if (TypePrinter.NumberedTypes.empty() &&
2450 TypePrinter.NamedTypes.empty())
2455 // We know all the numbers that each type is used and we know that it is a
2456 // dense assignment. Convert the map to an index table.
2457 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2458 for (DenseMap<StructType*, unsigned>::iterator I =
2459 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2461 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2462 NumberedTypes[I->second] = I->first;
2465 // Emit all numbered types.
2466 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2467 Out << '%' << i << " = type ";
2469 // Make sure we print out at least one level of the type structure, so
2470 // that we do not get %2 = type %2
2471 TypePrinter.printStructBody(NumberedTypes[i], Out);
2475 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2476 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2479 // Make sure we print out at least one level of the type structure, so
2480 // that we do not get %FILE = type %FILE
2481 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2486 /// printFunction - Print all aspects of a function.
2488 void AssemblyWriter::printFunction(const Function *F) {
2489 // Print out the return type and name.
2492 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2494 if (F->isMaterializable())
2495 Out << "; Materializable\n";
2497 const AttributeSet &Attrs = F->getAttributes();
2498 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2499 AttributeSet AS = Attrs.getFnAttributes();
2500 std::string AttrStr;
2503 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2504 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2507 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2509 Attribute Attr = *I;
2510 if (!Attr.isStringAttribute()) {
2511 if (!AttrStr.empty()) AttrStr += ' ';
2512 AttrStr += Attr.getAsString();
2516 if (!AttrStr.empty())
2517 Out << "; Function Attrs: " << AttrStr << '\n';
2520 if (F->isDeclaration())
2525 PrintLinkage(F->getLinkage(), Out);
2526 PrintVisibility(F->getVisibility(), Out);
2527 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2529 // Print the calling convention.
2530 if (F->getCallingConv() != CallingConv::C) {
2531 PrintCallingConv(F->getCallingConv(), Out);
2535 FunctionType *FT = F->getFunctionType();
2536 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2537 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2538 TypePrinter.print(F->getReturnType(), Out);
2540 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2542 Machine.incorporateFunction(F);
2544 // Loop over the arguments, printing them...
2545 if (F->isDeclaration() && !IsForDebug) {
2546 // We're only interested in the type here - don't print argument names.
2547 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2548 // Insert commas as we go... the first arg doesn't get a comma
2552 TypePrinter.print(FT->getParamType(I), Out);
2554 if (Attrs.hasAttributes(I + 1))
2555 Out << ' ' << Attrs.getAsString(I + 1);
2558 // The arguments are meaningful here, print them in detail.
2560 for (const Argument &Arg : F->args()) {
2561 // Insert commas as we go... the first arg doesn't get a comma
2564 printArgument(&Arg, Attrs, Idx++);
2568 // Finish printing arguments...
2569 if (FT->isVarArg()) {
2570 if (FT->getNumParams()) Out << ", ";
2571 Out << "..."; // Output varargs portion of signature!
2574 if (F->hasUnnamedAddr())
2575 Out << " unnamed_addr";
2576 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2577 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2578 if (F->hasSection()) {
2579 Out << " section \"";
2580 PrintEscapedString(F->getSection(), Out);
2583 maybePrintComdat(Out, *F);
2584 if (F->getAlignment())
2585 Out << " align " << F->getAlignment();
2587 Out << " gc \"" << F->getGC() << '"';
2588 if (F->hasPrefixData()) {
2590 writeOperand(F->getPrefixData(), true);
2592 if (F->hasPrologueData()) {
2593 Out << " prologue ";
2594 writeOperand(F->getPrologueData(), true);
2596 if (F->hasPersonalityFn()) {
2597 Out << " personality ";
2598 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2601 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2602 F->getAllMetadata(MDs);
2603 printMetadataAttachments(MDs, " ");
2605 if (F->isDeclaration()) {
2609 // Output all of the function's basic blocks.
2610 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2611 printBasicBlock(&*I);
2613 // Output the function's use-lists.
2619 Machine.purgeFunction();
2622 /// printArgument - This member is called for every argument that is passed into
2623 /// the function. Simply print it out
2625 void AssemblyWriter::printArgument(const Argument *Arg,
2626 AttributeSet Attrs, unsigned Idx) {
2628 TypePrinter.print(Arg->getType(), Out);
2630 // Output parameter attributes list
2631 if (Attrs.hasAttributes(Idx))
2632 Out << ' ' << Attrs.getAsString(Idx);
2634 // Output name, if available...
2635 if (Arg->hasName()) {
2637 PrintLLVMName(Out, Arg);
2641 /// printBasicBlock - This member is called for each basic block in a method.
2643 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2644 if (BB->hasName()) { // Print out the label if it exists...
2646 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2648 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2649 Out << "\n; <label>:";
2650 int Slot = Machine.getLocalSlot(BB);
2657 if (!BB->getParent()) {
2658 Out.PadToColumn(50);
2659 Out << "; Error: Block without parent!";
2660 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2661 // Output predecessors for the block.
2662 Out.PadToColumn(50);
2664 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2667 Out << " No predecessors!";
2670 writeOperand(*PI, false);
2671 for (++PI; PI != PE; ++PI) {
2673 writeOperand(*PI, false);
2680 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2682 // Output all of the instructions in the basic block...
2683 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2684 printInstructionLine(*I);
2687 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2690 /// printInstructionLine - Print an instruction and a newline character.
2691 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2692 printInstruction(I);
2696 /// printGCRelocateComment - print comment after call to the gc.relocate
2697 /// intrinsic indicating base and derived pointer names.
2698 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2699 assert(isGCRelocate(&V));
2700 GCRelocateOperands GCOps(cast<Instruction>(&V));
2703 writeOperand(GCOps.getBasePtr(), false);
2705 writeOperand(GCOps.getDerivedPtr(), false);
2709 /// printInfoComment - Print a little comment after the instruction indicating
2710 /// which slot it occupies.
2712 void AssemblyWriter::printInfoComment(const Value &V) {
2713 if (isGCRelocate(&V))
2714 printGCRelocateComment(V);
2716 if (AnnotationWriter)
2717 AnnotationWriter->printInfoComment(V, Out);
2720 // This member is called for each Instruction in a function..
2721 void AssemblyWriter::printInstruction(const Instruction &I) {
2722 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2724 // Print out indentation for an instruction.
2727 // Print out name if it exists...
2729 PrintLLVMName(Out, &I);
2731 } else if (!I.getType()->isVoidTy()) {
2732 // Print out the def slot taken.
2733 int SlotNum = Machine.getLocalSlot(&I);
2735 Out << "<badref> = ";
2737 Out << '%' << SlotNum << " = ";
2740 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2741 if (CI->isMustTailCall())
2743 else if (CI->isTailCall())
2745 else if (CI->isNoTailCall())
2749 // Print out the opcode...
2750 Out << I.getOpcodeName();
2752 // If this is an atomic load or store, print out the atomic marker.
2753 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2754 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2757 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2760 // If this is a volatile operation, print out the volatile marker.
2761 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2762 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2763 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2764 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2767 // Print out optimization information.
2768 WriteOptimizationInfo(Out, &I);
2770 // Print out the compare instruction predicates
2771 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2772 Out << ' ' << getPredicateText(CI->getPredicate());
2774 // Print out the atomicrmw operation
2775 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2776 writeAtomicRMWOperation(Out, RMWI->getOperation());
2778 // Print out the type of the operands...
2779 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2781 // Special case conditional branches to swizzle the condition out to the front
2782 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2783 const BranchInst &BI(cast<BranchInst>(I));
2785 writeOperand(BI.getCondition(), true);
2787 writeOperand(BI.getSuccessor(0), true);
2789 writeOperand(BI.getSuccessor(1), true);
2791 } else if (isa<SwitchInst>(I)) {
2792 const SwitchInst& SI(cast<SwitchInst>(I));
2793 // Special case switch instruction to get formatting nice and correct.
2795 writeOperand(SI.getCondition(), true);
2797 writeOperand(SI.getDefaultDest(), true);
2799 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2802 writeOperand(i.getCaseValue(), true);
2804 writeOperand(i.getCaseSuccessor(), true);
2807 } else if (isa<IndirectBrInst>(I)) {
2808 // Special case indirectbr instruction to get formatting nice and correct.
2810 writeOperand(Operand, true);
2813 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2816 writeOperand(I.getOperand(i), true);
2819 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2821 TypePrinter.print(I.getType(), Out);
2824 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2825 if (op) Out << ", ";
2827 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2828 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2830 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2832 writeOperand(I.getOperand(0), true);
2833 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2835 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2837 writeOperand(I.getOperand(0), true); Out << ", ";
2838 writeOperand(I.getOperand(1), true);
2839 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2841 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2843 TypePrinter.print(I.getType(), Out);
2844 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2847 if (LPI->isCleanup())
2850 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2851 if (i != 0 || LPI->isCleanup()) Out << "\n";
2852 if (LPI->isCatch(i))
2857 writeOperand(LPI->getClause(i), true);
2859 } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2861 for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps;
2865 writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true);
2868 writeOperand(CPI->getNormalDest(), /*PrintType=*/true);
2870 writeOperand(CPI->getUnwindDest(), /*PrintType=*/true);
2871 } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) {
2873 for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps;
2877 writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true);
2880 if (TPI->hasUnwindDest())
2881 writeOperand(TPI->getUnwindDest(), /*PrintType=*/true);
2884 } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) {
2886 for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) {
2889 writeOperand(CPI->getOperand(Op), /*PrintType=*/true);
2892 } else if (isa<ReturnInst>(I) && !Operand) {
2894 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2896 writeOperand(CRI->getCatchPad(), /*PrintType=*/false);
2899 writeOperand(CRI->getSuccessor(), /*PrintType=*/true);
2900 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2902 writeOperand(CRI->getCleanupPad(), /*PrintType=*/false);
2905 if (CRI->hasUnwindDest())
2906 writeOperand(CRI->getUnwindDest(), /*PrintType=*/true);
2909 } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) {
2911 if (CEPI->hasUnwindDest())
2912 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2915 } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) {
2917 writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false);
2920 if (CEPI->hasUnwindDest())
2921 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2924 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2925 // Print the calling convention being used.
2926 if (CI->getCallingConv() != CallingConv::C) {
2928 PrintCallingConv(CI->getCallingConv(), Out);
2931 Operand = CI->getCalledValue();
2932 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2933 Type *RetTy = FTy->getReturnType();
2934 const AttributeSet &PAL = CI->getAttributes();
2936 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2937 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2939 // If possible, print out the short form of the call instruction. We can
2940 // only do this if the first argument is a pointer to a nonvararg function,
2941 // and if the return type is not a pointer to a function.
2944 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2946 writeOperand(Operand, false);
2948 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2951 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2954 // Emit an ellipsis if this is a musttail call in a vararg function. This
2955 // is only to aid readability, musttail calls forward varargs by default.
2956 if (CI->isMustTailCall() && CI->getParent() &&
2957 CI->getParent()->getParent() &&
2958 CI->getParent()->getParent()->isVarArg())
2962 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2963 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2965 writeOperandBundles(CI);
2967 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2968 Operand = II->getCalledValue();
2969 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
2970 Type *RetTy = FTy->getReturnType();
2971 const AttributeSet &PAL = II->getAttributes();
2973 // Print the calling convention being used.
2974 if (II->getCallingConv() != CallingConv::C) {
2976 PrintCallingConv(II->getCallingConv(), Out);
2979 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2980 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2982 // If possible, print out the short form of the invoke instruction. We can
2983 // only do this if the first argument is a pointer to a nonvararg function,
2984 // and if the return type is not a pointer to a function.
2987 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2989 writeOperand(Operand, false);
2991 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2994 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
2998 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2999 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3001 writeOperandBundles(II);
3004 writeOperand(II->getNormalDest(), true);
3006 writeOperand(II->getUnwindDest(), true);
3008 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3010 if (AI->isUsedWithInAlloca())
3012 TypePrinter.print(AI->getAllocatedType(), Out);
3014 // Explicitly write the array size if the code is broken, if it's an array
3015 // allocation, or if the type is not canonical for scalar allocations. The
3016 // latter case prevents the type from mutating when round-tripping through
3018 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3019 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3021 writeOperand(AI->getArraySize(), true);
3023 if (AI->getAlignment()) {
3024 Out << ", align " << AI->getAlignment();
3026 } else if (isa<CastInst>(I)) {
3029 writeOperand(Operand, true); // Work with broken code
3032 TypePrinter.print(I.getType(), Out);
3033 } else if (isa<VAArgInst>(I)) {
3036 writeOperand(Operand, true); // Work with broken code
3039 TypePrinter.print(I.getType(), Out);
3040 } else if (Operand) { // Print the normal way.
3041 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3043 TypePrinter.print(GEP->getSourceElementType(), Out);
3045 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3047 TypePrinter.print(LI->getType(), Out);
3051 // PrintAllTypes - Instructions who have operands of all the same type
3052 // omit the type from all but the first operand. If the instruction has
3053 // different type operands (for example br), then they are all printed.
3054 bool PrintAllTypes = false;
3055 Type *TheType = Operand->getType();
3057 // Select, Store and ShuffleVector always print all types.
3058 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3059 || isa<ReturnInst>(I)) {
3060 PrintAllTypes = true;
3062 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3063 Operand = I.getOperand(i);
3064 // note that Operand shouldn't be null, but the test helps make dump()
3065 // more tolerant of malformed IR
3066 if (Operand && Operand->getType() != TheType) {
3067 PrintAllTypes = true; // We have differing types! Print them all!
3073 if (!PrintAllTypes) {
3075 TypePrinter.print(TheType, Out);
3079 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3081 writeOperand(I.getOperand(i), PrintAllTypes);
3085 // Print atomic ordering/alignment for memory operations
3086 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3088 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3089 if (LI->getAlignment())
3090 Out << ", align " << LI->getAlignment();
3091 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3093 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3094 if (SI->getAlignment())
3095 Out << ", align " << SI->getAlignment();
3096 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3097 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3098 CXI->getSynchScope());
3099 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3100 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3101 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3102 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3105 // Print Metadata info.
3106 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3107 I.getAllMetadata(InstMD);
3108 printMetadataAttachments(InstMD, ", ");
3110 // Print a nice comment.
3111 printInfoComment(I);
3114 void AssemblyWriter::printMetadataAttachments(
3115 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3116 StringRef Separator) {
3120 if (MDNames.empty())
3121 TheModule->getMDKindNames(MDNames);
3123 for (const auto &I : MDs) {
3124 unsigned Kind = I.first;
3126 if (Kind < MDNames.size()) {
3128 printMetadataIdentifier(MDNames[Kind], Out);
3130 Out << "!<unknown kind #" << Kind << ">";
3132 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3136 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3137 Out << '!' << Slot << " = ";
3138 printMDNodeBody(Node);
3142 void AssemblyWriter::writeAllMDNodes() {
3143 SmallVector<const MDNode *, 16> Nodes;
3144 Nodes.resize(Machine.mdn_size());
3145 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3147 Nodes[I->second] = cast<MDNode>(I->first);
3149 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3150 writeMDNode(i, Nodes[i]);
3154 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3155 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3158 void AssemblyWriter::writeAllAttributeGroups() {
3159 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3160 asVec.resize(Machine.as_size());
3162 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3164 asVec[I->second] = *I;
3166 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3167 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3168 Out << "attributes #" << I->second << " = { "
3169 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3172 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3173 bool IsInFunction = Machine.getFunction();
3177 Out << "uselistorder";
3178 if (const BasicBlock *BB =
3179 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3181 writeOperand(BB->getParent(), false);
3183 writeOperand(BB, false);
3186 writeOperand(Order.V, true);
3190 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3191 Out << Order.Shuffle[0];
3192 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3193 Out << ", " << Order.Shuffle[I];
3197 void AssemblyWriter::printUseLists(const Function *F) {
3199 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3204 Out << "\n; uselistorder directives\n";
3206 printUseListOrder(UseListOrders.back());
3207 UseListOrders.pop_back();
3211 //===----------------------------------------------------------------------===//
3212 // External Interface declarations
3213 //===----------------------------------------------------------------------===//
3215 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3216 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3217 SlotTracker SlotTable(this);
3218 formatted_raw_ostream OS(ROS);
3219 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3220 ShouldPreserveUseListOrder);
3221 W.printModule(this);
3224 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3225 SlotTracker SlotTable(getParent());
3226 formatted_raw_ostream OS(ROS);
3227 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3228 W.printNamedMDNode(this);
3231 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3232 PrintLLVMName(ROS, getName(), ComdatPrefix);
3233 ROS << " = comdat ";
3235 switch (getSelectionKind()) {
3239 case Comdat::ExactMatch:
3240 ROS << "exactmatch";
3242 case Comdat::Largest:
3245 case Comdat::NoDuplicates:
3246 ROS << "noduplicates";
3248 case Comdat::SameSize:
3256 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3258 TP.print(const_cast<Type*>(this), OS);
3260 // If the type is a named struct type, print the body as well.
3261 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3262 if (!STy->isLiteral()) {
3264 TP.printStructBody(STy, OS);
3268 static bool isReferencingMDNode(const Instruction &I) {
3269 if (const auto *CI = dyn_cast<CallInst>(&I))
3270 if (Function *F = CI->getCalledFunction())
3271 if (F->isIntrinsic())
3272 for (auto &Op : I.operands())
3273 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3274 if (isa<MDNode>(V->getMetadata()))
3279 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3280 bool ShouldInitializeAllMetadata = false;
3281 if (auto *I = dyn_cast<Instruction>(this))
3282 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3283 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3284 ShouldInitializeAllMetadata = true;
3286 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3287 print(ROS, MST, IsForDebug);
3290 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3291 bool IsForDebug) const {
3292 formatted_raw_ostream OS(ROS);
3293 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3294 SlotTracker &SlotTable =
3295 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3296 auto incorporateFunction = [&](const Function *F) {
3298 MST.incorporateFunction(*F);
3301 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3302 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3303 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3304 W.printInstruction(*I);
3305 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3306 incorporateFunction(BB->getParent());
3307 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3308 W.printBasicBlock(BB);
3309 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3310 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3311 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3313 else if (const Function *F = dyn_cast<Function>(GV))
3316 W.printAlias(cast<GlobalAlias>(GV));
3317 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3318 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3319 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3320 TypePrinting TypePrinter;
3321 TypePrinter.print(C->getType(), OS);
3323 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3324 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3325 this->printAsOperand(OS, /* PrintType */ true, MST);
3327 llvm_unreachable("Unknown value to print out!");
3331 /// Print without a type, skipping the TypePrinting object.
3333 /// \return \c true iff printing was successful.
3334 static bool printWithoutType(const Value &V, raw_ostream &O,
3335 SlotTracker *Machine, const Module *M) {
3336 if (V.hasName() || isa<GlobalValue>(V) ||
3337 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3338 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3344 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3345 ModuleSlotTracker &MST) {
3346 TypePrinting TypePrinter;
3347 if (const Module *M = MST.getModule())
3348 TypePrinter.incorporateTypes(*M);
3350 TypePrinter.print(V.getType(), O);
3354 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3358 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3359 const Module *M) const {
3361 M = getModuleFromVal(this);
3364 if (printWithoutType(*this, O, nullptr, M))
3367 SlotTracker Machine(
3368 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3369 ModuleSlotTracker MST(Machine, M);
3370 printAsOperandImpl(*this, O, PrintType, MST);
3373 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3374 ModuleSlotTracker &MST) const {
3376 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3379 printAsOperandImpl(*this, O, PrintType, MST);
3382 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3383 ModuleSlotTracker &MST, const Module *M,
3384 bool OnlyAsOperand) {
3385 formatted_raw_ostream OS(ROS);
3387 TypePrinting TypePrinter;
3389 TypePrinter.incorporateTypes(*M);
3391 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3392 /* FromValue */ true);
3394 auto *N = dyn_cast<MDNode>(&MD);
3395 if (OnlyAsOperand || !N)
3399 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3402 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3403 ModuleSlotTracker MST(M, isa<MDNode>(this));
3404 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3407 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3408 const Module *M) const {
3409 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3412 void Metadata::print(raw_ostream &OS, const Module *M,
3413 bool /*IsForDebug*/) const {
3414 ModuleSlotTracker MST(M, isa<MDNode>(this));
3415 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3418 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3419 const Module *M, bool /*IsForDebug*/) const {
3420 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3423 // Value::dump - allow easy printing of Values from the debugger.
3425 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3427 // Type::dump - allow easy printing of Types from the debugger.
3429 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3431 // Module::dump() - Allow printing of Modules from the debugger.
3433 void Module::dump() const {
3434 print(dbgs(), nullptr,
3435 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3438 // \brief Allow printing of Comdats from the debugger.
3440 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3442 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3444 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3447 void Metadata::dump() const { dump(nullptr); }
3450 void Metadata::dump(const Module *M) const {
3451 print(dbgs(), M, /*IsForDebug=*/true);