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/Operator.h"
34 #include "llvm/IR/Statepoint.h"
35 #include "llvm/IR/TypeFinder.h"
36 #include "llvm/IR/UseListOrder.h"
37 #include "llvm/IR/ValueSymbolTable.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
48 // Make virtual table appear in this compilation unit.
49 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
57 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
59 unsigned size() const { return IDs.size(); }
60 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
61 std::pair<unsigned, bool> lookup(const Value *V) const {
64 void index(const Value *V) {
65 // Explicitly sequence get-size and insert-value operations to avoid UB.
66 unsigned ID = IDs.size() + 1;
72 static void orderValue(const Value *V, OrderMap &OM) {
73 if (OM.lookup(V).first)
76 if (const Constant *C = dyn_cast<Constant>(V))
77 if (C->getNumOperands() && !isa<GlobalValue>(C))
78 for (const Value *Op : C->operands())
79 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
82 // Note: we cannot cache this lookup above, since inserting into the map
83 // changes the map's size, and thus affects the other IDs.
87 static OrderMap orderModule(const Module *M) {
88 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
89 // and ValueEnumerator::incorporateFunction().
92 for (const GlobalVariable &G : M->globals()) {
93 if (G.hasInitializer())
94 if (!isa<GlobalValue>(G.getInitializer()))
95 orderValue(G.getInitializer(), OM);
98 for (const GlobalAlias &A : M->aliases()) {
99 if (!isa<GlobalValue>(A.getAliasee()))
100 orderValue(A.getAliasee(), OM);
103 for (const Function &F : *M) {
104 if (F.hasPrefixData())
105 if (!isa<GlobalValue>(F.getPrefixData()))
106 orderValue(F.getPrefixData(), OM);
108 if (F.hasPrologueData())
109 if (!isa<GlobalValue>(F.getPrologueData()))
110 orderValue(F.getPrologueData(), OM);
112 if (F.hasPersonalityFn())
113 if (!isa<GlobalValue>(F.getPersonalityFn()))
114 orderValue(F.getPersonalityFn(), OM);
118 if (F.isDeclaration())
121 for (const Argument &A : F.args())
123 for (const BasicBlock &BB : F) {
125 for (const Instruction &I : BB) {
126 for (const Value *Op : I.operands())
127 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
137 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
138 unsigned ID, const OrderMap &OM,
139 UseListOrderStack &Stack) {
140 // Predict use-list order for this one.
141 typedef std::pair<const Use *, unsigned> Entry;
142 SmallVector<Entry, 64> List;
143 for (const Use &U : V->uses())
144 // Check if this user will be serialized.
145 if (OM.lookup(U.getUser()).first)
146 List.push_back(std::make_pair(&U, List.size()));
149 // We may have lost some users.
153 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
154 if (auto *BA = dyn_cast<BlockAddress>(V))
155 ID = OM.lookup(BA->getBasicBlock()).first;
156 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
157 const Use *LU = L.first;
158 const Use *RU = R.first;
162 auto LID = OM.lookup(LU->getUser()).first;
163 auto RID = OM.lookup(RU->getUser()).first;
165 // If ID is 4, then expect: 7 6 5 1 2 3.
179 // LID and RID are equal, so we have different operands of the same user.
180 // Assume operands are added in order for all instructions.
183 return LU->getOperandNo() < RU->getOperandNo();
184 return LU->getOperandNo() > RU->getOperandNo();
188 List.begin(), List.end(),
189 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
190 // Order is already correct.
193 // Store the shuffle.
194 Stack.emplace_back(V, F, List.size());
195 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
196 for (size_t I = 0, E = List.size(); I != E; ++I)
197 Stack.back().Shuffle[I] = List[I].second;
200 static void predictValueUseListOrder(const Value *V, const Function *F,
201 OrderMap &OM, UseListOrderStack &Stack) {
202 auto &IDPair = OM[V];
203 assert(IDPair.first && "Unmapped value");
205 // Already predicted.
208 // Do the actual prediction.
209 IDPair.second = true;
210 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
211 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
213 // Recursive descent into constants.
214 if (const Constant *C = dyn_cast<Constant>(V))
215 if (C->getNumOperands()) // Visit GlobalValues.
216 for (const Value *Op : C->operands())
217 if (isa<Constant>(Op)) // Visit GlobalValues.
218 predictValueUseListOrder(Op, F, OM, Stack);
221 static UseListOrderStack predictUseListOrder(const Module *M) {
222 OrderMap OM = orderModule(M);
224 // Use-list orders need to be serialized after all the users have been added
225 // to a value, or else the shuffles will be incomplete. Store them per
226 // function in a stack.
228 // Aside from function order, the order of values doesn't matter much here.
229 UseListOrderStack Stack;
231 // We want to visit the functions backward now so we can list function-local
232 // constants in the last Function they're used in. Module-level constants
233 // have already been visited above.
234 for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
235 const Function &F = *I;
236 if (F.isDeclaration())
238 for (const BasicBlock &BB : F)
239 predictValueUseListOrder(&BB, &F, OM, Stack);
240 for (const Argument &A : F.args())
241 predictValueUseListOrder(&A, &F, OM, Stack);
242 for (const BasicBlock &BB : F)
243 for (const Instruction &I : BB)
244 for (const Value *Op : I.operands())
245 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
246 predictValueUseListOrder(Op, &F, OM, Stack);
247 for (const BasicBlock &BB : F)
248 for (const Instruction &I : BB)
249 predictValueUseListOrder(&I, &F, OM, Stack);
252 // Visit globals last.
253 for (const GlobalVariable &G : M->globals())
254 predictValueUseListOrder(&G, nullptr, OM, Stack);
255 for (const Function &F : *M)
256 predictValueUseListOrder(&F, nullptr, OM, Stack);
257 for (const GlobalAlias &A : M->aliases())
258 predictValueUseListOrder(&A, nullptr, OM, Stack);
259 for (const GlobalVariable &G : M->globals())
260 if (G.hasInitializer())
261 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
262 for (const GlobalAlias &A : M->aliases())
263 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
264 for (const Function &F : *M)
265 if (F.hasPrefixData())
266 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
271 static const Module *getModuleFromVal(const Value *V) {
272 if (const Argument *MA = dyn_cast<Argument>(V))
273 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
275 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
276 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
278 if (const Instruction *I = dyn_cast<Instruction>(V)) {
279 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
280 return M ? M->getParent() : nullptr;
283 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
284 return GV->getParent();
286 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
287 for (const User *U : MAV->users())
288 if (isa<Instruction>(U))
289 if (const Module *M = getModuleFromVal(U))
297 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
299 default: Out << "cc" << cc; break;
300 case CallingConv::Fast: Out << "fastcc"; break;
301 case CallingConv::Cold: Out << "coldcc"; break;
302 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
303 case CallingConv::AnyReg: Out << "anyregcc"; break;
304 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
305 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
306 case CallingConv::GHC: Out << "ghccc"; break;
307 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
308 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
309 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
310 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
311 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
312 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
313 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
314 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
315 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
316 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
317 case CallingConv::PTX_Device: Out << "ptx_device"; break;
318 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
319 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
320 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
321 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
325 // PrintEscapedString - Print each character of the specified string, escaping
326 // it if it is not printable or if it is an escape char.
327 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
328 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
329 unsigned char C = Name[i];
330 if (isprint(C) && C != '\\' && C != '"')
333 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
345 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
346 /// prefixed with % (if the string only contains simple characters) or is
347 /// surrounded with ""'s (if it has special chars in it). Print it out.
348 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
349 assert(!Name.empty() && "Cannot get empty name!");
351 case NoPrefix: break;
352 case GlobalPrefix: OS << '@'; break;
353 case ComdatPrefix: OS << '$'; break;
354 case LabelPrefix: break;
355 case LocalPrefix: OS << '%'; break;
358 // Scan the name to see if it needs quotes first.
359 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
361 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
362 // By making this unsigned, the value passed in to isalnum will always be
363 // in the range 0-255. This is important when building with MSVC because
364 // its implementation will assert. This situation can arise when dealing
365 // with UTF-8 multibyte characters.
366 unsigned char C = Name[i];
367 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
375 // If we didn't need any quotes, just write out the name in one blast.
381 // Okay, we need quotes. Output the quotes and escape any scary characters as
384 PrintEscapedString(Name, OS);
388 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
389 /// prefixed with % (if the string only contains simple characters) or is
390 /// surrounded with ""'s (if it has special chars in it). Print it out.
391 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
392 PrintLLVMName(OS, V->getName(),
393 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
399 TypePrinting(const TypePrinting &) = delete;
400 void operator=(const TypePrinting&) = delete;
403 /// NamedTypes - The named types that are used by the current module.
404 TypeFinder NamedTypes;
406 /// NumberedTypes - The numbered types, along with their value.
407 DenseMap<StructType*, unsigned> NumberedTypes;
409 TypePrinting() = default;
411 void incorporateTypes(const Module &M);
413 void print(Type *Ty, raw_ostream &OS);
415 void printStructBody(StructType *Ty, raw_ostream &OS);
419 void TypePrinting::incorporateTypes(const Module &M) {
420 NamedTypes.run(M, false);
422 // The list of struct types we got back includes all the struct types, split
423 // the unnamed ones out to a numbering and remove the anonymous structs.
424 unsigned NextNumber = 0;
426 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
427 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
428 StructType *STy = *I;
430 // Ignore anonymous types.
431 if (STy->isLiteral())
434 if (STy->getName().empty())
435 NumberedTypes[STy] = NextNumber++;
440 NamedTypes.erase(NextToUse, NamedTypes.end());
444 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
445 /// use of type names or up references to shorten the type name where possible.
446 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
447 switch (Ty->getTypeID()) {
448 case Type::VoidTyID: OS << "void"; return;
449 case Type::HalfTyID: OS << "half"; return;
450 case Type::FloatTyID: OS << "float"; return;
451 case Type::DoubleTyID: OS << "double"; return;
452 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
453 case Type::FP128TyID: OS << "fp128"; return;
454 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
455 case Type::LabelTyID: OS << "label"; return;
456 case Type::MetadataTyID: OS << "metadata"; return;
457 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
458 case Type::IntegerTyID:
459 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
462 case Type::FunctionTyID: {
463 FunctionType *FTy = cast<FunctionType>(Ty);
464 print(FTy->getReturnType(), OS);
466 for (FunctionType::param_iterator I = FTy->param_begin(),
467 E = FTy->param_end(); I != E; ++I) {
468 if (I != FTy->param_begin())
472 if (FTy->isVarArg()) {
473 if (FTy->getNumParams()) OS << ", ";
479 case Type::StructTyID: {
480 StructType *STy = cast<StructType>(Ty);
482 if (STy->isLiteral())
483 return printStructBody(STy, OS);
485 if (!STy->getName().empty())
486 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
488 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
489 if (I != NumberedTypes.end())
490 OS << '%' << I->second;
491 else // Not enumerated, print the hex address.
492 OS << "%\"type " << STy << '\"';
495 case Type::PointerTyID: {
496 PointerType *PTy = cast<PointerType>(Ty);
497 print(PTy->getElementType(), OS);
498 if (unsigned AddressSpace = PTy->getAddressSpace())
499 OS << " addrspace(" << AddressSpace << ')';
503 case Type::ArrayTyID: {
504 ArrayType *ATy = cast<ArrayType>(Ty);
505 OS << '[' << ATy->getNumElements() << " x ";
506 print(ATy->getElementType(), OS);
510 case Type::VectorTyID: {
511 VectorType *PTy = cast<VectorType>(Ty);
512 OS << "<" << PTy->getNumElements() << " x ";
513 print(PTy->getElementType(), OS);
518 llvm_unreachable("Invalid TypeID");
521 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
522 if (STy->isOpaque()) {
530 if (STy->getNumElements() == 0) {
533 StructType::element_iterator I = STy->element_begin();
536 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
548 //===----------------------------------------------------------------------===//
549 // SlotTracker Class: Enumerate slot numbers for unnamed values
550 //===----------------------------------------------------------------------===//
551 /// This class provides computation of slot numbers for LLVM Assembly writing.
555 /// ValueMap - A mapping of Values to slot numbers.
556 typedef DenseMap<const Value*, unsigned> ValueMap;
559 /// TheModule - The module for which we are holding slot numbers.
560 const Module* TheModule;
562 /// TheFunction - The function for which we are holding slot numbers.
563 const Function* TheFunction;
564 bool FunctionProcessed;
565 bool ShouldInitializeAllMetadata;
567 /// mMap - The slot map for the module level data.
571 /// fMap - The slot map for the function level data.
575 /// mdnMap - Map for MDNodes.
576 DenseMap<const MDNode*, unsigned> mdnMap;
579 /// asMap - The slot map for attribute sets.
580 DenseMap<AttributeSet, unsigned> asMap;
583 /// Construct from a module.
585 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
586 /// functions, giving correct numbering for metadata referenced only from
587 /// within a function (even if no functions have been initialized).
588 explicit SlotTracker(const Module *M,
589 bool ShouldInitializeAllMetadata = false);
590 /// Construct from a function, starting out in incorp state.
592 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
593 /// functions, giving correct numbering for metadata referenced only from
594 /// within a function (even if no functions have been initialized).
595 explicit SlotTracker(const Function *F,
596 bool ShouldInitializeAllMetadata = false);
598 /// Return the slot number of the specified value in it's type
599 /// plane. If something is not in the SlotTracker, return -1.
600 int getLocalSlot(const Value *V);
601 int getGlobalSlot(const GlobalValue *V);
602 int getMetadataSlot(const MDNode *N);
603 int getAttributeGroupSlot(AttributeSet AS);
605 /// If you'd like to deal with a function instead of just a module, use
606 /// this method to get its data into the SlotTracker.
607 void incorporateFunction(const Function *F) {
609 FunctionProcessed = false;
612 const Function *getFunction() const { return TheFunction; }
614 /// After calling incorporateFunction, use this method to remove the
615 /// most recently incorporated function from the SlotTracker. This
616 /// will reset the state of the machine back to just the module contents.
617 void purgeFunction();
619 /// MDNode map iterators.
620 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
621 mdn_iterator mdn_begin() { return mdnMap.begin(); }
622 mdn_iterator mdn_end() { return mdnMap.end(); }
623 unsigned mdn_size() const { return mdnMap.size(); }
624 bool mdn_empty() const { return mdnMap.empty(); }
626 /// AttributeSet map iterators.
627 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
628 as_iterator as_begin() { return asMap.begin(); }
629 as_iterator as_end() { return asMap.end(); }
630 unsigned as_size() const { return asMap.size(); }
631 bool as_empty() const { return asMap.empty(); }
633 /// This function does the actual initialization.
634 inline void initialize();
636 // Implementation Details
638 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
639 void CreateModuleSlot(const GlobalValue *V);
641 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
642 void CreateMetadataSlot(const MDNode *N);
644 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
645 void CreateFunctionSlot(const Value *V);
647 /// \brief Insert the specified AttributeSet into the slot table.
648 void CreateAttributeSetSlot(AttributeSet AS);
650 /// Add all of the module level global variables (and their initializers)
651 /// and function declarations, but not the contents of those functions.
652 void processModule();
654 /// Add all of the functions arguments, basic blocks, and instructions.
655 void processFunction();
657 /// Add all of the metadata from a function.
658 void processFunctionMetadata(const Function &F);
660 /// Add all of the metadata from an instruction.
661 void processInstructionMetadata(const Instruction &I);
663 SlotTracker(const SlotTracker &) = delete;
664 void operator=(const SlotTracker &) = delete;
668 static SlotTracker *createSlotTracker(const Module *M) {
669 return new SlotTracker(M);
672 static SlotTracker *createSlotTracker(const Value *V) {
673 if (const Argument *FA = dyn_cast<Argument>(V))
674 return new SlotTracker(FA->getParent());
676 if (const Instruction *I = dyn_cast<Instruction>(V))
678 return new SlotTracker(I->getParent()->getParent());
680 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
681 return new SlotTracker(BB->getParent());
683 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
684 return new SlotTracker(GV->getParent());
686 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
687 return new SlotTracker(GA->getParent());
689 if (const Function *Func = dyn_cast<Function>(V))
690 return new SlotTracker(Func);
696 #define ST_DEBUG(X) dbgs() << X
701 // Module level constructor. Causes the contents of the Module (sans functions)
702 // to be added to the slot table.
703 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
704 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
705 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
706 fNext(0), mdnNext(0), asNext(0) {}
708 // Function level constructor. Causes the contents of the Module and the one
709 // function provided to be added to the slot table.
710 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
711 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
712 FunctionProcessed(false),
713 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
714 fNext(0), mdnNext(0), asNext(0) {}
716 inline void SlotTracker::initialize() {
719 TheModule = nullptr; ///< Prevent re-processing next time we're called.
722 if (TheFunction && !FunctionProcessed)
726 // Iterate through all the global variables, functions, and global
727 // variable initializers and create slots for them.
728 void SlotTracker::processModule() {
729 ST_DEBUG("begin processModule!\n");
731 // Add all of the unnamed global variables to the value table.
732 for (const GlobalVariable &Var : TheModule->globals()) {
734 CreateModuleSlot(&Var);
737 for (const GlobalAlias &A : TheModule->aliases()) {
739 CreateModuleSlot(&A);
742 // Add metadata used by named metadata.
743 for (const NamedMDNode &NMD : TheModule->named_metadata()) {
744 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
745 CreateMetadataSlot(NMD.getOperand(i));
748 for (const Function &F : *TheModule) {
750 // Add all the unnamed functions to the table.
751 CreateModuleSlot(&F);
753 if (ShouldInitializeAllMetadata)
754 processFunctionMetadata(F);
756 // Add all the function attributes to the table.
757 // FIXME: Add attributes of other objects?
758 AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
759 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
760 CreateAttributeSetSlot(FnAttrs);
763 ST_DEBUG("end processModule!\n");
766 // Process the arguments, basic blocks, and instructions of a function.
767 void SlotTracker::processFunction() {
768 ST_DEBUG("begin processFunction!\n");
771 // Add all the function arguments with no names.
772 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
773 AE = TheFunction->arg_end(); AI != AE; ++AI)
775 CreateFunctionSlot(AI);
777 ST_DEBUG("Inserting Instructions:\n");
779 // Add all of the basic blocks and instructions with no names.
780 for (auto &BB : *TheFunction) {
782 CreateFunctionSlot(&BB);
784 processFunctionMetadata(*TheFunction);
787 if (!I.getType()->isVoidTy() && !I.hasName())
788 CreateFunctionSlot(&I);
790 // We allow direct calls to any llvm.foo function here, because the
791 // target may not be linked into the optimizer.
792 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
793 // Add all the call attributes to the table.
794 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
795 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
796 CreateAttributeSetSlot(Attrs);
797 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
798 // Add all the call attributes to the table.
799 AttributeSet Attrs = II->getAttributes().getFnAttributes();
800 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
801 CreateAttributeSetSlot(Attrs);
806 FunctionProcessed = true;
808 ST_DEBUG("end processFunction!\n");
811 void SlotTracker::processFunctionMetadata(const Function &F) {
812 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
814 F.getAllMetadata(MDs);
816 CreateMetadataSlot(MD.second);
819 processInstructionMetadata(I);
823 void SlotTracker::processInstructionMetadata(const Instruction &I) {
824 // Process metadata used directly by intrinsics.
825 if (const CallInst *CI = dyn_cast<CallInst>(&I))
826 if (Function *F = CI->getCalledFunction())
827 if (F->isIntrinsic())
828 for (auto &Op : I.operands())
829 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
830 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
831 CreateMetadataSlot(N);
833 // Process metadata attached to this instruction.
834 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
835 I.getAllMetadata(MDs);
837 CreateMetadataSlot(MD.second);
840 /// Clean up after incorporating a function. This is the only way to get out of
841 /// the function incorporation state that affects get*Slot/Create*Slot. Function
842 /// incorporation state is indicated by TheFunction != 0.
843 void SlotTracker::purgeFunction() {
844 ST_DEBUG("begin purgeFunction!\n");
845 fMap.clear(); // Simply discard the function level map
846 TheFunction = nullptr;
847 FunctionProcessed = false;
848 ST_DEBUG("end purgeFunction!\n");
851 /// getGlobalSlot - Get the slot number of a global value.
852 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
853 // Check for uninitialized state and do lazy initialization.
856 // Find the value in the module map
857 ValueMap::iterator MI = mMap.find(V);
858 return MI == mMap.end() ? -1 : (int)MI->second;
861 /// getMetadataSlot - Get the slot number of a MDNode.
862 int SlotTracker::getMetadataSlot(const MDNode *N) {
863 // Check for uninitialized state and do lazy initialization.
866 // Find the MDNode in the module map
867 mdn_iterator MI = mdnMap.find(N);
868 return MI == mdnMap.end() ? -1 : (int)MI->second;
872 /// getLocalSlot - Get the slot number for a value that is local to a function.
873 int SlotTracker::getLocalSlot(const Value *V) {
874 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
876 // Check for uninitialized state and do lazy initialization.
879 ValueMap::iterator FI = fMap.find(V);
880 return FI == fMap.end() ? -1 : (int)FI->second;
883 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
884 // Check for uninitialized state and do lazy initialization.
887 // Find the AttributeSet in the module map.
888 as_iterator AI = asMap.find(AS);
889 return AI == asMap.end() ? -1 : (int)AI->second;
892 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
893 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
894 assert(V && "Can't insert a null Value into SlotTracker!");
895 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
896 assert(!V->hasName() && "Doesn't need a slot!");
898 unsigned DestSlot = mNext++;
901 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
903 // G = Global, F = Function, A = Alias, o = other
904 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
905 (isa<Function>(V) ? 'F' :
906 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
909 /// CreateSlot - Create a new slot for the specified value if it has no name.
910 void SlotTracker::CreateFunctionSlot(const Value *V) {
911 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
913 unsigned DestSlot = fNext++;
916 // G = Global, F = Function, o = other
917 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
918 DestSlot << " [o]\n");
921 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
922 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
923 assert(N && "Can't insert a null Value into SlotTracker!");
925 unsigned DestSlot = mdnNext;
926 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
930 // Recursively add any MDNodes referenced by operands.
931 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
932 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
933 CreateMetadataSlot(Op);
936 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
937 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
938 "Doesn't need a slot!");
940 as_iterator I = asMap.find(AS);
941 if (I != asMap.end())
944 unsigned DestSlot = asNext++;
945 asMap[AS] = DestSlot;
948 //===----------------------------------------------------------------------===//
949 // AsmWriter Implementation
950 //===----------------------------------------------------------------------===//
952 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
953 TypePrinting *TypePrinter,
954 SlotTracker *Machine,
955 const Module *Context);
957 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
958 TypePrinting *TypePrinter,
959 SlotTracker *Machine, const Module *Context,
960 bool FromValue = false);
962 static const char *getPredicateText(unsigned predicate) {
963 const char * pred = "unknown";
965 case FCmpInst::FCMP_FALSE: pred = "false"; break;
966 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
967 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
968 case FCmpInst::FCMP_OGE: pred = "oge"; break;
969 case FCmpInst::FCMP_OLT: pred = "olt"; break;
970 case FCmpInst::FCMP_OLE: pred = "ole"; break;
971 case FCmpInst::FCMP_ONE: pred = "one"; break;
972 case FCmpInst::FCMP_ORD: pred = "ord"; break;
973 case FCmpInst::FCMP_UNO: pred = "uno"; break;
974 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
975 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
976 case FCmpInst::FCMP_UGE: pred = "uge"; break;
977 case FCmpInst::FCMP_ULT: pred = "ult"; break;
978 case FCmpInst::FCMP_ULE: pred = "ule"; break;
979 case FCmpInst::FCMP_UNE: pred = "une"; break;
980 case FCmpInst::FCMP_TRUE: pred = "true"; break;
981 case ICmpInst::ICMP_EQ: pred = "eq"; break;
982 case ICmpInst::ICMP_NE: pred = "ne"; break;
983 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
984 case ICmpInst::ICMP_SGE: pred = "sge"; break;
985 case ICmpInst::ICMP_SLT: pred = "slt"; break;
986 case ICmpInst::ICMP_SLE: pred = "sle"; break;
987 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
988 case ICmpInst::ICMP_UGE: pred = "uge"; break;
989 case ICmpInst::ICMP_ULT: pred = "ult"; break;
990 case ICmpInst::ICMP_ULE: pred = "ule"; break;
995 static void writeAtomicRMWOperation(raw_ostream &Out,
996 AtomicRMWInst::BinOp Op) {
998 default: Out << " <unknown operation " << Op << ">"; break;
999 case AtomicRMWInst::Xchg: Out << " xchg"; break;
1000 case AtomicRMWInst::Add: Out << " add"; break;
1001 case AtomicRMWInst::Sub: Out << " sub"; break;
1002 case AtomicRMWInst::And: Out << " and"; break;
1003 case AtomicRMWInst::Nand: Out << " nand"; break;
1004 case AtomicRMWInst::Or: Out << " or"; break;
1005 case AtomicRMWInst::Xor: Out << " xor"; break;
1006 case AtomicRMWInst::Max: Out << " max"; break;
1007 case AtomicRMWInst::Min: Out << " min"; break;
1008 case AtomicRMWInst::UMax: Out << " umax"; break;
1009 case AtomicRMWInst::UMin: Out << " umin"; break;
1013 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1014 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1015 // Unsafe algebra implies all the others, no need to write them all out
1016 if (FPO->hasUnsafeAlgebra())
1019 if (FPO->hasNoNaNs())
1021 if (FPO->hasNoInfs())
1023 if (FPO->hasNoSignedZeros())
1025 if (FPO->hasAllowReciprocal())
1030 if (const OverflowingBinaryOperator *OBO =
1031 dyn_cast<OverflowingBinaryOperator>(U)) {
1032 if (OBO->hasNoUnsignedWrap())
1034 if (OBO->hasNoSignedWrap())
1036 } else if (const PossiblyExactOperator *Div =
1037 dyn_cast<PossiblyExactOperator>(U)) {
1040 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1041 if (GEP->isInBounds())
1046 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1047 TypePrinting &TypePrinter,
1048 SlotTracker *Machine,
1049 const Module *Context) {
1050 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1051 if (CI->getType()->isIntegerTy(1)) {
1052 Out << (CI->getZExtValue() ? "true" : "false");
1055 Out << CI->getValue();
1059 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1060 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1061 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1062 // We would like to output the FP constant value in exponential notation,
1063 // but we cannot do this if doing so will lose precision. Check here to
1064 // make sure that we only output it in exponential format if we can parse
1065 // the value back and get the same value.
1068 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
1069 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1070 bool isInf = CFP->getValueAPF().isInfinity();
1071 bool isNaN = CFP->getValueAPF().isNaN();
1072 if (!isHalf && !isInf && !isNaN) {
1073 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1074 CFP->getValueAPF().convertToFloat();
1075 SmallString<128> StrVal;
1076 raw_svector_ostream(StrVal) << Val;
1078 // Check to make sure that the stringized number is not some string like
1079 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1080 // that the string matches the "[-+]?[0-9]" regex.
1082 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1083 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1084 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1085 // Reparse stringized version!
1086 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1092 // Otherwise we could not reparse it to exactly the same value, so we must
1093 // output the string in hexadecimal format! Note that loading and storing
1094 // floating point types changes the bits of NaNs on some hosts, notably
1095 // x86, so we must not use these types.
1096 static_assert(sizeof(double) == sizeof(uint64_t),
1097 "assuming that double is 64 bits!");
1099 APFloat apf = CFP->getValueAPF();
1100 // Halves and floats are represented in ASCII IR as double, convert.
1102 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1105 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1110 // Either half, or some form of long double.
1111 // These appear as a magic letter identifying the type, then a
1112 // fixed number of hex digits.
1114 // Bit position, in the current word, of the next nibble to print.
1117 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1119 // api needed to prevent premature destruction
1120 APInt api = CFP->getValueAPF().bitcastToAPInt();
1121 const uint64_t* p = api.getRawData();
1122 uint64_t word = p[1];
1124 int width = api.getBitWidth();
1125 for (int j=0; j<width; j+=4, shiftcount-=4) {
1126 unsigned int nibble = (word>>shiftcount) & 15;
1128 Out << (unsigned char)(nibble + '0');
1130 Out << (unsigned char)(nibble - 10 + 'A');
1131 if (shiftcount == 0 && j+4 < width) {
1135 shiftcount = width-j-4;
1139 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1142 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1145 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1149 llvm_unreachable("Unsupported floating point type");
1150 // api needed to prevent premature destruction
1151 APInt api = CFP->getValueAPF().bitcastToAPInt();
1152 const uint64_t* p = api.getRawData();
1154 int width = api.getBitWidth();
1155 for (int j=0; j<width; j+=4, shiftcount-=4) {
1156 unsigned int nibble = (word>>shiftcount) & 15;
1158 Out << (unsigned char)(nibble + '0');
1160 Out << (unsigned char)(nibble - 10 + 'A');
1161 if (shiftcount == 0 && j+4 < width) {
1165 shiftcount = width-j-4;
1171 if (isa<ConstantAggregateZero>(CV)) {
1172 Out << "zeroinitializer";
1176 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1177 Out << "blockaddress(";
1178 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1181 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1187 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1188 Type *ETy = CA->getType()->getElementType();
1190 TypePrinter.print(ETy, Out);
1192 WriteAsOperandInternal(Out, CA->getOperand(0),
1193 &TypePrinter, Machine,
1195 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1197 TypePrinter.print(ETy, Out);
1199 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1206 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1207 // As a special case, print the array as a string if it is an array of
1208 // i8 with ConstantInt values.
1209 if (CA->isString()) {
1211 PrintEscapedString(CA->getAsString(), Out);
1216 Type *ETy = CA->getType()->getElementType();
1218 TypePrinter.print(ETy, Out);
1220 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1221 &TypePrinter, Machine,
1223 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1225 TypePrinter.print(ETy, Out);
1227 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1235 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1236 if (CS->getType()->isPacked())
1239 unsigned N = CS->getNumOperands();
1242 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1245 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1248 for (unsigned i = 1; i < N; i++) {
1250 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1253 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1260 if (CS->getType()->isPacked())
1265 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1266 Type *ETy = CV->getType()->getVectorElementType();
1268 TypePrinter.print(ETy, Out);
1270 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1272 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1274 TypePrinter.print(ETy, Out);
1276 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1283 if (isa<ConstantPointerNull>(CV)) {
1288 if (isa<UndefValue>(CV)) {
1293 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1294 Out << CE->getOpcodeName();
1295 WriteOptimizationInfo(Out, CE);
1296 if (CE->isCompare())
1297 Out << ' ' << getPredicateText(CE->getPredicate());
1300 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1302 cast<PointerType>(GEP->getPointerOperandType()->getScalarType())
1308 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1309 TypePrinter.print((*OI)->getType(), Out);
1311 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1312 if (OI+1 != CE->op_end())
1316 if (CE->hasIndices()) {
1317 ArrayRef<unsigned> Indices = CE->getIndices();
1318 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1319 Out << ", " << Indices[i];
1324 TypePrinter.print(CE->getType(), Out);
1331 Out << "<placeholder or erroneous Constant>";
1334 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1335 TypePrinting *TypePrinter, SlotTracker *Machine,
1336 const Module *Context) {
1338 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1339 const Metadata *MD = Node->getOperand(mi);
1342 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1343 Value *V = MDV->getValue();
1344 TypePrinter->print(V->getType(), Out);
1346 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1348 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1358 struct FieldSeparator {
1361 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1363 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1368 return OS << FS.Sep;
1370 struct MDFieldPrinter {
1373 TypePrinting *TypePrinter;
1374 SlotTracker *Machine;
1375 const Module *Context;
1377 explicit MDFieldPrinter(raw_ostream &Out)
1378 : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1379 MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1380 SlotTracker *Machine, const Module *Context)
1381 : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1383 void printTag(const DINode *N);
1384 void printString(StringRef Name, StringRef Value,
1385 bool ShouldSkipEmpty = true);
1386 void printMetadata(StringRef Name, const Metadata *MD,
1387 bool ShouldSkipNull = true);
1388 template <class IntTy>
1389 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1390 void printBool(StringRef Name, bool Value);
1391 void printDIFlags(StringRef Name, unsigned Flags);
1392 template <class IntTy, class Stringifier>
1393 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1394 bool ShouldSkipZero = true);
1398 void MDFieldPrinter::printTag(const DINode *N) {
1399 Out << FS << "tag: ";
1400 if (const char *Tag = dwarf::TagString(N->getTag()))
1406 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1407 bool ShouldSkipEmpty) {
1408 if (ShouldSkipEmpty && Value.empty())
1411 Out << FS << Name << ": \"";
1412 PrintEscapedString(Value, Out);
1416 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1417 TypePrinting *TypePrinter,
1418 SlotTracker *Machine,
1419 const Module *Context) {
1424 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1427 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1428 bool ShouldSkipNull) {
1429 if (ShouldSkipNull && !MD)
1432 Out << FS << Name << ": ";
1433 writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1436 template <class IntTy>
1437 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1438 if (ShouldSkipZero && !Int)
1441 Out << FS << Name << ": " << Int;
1444 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1445 Out << FS << Name << ": " << (Value ? "true" : "false");
1448 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1452 Out << FS << Name << ": ";
1454 SmallVector<unsigned, 8> SplitFlags;
1455 unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1457 FieldSeparator FlagsFS(" | ");
1458 for (unsigned F : SplitFlags) {
1459 const char *StringF = DINode::getFlagString(F);
1460 assert(StringF && "Expected valid flag");
1461 Out << FlagsFS << StringF;
1463 if (Extra || SplitFlags.empty())
1464 Out << FlagsFS << Extra;
1467 template <class IntTy, class Stringifier>
1468 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1469 Stringifier toString, bool ShouldSkipZero) {
1473 Out << FS << Name << ": ";
1474 if (const char *S = toString(Value))
1480 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1481 TypePrinting *TypePrinter, SlotTracker *Machine,
1482 const Module *Context) {
1483 Out << "!GenericDINode(";
1484 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1485 Printer.printTag(N);
1486 Printer.printString("header", N->getHeader());
1487 if (N->getNumDwarfOperands()) {
1488 Out << Printer.FS << "operands: {";
1490 for (auto &I : N->dwarf_operands()) {
1492 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1499 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1500 TypePrinting *TypePrinter, SlotTracker *Machine,
1501 const Module *Context) {
1502 Out << "!DILocation(";
1503 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1504 // Always output the line, since 0 is a relevant and important value for it.
1505 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1506 Printer.printInt("column", DL->getColumn());
1507 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1508 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1512 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1513 TypePrinting *, SlotTracker *, const Module *) {
1514 Out << "!DISubrange(";
1515 MDFieldPrinter Printer(Out);
1516 Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1517 Printer.printInt("lowerBound", N->getLowerBound());
1521 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1522 TypePrinting *, SlotTracker *, const Module *) {
1523 Out << "!DIEnumerator(";
1524 MDFieldPrinter Printer(Out);
1525 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1526 Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1530 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1531 TypePrinting *, SlotTracker *, const Module *) {
1532 Out << "!DIBasicType(";
1533 MDFieldPrinter Printer(Out);
1534 if (N->getTag() != dwarf::DW_TAG_base_type)
1535 Printer.printTag(N);
1536 Printer.printString("name", N->getName());
1537 Printer.printInt("size", N->getSizeInBits());
1538 Printer.printInt("align", N->getAlignInBits());
1539 Printer.printDwarfEnum("encoding", N->getEncoding(),
1540 dwarf::AttributeEncodingString);
1544 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1545 TypePrinting *TypePrinter, SlotTracker *Machine,
1546 const Module *Context) {
1547 Out << "!DIDerivedType(";
1548 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1549 Printer.printTag(N);
1550 Printer.printString("name", N->getName());
1551 Printer.printMetadata("scope", N->getRawScope());
1552 Printer.printMetadata("file", N->getRawFile());
1553 Printer.printInt("line", N->getLine());
1554 Printer.printMetadata("baseType", N->getRawBaseType(),
1555 /* ShouldSkipNull */ false);
1556 Printer.printInt("size", N->getSizeInBits());
1557 Printer.printInt("align", N->getAlignInBits());
1558 Printer.printInt("offset", N->getOffsetInBits());
1559 Printer.printDIFlags("flags", N->getFlags());
1560 Printer.printMetadata("extraData", N->getRawExtraData());
1564 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1565 TypePrinting *TypePrinter,
1566 SlotTracker *Machine, const Module *Context) {
1567 Out << "!DICompositeType(";
1568 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1569 Printer.printTag(N);
1570 Printer.printString("name", N->getName());
1571 Printer.printMetadata("scope", N->getRawScope());
1572 Printer.printMetadata("file", N->getRawFile());
1573 Printer.printInt("line", N->getLine());
1574 Printer.printMetadata("baseType", N->getRawBaseType());
1575 Printer.printInt("size", N->getSizeInBits());
1576 Printer.printInt("align", N->getAlignInBits());
1577 Printer.printInt("offset", N->getOffsetInBits());
1578 Printer.printDIFlags("flags", N->getFlags());
1579 Printer.printMetadata("elements", N->getRawElements());
1580 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1581 dwarf::LanguageString);
1582 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1583 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1584 Printer.printString("identifier", N->getIdentifier());
1588 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1589 TypePrinting *TypePrinter,
1590 SlotTracker *Machine, const Module *Context) {
1591 Out << "!DISubroutineType(";
1592 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1593 Printer.printDIFlags("flags", N->getFlags());
1594 Printer.printMetadata("types", N->getRawTypeArray(),
1595 /* ShouldSkipNull */ false);
1599 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1600 SlotTracker *, const Module *) {
1602 MDFieldPrinter Printer(Out);
1603 Printer.printString("filename", N->getFilename(),
1604 /* ShouldSkipEmpty */ false);
1605 Printer.printString("directory", N->getDirectory(),
1606 /* ShouldSkipEmpty */ false);
1610 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1611 TypePrinting *TypePrinter, SlotTracker *Machine,
1612 const Module *Context) {
1613 Out << "!DICompileUnit(";
1614 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1615 Printer.printDwarfEnum("language", N->getSourceLanguage(),
1616 dwarf::LanguageString, /* ShouldSkipZero */ false);
1617 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1618 Printer.printString("producer", N->getProducer());
1619 Printer.printBool("isOptimized", N->isOptimized());
1620 Printer.printString("flags", N->getFlags());
1621 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1622 /* ShouldSkipZero */ false);
1623 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1624 Printer.printInt("emissionKind", N->getEmissionKind(),
1625 /* ShouldSkipZero */ false);
1626 Printer.printMetadata("enums", N->getRawEnumTypes());
1627 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1628 Printer.printMetadata("subprograms", N->getRawSubprograms());
1629 Printer.printMetadata("globals", N->getRawGlobalVariables());
1630 Printer.printMetadata("imports", N->getRawImportedEntities());
1631 Printer.printInt("dwoId", N->getDWOId());
1635 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1636 TypePrinting *TypePrinter, SlotTracker *Machine,
1637 const Module *Context) {
1638 Out << "!DISubprogram(";
1639 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1640 Printer.printString("name", N->getName());
1641 Printer.printString("linkageName", N->getLinkageName());
1642 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1643 Printer.printMetadata("file", N->getRawFile());
1644 Printer.printInt("line", N->getLine());
1645 Printer.printMetadata("type", N->getRawType());
1646 Printer.printBool("isLocal", N->isLocalToUnit());
1647 Printer.printBool("isDefinition", N->isDefinition());
1648 Printer.printInt("scopeLine", N->getScopeLine());
1649 Printer.printMetadata("containingType", N->getRawContainingType());
1650 Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1651 dwarf::VirtualityString);
1652 Printer.printInt("virtualIndex", N->getVirtualIndex());
1653 Printer.printDIFlags("flags", N->getFlags());
1654 Printer.printBool("isOptimized", N->isOptimized());
1655 Printer.printMetadata("function", N->getRawFunction());
1656 Printer.printMetadata("templateParams", N->getRawTemplateParams());
1657 Printer.printMetadata("declaration", N->getRawDeclaration());
1658 Printer.printMetadata("variables", N->getRawVariables());
1662 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1663 TypePrinting *TypePrinter, SlotTracker *Machine,
1664 const Module *Context) {
1665 Out << "!DILexicalBlock(";
1666 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1667 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1668 Printer.printMetadata("file", N->getRawFile());
1669 Printer.printInt("line", N->getLine());
1670 Printer.printInt("column", N->getColumn());
1674 static void writeDILexicalBlockFile(raw_ostream &Out,
1675 const DILexicalBlockFile *N,
1676 TypePrinting *TypePrinter,
1677 SlotTracker *Machine,
1678 const Module *Context) {
1679 Out << "!DILexicalBlockFile(";
1680 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1681 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1682 Printer.printMetadata("file", N->getRawFile());
1683 Printer.printInt("discriminator", N->getDiscriminator(),
1684 /* ShouldSkipZero */ false);
1688 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1689 TypePrinting *TypePrinter, SlotTracker *Machine,
1690 const Module *Context) {
1691 Out << "!DINamespace(";
1692 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1693 Printer.printString("name", N->getName());
1694 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1695 Printer.printMetadata("file", N->getRawFile());
1696 Printer.printInt("line", N->getLine());
1700 static void writeDITemplateTypeParameter(raw_ostream &Out,
1701 const DITemplateTypeParameter *N,
1702 TypePrinting *TypePrinter,
1703 SlotTracker *Machine,
1704 const Module *Context) {
1705 Out << "!DITemplateTypeParameter(";
1706 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1707 Printer.printString("name", N->getName());
1708 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1712 static void writeDITemplateValueParameter(raw_ostream &Out,
1713 const DITemplateValueParameter *N,
1714 TypePrinting *TypePrinter,
1715 SlotTracker *Machine,
1716 const Module *Context) {
1717 Out << "!DITemplateValueParameter(";
1718 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1719 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1720 Printer.printTag(N);
1721 Printer.printString("name", N->getName());
1722 Printer.printMetadata("type", N->getRawType());
1723 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1727 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1728 TypePrinting *TypePrinter,
1729 SlotTracker *Machine, const Module *Context) {
1730 Out << "!DIGlobalVariable(";
1731 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1732 Printer.printString("name", N->getName());
1733 Printer.printString("linkageName", N->getLinkageName());
1734 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1735 Printer.printMetadata("file", N->getRawFile());
1736 Printer.printInt("line", N->getLine());
1737 Printer.printMetadata("type", N->getRawType());
1738 Printer.printBool("isLocal", N->isLocalToUnit());
1739 Printer.printBool("isDefinition", N->isDefinition());
1740 Printer.printMetadata("variable", N->getRawVariable());
1741 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1745 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1746 TypePrinting *TypePrinter,
1747 SlotTracker *Machine, const Module *Context) {
1748 Out << "!DILocalVariable(";
1749 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1750 Printer.printTag(N);
1751 Printer.printString("name", N->getName());
1752 Printer.printInt("arg", N->getArg(),
1753 /* ShouldSkipZero */
1754 N->getTag() == dwarf::DW_TAG_auto_variable);
1755 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1756 Printer.printMetadata("file", N->getRawFile());
1757 Printer.printInt("line", N->getLine());
1758 Printer.printMetadata("type", N->getRawType());
1759 Printer.printDIFlags("flags", N->getFlags());
1763 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1764 TypePrinting *TypePrinter, SlotTracker *Machine,
1765 const Module *Context) {
1766 Out << "!DIExpression(";
1769 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1770 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1771 assert(OpStr && "Expected valid opcode");
1774 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1775 Out << FS << I->getArg(A);
1778 for (const auto &I : N->getElements())
1784 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1785 TypePrinting *TypePrinter, SlotTracker *Machine,
1786 const Module *Context) {
1787 Out << "!DIObjCProperty(";
1788 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1789 Printer.printString("name", N->getName());
1790 Printer.printMetadata("file", N->getRawFile());
1791 Printer.printInt("line", N->getLine());
1792 Printer.printString("setter", N->getSetterName());
1793 Printer.printString("getter", N->getGetterName());
1794 Printer.printInt("attributes", N->getAttributes());
1795 Printer.printMetadata("type", N->getRawType());
1799 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1800 TypePrinting *TypePrinter,
1801 SlotTracker *Machine, const Module *Context) {
1802 Out << "!DIImportedEntity(";
1803 MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1804 Printer.printTag(N);
1805 Printer.printString("name", N->getName());
1806 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1807 Printer.printMetadata("entity", N->getRawEntity());
1808 Printer.printInt("line", N->getLine());
1813 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1814 TypePrinting *TypePrinter,
1815 SlotTracker *Machine,
1816 const Module *Context) {
1817 if (Node->isDistinct())
1819 else if (Node->isTemporary())
1820 Out << "<temporary!> "; // Handle broken code.
1822 switch (Node->getMetadataID()) {
1824 llvm_unreachable("Expected uniquable MDNode");
1825 #define HANDLE_MDNODE_LEAF(CLASS) \
1826 case Metadata::CLASS##Kind: \
1827 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1829 #include "llvm/IR/Metadata.def"
1833 // Full implementation of printing a Value as an operand with support for
1834 // TypePrinting, etc.
1835 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1836 TypePrinting *TypePrinter,
1837 SlotTracker *Machine,
1838 const Module *Context) {
1840 PrintLLVMName(Out, V);
1844 const Constant *CV = dyn_cast<Constant>(V);
1845 if (CV && !isa<GlobalValue>(CV)) {
1846 assert(TypePrinter && "Constants require TypePrinting!");
1847 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1851 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1853 if (IA->hasSideEffects())
1854 Out << "sideeffect ";
1855 if (IA->isAlignStack())
1856 Out << "alignstack ";
1857 // We don't emit the AD_ATT dialect as it's the assumed default.
1858 if (IA->getDialect() == InlineAsm::AD_Intel)
1859 Out << "inteldialect ";
1861 PrintEscapedString(IA->getAsmString(), Out);
1863 PrintEscapedString(IA->getConstraintString(), Out);
1868 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1869 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1870 Context, /* FromValue */ true);
1876 // If we have a SlotTracker, use it.
1878 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1879 Slot = Machine->getGlobalSlot(GV);
1882 Slot = Machine->getLocalSlot(V);
1884 // If the local value didn't succeed, then we may be referring to a value
1885 // from a different function. Translate it, as this can happen when using
1886 // address of blocks.
1888 if ((Machine = createSlotTracker(V))) {
1889 Slot = Machine->getLocalSlot(V);
1893 } else if ((Machine = createSlotTracker(V))) {
1894 // Otherwise, create one to get the # and then destroy it.
1895 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1896 Slot = Machine->getGlobalSlot(GV);
1899 Slot = Machine->getLocalSlot(V);
1908 Out << Prefix << Slot;
1913 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1914 TypePrinting *TypePrinter,
1915 SlotTracker *Machine, const Module *Context,
1917 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1919 Machine = new SlotTracker(Context);
1920 int Slot = Machine->getMetadataSlot(N);
1922 // Give the pointer value instead of "badref", since this comes up all
1923 // the time when debugging.
1924 Out << "<" << N << ">";
1930 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1932 PrintEscapedString(MDS->getString(), Out);
1937 auto *V = cast<ValueAsMetadata>(MD);
1938 assert(TypePrinter && "TypePrinter required for metadata values");
1939 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1940 "Unexpected function-local metadata outside of value argument");
1942 TypePrinter->print(V->getValue()->getType(), Out);
1944 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
1948 class AssemblyWriter {
1949 formatted_raw_ostream &Out;
1950 const Module *TheModule;
1951 std::unique_ptr<SlotTracker> ModuleSlotTracker;
1952 SlotTracker &Machine;
1953 TypePrinting TypePrinter;
1954 AssemblyAnnotationWriter *AnnotationWriter;
1955 SetVector<const Comdat *> Comdats;
1956 bool ShouldPreserveUseListOrder;
1957 UseListOrderStack UseListOrders;
1958 SmallVector<StringRef, 8> MDNames;
1961 /// Construct an AssemblyWriter with an external SlotTracker
1962 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
1963 AssemblyAnnotationWriter *AAW,
1964 bool ShouldPreserveUseListOrder = false);
1966 /// Construct an AssemblyWriter with an internally allocated SlotTracker
1967 AssemblyWriter(formatted_raw_ostream &o, const Module *M,
1968 AssemblyAnnotationWriter *AAW,
1969 bool ShouldPreserveUseListOrder = false);
1971 void printMDNodeBody(const MDNode *MD);
1972 void printNamedMDNode(const NamedMDNode *NMD);
1974 void printModule(const Module *M);
1976 void writeOperand(const Value *Op, bool PrintType);
1977 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
1978 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1979 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
1980 AtomicOrdering FailureOrdering,
1981 SynchronizationScope SynchScope);
1983 void writeAllMDNodes();
1984 void writeMDNode(unsigned Slot, const MDNode *Node);
1985 void writeAllAttributeGroups();
1987 void printTypeIdentities();
1988 void printGlobal(const GlobalVariable *GV);
1989 void printAlias(const GlobalAlias *GV);
1990 void printComdat(const Comdat *C);
1991 void printFunction(const Function *F);
1992 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
1993 void printBasicBlock(const BasicBlock *BB);
1994 void printInstructionLine(const Instruction &I);
1995 void printInstruction(const Instruction &I);
1997 void printUseListOrder(const UseListOrder &Order);
1998 void printUseLists(const Function *F);
2003 /// \brief Print out metadata attachments.
2004 void printMetadataAttachments(
2005 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2006 StringRef Separator);
2008 // printInfoComment - Print a little comment after the instruction indicating
2009 // which slot it occupies.
2010 void printInfoComment(const Value &V);
2012 // printGCRelocateComment - print comment after call to the gc.relocate
2013 // intrinsic indicating base and derived pointer names.
2014 void printGCRelocateComment(const Value &V);
2018 void AssemblyWriter::init() {
2021 TypePrinter.incorporateTypes(*TheModule);
2022 for (const Function &F : *TheModule)
2023 if (const Comdat *C = F.getComdat())
2025 for (const GlobalVariable &GV : TheModule->globals())
2026 if (const Comdat *C = GV.getComdat())
2030 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2031 const Module *M, AssemblyAnnotationWriter *AAW,
2032 bool ShouldPreserveUseListOrder)
2033 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2034 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2038 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
2039 AssemblyAnnotationWriter *AAW,
2040 bool ShouldPreserveUseListOrder)
2041 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
2042 Machine(*ModuleSlotTracker), AnnotationWriter(AAW),
2043 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2047 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2049 Out << "<null operand!>";
2053 TypePrinter.print(Operand->getType(), Out);
2056 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2059 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2060 SynchronizationScope SynchScope) {
2061 if (Ordering == NotAtomic)
2064 switch (SynchScope) {
2065 case SingleThread: Out << " singlethread"; break;
2066 case CrossThread: break;
2070 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2071 case Unordered: Out << " unordered"; break;
2072 case Monotonic: Out << " monotonic"; break;
2073 case Acquire: Out << " acquire"; break;
2074 case Release: Out << " release"; break;
2075 case AcquireRelease: Out << " acq_rel"; break;
2076 case SequentiallyConsistent: Out << " seq_cst"; break;
2080 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2081 AtomicOrdering FailureOrdering,
2082 SynchronizationScope SynchScope) {
2083 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2085 switch (SynchScope) {
2086 case SingleThread: Out << " singlethread"; break;
2087 case CrossThread: break;
2090 switch (SuccessOrdering) {
2091 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2092 case Unordered: Out << " unordered"; break;
2093 case Monotonic: Out << " monotonic"; break;
2094 case Acquire: Out << " acquire"; break;
2095 case Release: Out << " release"; break;
2096 case AcquireRelease: Out << " acq_rel"; break;
2097 case SequentiallyConsistent: Out << " seq_cst"; break;
2100 switch (FailureOrdering) {
2101 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2102 case Unordered: Out << " unordered"; break;
2103 case Monotonic: Out << " monotonic"; break;
2104 case Acquire: Out << " acquire"; break;
2105 case Release: Out << " release"; break;
2106 case AcquireRelease: Out << " acq_rel"; break;
2107 case SequentiallyConsistent: Out << " seq_cst"; break;
2111 void AssemblyWriter::writeParamOperand(const Value *Operand,
2112 AttributeSet Attrs, unsigned Idx) {
2114 Out << "<null operand!>";
2119 TypePrinter.print(Operand->getType(), Out);
2120 // Print parameter attributes list
2121 if (Attrs.hasAttributes(Idx))
2122 Out << ' ' << Attrs.getAsString(Idx);
2124 // Print the operand
2125 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2128 void AssemblyWriter::printModule(const Module *M) {
2129 Machine.initialize();
2131 if (ShouldPreserveUseListOrder)
2132 UseListOrders = predictUseListOrder(M);
2134 if (!M->getModuleIdentifier().empty() &&
2135 // Don't print the ID if it will start a new line (which would
2136 // require a comment char before it).
2137 M->getModuleIdentifier().find('\n') == std::string::npos)
2138 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2140 const std::string &DL = M->getDataLayoutStr();
2142 Out << "target datalayout = \"" << DL << "\"\n";
2143 if (!M->getTargetTriple().empty())
2144 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2146 if (!M->getModuleInlineAsm().empty()) {
2149 // Split the string into lines, to make it easier to read the .ll file.
2150 StringRef Asm = M->getModuleInlineAsm();
2153 std::tie(Front, Asm) = Asm.split('\n');
2155 // We found a newline, print the portion of the asm string from the
2156 // last newline up to this newline.
2157 Out << "module asm \"";
2158 PrintEscapedString(Front, Out);
2160 } while (!Asm.empty());
2163 printTypeIdentities();
2165 // Output all comdats.
2166 if (!Comdats.empty())
2168 for (const Comdat *C : Comdats) {
2170 if (C != Comdats.back())
2174 // Output all globals.
2175 if (!M->global_empty()) Out << '\n';
2176 for (const GlobalVariable &GV : M->globals()) {
2177 printGlobal(&GV); Out << '\n';
2180 // Output all aliases.
2181 if (!M->alias_empty()) Out << "\n";
2182 for (const GlobalAlias &GA : M->aliases())
2185 // Output global use-lists.
2186 printUseLists(nullptr);
2188 // Output all of the functions.
2189 for (const Function &F : *M)
2191 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2193 // Output all attribute groups.
2194 if (!Machine.as_empty()) {
2196 writeAllAttributeGroups();
2199 // Output named metadata.
2200 if (!M->named_metadata_empty()) Out << '\n';
2202 for (const NamedMDNode &Node : M->named_metadata())
2203 printNamedMDNode(&Node);
2206 if (!Machine.mdn_empty()) {
2212 static void printMetadataIdentifier(StringRef Name,
2213 formatted_raw_ostream &Out) {
2215 Out << "<empty name> ";
2217 if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2218 Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2221 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2222 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2223 unsigned char C = Name[i];
2224 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2225 C == '.' || C == '_')
2228 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2233 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2235 printMetadataIdentifier(NMD->getName(), Out);
2237 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2240 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2249 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2250 formatted_raw_ostream &Out) {
2252 case GlobalValue::ExternalLinkage: break;
2253 case GlobalValue::PrivateLinkage: Out << "private "; break;
2254 case GlobalValue::InternalLinkage: Out << "internal "; break;
2255 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2256 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2257 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2258 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2259 case GlobalValue::CommonLinkage: Out << "common "; break;
2260 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2261 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2262 case GlobalValue::AvailableExternallyLinkage:
2263 Out << "available_externally ";
2268 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2269 formatted_raw_ostream &Out) {
2271 case GlobalValue::DefaultVisibility: break;
2272 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2273 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2277 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2278 formatted_raw_ostream &Out) {
2280 case GlobalValue::DefaultStorageClass: break;
2281 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2282 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2286 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2287 formatted_raw_ostream &Out) {
2289 case GlobalVariable::NotThreadLocal:
2291 case GlobalVariable::GeneralDynamicTLSModel:
2292 Out << "thread_local ";
2294 case GlobalVariable::LocalDynamicTLSModel:
2295 Out << "thread_local(localdynamic) ";
2297 case GlobalVariable::InitialExecTLSModel:
2298 Out << "thread_local(initialexec) ";
2300 case GlobalVariable::LocalExecTLSModel:
2301 Out << "thread_local(localexec) ";
2306 static void maybePrintComdat(formatted_raw_ostream &Out,
2307 const GlobalObject &GO) {
2308 const Comdat *C = GO.getComdat();
2312 if (isa<GlobalVariable>(GO))
2316 if (GO.getName() == C->getName())
2320 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2324 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2325 if (GV->isMaterializable())
2326 Out << "; Materializable\n";
2328 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2331 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2334 PrintLinkage(GV->getLinkage(), Out);
2335 PrintVisibility(GV->getVisibility(), Out);
2336 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2337 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2338 if (GV->hasUnnamedAddr())
2339 Out << "unnamed_addr ";
2341 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2342 Out << "addrspace(" << AddressSpace << ") ";
2343 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2344 Out << (GV->isConstant() ? "constant " : "global ");
2345 TypePrinter.print(GV->getType()->getElementType(), Out);
2347 if (GV->hasInitializer()) {
2349 writeOperand(GV->getInitializer(), false);
2352 if (GV->hasSection()) {
2353 Out << ", section \"";
2354 PrintEscapedString(GV->getSection(), Out);
2357 maybePrintComdat(Out, *GV);
2358 if (GV->getAlignment())
2359 Out << ", align " << GV->getAlignment();
2361 printInfoComment(*GV);
2364 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2365 if (GA->isMaterializable())
2366 Out << "; Materializable\n";
2368 WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2371 PrintLinkage(GA->getLinkage(), Out);
2372 PrintVisibility(GA->getVisibility(), Out);
2373 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2374 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2375 if (GA->hasUnnamedAddr())
2376 Out << "unnamed_addr ";
2380 const Constant *Aliasee = GA->getAliasee();
2383 TypePrinter.print(GA->getType(), Out);
2384 Out << " <<NULL ALIASEE>>";
2386 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2389 printInfoComment(*GA);
2393 void AssemblyWriter::printComdat(const Comdat *C) {
2397 void AssemblyWriter::printTypeIdentities() {
2398 if (TypePrinter.NumberedTypes.empty() &&
2399 TypePrinter.NamedTypes.empty())
2404 // We know all the numbers that each type is used and we know that it is a
2405 // dense assignment. Convert the map to an index table.
2406 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2407 for (DenseMap<StructType*, unsigned>::iterator I =
2408 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2410 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2411 NumberedTypes[I->second] = I->first;
2414 // Emit all numbered types.
2415 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2416 Out << '%' << i << " = type ";
2418 // Make sure we print out at least one level of the type structure, so
2419 // that we do not get %2 = type %2
2420 TypePrinter.printStructBody(NumberedTypes[i], Out);
2424 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2425 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2428 // Make sure we print out at least one level of the type structure, so
2429 // that we do not get %FILE = type %FILE
2430 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2435 /// printFunction - Print all aspects of a function.
2437 void AssemblyWriter::printFunction(const Function *F) {
2438 // Print out the return type and name.
2441 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2443 if (F->isMaterializable())
2444 Out << "; Materializable\n";
2446 const AttributeSet &Attrs = F->getAttributes();
2447 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2448 AttributeSet AS = Attrs.getFnAttributes();
2449 std::string AttrStr;
2452 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2453 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2456 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2458 Attribute Attr = *I;
2459 if (!Attr.isStringAttribute()) {
2460 if (!AttrStr.empty()) AttrStr += ' ';
2461 AttrStr += Attr.getAsString();
2465 if (!AttrStr.empty())
2466 Out << "; Function Attrs: " << AttrStr << '\n';
2469 if (F->isDeclaration())
2474 PrintLinkage(F->getLinkage(), Out);
2475 PrintVisibility(F->getVisibility(), Out);
2476 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2478 // Print the calling convention.
2479 if (F->getCallingConv() != CallingConv::C) {
2480 PrintCallingConv(F->getCallingConv(), Out);
2484 FunctionType *FT = F->getFunctionType();
2485 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2486 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2487 TypePrinter.print(F->getReturnType(), Out);
2489 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2491 Machine.incorporateFunction(F);
2493 // Loop over the arguments, printing them...
2496 if (!F->isDeclaration()) {
2497 // If this isn't a declaration, print the argument names as well.
2498 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2500 // Insert commas as we go... the first arg doesn't get a comma
2501 if (I != F->arg_begin()) Out << ", ";
2502 printArgument(I, Attrs, Idx);
2506 // Otherwise, print the types from the function type.
2507 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2508 // Insert commas as we go... the first arg doesn't get a comma
2512 TypePrinter.print(FT->getParamType(i), Out);
2514 if (Attrs.hasAttributes(i+1))
2515 Out << ' ' << Attrs.getAsString(i+1);
2519 // Finish printing arguments...
2520 if (FT->isVarArg()) {
2521 if (FT->getNumParams()) Out << ", ";
2522 Out << "..."; // Output varargs portion of signature!
2525 if (F->hasUnnamedAddr())
2526 Out << " unnamed_addr";
2527 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2528 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2529 if (F->hasSection()) {
2530 Out << " section \"";
2531 PrintEscapedString(F->getSection(), Out);
2534 maybePrintComdat(Out, *F);
2535 if (F->getAlignment())
2536 Out << " align " << F->getAlignment();
2538 Out << " gc \"" << F->getGC() << '"';
2539 if (F->hasPrefixData()) {
2541 writeOperand(F->getPrefixData(), true);
2543 if (F->hasPrologueData()) {
2544 Out << " prologue ";
2545 writeOperand(F->getPrologueData(), true);
2547 if (F->hasPersonalityFn()) {
2548 Out << " personality ";
2549 writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2552 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2553 F->getAllMetadata(MDs);
2554 printMetadataAttachments(MDs, " ");
2556 if (F->isDeclaration()) {
2560 // Output all of the function's basic blocks.
2561 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2564 // Output the function's use-lists.
2570 Machine.purgeFunction();
2573 /// printArgument - This member is called for every argument that is passed into
2574 /// the function. Simply print it out
2576 void AssemblyWriter::printArgument(const Argument *Arg,
2577 AttributeSet Attrs, unsigned Idx) {
2579 TypePrinter.print(Arg->getType(), Out);
2581 // Output parameter attributes list
2582 if (Attrs.hasAttributes(Idx))
2583 Out << ' ' << Attrs.getAsString(Idx);
2585 // Output name, if available...
2586 if (Arg->hasName()) {
2588 PrintLLVMName(Out, Arg);
2592 /// printBasicBlock - This member is called for each basic block in a method.
2594 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2595 if (BB->hasName()) { // Print out the label if it exists...
2597 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2599 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2600 Out << "\n; <label>:";
2601 int Slot = Machine.getLocalSlot(BB);
2608 if (!BB->getParent()) {
2609 Out.PadToColumn(50);
2610 Out << "; Error: Block without parent!";
2611 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2612 // Output predecessors for the block.
2613 Out.PadToColumn(50);
2615 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2618 Out << " No predecessors!";
2621 writeOperand(*PI, false);
2622 for (++PI; PI != PE; ++PI) {
2624 writeOperand(*PI, false);
2631 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2633 // Output all of the instructions in the basic block...
2634 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2635 printInstructionLine(*I);
2638 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2641 /// printInstructionLine - Print an instruction and a newline character.
2642 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2643 printInstruction(I);
2647 /// printGCRelocateComment - print comment after call to the gc.relocate
2648 /// intrinsic indicating base and derived pointer names.
2649 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2650 assert(isGCRelocate(&V));
2651 GCRelocateOperands GCOps(cast<Instruction>(&V));
2654 writeOperand(GCOps.getBasePtr(), false);
2656 writeOperand(GCOps.getDerivedPtr(), false);
2660 /// printInfoComment - Print a little comment after the instruction indicating
2661 /// which slot it occupies.
2663 void AssemblyWriter::printInfoComment(const Value &V) {
2664 if (isGCRelocate(&V))
2665 printGCRelocateComment(V);
2667 if (AnnotationWriter)
2668 AnnotationWriter->printInfoComment(V, Out);
2671 // This member is called for each Instruction in a function..
2672 void AssemblyWriter::printInstruction(const Instruction &I) {
2673 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2675 // Print out indentation for an instruction.
2678 // Print out name if it exists...
2680 PrintLLVMName(Out, &I);
2682 } else if (!I.getType()->isVoidTy()) {
2683 // Print out the def slot taken.
2684 int SlotNum = Machine.getLocalSlot(&I);
2686 Out << "<badref> = ";
2688 Out << '%' << SlotNum << " = ";
2691 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2692 if (CI->isMustTailCall())
2694 else if (CI->isTailCall())
2698 // Print out the opcode...
2699 Out << I.getOpcodeName();
2701 // If this is an atomic load or store, print out the atomic marker.
2702 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2703 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2706 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2709 // If this is a volatile operation, print out the volatile marker.
2710 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2711 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2712 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2713 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2716 // Print out optimization information.
2717 WriteOptimizationInfo(Out, &I);
2719 // Print out the compare instruction predicates
2720 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2721 Out << ' ' << getPredicateText(CI->getPredicate());
2723 // Print out the atomicrmw operation
2724 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2725 writeAtomicRMWOperation(Out, RMWI->getOperation());
2727 // Print out the type of the operands...
2728 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2730 // Special case conditional branches to swizzle the condition out to the front
2731 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2732 const BranchInst &BI(cast<BranchInst>(I));
2734 writeOperand(BI.getCondition(), true);
2736 writeOperand(BI.getSuccessor(0), true);
2738 writeOperand(BI.getSuccessor(1), true);
2740 } else if (isa<SwitchInst>(I)) {
2741 const SwitchInst& SI(cast<SwitchInst>(I));
2742 // Special case switch instruction to get formatting nice and correct.
2744 writeOperand(SI.getCondition(), true);
2746 writeOperand(SI.getDefaultDest(), true);
2748 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2751 writeOperand(i.getCaseValue(), true);
2753 writeOperand(i.getCaseSuccessor(), true);
2756 } else if (isa<IndirectBrInst>(I)) {
2757 // Special case indirectbr instruction to get formatting nice and correct.
2759 writeOperand(Operand, true);
2762 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2765 writeOperand(I.getOperand(i), true);
2768 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2770 TypePrinter.print(I.getType(), Out);
2773 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2774 if (op) Out << ", ";
2776 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2777 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2779 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2781 writeOperand(I.getOperand(0), true);
2782 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2784 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2786 writeOperand(I.getOperand(0), true); Out << ", ";
2787 writeOperand(I.getOperand(1), true);
2788 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2790 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2792 TypePrinter.print(I.getType(), Out);
2793 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2796 if (LPI->isCleanup())
2799 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2800 if (i != 0 || LPI->isCleanup()) Out << "\n";
2801 if (LPI->isCatch(i))
2806 writeOperand(LPI->getClause(i), true);
2808 } else if (isa<ReturnInst>(I) && !Operand) {
2810 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2811 // Print the calling convention being used.
2812 if (CI->getCallingConv() != CallingConv::C) {
2814 PrintCallingConv(CI->getCallingConv(), Out);
2817 Operand = CI->getCalledValue();
2818 FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2819 Type *RetTy = FTy->getReturnType();
2820 const AttributeSet &PAL = CI->getAttributes();
2822 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2823 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2825 // If possible, print out the short form of the call instruction. We can
2826 // only do this if the first argument is a pointer to a nonvararg function,
2827 // and if the return type is not a pointer to a function.
2830 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2832 writeOperand(Operand, false);
2834 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2837 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2840 // Emit an ellipsis if this is a musttail call in a vararg function. This
2841 // is only to aid readability, musttail calls forward varargs by default.
2842 if (CI->isMustTailCall() && CI->getParent() &&
2843 CI->getParent()->getParent() &&
2844 CI->getParent()->getParent()->isVarArg())
2848 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2849 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2850 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2851 Operand = II->getCalledValue();
2852 FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
2853 Type *RetTy = FTy->getReturnType();
2854 const AttributeSet &PAL = II->getAttributes();
2856 // Print the calling convention being used.
2857 if (II->getCallingConv() != CallingConv::C) {
2859 PrintCallingConv(II->getCallingConv(), Out);
2862 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2863 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2865 // If possible, print out the short form of the invoke instruction. We can
2866 // only do this if the first argument is a pointer to a nonvararg function,
2867 // and if the return type is not a pointer to a function.
2870 TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2872 writeOperand(Operand, false);
2874 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2877 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
2881 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2882 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2885 writeOperand(II->getNormalDest(), true);
2887 writeOperand(II->getUnwindDest(), true);
2889 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
2891 if (AI->isUsedWithInAlloca())
2893 TypePrinter.print(AI->getAllocatedType(), Out);
2895 // Explicitly write the array size if the code is broken, if it's an array
2896 // allocation, or if the type is not canonical for scalar allocations. The
2897 // latter case prevents the type from mutating when round-tripping through
2899 if (!AI->getArraySize() || AI->isArrayAllocation() ||
2900 !AI->getArraySize()->getType()->isIntegerTy(32)) {
2902 writeOperand(AI->getArraySize(), true);
2904 if (AI->getAlignment()) {
2905 Out << ", align " << AI->getAlignment();
2907 } else if (isa<CastInst>(I)) {
2910 writeOperand(Operand, true); // Work with broken code
2913 TypePrinter.print(I.getType(), Out);
2914 } else if (isa<VAArgInst>(I)) {
2917 writeOperand(Operand, true); // Work with broken code
2920 TypePrinter.print(I.getType(), Out);
2921 } else if (Operand) { // Print the normal way.
2922 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
2924 TypePrinter.print(GEP->getSourceElementType(), Out);
2926 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
2928 TypePrinter.print(LI->getType(), Out);
2932 // PrintAllTypes - Instructions who have operands of all the same type
2933 // omit the type from all but the first operand. If the instruction has
2934 // different type operands (for example br), then they are all printed.
2935 bool PrintAllTypes = false;
2936 Type *TheType = Operand->getType();
2938 // Select, Store and ShuffleVector always print all types.
2939 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2940 || isa<ReturnInst>(I)) {
2941 PrintAllTypes = true;
2943 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2944 Operand = I.getOperand(i);
2945 // note that Operand shouldn't be null, but the test helps make dump()
2946 // more tolerant of malformed IR
2947 if (Operand && Operand->getType() != TheType) {
2948 PrintAllTypes = true; // We have differing types! Print them all!
2954 if (!PrintAllTypes) {
2956 TypePrinter.print(TheType, Out);
2960 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2962 writeOperand(I.getOperand(i), PrintAllTypes);
2966 // Print atomic ordering/alignment for memory operations
2967 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2969 writeAtomic(LI->getOrdering(), LI->getSynchScope());
2970 if (LI->getAlignment())
2971 Out << ", align " << LI->getAlignment();
2972 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2974 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2975 if (SI->getAlignment())
2976 Out << ", align " << SI->getAlignment();
2977 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2978 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
2979 CXI->getSynchScope());
2980 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2981 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2982 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2983 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2986 // Print Metadata info.
2987 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
2988 I.getAllMetadata(InstMD);
2989 printMetadataAttachments(InstMD, ", ");
2991 // Print a nice comment.
2992 printInfoComment(I);
2995 void AssemblyWriter::printMetadataAttachments(
2996 const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2997 StringRef Separator) {
3001 if (MDNames.empty())
3002 TheModule->getMDKindNames(MDNames);
3004 for (const auto &I : MDs) {
3005 unsigned Kind = I.first;
3007 if (Kind < MDNames.size()) {
3009 printMetadataIdentifier(MDNames[Kind], Out);
3011 Out << "!<unknown kind #" << Kind << ">";
3013 WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3017 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3018 Out << '!' << Slot << " = ";
3019 printMDNodeBody(Node);
3023 void AssemblyWriter::writeAllMDNodes() {
3024 SmallVector<const MDNode *, 16> Nodes;
3025 Nodes.resize(Machine.mdn_size());
3026 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3028 Nodes[I->second] = cast<MDNode>(I->first);
3030 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3031 writeMDNode(i, Nodes[i]);
3035 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3036 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3039 void AssemblyWriter::writeAllAttributeGroups() {
3040 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3041 asVec.resize(Machine.as_size());
3043 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3045 asVec[I->second] = *I;
3047 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3048 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3049 Out << "attributes #" << I->second << " = { "
3050 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3053 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3054 bool IsInFunction = Machine.getFunction();
3058 Out << "uselistorder";
3059 if (const BasicBlock *BB =
3060 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3062 writeOperand(BB->getParent(), false);
3064 writeOperand(BB, false);
3067 writeOperand(Order.V, true);
3071 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3072 Out << Order.Shuffle[0];
3073 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3074 Out << ", " << Order.Shuffle[I];
3078 void AssemblyWriter::printUseLists(const Function *F) {
3080 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3085 Out << "\n; uselistorder directives\n";
3087 printUseListOrder(UseListOrders.back());
3088 UseListOrders.pop_back();
3092 //===----------------------------------------------------------------------===//
3093 // External Interface declarations
3094 //===----------------------------------------------------------------------===//
3096 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
3097 SlotTracker SlotTable(this->getParent());
3098 formatted_raw_ostream OS(ROS);
3099 AssemblyWriter W(OS, SlotTable, this->getParent(), AAW);
3100 W.printFunction(this);
3103 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3104 bool ShouldPreserveUseListOrder) const {
3105 SlotTracker SlotTable(this);
3106 formatted_raw_ostream OS(ROS);
3107 AssemblyWriter W(OS, SlotTable, this, AAW, ShouldPreserveUseListOrder);
3108 W.printModule(this);
3111 void NamedMDNode::print(raw_ostream &ROS) const {
3112 SlotTracker SlotTable(getParent());
3113 formatted_raw_ostream OS(ROS);
3114 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
3115 W.printNamedMDNode(this);
3118 void Comdat::print(raw_ostream &ROS) const {
3119 PrintLLVMName(ROS, getName(), ComdatPrefix);
3120 ROS << " = comdat ";
3122 switch (getSelectionKind()) {
3126 case Comdat::ExactMatch:
3127 ROS << "exactmatch";
3129 case Comdat::Largest:
3132 case Comdat::NoDuplicates:
3133 ROS << "noduplicates";
3135 case Comdat::SameSize:
3143 void Type::print(raw_ostream &OS) const {
3145 TP.print(const_cast<Type*>(this), OS);
3147 // If the type is a named struct type, print the body as well.
3148 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3149 if (!STy->isLiteral()) {
3151 TP.printStructBody(STy, OS);
3155 static bool isReferencingMDNode(const Instruction &I) {
3156 if (const auto *CI = dyn_cast<CallInst>(&I))
3157 if (Function *F = CI->getCalledFunction())
3158 if (F->isIntrinsic())
3159 for (auto &Op : I.operands())
3160 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3161 if (isa<MDNode>(V->getMetadata()))
3166 void Value::print(raw_ostream &ROS) const {
3167 formatted_raw_ostream OS(ROS);
3168 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3169 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
3170 SlotTracker SlotTable(
3172 /* ShouldInitializeAllMetadata */ isReferencingMDNode(*I));
3173 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
3174 W.printInstruction(*I);
3175 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3176 SlotTracker SlotTable(BB->getParent());
3177 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
3178 W.printBasicBlock(BB);
3179 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3180 SlotTracker SlotTable(GV->getParent(),
3181 /* ShouldInitializeAllMetadata */ isa<Function>(GV));
3182 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
3183 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3185 else if (const Function *F = dyn_cast<Function>(GV))
3188 W.printAlias(cast<GlobalAlias>(GV));
3189 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3190 V->getMetadata()->print(ROS, getModuleFromVal(V));
3191 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3192 TypePrinting TypePrinter;
3193 TypePrinter.print(C->getType(), OS);
3195 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
3196 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3197 this->printAsOperand(OS);
3199 llvm_unreachable("Unknown value to print out!");
3203 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
3204 // Fast path: Don't construct and populate a TypePrinting object if we
3205 // won't be needing any types printed.
3206 bool IsMetadata = isa<MetadataAsValue>(this);
3207 if (!PrintType && ((!isa<Constant>(this) && !IsMetadata) || hasName() ||
3208 isa<GlobalValue>(this))) {
3209 WriteAsOperandInternal(O, this, nullptr, nullptr, M);
3214 M = getModuleFromVal(this);
3216 TypePrinting TypePrinter;
3218 TypePrinter.incorporateTypes(*M);
3220 TypePrinter.print(getType(), O);
3224 SlotTracker Machine(M, /* ShouldInitializeAllMetadata */ IsMetadata);
3225 WriteAsOperandInternal(O, this, &TypePrinter, &Machine, M);
3228 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3229 const Module *M, bool OnlyAsOperand) {
3230 formatted_raw_ostream OS(ROS);
3232 auto *N = dyn_cast<MDNode>(&MD);
3233 TypePrinting TypePrinter;
3234 SlotTracker Machine(M, /* ShouldInitializeAllMetadata */ N);
3236 TypePrinter.incorporateTypes(*M);
3238 WriteAsOperandInternal(OS, &MD, &TypePrinter, &Machine, M,
3239 /* FromValue */ true);
3240 if (OnlyAsOperand || !N)
3244 WriteMDNodeBodyInternal(OS, N, &TypePrinter, &Machine, M);
3247 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3248 printMetadataImpl(OS, *this, M, /* OnlyAsOperand */ true);
3251 void Metadata::print(raw_ostream &OS, const Module *M) const {
3252 printMetadataImpl(OS, *this, M, /* OnlyAsOperand */ false);
3255 // Value::dump - allow easy printing of Values from the debugger.
3257 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
3259 // Type::dump - allow easy printing of Types from the debugger.
3261 void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
3263 // Module::dump() - Allow printing of Modules from the debugger.
3265 void Module::dump() const { print(dbgs(), nullptr); }
3267 // \brief Allow printing of Comdats from the debugger.
3269 void Comdat::dump() const { print(dbgs()); }
3271 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3273 void NamedMDNode::dump() const { print(dbgs()); }
3276 void Metadata::dump() const { dump(nullptr); }
3279 void Metadata::dump(const Module *M) const {