1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/IR/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/TypeFinder.h"
37 #include "llvm/IR/UseListOrder.h"
38 #include "llvm/IR/ValueSymbolTable.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
50 // Make virtual table appear in this compilation unit.
51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
59 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
61 unsigned size() const { return IDs.size(); }
62 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
63 std::pair<unsigned, bool> lookup(const Value *V) const {
66 void index(const Value *V) {
67 // Explicitly sequence get-size and insert-value operations to avoid UB.
68 unsigned ID = IDs.size() + 1;
74 static void orderValue(const Value *V, OrderMap &OM) {
75 if (OM.lookup(V).first)
78 if (const Constant *C = dyn_cast<Constant>(V))
79 if (C->getNumOperands() && !isa<GlobalValue>(C))
80 for (const Value *Op : C->operands())
81 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
84 // Note: we cannot cache this lookup above, since inserting into the map
85 // changes the map's size, and thus affects the other IDs.
89 static OrderMap orderModule(const Module *M) {
90 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
91 // and ValueEnumerator::incorporateFunction().
94 for (const GlobalVariable &G : M->globals()) {
95 if (G.hasInitializer())
96 if (!isa<GlobalValue>(G.getInitializer()))
97 orderValue(G.getInitializer(), OM);
100 for (const GlobalAlias &A : M->aliases()) {
101 if (!isa<GlobalValue>(A.getAliasee()))
102 orderValue(A.getAliasee(), OM);
105 for (const Function &F : *M) {
106 if (F.hasPrefixData())
107 if (!isa<GlobalValue>(F.getPrefixData()))
108 orderValue(F.getPrefixData(), OM);
110 if (F.hasPrologueData())
111 if (!isa<GlobalValue>(F.getPrologueData()))
112 orderValue(F.getPrologueData(), OM);
114 if (F.hasPersonalityFn())
115 if (!isa<GlobalValue>(F.getPersonalityFn()))
116 orderValue(F.getPersonalityFn(), OM);
120 if (F.isDeclaration())
123 for (const Argument &A : F.args())
125 for (const BasicBlock &BB : F) {
127 for (const Instruction &I : BB) {
128 for (const Value *Op : I.operands())
129 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
139 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
140 unsigned ID, const OrderMap &OM,
141 UseListOrderStack &Stack) {
142 // Predict use-list order for this one.
143 typedef std::pair<const Use *, unsigned> Entry;
144 SmallVector<Entry, 64> List;
145 for (const Use &U : V->uses())
146 // Check if this user will be serialized.
147 if (OM.lookup(U.getUser()).first)
148 List.push_back(std::make_pair(&U, List.size()));
151 // We may have lost some users.
155 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
156 if (auto *BA = dyn_cast<BlockAddress>(V))
157 ID = OM.lookup(BA->getBasicBlock()).first;
158 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
159 const Use *LU = L.first;
160 const Use *RU = R.first;
164 auto LID = OM.lookup(LU->getUser()).first;
165 auto RID = OM.lookup(RU->getUser()).first;
167 // If ID is 4, then expect: 7 6 5 1 2 3.
181 // LID and RID are equal, so we have different operands of the same user.
182 // Assume operands are added in order for all instructions.
185 return LU->getOperandNo() < RU->getOperandNo();
186 return LU->getOperandNo() > RU->getOperandNo();
190 List.begin(), List.end(),
191 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
192 // Order is already correct.
195 // Store the shuffle.
196 Stack.emplace_back(V, F, List.size());
197 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
198 for (size_t I = 0, E = List.size(); I != E; ++I)
199 Stack.back().Shuffle[I] = List[I].second;
202 static void predictValueUseListOrder(const Value *V, const Function *F,
203 OrderMap &OM, UseListOrderStack &Stack) {
204 auto &IDPair = OM[V];
205 assert(IDPair.first && "Unmapped value");
207 // Already predicted.
210 // Do the actual prediction.
211 IDPair.second = true;
212 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
213 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
215 // Recursive descent into constants.
216 if (const Constant *C = dyn_cast<Constant>(V))
217 if (C->getNumOperands()) // Visit GlobalValues.
218 for (const Value *Op : C->operands())
219 if (isa<Constant>(Op)) // Visit GlobalValues.
220 predictValueUseListOrder(Op, F, OM, Stack);
223 static UseListOrderStack predictUseListOrder(const Module *M) {
224 OrderMap OM = orderModule(M);
226 // Use-list orders need to be serialized after all the users have been added
227 // to a value, or else the shuffles will be incomplete. Store them per
228 // function in a stack.
230 // Aside from function order, the order of values doesn't matter much here.
231 UseListOrderStack Stack;
233 // We want to visit the functions backward now so we can list function-local
234 // constants in the last Function they're used in. Module-level constants
235 // have already been visited above.
236 for (const Function &F : make_range(M->rbegin(), M->rend())) {
237 if (F.isDeclaration())
239 for (const BasicBlock &BB : F)
240 predictValueUseListOrder(&BB, &F, OM, Stack);
241 for (const Argument &A : F.args())
242 predictValueUseListOrder(&A, &F, OM, Stack);
243 for (const BasicBlock &BB : F)
244 for (const Instruction &I : BB)
245 for (const Value *Op : I.operands())
246 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
247 predictValueUseListOrder(Op, &F, OM, Stack);
248 for (const BasicBlock &BB : F)
249 for (const Instruction &I : BB)
250 predictValueUseListOrder(&I, &F, OM, Stack);
253 // Visit globals last.
254 for (const GlobalVariable &G : M->globals())
255 predictValueUseListOrder(&G, nullptr, OM, Stack);
256 for (const Function &F : *M)
257 predictValueUseListOrder(&F, nullptr, OM, Stack);
258 for (const GlobalAlias &A : M->aliases())
259 predictValueUseListOrder(&A, nullptr, OM, Stack);
260 for (const GlobalVariable &G : M->globals())
261 if (G.hasInitializer())
262 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
263 for (const GlobalAlias &A : M->aliases())
264 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
265 for (const Function &F : *M)
266 if (F.hasPrefixData())
267 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
272 static const Module *getModuleFromVal(const Value *V) {
273 if (const Argument *MA = dyn_cast<Argument>(V))
274 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
276 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
277 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
279 if (const Instruction *I = dyn_cast<Instruction>(V)) {
280 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
281 return M ? M->getParent() : nullptr;
284 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
285 return GV->getParent();
287 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
288 for (const User *U : MAV->users())
289 if (isa<Instruction>(U))
290 if (const Module *M = getModuleFromVal(U))
298 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
300 default: Out << "cc" << cc; break;
301 case CallingConv::Fast: Out << "fastcc"; break;
302 case CallingConv::Cold: Out << "coldcc"; break;
303 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
304 case CallingConv::AnyReg: Out << "anyregcc"; break;
305 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
306 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
307 case CallingConv::CXX_FAST_TLS: Out << "cxx_fast_tlscc"; break;
308 case CallingConv::GHC: Out << "ghccc"; break;
309 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
310 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
311 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
312 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
313 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
314 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
315 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
316 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
317 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
318 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
319 case CallingConv::PTX_Device: Out << "ptx_device"; break;
320 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
321 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
322 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
323 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
324 case CallingConv::HHVM: Out << "hhvmcc"; break;
325 case CallingConv::HHVM_C: Out << "hhvm_ccc"; break;
329 // PrintEscapedString - Print each character of the specified string, escaping
330 // it if it is not printable or if it is an escape char.
331 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
332 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
333 unsigned char C = Name[i];
334 if (isprint(C) && C != '\\' && C != '"')
337 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
349 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
350 assert(!Name.empty() && "Cannot get empty name!");
352 // Scan the name to see if it needs quotes first.
353 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
355 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
356 // By making this unsigned, the value passed in to isalnum will always be
357 // in the range 0-255. This is important when building with MSVC because
358 // its implementation will assert. This situation can arise when dealing
359 // with UTF-8 multibyte characters.
360 unsigned char C = Name[i];
361 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
369 // If we didn't need any quotes, just write out the name in one blast.
375 // Okay, we need quotes. Output the quotes and escape any scary characters as
378 PrintEscapedString(Name, OS);
382 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
383 /// (if the string only contains simple characters) or is surrounded with ""'s
384 /// (if it has special chars in it). Print it out.
385 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
401 printLLVMNameWithoutPrefix(OS, Name);
404 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
405 /// (if the string only contains simple characters) or is surrounded with ""'s
406 /// (if it has special chars in it). Print it out.
407 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
408 PrintLLVMName(OS, V->getName(),
409 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
415 TypePrinting(const TypePrinting &) = delete;
416 void operator=(const TypePrinting&) = delete;
419 /// NamedTypes - The named types that are used by the current module.
420 TypeFinder NamedTypes;
422 /// NumberedTypes - The numbered types, along with their value.
423 DenseMap<StructType*, unsigned> NumberedTypes;
425 TypePrinting() = default;
427 void incorporateTypes(const Module &M);
429 void print(Type *Ty, raw_ostream &OS);
431 void printStructBody(StructType *Ty, raw_ostream &OS);
435 void TypePrinting::incorporateTypes(const Module &M) {
436 NamedTypes.run(M, false);
438 // The list of struct types we got back includes all the struct types, split
439 // the unnamed ones out to a numbering and remove the anonymous structs.
440 unsigned NextNumber = 0;
442 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
443 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
444 StructType *STy = *I;
446 // Ignore anonymous types.
447 if (STy->isLiteral())
450 if (STy->getName().empty())
451 NumberedTypes[STy] = NextNumber++;
456 NamedTypes.erase(NextToUse, NamedTypes.end());
460 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
461 /// use of type names or up references to shorten the type name where possible.
462 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
463 switch (Ty->getTypeID()) {
464 case Type::VoidTyID: OS << "void"; return;
465 case Type::HalfTyID: OS << "half"; return;
466 case Type::FloatTyID: OS << "float"; return;
467 case Type::DoubleTyID: OS << "double"; return;
468 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
469 case Type::FP128TyID: OS << "fp128"; return;
470 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
471 case Type::LabelTyID: OS << "label"; return;
472 case Type::MetadataTyID: OS << "metadata"; return;
473 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
474 case Type::TokenTyID: OS << "token"; return;
475 case Type::IntegerTyID:
476 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
479 case Type::FunctionTyID: {
480 FunctionType *FTy = cast<FunctionType>(Ty);
481 print(FTy->getReturnType(), OS);
483 for (FunctionType::param_iterator I = FTy->param_begin(),
484 E = FTy->param_end(); I != E; ++I) {
485 if (I != FTy->param_begin())
489 if (FTy->isVarArg()) {
490 if (FTy->getNumParams()) OS << ", ";
496 case Type::StructTyID: {
497 StructType *STy = cast<StructType>(Ty);
499 if (STy->isLiteral())
500 return printStructBody(STy, OS);
502 if (!STy->getName().empty())
503 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
505 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
506 if (I != NumberedTypes.end())
507 OS << '%' << I->second;
508 else // Not enumerated, print the hex address.
509 OS << "%\"type " << STy << '\"';
512 case Type::PointerTyID: {
513 PointerType *PTy = cast<PointerType>(Ty);
514 print(PTy->getElementType(), OS);
515 if (unsigned AddressSpace = PTy->getAddressSpace())
516 OS << " addrspace(" << AddressSpace << ')';
520 case Type::ArrayTyID: {
521 ArrayType *ATy = cast<ArrayType>(Ty);
522 OS << '[' << ATy->getNumElements() << " x ";
523 print(ATy->getElementType(), OS);
527 case Type::VectorTyID: {
528 VectorType *PTy = cast<VectorType>(Ty);
529 OS << "<" << PTy->getNumElements() << " x ";
530 print(PTy->getElementType(), OS);
535 llvm_unreachable("Invalid TypeID");
538 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
539 if (STy->isOpaque()) {
547 if (STy->getNumElements() == 0) {
550 StructType::element_iterator I = STy->element_begin();
553 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
565 //===----------------------------------------------------------------------===//
566 // SlotTracker Class: Enumerate slot numbers for unnamed values
567 //===----------------------------------------------------------------------===//
568 /// This class provides computation of slot numbers for LLVM Assembly writing.
572 /// ValueMap - A mapping of Values to slot numbers.
573 typedef DenseMap<const Value*, unsigned> ValueMap;
576 /// TheModule - The module for which we are holding slot numbers.
577 const Module* TheModule;
579 /// TheFunction - The function for which we are holding slot numbers.
580 const Function* TheFunction;
581 bool FunctionProcessed;
582 bool ShouldInitializeAllMetadata;
584 /// mMap - The slot map for the module level data.
588 /// fMap - The slot map for the function level data.
592 /// mdnMap - Map for MDNodes.
593 DenseMap<const MDNode*, unsigned> mdnMap;
596 /// asMap - The slot map for attribute sets.
597 DenseMap<AttributeSet, unsigned> asMap;
600 /// Construct from a module.
602 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
603 /// functions, giving correct numbering for metadata referenced only from
604 /// within a function (even if no functions have been initialized).
605 explicit SlotTracker(const Module *M,
606 bool ShouldInitializeAllMetadata = false);
607 /// Construct from a function, starting out in incorp state.
609 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
610 /// functions, giving correct numbering for metadata referenced only from
611 /// within a function (even if no functions have been initialized).
612 explicit SlotTracker(const Function *F,
613 bool ShouldInitializeAllMetadata = false);
615 /// Return the slot number of the specified value in it's type
616 /// plane. If something is not in the SlotTracker, return -1.
617 int getLocalSlot(const Value *V);
618 int getGlobalSlot(const GlobalValue *V);
619 int getMetadataSlot(const MDNode *N);
620 int getAttributeGroupSlot(AttributeSet AS);
622 /// If you'd like to deal with a function instead of just a module, use
623 /// this method to get its data into the SlotTracker.
624 void incorporateFunction(const Function *F) {
626 FunctionProcessed = false;
629 const Function *getFunction() const { return TheFunction; }
631 /// After calling incorporateFunction, use this method to remove the
632 /// most recently incorporated function from the SlotTracker. This
633 /// will reset the state of the machine back to just the module contents.
634 void purgeFunction();
636 /// MDNode map iterators.
637 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
638 mdn_iterator mdn_begin() { return mdnMap.begin(); }
639 mdn_iterator mdn_end() { return mdnMap.end(); }
640 unsigned mdn_size() const { return mdnMap.size(); }
641 bool mdn_empty() const { return mdnMap.empty(); }
643 /// AttributeSet map iterators.
644 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
645 as_iterator as_begin() { return asMap.begin(); }
646 as_iterator as_end() { return asMap.end(); }
647 unsigned as_size() const { return asMap.size(); }
648 bool as_empty() const { return asMap.empty(); }
650 /// This function does the actual initialization.
651 inline void initialize();
653 // Implementation Details
655 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
656 void CreateModuleSlot(const GlobalValue *V);
658 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
659 void CreateMetadataSlot(const MDNode *N);
661 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
662 void CreateFunctionSlot(const Value *V);
664 /// \brief Insert the specified AttributeSet into the slot table.
665 void CreateAttributeSetSlot(AttributeSet AS);
667 /// Add all of the module level global variables (and their initializers)
668 /// and function declarations, but not the contents of those functions.
669 void processModule();
671 /// Add all of the functions arguments, basic blocks, and instructions.
672 void processFunction();
674 /// Add all of the metadata from a function.
675 void processFunctionMetadata(const Function &F);
677 /// Add all of the metadata from an instruction.
678 void processInstructionMetadata(const Instruction &I);
680 SlotTracker(const SlotTracker &) = delete;
681 void operator=(const SlotTracker &) = delete;
685 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
687 : M(M), F(F), Machine(&Machine) {}
689 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
690 bool ShouldInitializeAllMetadata)
691 : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
693 M(M), Machine(MachineStorage.get()) {}
695 ModuleSlotTracker::~ModuleSlotTracker() {}
697 void ModuleSlotTracker::incorporateFunction(const Function &F) {
701 // Nothing to do if this is the right function already.
705 Machine->purgeFunction();
706 Machine->incorporateFunction(&F);
710 int ModuleSlotTracker::getLocalSlot(const Value *V) {
711 assert(F && "No function incorporated");
712 return Machine->getLocalSlot(V);
715 static SlotTracker *createSlotTracker(const Value *V) {
716 if (const Argument *FA = dyn_cast<Argument>(V))
717 return new SlotTracker(FA->getParent());
719 if (const Instruction *I = dyn_cast<Instruction>(V))
721 return new SlotTracker(I->getParent()->getParent());
723 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
724 return new SlotTracker(BB->getParent());
726 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
727 return new SlotTracker(GV->getParent());
729 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
730 return new SlotTracker(GA->getParent());
732 if (const Function *Func = dyn_cast<Function>(V))
733 return new SlotTracker(Func);
739 #define ST_DEBUG(X) dbgs() << X
744 // Module level constructor. Causes the contents of the Module (sans functions)
745 // to be added to the slot table.
746 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
747 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
748 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
749 fNext(0), mdnNext(0), asNext(0) {}
751 // Function level constructor. Causes the contents of the Module and the one
752 // function provided to be added to the slot table.
753 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
754 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
755 FunctionProcessed(false),
756 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
757 fNext(0), mdnNext(0), asNext(0) {}
759 inline void SlotTracker::initialize() {
762 TheModule = nullptr; ///< Prevent re-processing next time we're called.
765 if (TheFunction && !FunctionProcessed)
769 // Iterate through all the global variables, functions, and global
770 // variable initializers and create slots for them.
771 void SlotTracker::processModule() {
772 ST_DEBUG("begin processModule!\n");
774 // Add all of the unnamed global variables to the value table.
775 for (const GlobalVariable &Var : TheModule->globals()) {
777 CreateModuleSlot(&Var);
780 for (const GlobalAlias &A : TheModule->aliases()) {
782 CreateModuleSlot(&A);
785 // Add metadata used by named metadata.
786 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
787 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
788 CreateMetadataSlot(NMD.getOperand(i));
791 for (const Function &F : *TheModule) {
793 // Add all the unnamed functions to the table.
794 CreateModuleSlot(&F);
796 if (ShouldInitializeAllMetadata)
797 processFunctionMetadata(F);
799 // Add all the function attributes to the table.
800 // FIXME: Add attributes of other objects?
801 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
802 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
803 CreateAttributeSetSlot(FnAttrs);
806 ST_DEBUG("end processModule!\n");
809 // Process the arguments, basic blocks, and instructions of a function.
810 void SlotTracker::processFunction() {
811 ST_DEBUG("begin processFunction!\n");
814 // Process function metadata if it wasn't hit at the module-level.
815 if (!ShouldInitializeAllMetadata)
816 processFunctionMetadata(*TheFunction);
818 // Add all the function arguments with no names.
819 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
820 AE = TheFunction->arg_end(); AI != AE; ++AI)
822 CreateFunctionSlot(&*AI);
824 ST_DEBUG("Inserting Instructions:\n");
826 // Add all of the basic blocks and instructions with no names.
827 for (auto &BB : *TheFunction) {
829 CreateFunctionSlot(&BB);
832 if (!I.getType()->isVoidTy() && !I.hasName())
833 CreateFunctionSlot(&I);
835 // We allow direct calls to any llvm.foo function here, because the
836 // target may not be linked into the optimizer.
837 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
838 // Add all the call attributes to the table.
839 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
840 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
841 CreateAttributeSetSlot(Attrs);
842 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
843 // Add all the call attributes to the table.
844 AttributeSet Attrs = II->getAttributes().getFnAttributes();
845 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
846 CreateAttributeSetSlot(Attrs);
851 FunctionProcessed = true;
853 ST_DEBUG("end processFunction!\n");
856 void SlotTracker::processFunctionMetadata(const Function &F) {
857 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
858 F.getAllMetadata(MDs);
860 CreateMetadataSlot(MD.second);
864 processInstructionMetadata(I);
868 void SlotTracker::processInstructionMetadata(const Instruction &I) {
869 // Process metadata used directly by intrinsics.
870 if (const CallInst *CI = dyn_cast<CallInst>(&I))
871 if (Function *F = CI->getCalledFunction())
872 if (F->isIntrinsic())
873 for (auto &Op : I.operands())
874 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
875 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
876 CreateMetadataSlot(N);
878 // Process metadata attached to this instruction.
879 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
880 I.getAllMetadata(MDs);
882 CreateMetadataSlot(MD.second);
885 /// Clean up after incorporating a function. This is the only way to get out of
886 /// the function incorporation state that affects get*Slot/Create*Slot. Function
887 /// incorporation state is indicated by TheFunction != 0.
888 void SlotTracker::purgeFunction() {
889 ST_DEBUG("begin purgeFunction!\n");
890 fMap.clear(); // Simply discard the function level map
891 TheFunction = nullptr;
892 FunctionProcessed = false;
893 ST_DEBUG("end purgeFunction!\n");
896 /// getGlobalSlot - Get the slot number of a global value.
897 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
898 // Check for uninitialized state and do lazy initialization.
901 // Find the value in the module map
902 ValueMap::iterator MI = mMap.find(V);
903 return MI == mMap.end() ? -1 : (int)MI->second;
906 /// getMetadataSlot - Get the slot number of a MDNode.
907 int SlotTracker::getMetadataSlot(const MDNode *N) {
908 // Check for uninitialized state and do lazy initialization.
911 // Find the MDNode in the module map
912 mdn_iterator MI = mdnMap.find(N);
913 return MI == mdnMap.end() ? -1 : (int)MI->second;
917 /// getLocalSlot - Get the slot number for a value that is local to a function.
918 int SlotTracker::getLocalSlot(const Value *V) {
919 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
921 // Check for uninitialized state and do lazy initialization.
924 ValueMap::iterator FI = fMap.find(V);
925 return FI == fMap.end() ? -1 : (int)FI->second;
928 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
929 // Check for uninitialized state and do lazy initialization.
932 // Find the AttributeSet in the module map.
933 as_iterator AI = asMap.find(AS);
934 return AI == asMap.end() ? -1 : (int)AI->second;
937 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
938 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
939 assert(V && "Can't insert a null Value into SlotTracker!");
940 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
941 assert(!V->hasName() && "Doesn't need a slot!");
943 unsigned DestSlot = mNext++;
946 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
948 // G = Global, F = Function, A = Alias, o = other
949 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
950 (isa<Function>(V) ? 'F' :
951 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
954 /// CreateSlot - Create a new slot for the specified value if it has no name.
955 void SlotTracker::CreateFunctionSlot(const Value *V) {
956 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
958 unsigned DestSlot = fNext++;
961 // G = Global, F = Function, o = other
962 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
963 DestSlot << " [o]\n");
966 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
967 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
968 assert(N && "Can't insert a null Value into SlotTracker!");
970 unsigned DestSlot = mdnNext;
971 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
975 // Recursively add any MDNodes referenced by operands.
976 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
977 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
978 CreateMetadataSlot(Op);
981 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
982 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
983 "Doesn't need a slot!");
985 as_iterator I = asMap.find(AS);
986 if (I != asMap.end())
989 unsigned DestSlot = asNext++;
990 asMap[AS] = DestSlot;
993 //===----------------------------------------------------------------------===//
994 // AsmWriter Implementation
995 //===----------------------------------------------------------------------===//
997 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
998 TypePrinting *TypePrinter,
999 SlotTracker *Machine,
1000 const Module *Context);
1002 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1003 TypePrinting *TypePrinter,
1004 SlotTracker *Machine, const Module *Context,
1005 bool FromValue = false);
1007 static const char *getPredicateText(unsigned predicate) {
1008 const char * pred = "unknown";
1009 switch (predicate) {
1010 case FCmpInst::FCMP_FALSE: pred = "false"; break;
1011 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
1012 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
1013 case FCmpInst::FCMP_OGE: pred = "oge"; break;
1014 case FCmpInst::FCMP_OLT: pred = "olt"; break;
1015 case FCmpInst::FCMP_OLE: pred = "ole"; break;
1016 case FCmpInst::FCMP_ONE: pred = "one"; break;
1017 case FCmpInst::FCMP_ORD: pred = "ord"; break;
1018 case FCmpInst::FCMP_UNO: pred = "uno"; break;
1019 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
1020 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
1021 case FCmpInst::FCMP_UGE: pred = "uge"; break;
1022 case FCmpInst::FCMP_ULT: pred = "ult"; break;
1023 case FCmpInst::FCMP_ULE: pred = "ule"; break;
1024 case FCmpInst::FCMP_UNE: pred = "une"; break;
1025 case FCmpInst::FCMP_TRUE: pred = "true"; break;
1026 case ICmpInst::ICMP_EQ: pred = "eq"; break;
1027 case ICmpInst::ICMP_NE: pred = "ne"; break;
1028 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
1029 case ICmpInst::ICMP_SGE: pred = "sge"; break;
1030 case ICmpInst::ICMP_SLT: pred = "slt"; break;
1031 case ICmpInst::ICMP_SLE: pred = "sle"; break;
1032 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
1033 case ICmpInst::ICMP_UGE: pred = "uge"; break;
1034 case ICmpInst::ICMP_ULT: pred = "ult"; break;
1035 case ICmpInst::ICMP_ULE: pred = "ule"; break;
1040 static void writeAtomicRMWOperation(raw_ostream &Out,
1041 AtomicRMWInst::BinOp Op) {
1043 default: Out << " <unknown operation " << Op << ">"; break;
1044 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1045 case AtomicRMWInst::Add: Out << " add"; break;
1046 case AtomicRMWInst::Sub: Out << " sub"; break;
1047 case AtomicRMWInst::And: Out << " and"; break;
1048 case AtomicRMWInst::Nand: Out << " nand"; break;
1049 case AtomicRMWInst::Or: Out << " or"; break;
1050 case AtomicRMWInst::Xor: Out << " xor"; break;
1051 case AtomicRMWInst::Max: Out << " max"; break;
1052 case AtomicRMWInst::Min: Out << " min"; break;
1053 case AtomicRMWInst::UMax: Out << " umax"; break;
1054 case AtomicRMWInst::UMin: Out << " umin"; break;
1058 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1059 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1060 // Unsafe algebra implies all the others, no need to write them all out
1061 if (FPO->hasUnsafeAlgebra())
1064 if (FPO->hasNoNaNs())
1066 if (FPO->hasNoInfs())
1068 if (FPO->hasNoSignedZeros())
1070 if (FPO->hasAllowReciprocal())
1075 if (const OverflowingBinaryOperator *OBO =
1076 dyn_cast<OverflowingBinaryOperator>(U)) {
1077 if (OBO->hasNoUnsignedWrap())
1079 if (OBO->hasNoSignedWrap())
1081 } else if (const PossiblyExactOperator *Div =
1082 dyn_cast<PossiblyExactOperator>(U)) {
1085 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1086 if (GEP->isInBounds())
1091 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1092 TypePrinting &TypePrinter,
1093 SlotTracker *Machine,
1094 const Module *Context) {
1095 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1096 if (CI->getType()->isIntegerTy(1)) {
1097 Out << (CI->getZExtValue() ? "true" : "false");
1100 Out << CI->getValue();
1104 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1105 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1106 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1107 // We would like to output the FP constant value in exponential notation,
1108 // but we cannot do this if doing so will lose precision. Check here to
1109 // make sure that we only output it in exponential format if we can parse
1110 // the value back and get the same value.
1113 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1114 bool isInf = CFP->getValueAPF().isInfinity();
1115 bool isNaN = CFP->getValueAPF().isNaN();
1116 if (!isInf && !isNaN) {
1117 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1118 CFP->getValueAPF().convertToFloat();
1119 SmallString<128> StrVal;
1120 raw_svector_ostream(StrVal) << Val;
1122 // Check to make sure that the stringized number is not some string like
1123 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1124 // that the string matches the "[-+]?[0-9]" regex.
1126 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1127 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1128 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1129 // Reparse stringized version!
1130 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1136 // Otherwise we could not reparse it to exactly the same value, so we must
1137 // output the string in hexadecimal format! Note that loading and storing
1138 // floating point types changes the bits of NaNs on some hosts, notably
1139 // x86, so we must not use these types.
1140 static_assert(sizeof(double) == sizeof(uint64_t),
1141 "assuming that double is 64 bits!");
1142 APFloat apf = CFP->getValueAPF();
1143 // Floats are represented in ASCII IR as double, convert.
1145 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1147 Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1151 // Either half, or some form of long double.
1152 // These appear as a magic letter identifying the type, then a
1153 // fixed number of hex digits.
1155 APInt API = CFP->getValueAPF().bitcastToAPInt();
1156 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1158 Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1160 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1163 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1165 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1167 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1169 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1171 Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1173 Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1175 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1177 Out << format_hex_no_prefix(API.getZExtValue(), 4,
1180 llvm_unreachable("Unsupported floating point type");
1184 if (isa<ConstantAggregateZero>(CV)) {
1185 Out << "zeroinitializer";
1189 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1190 Out << "blockaddress(";
1191 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1194 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1200 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1201 Type *ETy = CA->getType()->getElementType();
1203 TypePrinter.print(ETy, Out);
1205 WriteAsOperandInternal(Out, CA->getOperand(0),
1206 &TypePrinter, Machine,
1208 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1210 TypePrinter.print(ETy, Out);
1212 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1219 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1220 // As a special case, print the array as a string if it is an array of
1221 // i8 with ConstantInt values.
1222 if (CA->isString()) {
1224 PrintEscapedString(CA->getAsString(), Out);
1229 Type *ETy = CA->getType()->getElementType();
1231 TypePrinter.print(ETy, Out);
1233 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1234 &TypePrinter, Machine,
1236 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1238 TypePrinter.print(ETy, Out);
1240 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1248 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1249 if (CS->getType()->isPacked())
1252 unsigned N = CS->getNumOperands();
1255 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1258 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1261 for (unsigned i = 1; i < N; i++) {
1263 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1266 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1273 if (CS->getType()->isPacked())
1278 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1279 Type *ETy = CV->getType()->getVectorElementType();
1281 TypePrinter.print(ETy, Out);
1283 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1285 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1287 TypePrinter.print(ETy, Out);
1289 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1296 if (isa<ConstantPointerNull>(CV)) {
1301 if (isa<ConstantTokenNone>(CV)) {
1306 if (isa<UndefValue>(CV)) {
1311 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1312 Out << CE->getOpcodeName();
1313 WriteOptimizationInfo(Out, CE);
1314 if (CE->isCompare())
1315 Out << ' ' << getPredicateText(CE->getPredicate());
1318 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1319 TypePrinter.print(GEP->getSourceElementType(), Out);
1323 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1324 TypePrinter.print((*OI)->getType(), Out);
1326 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1327 if (OI+1 != CE->op_end())
1331 if (CE->hasIndices()) {
1332 ArrayRef<unsigned> Indices = CE->getIndices();
1333 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1334 Out << ", " << Indices[i];
1339 TypePrinter.print(CE->getType(), Out);
1346 Out << "<placeholder or erroneous Constant>";
1349 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1350 TypePrinting *TypePrinter, SlotTracker *Machine,
1351 const Module *Context) {
1353 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1354 const Metadata *MD = Node->getOperand(mi);
1357 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1358 Value *V = MDV->getValue();
1359 TypePrinter->print(V->getType(), Out);
1361 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1363 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1373 struct FieldSeparator {
1376 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1378 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1383 return OS << FS.Sep;
1385 struct MDFieldPrinter {
1388 TypePrinting *TypePrinter;
1389 SlotTracker *Machine;
1390 const Module *Context;
1392 explicit MDFieldPrinter(raw_ostream &Out)
1393 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1394 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1395 SlotTracker *Machine, const Module *Context)
1396 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1398 void printTag(const DINode *N);
1399 void printString(StringRef Name, StringRef Value,
1400 bool ShouldSkipEmpty = true);
1401 void printMetadata(StringRef Name, const Metadata *MD,
1402 bool ShouldSkipNull = true);
1403 template <class IntTy>
1404 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1405 void printBool(StringRef Name, bool Value);
1406 void printDIFlags(StringRef Name, unsigned Flags);
1407 template <class IntTy, class Stringifier>
1408 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1409 bool ShouldSkipZero = true);
1413 void MDFieldPrinter::printTag(const DINode *N) {
1414 Out << FS << "tag: ";
1415 if (const char *Tag = dwarf::TagString(N->getTag()))
1421 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1422 bool ShouldSkipEmpty) {
1423 if (ShouldSkipEmpty && Value.empty())
1426 Out << FS << Name << ": \"";
1427 PrintEscapedString(Value, Out);
1431 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1432 TypePrinting *TypePrinter,
1433 SlotTracker *Machine,
1434 const Module *Context) {
1439 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1442 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1443 bool ShouldSkipNull) {
1444 if (ShouldSkipNull && !MD)
1447 Out << FS << Name << ": ";
1448 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1451 template <class IntTy>
1452 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1453 if (ShouldSkipZero && !Int)
1456 Out << FS << Name << ": " << Int;
1459 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1460 Out << FS << Name << ": " << (Value ? "true" : "false");
1463 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1467 Out << FS << Name << ": ";
1469 SmallVector<unsigned, 8> SplitFlags;
1470 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1472 FieldSeparator FlagsFS(" | ");
1473 for (unsigned F : SplitFlags) {
1474 const char *StringF = DINode::getFlagString(F);
1475 assert(StringF && "Expected valid flag");
1476 Out << FlagsFS << StringF;
1478 if (Extra || SplitFlags.empty())
1479 Out << FlagsFS << Extra;
1482 template <class IntTy, class Stringifier>
1483 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1484 Stringifier toString, bool ShouldSkipZero) {
1488 Out << FS << Name << ": ";
1489 if (const char *S = toString(Value))
1495 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1496 TypePrinting *TypePrinter, SlotTracker *Machine,
1497 const Module *Context) {
1498 Out << "!GenericDINode(";
1499 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1500 Printer.printTag(N);
1501 Printer.printString("header", N->getHeader());
1502 if (N->getNumDwarfOperands()) {
1503 Out << Printer.FS << "operands: {";
1505 for (auto &I : N->dwarf_operands()) {
1507 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1514 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1515 TypePrinting *TypePrinter, SlotTracker *Machine,
1516 const Module *Context) {
1517 Out << "!DILocation(";
1518 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1519 // Always output the line, since 0 is a relevant and important value for it.
1520 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1521 Printer.printInt("column", DL->getColumn());
1522 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1523 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1527 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1528 TypePrinting *, SlotTracker *, const Module *) {
1529 Out << "!DISubrange(";
1530 MDFieldPrinter Printer(Out);
1531 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1532 Printer.printInt("lowerBound", N->getLowerBound());
1536 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1537 TypePrinting *, SlotTracker *, const Module *) {
1538 Out << "!DIEnumerator(";
1539 MDFieldPrinter Printer(Out);
1540 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1541 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1545 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1546 TypePrinting *, SlotTracker *, const Module *) {
1547 Out << "!DIBasicType(";
1548 MDFieldPrinter Printer(Out);
1549 if (N->getTag() != dwarf::DW_TAG_base_type)
1550 Printer.printTag(N);
1551 Printer.printString("name", N->getName());
1552 Printer.printInt("size", N->getSizeInBits());
1553 Printer.printInt("align", N->getAlignInBits());
1554 Printer.printDwarfEnum("encoding", N->getEncoding(),
1555 dwarf::AttributeEncodingString);
1559 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1560 TypePrinting *TypePrinter, SlotTracker *Machine,
1561 const Module *Context) {
1562 Out << "!DIDerivedType(";
1563 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1564 Printer.printTag(N);
1565 Printer.printString("name", N->getName());
1566 Printer.printMetadata("scope", N->getRawScope());
1567 Printer.printMetadata("file", N->getRawFile());
1568 Printer.printInt("line", N->getLine());
1569 Printer.printMetadata("baseType", N->getRawBaseType(),
1570 /* ShouldSkipNull */ false);
1571 Printer.printInt("size", N->getSizeInBits());
1572 Printer.printInt("align", N->getAlignInBits());
1573 Printer.printInt("offset", N->getOffsetInBits());
1574 Printer.printDIFlags("flags", N->getFlags());
1575 Printer.printMetadata("extraData", N->getRawExtraData());
1579 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1580 TypePrinting *TypePrinter,
1581 SlotTracker *Machine, const Module *Context) {
1582 Out << "!DICompositeType(";
1583 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1584 Printer.printTag(N);
1585 Printer.printString("name", N->getName());
1586 Printer.printMetadata("scope", N->getRawScope());
1587 Printer.printMetadata("file", N->getRawFile());
1588 Printer.printInt("line", N->getLine());
1589 Printer.printMetadata("baseType", N->getRawBaseType());
1590 Printer.printInt("size", N->getSizeInBits());
1591 Printer.printInt("align", N->getAlignInBits());
1592 Printer.printInt("offset", N->getOffsetInBits());
1593 Printer.printDIFlags("flags", N->getFlags());
1594 Printer.printMetadata("elements", N->getRawElements());
1595 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1596 dwarf::LanguageString);
1597 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1598 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1599 Printer.printString("identifier", N->getIdentifier());
1603 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1604 TypePrinting *TypePrinter,
1605 SlotTracker *Machine, const Module *Context) {
1606 Out << "!DISubroutineType(";
1607 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1608 Printer.printDIFlags("flags", N->getFlags());
1609 Printer.printMetadata("types", N->getRawTypeArray(),
1610 /* ShouldSkipNull */ false);
1614 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1615 SlotTracker *, const Module *) {
1617 MDFieldPrinter Printer(Out);
1618 Printer.printString("filename", N->getFilename(),
1619 /* ShouldSkipEmpty */ false);
1620 Printer.printString("directory", N->getDirectory(),
1621 /* ShouldSkipEmpty */ false);
1625 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1626 TypePrinting *TypePrinter, SlotTracker *Machine,
1627 const Module *Context) {
1628 Out << "!DICompileUnit(";
1629 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1630 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1631 dwarf::LanguageString, /* ShouldSkipZero */ false);
1632 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1633 Printer.printString("producer", N->getProducer());
1634 Printer.printBool("isOptimized", N->isOptimized());
1635 Printer.printString("flags", N->getFlags());
1636 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1637 /* ShouldSkipZero */ false);
1638 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1639 Printer.printInt("emissionKind", N->getEmissionKind(),
1640 /* ShouldSkipZero */ false);
1641 Printer.printMetadata("enums", N->getRawEnumTypes());
1642 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1643 Printer.printMetadata("subprograms", N->getRawSubprograms());
1644 Printer.printMetadata("globals", N->getRawGlobalVariables());
1645 Printer.printMetadata("imports", N->getRawImportedEntities());
1646 Printer.printInt("dwoId", N->getDWOId());
1650 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1651 TypePrinting *TypePrinter, SlotTracker *Machine,
1652 const Module *Context) {
1653 Out << "!DISubprogram(";
1654 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1655 Printer.printString("name", N->getName());
1656 Printer.printString("linkageName", N->getLinkageName());
1657 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1658 Printer.printMetadata("file", N->getRawFile());
1659 Printer.printInt("line", N->getLine());
1660 Printer.printMetadata("type", N->getRawType());
1661 Printer.printBool("isLocal", N->isLocalToUnit());
1662 Printer.printBool("isDefinition", N->isDefinition());
1663 Printer.printInt("scopeLine", N->getScopeLine());
1664 Printer.printMetadata("containingType", N->getRawContainingType());
1665 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1666 dwarf::VirtualityString);
1667 Printer.printInt("virtualIndex", N->getVirtualIndex());
1668 Printer.printDIFlags("flags", N->getFlags());
1669 Printer.printBool("isOptimized", N->isOptimized());
1670 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1671 Printer.printMetadata("declaration", N->getRawDeclaration());
1672 Printer.printMetadata("variables", N->getRawVariables());
1676 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1677 TypePrinting *TypePrinter, SlotTracker *Machine,
1678 const Module *Context) {
1679 Out << "!DILexicalBlock(";
1680 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1681 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1682 Printer.printMetadata("file", N->getRawFile());
1683 Printer.printInt("line", N->getLine());
1684 Printer.printInt("column", N->getColumn());
1688 static void writeDILexicalBlockFile(raw_ostream &Out,
1689 const DILexicalBlockFile *N,
1690 TypePrinting *TypePrinter,
1691 SlotTracker *Machine,
1692 const Module *Context) {
1693 Out << "!DILexicalBlockFile(";
1694 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1695 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1696 Printer.printMetadata("file", N->getRawFile());
1697 Printer.printInt("discriminator", N->getDiscriminator(),
1698 /* ShouldSkipZero */ false);
1702 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1703 TypePrinting *TypePrinter, SlotTracker *Machine,
1704 const Module *Context) {
1705 Out << "!DINamespace(";
1706 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1707 Printer.printString("name", N->getName());
1708 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1709 Printer.printMetadata("file", N->getRawFile());
1710 Printer.printInt("line", N->getLine());
1714 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1715 TypePrinting *TypePrinter, SlotTracker *Machine,
1716 const Module *Context) {
1717 Out << "!DIModule(";
1718 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1719 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1720 Printer.printString("name", N->getName());
1721 Printer.printString("configMacros", N->getConfigurationMacros());
1722 Printer.printString("includePath", N->getIncludePath());
1723 Printer.printString("isysroot", N->getISysRoot());
1728 static void writeDITemplateTypeParameter(raw_ostream &Out,
1729 const DITemplateTypeParameter *N,
1730 TypePrinting *TypePrinter,
1731 SlotTracker *Machine,
1732 const Module *Context) {
1733 Out << "!DITemplateTypeParameter(";
1734 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1735 Printer.printString("name", N->getName());
1736 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1740 static void writeDITemplateValueParameter(raw_ostream &Out,
1741 const DITemplateValueParameter *N,
1742 TypePrinting *TypePrinter,
1743 SlotTracker *Machine,
1744 const Module *Context) {
1745 Out << "!DITemplateValueParameter(";
1746 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1747 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1748 Printer.printTag(N);
1749 Printer.printString("name", N->getName());
1750 Printer.printMetadata("type", N->getRawType());
1751 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1755 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1756 TypePrinting *TypePrinter,
1757 SlotTracker *Machine, const Module *Context) {
1758 Out << "!DIGlobalVariable(";
1759 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1760 Printer.printString("name", N->getName());
1761 Printer.printString("linkageName", N->getLinkageName());
1762 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1763 Printer.printMetadata("file", N->getRawFile());
1764 Printer.printInt("line", N->getLine());
1765 Printer.printMetadata("type", N->getRawType());
1766 Printer.printBool("isLocal", N->isLocalToUnit());
1767 Printer.printBool("isDefinition", N->isDefinition());
1768 Printer.printMetadata("variable", N->getRawVariable());
1769 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1773 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1774 TypePrinting *TypePrinter,
1775 SlotTracker *Machine, const Module *Context) {
1776 Out << "!DILocalVariable(";
1777 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1778 Printer.printString("name", N->getName());
1779 Printer.printInt("arg", N->getArg());
1780 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1781 Printer.printMetadata("file", N->getRawFile());
1782 Printer.printInt("line", N->getLine());
1783 Printer.printMetadata("type", N->getRawType());
1784 Printer.printDIFlags("flags", N->getFlags());
1788 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1789 TypePrinting *TypePrinter, SlotTracker *Machine,
1790 const Module *Context) {
1791 Out << "!DIExpression(";
1794 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1795 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1796 assert(OpStr && "Expected valid opcode");
1799 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1800 Out << FS << I->getArg(A);
1803 for (const auto &I : N->getElements())
1809 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1810 TypePrinting *TypePrinter, SlotTracker *Machine,
1811 const Module *Context) {
1812 Out << "!DIObjCProperty(";
1813 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1814 Printer.printString("name", N->getName());
1815 Printer.printMetadata("file", N->getRawFile());
1816 Printer.printInt("line", N->getLine());
1817 Printer.printString("setter", N->getSetterName());
1818 Printer.printString("getter", N->getGetterName());
1819 Printer.printInt("attributes", N->getAttributes());
1820 Printer.printMetadata("type", N->getRawType());
1824 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1825 TypePrinting *TypePrinter,
1826 SlotTracker *Machine, const Module *Context) {
1827 Out << "!DIImportedEntity(";
1828 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1829 Printer.printTag(N);
1830 Printer.printString("name", N->getName());
1831 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1832 Printer.printMetadata("entity", N->getRawEntity());
1833 Printer.printInt("line", N->getLine());
1838 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1839 TypePrinting *TypePrinter,
1840 SlotTracker *Machine,
1841 const Module *Context) {
1842 if (Node->isDistinct())
1844 else if (Node->isTemporary())
1845 Out << "<temporary!> "; // Handle broken code.
1847 switch (Node->getMetadataID()) {
1849 llvm_unreachable("Expected uniquable MDNode");
1850 #define HANDLE_MDNODE_LEAF(CLASS) \
1851 case Metadata::CLASS##Kind: \
1852 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1854 #include "llvm/IR/Metadata.def"
1858 // Full implementation of printing a Value as an operand with support for
1859 // TypePrinting, etc.
1860 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1861 TypePrinting *TypePrinter,
1862 SlotTracker *Machine,
1863 const Module *Context) {
1865 PrintLLVMName(Out, V);
1869 const Constant *CV = dyn_cast<Constant>(V);
1870 if (CV && !isa<GlobalValue>(CV)) {
1871 assert(TypePrinter && "Constants require TypePrinting!");
1872 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1876 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1878 if (IA->hasSideEffects())
1879 Out << "sideeffect ";
1880 if (IA->isAlignStack())
1881 Out << "alignstack ";
1882 // We don't emit the AD_ATT dialect as it's the assumed default.
1883 if (IA->getDialect() == InlineAsm::AD_Intel)
1884 Out << "inteldialect ";
1886 PrintEscapedString(IA->getAsmString(), Out);
1888 PrintEscapedString(IA->getConstraintString(), Out);
1893 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1894 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1895 Context, /* FromValue */ true);
1901 // If we have a SlotTracker, use it.
1903 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1904 Slot = Machine->getGlobalSlot(GV);
1907 Slot = Machine->getLocalSlot(V);
1909 // If the local value didn't succeed, then we may be referring to a value
1910 // from a different function. Translate it, as this can happen when using
1911 // address of blocks.
1913 if ((Machine = createSlotTracker(V))) {
1914 Slot = Machine->getLocalSlot(V);
1918 } else if ((Machine = createSlotTracker(V))) {
1919 // Otherwise, create one to get the # and then destroy it.
1920 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1921 Slot = Machine->getGlobalSlot(GV);
1924 Slot = Machine->getLocalSlot(V);
1933 Out << Prefix << Slot;
1938 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1939 TypePrinting *TypePrinter,
1940 SlotTracker *Machine, const Module *Context,
1942 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1943 std::unique_ptr<SlotTracker> MachineStorage;
1945 MachineStorage = make_unique<SlotTracker>(Context);
1946 Machine = MachineStorage.get();
1948 int Slot = Machine->getMetadataSlot(N);
1950 // Give the pointer value instead of "badref", since this comes up all
1951 // the time when debugging.
1952 Out << "<" << N << ">";
1958 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1960 PrintEscapedString(MDS->getString(), Out);
1965 auto *V = cast<ValueAsMetadata>(MD);
1966 assert(TypePrinter && "TypePrinter required for metadata values");
1967 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1968 "Unexpected function-local metadata outside of value argument");
1970 TypePrinter->print(V->getValue()->getType(), Out);
1972 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
1976 class AssemblyWriter {
1977 formatted_raw_ostream &Out;
1978 const Module *TheModule;
1979 std::unique_ptr<SlotTracker> SlotTrackerStorage;
1980 SlotTracker &Machine;
1981 TypePrinting TypePrinter;
1982 AssemblyAnnotationWriter *AnnotationWriter;
1983 SetVector<const Comdat *> Comdats;
1985 bool ShouldPreserveUseListOrder;
1986 UseListOrderStack UseListOrders;
1987 SmallVector<StringRef, 8> MDNames;
1990 /// Construct an AssemblyWriter with an external SlotTracker
1991 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
1992 AssemblyAnnotationWriter *AAW, bool IsForDebug,
1993 bool ShouldPreserveUseListOrder = false);
1995 void printMDNodeBody(const MDNode *MD);
1996 void printNamedMDNode(const NamedMDNode *NMD);
1998 void printModule(const Module *M);
2000 void writeOperand(const Value *Op, bool PrintType);
2001 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2002 void writeOperandBundles(ImmutableCallSite CS);
2003 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2004 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2005 AtomicOrdering FailureOrdering,
2006 SynchronizationScope SynchScope);
2008 void writeAllMDNodes();
2009 void writeMDNode(unsigned Slot, const MDNode *Node);
2010 void writeAllAttributeGroups();
2012 void printTypeIdentities();
2013 void printGlobal(const GlobalVariable *GV);
2014 void printAlias(const GlobalAlias *GV);
2015 void printComdat(const Comdat *C);
2016 void printFunction(const Function *F);
2017 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2018 void printBasicBlock(const BasicBlock *BB);
2019 void printInstructionLine(const Instruction &I);
2020 void printInstruction(const Instruction &I);
2022 void printUseListOrder(const UseListOrder &Order);
2023 void printUseLists(const Function *F);
2026 /// \brief Print out metadata attachments.
2027 void printMetadataAttachments(
2028 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2029 StringRef Separator);
2031 // printInfoComment - Print a little comment after the instruction indicating
2032 // which slot it occupies.
2033 void printInfoComment(const Value &V);
2035 // printGCRelocateComment - print comment after call to the gc.relocate
2036 // intrinsic indicating base and derived pointer names.
2037 void printGCRelocateComment(const Value &V);
2041 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2042 const Module *M, AssemblyAnnotationWriter *AAW,
2043 bool IsForDebug, bool ShouldPreserveUseListOrder)
2044 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2045 IsForDebug(IsForDebug),
2046 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2049 TypePrinter.incorporateTypes(*TheModule);
2050 for (const Function &F : *TheModule)
2051 if (const Comdat *C = F.getComdat())
2053 for (const GlobalVariable &GV : TheModule->globals())
2054 if (const Comdat *C = GV.getComdat())
2058 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2060 Out << "<null operand!>";
2064 TypePrinter.print(Operand->getType(), Out);
2067 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2070 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2071 SynchronizationScope SynchScope) {
2072 if (Ordering == NotAtomic)
2075 switch (SynchScope) {
2076 case SingleThread: Out << " singlethread"; break;
2077 case CrossThread: break;
2081 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2082 case Unordered: Out << " unordered"; break;
2083 case Monotonic: Out << " monotonic"; break;
2084 case Acquire: Out << " acquire"; break;
2085 case Release: Out << " release"; break;
2086 case AcquireRelease: Out << " acq_rel"; break;
2087 case SequentiallyConsistent: Out << " seq_cst"; break;
2091 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2092 AtomicOrdering FailureOrdering,
2093 SynchronizationScope SynchScope) {
2094 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2096 switch (SynchScope) {
2097 case SingleThread: Out << " singlethread"; break;
2098 case CrossThread: break;
2101 switch (SuccessOrdering) {
2102 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2103 case Unordered: Out << " unordered"; break;
2104 case Monotonic: Out << " monotonic"; break;
2105 case Acquire: Out << " acquire"; break;
2106 case Release: Out << " release"; break;
2107 case AcquireRelease: Out << " acq_rel"; break;
2108 case SequentiallyConsistent: Out << " seq_cst"; break;
2111 switch (FailureOrdering) {
2112 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2113 case Unordered: Out << " unordered"; break;
2114 case Monotonic: Out << " monotonic"; break;
2115 case Acquire: Out << " acquire"; break;
2116 case Release: Out << " release"; break;
2117 case AcquireRelease: Out << " acq_rel"; break;
2118 case SequentiallyConsistent: Out << " seq_cst"; break;
2122 void AssemblyWriter::writeParamOperand(const Value *Operand,
2123 AttributeSet Attrs, unsigned Idx) {
2125 Out << "<null operand!>";
2130 TypePrinter.print(Operand->getType(), Out);
2131 // Print parameter attributes list
2132 if (Attrs.hasAttributes(Idx))
2133 Out << ' ' << Attrs.getAsString(Idx);
2135 // Print the operand
2136 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2139 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2140 if (!CS.hasOperandBundles())
2145 bool FirstBundle = true;
2146 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2147 OperandBundleUse BU = CS.getOperandBundleAt(i);
2151 FirstBundle = false;
2154 PrintEscapedString(BU.getTagName(), Out);
2159 bool FirstInput = true;
2160 for (const auto &Input : BU.Inputs) {
2165 TypePrinter.print(Input->getType(), Out);
2167 WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2176 void AssemblyWriter::printModule(const Module *M) {
2177 Machine.initialize();
2179 if (ShouldPreserveUseListOrder)
2180 UseListOrders = predictUseListOrder(M);
2182 if (!M->getModuleIdentifier().empty() &&
2183 // Don't print the ID if it will start a new line (which would
2184 // require a comment char before it).
2185 M->getModuleIdentifier().find('\n') == std::string::npos)
2186 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2188 const std::string &DL = M->getDataLayoutStr();
2190 Out << "target datalayout = \"" << DL << "\"\n";
2191 if (!M->getTargetTriple().empty())
2192 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2194 if (!M->getModuleInlineAsm().empty()) {
2197 // Split the string into lines, to make it easier to read the .ll file.
2198 StringRef Asm = M->getModuleInlineAsm();
2201 std::tie(Front, Asm) = Asm.split('\n');
2203 // We found a newline, print the portion of the asm string from the
2204 // last newline up to this newline.
2205 Out << "module asm \"";
2206 PrintEscapedString(Front, Out);
2208 } while (!Asm.empty());
2211 printTypeIdentities();
2213 // Output all comdats.
2214 if (!Comdats.empty())
2216 for (const Comdat *C : Comdats) {
2218 if (C != Comdats.back())
2222 // Output all globals.
2223 if (!M->global_empty()) Out << '\n';
2224 for (const GlobalVariable &GV : M->globals()) {
2225 printGlobal(&GV); Out << '\n';
2228 // Output all aliases.
2229 if (!M->alias_empty()) Out << "\n";
2230 for (const GlobalAlias &GA : M->aliases())
2233 // Output global use-lists.
2234 printUseLists(nullptr);
2236 // Output all of the functions.
2237 for (const Function &F : *M)
2239 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2241 // Output all attribute groups.
2242 if (!Machine.as_empty()) {
2244 writeAllAttributeGroups();
2247 // Output named metadata.
2248 if (!M->named_metadata_empty()) Out << '\n';
2250 for (const NamedMDNode &Node : M->named_metadata())
2251 printNamedMDNode(&Node);
2254 if (!Machine.mdn_empty()) {
2260 static void printMetadataIdentifier(StringRef Name,
2261 formatted_raw_ostream &Out) {
2263 Out << "<empty name> ";
2265 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2266 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2269 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2270 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2271 unsigned char C = Name[i];
2272 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2273 C == '.' || C == '_')
2276 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2281 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2283 printMetadataIdentifier(NMD->getName(), Out);
2285 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2288 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2297 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2298 formatted_raw_ostream &Out) {
2300 case GlobalValue::ExternalLinkage: break;
2301 case GlobalValue::PrivateLinkage: Out << "private "; break;
2302 case GlobalValue::InternalLinkage: Out << "internal "; break;
2303 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2304 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2305 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2306 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2307 case GlobalValue::CommonLinkage: Out << "common "; break;
2308 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2309 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2310 case GlobalValue::AvailableExternallyLinkage:
2311 Out << "available_externally ";
2316 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2317 formatted_raw_ostream &Out) {
2319 case GlobalValue::DefaultVisibility: break;
2320 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2321 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2325 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2326 formatted_raw_ostream &Out) {
2328 case GlobalValue::DefaultStorageClass: break;
2329 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2330 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2334 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2335 formatted_raw_ostream &Out) {
2337 case GlobalVariable::NotThreadLocal:
2339 case GlobalVariable::GeneralDynamicTLSModel:
2340 Out << "thread_local ";
2342 case GlobalVariable::LocalDynamicTLSModel:
2343 Out << "thread_local(localdynamic) ";
2345 case GlobalVariable::InitialExecTLSModel:
2346 Out << "thread_local(initialexec) ";
2348 case GlobalVariable::LocalExecTLSModel:
2349 Out << "thread_local(localexec) ";
2354 static void maybePrintComdat(formatted_raw_ostream &Out,
2355 const GlobalObject &GO) {
2356 const Comdat *C = GO.getComdat();
2360 if (isa<GlobalVariable>(GO))
2364 if (GO.getName() == C->getName())
2368 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2372 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2373 if (GV->isMaterializable())
2374 Out << "; Materializable\n";
2376 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2379 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2382 PrintLinkage(GV->getLinkage(), Out);
2383 PrintVisibility(GV->getVisibility(), Out);
2384 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2385 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2386 if (GV->hasUnnamedAddr())
2387 Out << "unnamed_addr ";
2389 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2390 Out << "addrspace(" << AddressSpace << ") ";
2391 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2392 Out << (GV->isConstant() ? "constant " : "global ");
2393 TypePrinter.print(GV->getType()->getElementType(), Out);
2395 if (GV->hasInitializer()) {
2397 writeOperand(GV->getInitializer(), false);
2400 if (GV->hasSection()) {
2401 Out << ", section \"";
2402 PrintEscapedString(GV->getSection(), Out);
2405 maybePrintComdat(Out, *GV);
2406 if (GV->getAlignment())
2407 Out << ", align " << GV->getAlignment();
2409 printInfoComment(*GV);
2412 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2413 if (GA->isMaterializable())
2414 Out << "; Materializable\n";
2416 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2419 PrintLinkage(GA->getLinkage(), Out);
2420 PrintVisibility(GA->getVisibility(), Out);
2421 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2422 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2423 if (GA->hasUnnamedAddr())
2424 Out << "unnamed_addr ";
2428 TypePrinter.print(GA->getValueType(), Out);
2432 const Constant *Aliasee = GA->getAliasee();
2435 TypePrinter.print(GA->getType(), Out);
2436 Out << " <<NULL ALIASEE>>";
2438 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2441 printInfoComment(*GA);
2445 void AssemblyWriter::printComdat(const Comdat *C) {
2449 void AssemblyWriter::printTypeIdentities() {
2450 if (TypePrinter.NumberedTypes.empty() &&
2451 TypePrinter.NamedTypes.empty())
2456 // We know all the numbers that each type is used and we know that it is a
2457 // dense assignment. Convert the map to an index table.
2458 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2459 for (DenseMap<StructType*, unsigned>::iterator I =
2460 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2462 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2463 NumberedTypes[I->second] = I->first;
2466 // Emit all numbered types.
2467 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2468 Out << '%' << i << " = type ";
2470 // Make sure we print out at least one level of the type structure, so
2471 // that we do not get %2 = type %2
2472 TypePrinter.printStructBody(NumberedTypes[i], Out);
2476 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2477 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2480 // Make sure we print out at least one level of the type structure, so
2481 // that we do not get %FILE = type %FILE
2482 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2487 /// printFunction - Print all aspects of a function.
2489 void AssemblyWriter::printFunction(const Function *F) {
2490 // Print out the return type and name.
2493 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2495 if (F->isMaterializable())
2496 Out << "; Materializable\n";
2498 const AttributeSet &Attrs = F->getAttributes();
2499 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2500 AttributeSet AS = Attrs.getFnAttributes();
2501 std::string AttrStr;
2504 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2505 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2508 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2510 Attribute Attr = *I;
2511 if (!Attr.isStringAttribute()) {
2512 if (!AttrStr.empty()) AttrStr += ' ';
2513 AttrStr += Attr.getAsString();
2517 if (!AttrStr.empty())
2518 Out << "; Function Attrs: " << AttrStr << '\n';
2521 if (F->isDeclaration())
2526 PrintLinkage(F->getLinkage(), Out);
2527 PrintVisibility(F->getVisibility(), Out);
2528 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2530 // Print the calling convention.
2531 if (F->getCallingConv() != CallingConv::C) {
2532 PrintCallingConv(F->getCallingConv(), Out);
2536 FunctionType *FT = F->getFunctionType();
2537 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2538 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2539 TypePrinter.print(F->getReturnType(), Out);
2541 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2543 Machine.incorporateFunction(F);
2545 // Loop over the arguments, printing them...
2546 if (F->isDeclaration() && !IsForDebug) {
2547 // We're only interested in the type here - don't print argument names.
2548 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2549 // Insert commas as we go... the first arg doesn't get a comma
2553 TypePrinter.print(FT->getParamType(I), Out);
2555 if (Attrs.hasAttributes(I + 1))
2556 Out << ' ' << Attrs.getAsString(I + 1);
2559 // The arguments are meaningful here, print them in detail.
2561 for (const Argument &Arg : F->args()) {
2562 // Insert commas as we go... the first arg doesn't get a comma
2565 printArgument(&Arg, Attrs, Idx++);
2569 // Finish printing arguments...
2570 if (FT->isVarArg()) {
2571 if (FT->getNumParams()) Out << ", ";
2572 Out << "..."; // Output varargs portion of signature!
2575 if (F->hasUnnamedAddr())
2576 Out << " unnamed_addr";
2577 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2578 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2579 if (F->hasSection()) {
2580 Out << " section \"";
2581 PrintEscapedString(F->getSection(), Out);
2584 maybePrintComdat(Out, *F);
2585 if (F->getAlignment())
2586 Out << " align " << F->getAlignment();
2588 Out << " gc \"" << F->getGC() << '"';
2589 if (F->hasPrefixData()) {
2591 writeOperand(F->getPrefixData(), true);
2593 if (F->hasPrologueData()) {
2594 Out << " prologue ";
2595 writeOperand(F->getPrologueData(), true);
2597 if (F->hasPersonalityFn()) {
2598 Out << " personality ";
2599 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2602 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2603 F->getAllMetadata(MDs);
2604 printMetadataAttachments(MDs, " ");
2606 if (F->isDeclaration()) {
2610 // Output all of the function's basic blocks.
2611 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2612 printBasicBlock(&*I);
2614 // Output the function's use-lists.
2620 Machine.purgeFunction();
2623 /// printArgument - This member is called for every argument that is passed into
2624 /// the function. Simply print it out
2626 void AssemblyWriter::printArgument(const Argument *Arg,
2627 AttributeSet Attrs, unsigned Idx) {
2629 TypePrinter.print(Arg->getType(), Out);
2631 // Output parameter attributes list
2632 if (Attrs.hasAttributes(Idx))
2633 Out << ' ' << Attrs.getAsString(Idx);
2635 // Output name, if available...
2636 if (Arg->hasName()) {
2638 PrintLLVMName(Out, Arg);
2642 /// printBasicBlock - This member is called for each basic block in a method.
2644 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2645 if (BB->hasName()) { // Print out the label if it exists...
2647 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2649 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2650 Out << "\n; <label>:";
2651 int Slot = Machine.getLocalSlot(BB);
2658 if (!BB->getParent()) {
2659 Out.PadToColumn(50);
2660 Out << "; Error: Block without parent!";
2661 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2662 // Output predecessors for the block.
2663 Out.PadToColumn(50);
2665 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2668 Out << " No predecessors!";
2671 writeOperand(*PI, false);
2672 for (++PI; PI != PE; ++PI) {
2674 writeOperand(*PI, false);
2681 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2683 // Output all of the instructions in the basic block...
2684 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2685 printInstructionLine(*I);
2688 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2691 /// printInstructionLine - Print an instruction and a newline character.
2692 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2693 printInstruction(I);
2697 /// printGCRelocateComment - print comment after call to the gc.relocate
2698 /// intrinsic indicating base and derived pointer names.
2699 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2700 assert(isGCRelocate(&V));
2701 GCRelocateOperands GCOps(cast<Instruction>(&V));
2704 writeOperand(GCOps.getBasePtr(), false);
2706 writeOperand(GCOps.getDerivedPtr(), false);
2710 /// printInfoComment - Print a little comment after the instruction indicating
2711 /// which slot it occupies.
2713 void AssemblyWriter::printInfoComment(const Value &V) {
2714 if (isGCRelocate(&V))
2715 printGCRelocateComment(V);
2717 if (AnnotationWriter)
2718 AnnotationWriter->printInfoComment(V, Out);
2721 // This member is called for each Instruction in a function..
2722 void AssemblyWriter::printInstruction(const Instruction &I) {
2723 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2725 // Print out indentation for an instruction.
2728 // Print out name if it exists...
2730 PrintLLVMName(Out, &I);
2732 } else if (!I.getType()->isVoidTy()) {
2733 // Print out the def slot taken.
2734 int SlotNum = Machine.getLocalSlot(&I);
2736 Out << "<badref> = ";
2738 Out << '%' << SlotNum << " = ";
2741 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2742 if (CI->isMustTailCall())
2744 else if (CI->isTailCall())
2746 else if (CI->isNoTailCall())
2750 // Print out the opcode...
2751 Out << I.getOpcodeName();
2753 // If this is an atomic load or store, print out the atomic marker.
2754 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2755 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2758 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2761 // If this is a volatile operation, print out the volatile marker.
2762 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2763 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2764 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2765 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2768 // Print out optimization information.
2769 WriteOptimizationInfo(Out, &I);
2771 // Print out the compare instruction predicates
2772 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2773 Out << ' ' << getPredicateText(CI->getPredicate());
2775 // Print out the atomicrmw operation
2776 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2777 writeAtomicRMWOperation(Out, RMWI->getOperation());
2779 // Print out the type of the operands...
2780 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2782 // Special case conditional branches to swizzle the condition out to the front
2783 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2784 const BranchInst &BI(cast<BranchInst>(I));
2786 writeOperand(BI.getCondition(), true);
2788 writeOperand(BI.getSuccessor(0), true);
2790 writeOperand(BI.getSuccessor(1), true);
2792 } else if (isa<SwitchInst>(I)) {
2793 const SwitchInst& SI(cast<SwitchInst>(I));
2794 // Special case switch instruction to get formatting nice and correct.
2796 writeOperand(SI.getCondition(), true);
2798 writeOperand(SI.getDefaultDest(), true);
2800 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2803 writeOperand(i.getCaseValue(), true);
2805 writeOperand(i.getCaseSuccessor(), true);
2808 } else if (isa<IndirectBrInst>(I)) {
2809 // Special case indirectbr instruction to get formatting nice and correct.
2811 writeOperand(Operand, true);
2814 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2817 writeOperand(I.getOperand(i), true);
2820 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2822 TypePrinter.print(I.getType(), Out);
2825 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2826 if (op) Out << ", ";
2828 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2829 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2831 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2833 writeOperand(I.getOperand(0), true);
2834 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2836 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2838 writeOperand(I.getOperand(0), true); Out << ", ";
2839 writeOperand(I.getOperand(1), true);
2840 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2842 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2844 TypePrinter.print(I.getType(), Out);
2845 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2848 if (LPI->isCleanup())
2851 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2852 if (i != 0 || LPI->isCleanup()) Out << "\n";
2853 if (LPI->isCatch(i))
2858 writeOperand(LPI->getClause(i), true);
2860 } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2862 for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps;
2866 writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true);
2869 writeOperand(CPI->getNormalDest(), /*PrintType=*/true);
2871 writeOperand(CPI->getUnwindDest(), /*PrintType=*/true);
2872 } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) {
2874 for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps;
2878 writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true);
2881 if (TPI->hasUnwindDest())
2882 writeOperand(TPI->getUnwindDest(), /*PrintType=*/true);
2885 } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) {
2887 for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) {
2890 writeOperand(CPI->getOperand(Op), /*PrintType=*/true);
2893 } else if (isa<ReturnInst>(I) && !Operand) {
2895 } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2897 writeOperand(CRI->getCatchPad(), /*PrintType=*/false);
2900 writeOperand(CRI->getSuccessor(), /*PrintType=*/true);
2901 } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2903 writeOperand(CRI->getCleanupPad(), /*PrintType=*/false);
2906 if (CRI->hasUnwindDest())
2907 writeOperand(CRI->getUnwindDest(), /*PrintType=*/true);
2910 } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) {
2912 if (CEPI->hasUnwindDest())
2913 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2916 } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) {
2918 writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false);
2921 if (CEPI->hasUnwindDest())
2922 writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2925 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2926 // Print the calling convention being used.
2927 if (CI->getCallingConv() != CallingConv::C) {
2929 PrintCallingConv(CI->getCallingConv(), Out);
2932 Operand = CI->getCalledValue();
2933 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2934 Type *RetTy = FTy->getReturnType();
2935 const AttributeSet &PAL = CI->getAttributes();
2937 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2938 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2940 // If possible, print out the short form of the call instruction. We can
2941 // only do this if the first argument is a pointer to a nonvararg function,
2942 // and if the return type is not a pointer to a function.
2945 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2947 writeOperand(Operand, false);
2949 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2952 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2955 // Emit an ellipsis if this is a musttail call in a vararg function. This
2956 // is only to aid readability, musttail calls forward varargs by default.
2957 if (CI->isMustTailCall() && CI->getParent() &&
2958 CI->getParent()->getParent() &&
2959 CI->getParent()->getParent()->isVarArg())
2963 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2964 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2966 writeOperandBundles(CI);
2968 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2969 Operand = II->getCalledValue();
2970 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
2971 Type *RetTy = FTy->getReturnType();
2972 const AttributeSet &PAL = II->getAttributes();
2974 // Print the calling convention being used.
2975 if (II->getCallingConv() != CallingConv::C) {
2977 PrintCallingConv(II->getCallingConv(), Out);
2980 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2981 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2983 // If possible, print out the short form of the invoke instruction. We can
2984 // only do this if the first argument is a pointer to a nonvararg function,
2985 // and if the return type is not a pointer to a function.
2988 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2990 writeOperand(Operand, false);
2992 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2995 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
2999 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
3000 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3002 writeOperandBundles(II);
3005 writeOperand(II->getNormalDest(), true);
3007 writeOperand(II->getUnwindDest(), true);
3009 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3011 if (AI->isUsedWithInAlloca())
3013 TypePrinter.print(AI->getAllocatedType(), Out);
3015 // Explicitly write the array size if the code is broken, if it's an array
3016 // allocation, or if the type is not canonical for scalar allocations. The
3017 // latter case prevents the type from mutating when round-tripping through
3019 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3020 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3022 writeOperand(AI->getArraySize(), true);
3024 if (AI->getAlignment()) {
3025 Out << ", align " << AI->getAlignment();
3027 } else if (isa<CastInst>(I)) {
3030 writeOperand(Operand, true); // Work with broken code
3033 TypePrinter.print(I.getType(), Out);
3034 } else if (isa<VAArgInst>(I)) {
3037 writeOperand(Operand, true); // Work with broken code
3040 TypePrinter.print(I.getType(), Out);
3041 } else if (Operand) { // Print the normal way.
3042 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3044 TypePrinter.print(GEP->getSourceElementType(), Out);
3046 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3048 TypePrinter.print(LI->getType(), Out);
3052 // PrintAllTypes - Instructions who have operands of all the same type
3053 // omit the type from all but the first operand. If the instruction has
3054 // different type operands (for example br), then they are all printed.
3055 bool PrintAllTypes = false;
3056 Type *TheType = Operand->getType();
3058 // Select, Store and ShuffleVector always print all types.
3059 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3060 || isa<ReturnInst>(I)) {
3061 PrintAllTypes = true;
3063 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3064 Operand = I.getOperand(i);
3065 // note that Operand shouldn't be null, but the test helps make dump()
3066 // more tolerant of malformed IR
3067 if (Operand && Operand->getType() != TheType) {
3068 PrintAllTypes = true; // We have differing types! Print them all!
3074 if (!PrintAllTypes) {
3076 TypePrinter.print(TheType, Out);
3080 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3082 writeOperand(I.getOperand(i), PrintAllTypes);
3086 // Print atomic ordering/alignment for memory operations
3087 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3089 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3090 if (LI->getAlignment())
3091 Out << ", align " << LI->getAlignment();
3092 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3094 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3095 if (SI->getAlignment())
3096 Out << ", align " << SI->getAlignment();
3097 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3098 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3099 CXI->getSynchScope());
3100 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3101 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3102 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3103 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3106 // Print Metadata info.
3107 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3108 I.getAllMetadata(InstMD);
3109 printMetadataAttachments(InstMD, ", ");
3111 // Print a nice comment.
3112 printInfoComment(I);
3115 void AssemblyWriter::printMetadataAttachments(
3116 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3117 StringRef Separator) {
3121 if (MDNames.empty())
3122 TheModule->getMDKindNames(MDNames);
3124 for (const auto &I : MDs) {
3125 unsigned Kind = I.first;
3127 if (Kind < MDNames.size()) {
3129 printMetadataIdentifier(MDNames[Kind], Out);
3131 Out << "!<unknown kind #" << Kind << ">";
3133 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3137 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3138 Out << '!' << Slot << " = ";
3139 printMDNodeBody(Node);
3143 void AssemblyWriter::writeAllMDNodes() {
3144 SmallVector<const MDNode *, 16> Nodes;
3145 Nodes.resize(Machine.mdn_size());
3146 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3148 Nodes[I->second] = cast<MDNode>(I->first);
3150 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3151 writeMDNode(i, Nodes[i]);
3155 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3156 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3159 void AssemblyWriter::writeAllAttributeGroups() {
3160 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3161 asVec.resize(Machine.as_size());
3163 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3165 asVec[I->second] = *I;
3167 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3168 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3169 Out << "attributes #" << I->second << " = { "
3170 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3173 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3174 bool IsInFunction = Machine.getFunction();
3178 Out << "uselistorder";
3179 if (const BasicBlock *BB =
3180 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3182 writeOperand(BB->getParent(), false);
3184 writeOperand(BB, false);
3187 writeOperand(Order.V, true);
3191 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3192 Out << Order.Shuffle[0];
3193 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3194 Out << ", " << Order.Shuffle[I];
3198 void AssemblyWriter::printUseLists(const Function *F) {
3200 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3205 Out << "\n; uselistorder directives\n";
3207 printUseListOrder(UseListOrders.back());
3208 UseListOrders.pop_back();
3212 //===----------------------------------------------------------------------===//
3213 // External Interface declarations
3214 //===----------------------------------------------------------------------===//
3216 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3217 bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3218 SlotTracker SlotTable(this);
3219 formatted_raw_ostream OS(ROS);
3220 AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3221 ShouldPreserveUseListOrder);
3222 W.printModule(this);
3225 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3226 SlotTracker SlotTable(getParent());
3227 formatted_raw_ostream OS(ROS);
3228 AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3229 W.printNamedMDNode(this);
3232 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3233 PrintLLVMName(ROS, getName(), ComdatPrefix);
3234 ROS << " = comdat ";
3236 switch (getSelectionKind()) {
3240 case Comdat::ExactMatch:
3241 ROS << "exactmatch";
3243 case Comdat::Largest:
3246 case Comdat::NoDuplicates:
3247 ROS << "noduplicates";
3249 case Comdat::SameSize:
3257 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3259 TP.print(const_cast<Type*>(this), OS);
3261 // If the type is a named struct type, print the body as well.
3262 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3263 if (!STy->isLiteral()) {
3265 TP.printStructBody(STy, OS);
3269 static bool isReferencingMDNode(const Instruction &I) {
3270 if (const auto *CI = dyn_cast<CallInst>(&I))
3271 if (Function *F = CI->getCalledFunction())
3272 if (F->isIntrinsic())
3273 for (auto &Op : I.operands())
3274 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3275 if (isa<MDNode>(V->getMetadata()))
3280 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3281 bool ShouldInitializeAllMetadata = false;
3282 if (auto *I = dyn_cast<Instruction>(this))
3283 ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3284 else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3285 ShouldInitializeAllMetadata = true;
3287 ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3288 print(ROS, MST, IsForDebug);
3291 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3292 bool IsForDebug) const {
3293 formatted_raw_ostream OS(ROS);
3294 SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3295 SlotTracker &SlotTable =
3296 MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3297 auto incorporateFunction = [&](const Function *F) {
3299 MST.incorporateFunction(*F);
3302 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3303 incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3304 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3305 W.printInstruction(*I);
3306 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3307 incorporateFunction(BB->getParent());
3308 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3309 W.printBasicBlock(BB);
3310 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3311 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3312 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3314 else if (const Function *F = dyn_cast<Function>(GV))
3317 W.printAlias(cast<GlobalAlias>(GV));
3318 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3319 V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3320 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3321 TypePrinting TypePrinter;
3322 TypePrinter.print(C->getType(), OS);
3324 WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3325 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3326 this->printAsOperand(OS, /* PrintType */ true, MST);
3328 llvm_unreachable("Unknown value to print out!");
3332 /// Print without a type, skipping the TypePrinting object.
3334 /// \return \c true iff printing was successful.
3335 static bool printWithoutType(const Value &V, raw_ostream &O,
3336 SlotTracker *Machine, const Module *M) {
3337 if (V.hasName() || isa<GlobalValue>(V) ||
3338 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3339 WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3345 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3346 ModuleSlotTracker &MST) {
3347 TypePrinting TypePrinter;
3348 if (const Module *M = MST.getModule())
3349 TypePrinter.incorporateTypes(*M);
3351 TypePrinter.print(V.getType(), O);
3355 WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3359 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3360 const Module *M) const {
3362 M = getModuleFromVal(this);
3365 if (printWithoutType(*this, O, nullptr, M))
3368 SlotTracker Machine(
3369 M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3370 ModuleSlotTracker MST(Machine, M);
3371 printAsOperandImpl(*this, O, PrintType, MST);
3374 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3375 ModuleSlotTracker &MST) const {
3377 if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3380 printAsOperandImpl(*this, O, PrintType, MST);
3383 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3384 ModuleSlotTracker &MST, const Module *M,
3385 bool OnlyAsOperand) {
3386 formatted_raw_ostream OS(ROS);
3388 TypePrinting TypePrinter;
3390 TypePrinter.incorporateTypes(*M);
3392 WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3393 /* FromValue */ true);
3395 auto *N = dyn_cast<MDNode>(&MD);
3396 if (OnlyAsOperand || !N)
3400 WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3403 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3404 ModuleSlotTracker MST(M, isa<MDNode>(this));
3405 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3408 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3409 const Module *M) const {
3410 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3413 void Metadata::print(raw_ostream &OS, const Module *M,
3414 bool /*IsForDebug*/) const {
3415 ModuleSlotTracker MST(M, isa<MDNode>(this));
3416 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3419 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3420 const Module *M, bool /*IsForDebug*/) const {
3421 printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3424 // Value::dump - allow easy printing of Values from the debugger.
3426 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3428 // Type::dump - allow easy printing of Types from the debugger.
3430 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3432 // Module::dump() - Allow printing of Modules from the debugger.
3434 void Module::dump() const {
3435 print(dbgs(), nullptr,
3436 /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3439 // \brief Allow printing of Comdats from the debugger.
3441 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3443 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3445 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3448 void Metadata::dump() const { dump(nullptr); }
3451 void Metadata::dump(const Module *M) const {
3452 print(dbgs(), M, /*IsForDebug=*/true);