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/TypeFinder.h"
35 #include "llvm/IR/UseListOrder.h"
36 #include "llvm/IR/ValueSymbolTable.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
47 // Make virtual table appear in this compilation unit.
48 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
56 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
58 unsigned size() const { return IDs.size(); }
59 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
60 std::pair<unsigned, bool> lookup(const Value *V) const {
63 void index(const Value *V) {
64 // Explicitly sequence get-size and insert-value operations to avoid UB.
65 unsigned ID = IDs.size() + 1;
71 static void orderValue(const Value *V, OrderMap &OM) {
72 if (OM.lookup(V).first)
75 if (const Constant *C = dyn_cast<Constant>(V))
76 if (C->getNumOperands() && !isa<GlobalValue>(C))
77 for (const Value *Op : C->operands())
78 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
81 // Note: we cannot cache this lookup above, since inserting into the map
82 // changes the map's size, and thus affects the other IDs.
86 static OrderMap orderModule(const Module *M) {
87 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
88 // and ValueEnumerator::incorporateFunction().
91 for (const GlobalVariable &G : M->globals()) {
92 if (G.hasInitializer())
93 if (!isa<GlobalValue>(G.getInitializer()))
94 orderValue(G.getInitializer(), OM);
97 for (const GlobalAlias &A : M->aliases()) {
98 if (!isa<GlobalValue>(A.getAliasee()))
99 orderValue(A.getAliasee(), OM);
102 for (const Function &F : *M) {
103 if (F.hasPrefixData())
104 if (!isa<GlobalValue>(F.getPrefixData()))
105 orderValue(F.getPrefixData(), OM);
107 if (F.hasPrologueData())
108 if (!isa<GlobalValue>(F.getPrologueData()))
109 orderValue(F.getPrologueData(), OM);
113 if (F.isDeclaration())
116 for (const Argument &A : F.args())
118 for (const BasicBlock &BB : F) {
120 for (const Instruction &I : BB) {
121 for (const Value *Op : I.operands())
122 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
132 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
133 unsigned ID, const OrderMap &OM,
134 UseListOrderStack &Stack) {
135 // Predict use-list order for this one.
136 typedef std::pair<const Use *, unsigned> Entry;
137 SmallVector<Entry, 64> List;
138 for (const Use &U : V->uses())
139 // Check if this user will be serialized.
140 if (OM.lookup(U.getUser()).first)
141 List.push_back(std::make_pair(&U, List.size()));
144 // We may have lost some users.
148 !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
149 if (auto *BA = dyn_cast<BlockAddress>(V))
150 ID = OM.lookup(BA->getBasicBlock()).first;
151 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
152 const Use *LU = L.first;
153 const Use *RU = R.first;
157 auto LID = OM.lookup(LU->getUser()).first;
158 auto RID = OM.lookup(RU->getUser()).first;
160 // If ID is 4, then expect: 7 6 5 1 2 3.
174 // LID and RID are equal, so we have different operands of the same user.
175 // Assume operands are added in order for all instructions.
178 return LU->getOperandNo() < RU->getOperandNo();
179 return LU->getOperandNo() > RU->getOperandNo();
183 List.begin(), List.end(),
184 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
185 // Order is already correct.
188 // Store the shuffle.
189 Stack.emplace_back(V, F, List.size());
190 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
191 for (size_t I = 0, E = List.size(); I != E; ++I)
192 Stack.back().Shuffle[I] = List[I].second;
195 static void predictValueUseListOrder(const Value *V, const Function *F,
196 OrderMap &OM, UseListOrderStack &Stack) {
197 auto &IDPair = OM[V];
198 assert(IDPair.first && "Unmapped value");
200 // Already predicted.
203 // Do the actual prediction.
204 IDPair.second = true;
205 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
206 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
208 // Recursive descent into constants.
209 if (const Constant *C = dyn_cast<Constant>(V))
210 if (C->getNumOperands()) // Visit GlobalValues.
211 for (const Value *Op : C->operands())
212 if (isa<Constant>(Op)) // Visit GlobalValues.
213 predictValueUseListOrder(Op, F, OM, Stack);
216 static UseListOrderStack predictUseListOrder(const Module *M) {
217 OrderMap OM = orderModule(M);
219 // Use-list orders need to be serialized after all the users have been added
220 // to a value, or else the shuffles will be incomplete. Store them per
221 // function in a stack.
223 // Aside from function order, the order of values doesn't matter much here.
224 UseListOrderStack Stack;
226 // We want to visit the functions backward now so we can list function-local
227 // constants in the last Function they're used in. Module-level constants
228 // have already been visited above.
229 for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
230 const Function &F = *I;
231 if (F.isDeclaration())
233 for (const BasicBlock &BB : F)
234 predictValueUseListOrder(&BB, &F, OM, Stack);
235 for (const Argument &A : F.args())
236 predictValueUseListOrder(&A, &F, OM, Stack);
237 for (const BasicBlock &BB : F)
238 for (const Instruction &I : BB)
239 for (const Value *Op : I.operands())
240 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
241 predictValueUseListOrder(Op, &F, OM, Stack);
242 for (const BasicBlock &BB : F)
243 for (const Instruction &I : BB)
244 predictValueUseListOrder(&I, &F, OM, Stack);
247 // Visit globals last.
248 for (const GlobalVariable &G : M->globals())
249 predictValueUseListOrder(&G, nullptr, OM, Stack);
250 for (const Function &F : *M)
251 predictValueUseListOrder(&F, nullptr, OM, Stack);
252 for (const GlobalAlias &A : M->aliases())
253 predictValueUseListOrder(&A, nullptr, OM, Stack);
254 for (const GlobalVariable &G : M->globals())
255 if (G.hasInitializer())
256 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
257 for (const GlobalAlias &A : M->aliases())
258 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
259 for (const Function &F : *M)
260 if (F.hasPrefixData())
261 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
266 static const Module *getModuleFromVal(const Value *V) {
267 if (const Argument *MA = dyn_cast<Argument>(V))
268 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
270 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
271 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
273 if (const Instruction *I = dyn_cast<Instruction>(V)) {
274 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
275 return M ? M->getParent() : nullptr;
278 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
279 return GV->getParent();
281 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
282 for (const User *U : MAV->users())
283 if (isa<Instruction>(U))
284 if (const Module *M = getModuleFromVal(U))
292 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
294 default: Out << "cc" << cc; break;
295 case CallingConv::Fast: Out << "fastcc"; break;
296 case CallingConv::Cold: Out << "coldcc"; break;
297 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
298 case CallingConv::AnyReg: Out << "anyregcc"; break;
299 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
300 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
301 case CallingConv::GHC: Out << "ghccc"; break;
302 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
303 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
304 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
305 case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
306 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
307 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
308 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
309 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
310 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
311 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
312 case CallingConv::PTX_Device: Out << "ptx_device"; break;
313 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
314 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
315 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
316 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
320 // PrintEscapedString - Print each character of the specified string, escaping
321 // it if it is not printable or if it is an escape char.
322 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
323 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
324 unsigned char C = Name[i];
325 if (isprint(C) && C != '\\' && C != '"')
328 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
340 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
341 /// prefixed with % (if the string only contains simple characters) or is
342 /// surrounded with ""'s (if it has special chars in it). Print it out.
343 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
344 assert(!Name.empty() && "Cannot get empty name!");
346 case NoPrefix: break;
347 case GlobalPrefix: OS << '@'; break;
348 case ComdatPrefix: OS << '$'; break;
349 case LabelPrefix: break;
350 case LocalPrefix: OS << '%'; break;
353 // Scan the name to see if it needs quotes first.
354 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
356 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
357 // By making this unsigned, the value passed in to isalnum will always be
358 // in the range 0-255. This is important when building with MSVC because
359 // its implementation will assert. This situation can arise when dealing
360 // with UTF-8 multibyte characters.
361 unsigned char C = Name[i];
362 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
370 // If we didn't need any quotes, just write out the name in one blast.
376 // Okay, we need quotes. Output the quotes and escape any scary characters as
379 PrintEscapedString(Name, OS);
383 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
384 /// prefixed with % (if the string only contains simple characters) or is
385 /// surrounded with ""'s (if it has special chars in it). Print it out.
386 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
387 PrintLLVMName(OS, V->getName(),
388 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
394 TypePrinting(const TypePrinting &) = delete;
395 void operator=(const TypePrinting&) = delete;
398 /// NamedTypes - The named types that are used by the current module.
399 TypeFinder NamedTypes;
401 /// NumberedTypes - The numbered types, along with their value.
402 DenseMap<StructType*, unsigned> NumberedTypes;
408 void incorporateTypes(const Module &M);
410 void print(Type *Ty, raw_ostream &OS);
412 void printStructBody(StructType *Ty, raw_ostream &OS);
416 void TypePrinting::incorporateTypes(const Module &M) {
417 NamedTypes.run(M, false);
419 // The list of struct types we got back includes all the struct types, split
420 // the unnamed ones out to a numbering and remove the anonymous structs.
421 unsigned NextNumber = 0;
423 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
424 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
425 StructType *STy = *I;
427 // Ignore anonymous types.
428 if (STy->isLiteral())
431 if (STy->getName().empty())
432 NumberedTypes[STy] = NextNumber++;
437 NamedTypes.erase(NextToUse, NamedTypes.end());
441 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
442 /// use of type names or up references to shorten the type name where possible.
443 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
444 switch (Ty->getTypeID()) {
445 case Type::VoidTyID: OS << "void"; return;
446 case Type::HalfTyID: OS << "half"; return;
447 case Type::FloatTyID: OS << "float"; return;
448 case Type::DoubleTyID: OS << "double"; return;
449 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
450 case Type::FP128TyID: OS << "fp128"; return;
451 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
452 case Type::LabelTyID: OS << "label"; return;
453 case Type::MetadataTyID: OS << "metadata"; return;
454 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
455 case Type::IntegerTyID:
456 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
459 case Type::FunctionTyID: {
460 FunctionType *FTy = cast<FunctionType>(Ty);
461 print(FTy->getReturnType(), OS);
463 for (FunctionType::param_iterator I = FTy->param_begin(),
464 E = FTy->param_end(); I != E; ++I) {
465 if (I != FTy->param_begin())
469 if (FTy->isVarArg()) {
470 if (FTy->getNumParams()) OS << ", ";
476 case Type::StructTyID: {
477 StructType *STy = cast<StructType>(Ty);
479 if (STy->isLiteral())
480 return printStructBody(STy, OS);
482 if (!STy->getName().empty())
483 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
485 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
486 if (I != NumberedTypes.end())
487 OS << '%' << I->second;
488 else // Not enumerated, print the hex address.
489 OS << "%\"type " << STy << '\"';
492 case Type::PointerTyID: {
493 PointerType *PTy = cast<PointerType>(Ty);
494 print(PTy->getElementType(), OS);
495 if (unsigned AddressSpace = PTy->getAddressSpace())
496 OS << " addrspace(" << AddressSpace << ')';
500 case Type::ArrayTyID: {
501 ArrayType *ATy = cast<ArrayType>(Ty);
502 OS << '[' << ATy->getNumElements() << " x ";
503 print(ATy->getElementType(), OS);
507 case Type::VectorTyID: {
508 VectorType *PTy = cast<VectorType>(Ty);
509 OS << "<" << PTy->getNumElements() << " x ";
510 print(PTy->getElementType(), OS);
515 llvm_unreachable("Invalid TypeID");
518 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
519 if (STy->isOpaque()) {
527 if (STy->getNumElements() == 0) {
530 StructType::element_iterator I = STy->element_begin();
533 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
545 //===----------------------------------------------------------------------===//
546 // SlotTracker Class: Enumerate slot numbers for unnamed values
547 //===----------------------------------------------------------------------===//
548 /// This class provides computation of slot numbers for LLVM Assembly writing.
552 /// ValueMap - A mapping of Values to slot numbers.
553 typedef DenseMap<const Value*, unsigned> ValueMap;
556 /// TheModule - The module for which we are holding slot numbers.
557 const Module* TheModule;
559 /// TheFunction - The function for which we are holding slot numbers.
560 const Function* TheFunction;
561 bool FunctionProcessed;
562 bool ShouldInitializeAllMetadata;
564 /// mMap - The slot map for the module level data.
568 /// fMap - The slot map for the function level data.
572 /// mdnMap - Map for MDNodes.
573 DenseMap<const MDNode*, unsigned> mdnMap;
576 /// asMap - The slot map for attribute sets.
577 DenseMap<AttributeSet, unsigned> asMap;
580 /// Construct from a module.
582 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
583 /// functions, giving correct numbering for metadata referenced only from
584 /// within a function (even if no functions have been initialized).
585 explicit SlotTracker(const Module *M,
586 bool ShouldInitializeAllMetadata = false);
587 /// Construct from a function, starting out in incorp state.
589 /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
590 /// functions, giving correct numbering for metadata referenced only from
591 /// within a function (even if no functions have been initialized).
592 explicit SlotTracker(const Function *F,
593 bool ShouldInitializeAllMetadata = false);
595 /// Return the slot number of the specified value in it's type
596 /// plane. If something is not in the SlotTracker, return -1.
597 int getLocalSlot(const Value *V);
598 int getGlobalSlot(const GlobalValue *V);
599 int getMetadataSlot(const MDNode *N);
600 int getAttributeGroupSlot(AttributeSet AS);
602 /// If you'd like to deal with a function instead of just a module, use
603 /// this method to get its data into the SlotTracker.
604 void incorporateFunction(const Function *F) {
606 FunctionProcessed = false;
609 const Function *getFunction() const { return TheFunction; }
611 /// After calling incorporateFunction, use this method to remove the
612 /// most recently incorporated function from the SlotTracker. This
613 /// will reset the state of the machine back to just the module contents.
614 void purgeFunction();
616 /// MDNode map iterators.
617 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
618 mdn_iterator mdn_begin() { return mdnMap.begin(); }
619 mdn_iterator mdn_end() { return mdnMap.end(); }
620 unsigned mdn_size() const { return mdnMap.size(); }
621 bool mdn_empty() const { return mdnMap.empty(); }
623 /// AttributeSet map iterators.
624 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
625 as_iterator as_begin() { return asMap.begin(); }
626 as_iterator as_end() { return asMap.end(); }
627 unsigned as_size() const { return asMap.size(); }
628 bool as_empty() const { return asMap.empty(); }
630 /// This function does the actual initialization.
631 inline void initialize();
633 // Implementation Details
635 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
636 void CreateModuleSlot(const GlobalValue *V);
638 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
639 void CreateMetadataSlot(const MDNode *N);
641 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
642 void CreateFunctionSlot(const Value *V);
644 /// \brief Insert the specified AttributeSet into the slot table.
645 void CreateAttributeSetSlot(AttributeSet AS);
647 /// Add all of the module level global variables (and their initializers)
648 /// and function declarations, but not the contents of those functions.
649 void processModule();
651 /// Add all of the functions arguments, basic blocks, and instructions.
652 void processFunction();
654 /// Add all of the metadata from a function.
655 void processFunctionMetadata(const Function &F);
657 /// Add all of the metadata from an instruction.
658 void processInstructionMetadata(const Instruction &I);
660 SlotTracker(const SlotTracker &) = delete;
661 void operator=(const SlotTracker &) = delete;
665 static SlotTracker *createSlotTracker(const Module *M) {
666 return new SlotTracker(M);
669 static SlotTracker *createSlotTracker(const Value *V) {
670 if (const Argument *FA = dyn_cast<Argument>(V))
671 return new SlotTracker(FA->getParent());
673 if (const Instruction *I = dyn_cast<Instruction>(V))
675 return new SlotTracker(I->getParent()->getParent());
677 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
678 return new SlotTracker(BB->getParent());
680 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
681 return new SlotTracker(GV->getParent());
683 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
684 return new SlotTracker(GA->getParent());
686 if (const Function *Func = dyn_cast<Function>(V))
687 return new SlotTracker(Func);
693 #define ST_DEBUG(X) dbgs() << X
698 // Module level constructor. Causes the contents of the Module (sans functions)
699 // to be added to the slot table.
700 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
701 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
702 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
703 fNext(0), mdnNext(0), asNext(0) {}
705 // Function level constructor. Causes the contents of the Module and the one
706 // function provided to be added to the slot table.
707 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
708 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
709 FunctionProcessed(false),
710 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
711 fNext(0), mdnNext(0), asNext(0) {}
713 inline void SlotTracker::initialize() {
716 TheModule = nullptr; ///< Prevent re-processing next time we're called.
719 if (TheFunction && !FunctionProcessed)
723 // Iterate through all the global variables, functions, and global
724 // variable initializers and create slots for them.
725 void SlotTracker::processModule() {
726 ST_DEBUG("begin processModule!\n");
728 // Add all of the unnamed global variables to the value table.
729 for (Module::const_global_iterator I = TheModule->global_begin(),
730 E = TheModule->global_end(); I != E; ++I) {
735 // Add metadata used by named metadata.
736 for (Module::const_named_metadata_iterator
737 I = TheModule->named_metadata_begin(),
738 E = TheModule->named_metadata_end(); I != E; ++I) {
739 const NamedMDNode *NMD = I;
740 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
741 CreateMetadataSlot(NMD->getOperand(i));
744 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
747 // Add all the unnamed functions to the table.
750 if (ShouldInitializeAllMetadata)
751 processFunctionMetadata(*I);
753 // Add all the function attributes to the table.
754 // FIXME: Add attributes of other objects?
755 AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
756 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
757 CreateAttributeSetSlot(FnAttrs);
760 ST_DEBUG("end processModule!\n");
763 // Process the arguments, basic blocks, and instructions of a function.
764 void SlotTracker::processFunction() {
765 ST_DEBUG("begin processFunction!\n");
768 // Add all the function arguments with no names.
769 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
770 AE = TheFunction->arg_end(); AI != AE; ++AI)
772 CreateFunctionSlot(AI);
774 ST_DEBUG("Inserting Instructions:\n");
776 // Add all of the basic blocks and instructions with no names.
777 for (auto &BB : *TheFunction) {
779 CreateFunctionSlot(&BB);
782 if (!I.getType()->isVoidTy() && !I.hasName())
783 CreateFunctionSlot(&I);
785 processInstructionMetadata(I);
787 // We allow direct calls to any llvm.foo function here, because the
788 // target may not be linked into the optimizer.
789 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
790 // Add all the call attributes to the table.
791 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
792 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
793 CreateAttributeSetSlot(Attrs);
794 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
795 // Add all the call attributes to the table.
796 AttributeSet Attrs = II->getAttributes().getFnAttributes();
797 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
798 CreateAttributeSetSlot(Attrs);
803 FunctionProcessed = true;
805 ST_DEBUG("end processFunction!\n");
808 void SlotTracker::processFunctionMetadata(const Function &F) {
811 processInstructionMetadata(I);
814 void SlotTracker::processInstructionMetadata(const Instruction &I) {
815 // Process metadata used directly by intrinsics.
816 if (const CallInst *CI = dyn_cast<CallInst>(&I))
817 if (Function *F = CI->getCalledFunction())
818 if (F->isIntrinsic())
819 for (auto &Op : I.operands())
820 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
821 if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
822 CreateMetadataSlot(N);
824 // Process metadata attached to this instruction.
825 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
826 I.getAllMetadata(MDs);
828 CreateMetadataSlot(MD.second);
831 /// Clean up after incorporating a function. This is the only way to get out of
832 /// the function incorporation state that affects get*Slot/Create*Slot. Function
833 /// incorporation state is indicated by TheFunction != 0.
834 void SlotTracker::purgeFunction() {
835 ST_DEBUG("begin purgeFunction!\n");
836 fMap.clear(); // Simply discard the function level map
837 TheFunction = nullptr;
838 FunctionProcessed = false;
839 ST_DEBUG("end purgeFunction!\n");
842 /// getGlobalSlot - Get the slot number of a global value.
843 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
844 // Check for uninitialized state and do lazy initialization.
847 // Find the value in the module map
848 ValueMap::iterator MI = mMap.find(V);
849 return MI == mMap.end() ? -1 : (int)MI->second;
852 /// getMetadataSlot - Get the slot number of a MDNode.
853 int SlotTracker::getMetadataSlot(const MDNode *N) {
854 // Check for uninitialized state and do lazy initialization.
857 // Find the MDNode in the module map
858 mdn_iterator MI = mdnMap.find(N);
859 return MI == mdnMap.end() ? -1 : (int)MI->second;
863 /// getLocalSlot - Get the slot number for a value that is local to a function.
864 int SlotTracker::getLocalSlot(const Value *V) {
865 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
867 // Check for uninitialized state and do lazy initialization.
870 ValueMap::iterator FI = fMap.find(V);
871 return FI == fMap.end() ? -1 : (int)FI->second;
874 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
875 // Check for uninitialized state and do lazy initialization.
878 // Find the AttributeSet in the module map.
879 as_iterator AI = asMap.find(AS);
880 return AI == asMap.end() ? -1 : (int)AI->second;
883 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
884 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
885 assert(V && "Can't insert a null Value into SlotTracker!");
886 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
887 assert(!V->hasName() && "Doesn't need a slot!");
889 unsigned DestSlot = mNext++;
892 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
894 // G = Global, F = Function, A = Alias, o = other
895 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
896 (isa<Function>(V) ? 'F' :
897 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
900 /// CreateSlot - Create a new slot for the specified value if it has no name.
901 void SlotTracker::CreateFunctionSlot(const Value *V) {
902 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
904 unsigned DestSlot = fNext++;
907 // G = Global, F = Function, o = other
908 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
909 DestSlot << " [o]\n");
912 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
913 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
914 assert(N && "Can't insert a null Value into SlotTracker!");
916 unsigned DestSlot = mdnNext;
917 if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
921 // Recursively add any MDNodes referenced by operands.
922 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
923 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
924 CreateMetadataSlot(Op);
927 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
928 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
929 "Doesn't need a slot!");
931 as_iterator I = asMap.find(AS);
932 if (I != asMap.end())
935 unsigned DestSlot = asNext++;
936 asMap[AS] = DestSlot;
939 //===----------------------------------------------------------------------===//
940 // AsmWriter Implementation
941 //===----------------------------------------------------------------------===//
943 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
944 TypePrinting *TypePrinter,
945 SlotTracker *Machine,
946 const Module *Context);
948 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
949 TypePrinting *TypePrinter,
950 SlotTracker *Machine, const Module *Context,
951 bool FromValue = false);
953 static const char *getPredicateText(unsigned predicate) {
954 const char * pred = "unknown";
956 case FCmpInst::FCMP_FALSE: pred = "false"; break;
957 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
958 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
959 case FCmpInst::FCMP_OGE: pred = "oge"; break;
960 case FCmpInst::FCMP_OLT: pred = "olt"; break;
961 case FCmpInst::FCMP_OLE: pred = "ole"; break;
962 case FCmpInst::FCMP_ONE: pred = "one"; break;
963 case FCmpInst::FCMP_ORD: pred = "ord"; break;
964 case FCmpInst::FCMP_UNO: pred = "uno"; break;
965 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
966 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
967 case FCmpInst::FCMP_UGE: pred = "uge"; break;
968 case FCmpInst::FCMP_ULT: pred = "ult"; break;
969 case FCmpInst::FCMP_ULE: pred = "ule"; break;
970 case FCmpInst::FCMP_UNE: pred = "une"; break;
971 case FCmpInst::FCMP_TRUE: pred = "true"; break;
972 case ICmpInst::ICMP_EQ: pred = "eq"; break;
973 case ICmpInst::ICMP_NE: pred = "ne"; break;
974 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
975 case ICmpInst::ICMP_SGE: pred = "sge"; break;
976 case ICmpInst::ICMP_SLT: pred = "slt"; break;
977 case ICmpInst::ICMP_SLE: pred = "sle"; break;
978 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
979 case ICmpInst::ICMP_UGE: pred = "uge"; break;
980 case ICmpInst::ICMP_ULT: pred = "ult"; break;
981 case ICmpInst::ICMP_ULE: pred = "ule"; break;
986 static void writeAtomicRMWOperation(raw_ostream &Out,
987 AtomicRMWInst::BinOp Op) {
989 default: Out << " <unknown operation " << Op << ">"; break;
990 case AtomicRMWInst::Xchg: Out << " xchg"; break;
991 case AtomicRMWInst::Add: Out << " add"; break;
992 case AtomicRMWInst::Sub: Out << " sub"; break;
993 case AtomicRMWInst::And: Out << " and"; break;
994 case AtomicRMWInst::Nand: Out << " nand"; break;
995 case AtomicRMWInst::Or: Out << " or"; break;
996 case AtomicRMWInst::Xor: Out << " xor"; break;
997 case AtomicRMWInst::Max: Out << " max"; break;
998 case AtomicRMWInst::Min: Out << " min"; break;
999 case AtomicRMWInst::UMax: Out << " umax"; break;
1000 case AtomicRMWInst::UMin: Out << " umin"; break;
1004 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1005 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1006 // Unsafe algebra implies all the others, no need to write them all out
1007 if (FPO->hasUnsafeAlgebra())
1010 if (FPO->hasNoNaNs())
1012 if (FPO->hasNoInfs())
1014 if (FPO->hasNoSignedZeros())
1016 if (FPO->hasAllowReciprocal())
1021 if (const OverflowingBinaryOperator *OBO =
1022 dyn_cast<OverflowingBinaryOperator>(U)) {
1023 if (OBO->hasNoUnsignedWrap())
1025 if (OBO->hasNoSignedWrap())
1027 } else if (const PossiblyExactOperator *Div =
1028 dyn_cast<PossiblyExactOperator>(U)) {
1031 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1032 if (GEP->isInBounds())
1037 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1038 TypePrinting &TypePrinter,
1039 SlotTracker *Machine,
1040 const Module *Context) {
1041 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1042 if (CI->getType()->isIntegerTy(1)) {
1043 Out << (CI->getZExtValue() ? "true" : "false");
1046 Out << CI->getValue();
1050 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1051 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1052 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1053 // We would like to output the FP constant value in exponential notation,
1054 // but we cannot do this if doing so will lose precision. Check here to
1055 // make sure that we only output it in exponential format if we can parse
1056 // the value back and get the same value.
1059 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
1060 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1061 bool isInf = CFP->getValueAPF().isInfinity();
1062 bool isNaN = CFP->getValueAPF().isNaN();
1063 if (!isHalf && !isInf && !isNaN) {
1064 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1065 CFP->getValueAPF().convertToFloat();
1066 SmallString<128> StrVal;
1067 raw_svector_ostream(StrVal) << Val;
1069 // Check to make sure that the stringized number is not some string like
1070 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
1071 // that the string matches the "[-+]?[0-9]" regex.
1073 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1074 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1075 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1076 // Reparse stringized version!
1077 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1083 // Otherwise we could not reparse it to exactly the same value, so we must
1084 // output the string in hexadecimal format! Note that loading and storing
1085 // floating point types changes the bits of NaNs on some hosts, notably
1086 // x86, so we must not use these types.
1087 static_assert(sizeof(double) == sizeof(uint64_t),
1088 "assuming that double is 64 bits!");
1090 APFloat apf = CFP->getValueAPF();
1091 // Halves and floats are represented in ASCII IR as double, convert.
1093 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1096 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1101 // Either half, or some form of long double.
1102 // These appear as a magic letter identifying the type, then a
1103 // fixed number of hex digits.
1105 // Bit position, in the current word, of the next nibble to print.
1108 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1110 // api needed to prevent premature destruction
1111 APInt api = CFP->getValueAPF().bitcastToAPInt();
1112 const uint64_t* p = api.getRawData();
1113 uint64_t word = p[1];
1115 int width = api.getBitWidth();
1116 for (int j=0; j<width; j+=4, shiftcount-=4) {
1117 unsigned int nibble = (word>>shiftcount) & 15;
1119 Out << (unsigned char)(nibble + '0');
1121 Out << (unsigned char)(nibble - 10 + 'A');
1122 if (shiftcount == 0 && j+4 < width) {
1126 shiftcount = width-j-4;
1130 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1133 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1136 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1140 llvm_unreachable("Unsupported floating point type");
1141 // api needed to prevent premature destruction
1142 APInt api = CFP->getValueAPF().bitcastToAPInt();
1143 const uint64_t* p = api.getRawData();
1145 int width = api.getBitWidth();
1146 for (int j=0; j<width; j+=4, shiftcount-=4) {
1147 unsigned int nibble = (word>>shiftcount) & 15;
1149 Out << (unsigned char)(nibble + '0');
1151 Out << (unsigned char)(nibble - 10 + 'A');
1152 if (shiftcount == 0 && j+4 < width) {
1156 shiftcount = width-j-4;
1162 if (isa<ConstantAggregateZero>(CV)) {
1163 Out << "zeroinitializer";
1167 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1168 Out << "blockaddress(";
1169 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1172 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1178 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1179 Type *ETy = CA->getType()->getElementType();
1181 TypePrinter.print(ETy, Out);
1183 WriteAsOperandInternal(Out, CA->getOperand(0),
1184 &TypePrinter, Machine,
1186 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1188 TypePrinter.print(ETy, Out);
1190 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1197 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1198 // As a special case, print the array as a string if it is an array of
1199 // i8 with ConstantInt values.
1200 if (CA->isString()) {
1202 PrintEscapedString(CA->getAsString(), Out);
1207 Type *ETy = CA->getType()->getElementType();
1209 TypePrinter.print(ETy, Out);
1211 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1212 &TypePrinter, Machine,
1214 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1216 TypePrinter.print(ETy, Out);
1218 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1226 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1227 if (CS->getType()->isPacked())
1230 unsigned N = CS->getNumOperands();
1233 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1236 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1239 for (unsigned i = 1; i < N; i++) {
1241 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1244 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1251 if (CS->getType()->isPacked())
1256 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1257 Type *ETy = CV->getType()->getVectorElementType();
1259 TypePrinter.print(ETy, Out);
1261 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1263 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1265 TypePrinter.print(ETy, Out);
1267 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1274 if (isa<ConstantPointerNull>(CV)) {
1279 if (isa<UndefValue>(CV)) {
1284 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1285 Out << CE->getOpcodeName();
1286 WriteOptimizationInfo(Out, CE);
1287 if (CE->isCompare())
1288 Out << ' ' << getPredicateText(CE->getPredicate());
1291 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1293 cast<PointerType>(GEP->getPointerOperandType()->getScalarType())
1299 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1300 TypePrinter.print((*OI)->getType(), Out);
1302 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1303 if (OI+1 != CE->op_end())
1307 if (CE->hasIndices()) {
1308 ArrayRef<unsigned> Indices = CE->getIndices();
1309 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1310 Out << ", " << Indices[i];
1315 TypePrinter.print(CE->getType(), Out);
1322 Out << "<placeholder or erroneous Constant>";
1325 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1326 TypePrinting *TypePrinter, SlotTracker *Machine,
1327 const Module *Context) {
1329 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1330 const Metadata *MD = Node->getOperand(mi);
1333 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1334 Value *V = MDV->getValue();
1335 TypePrinter->print(V->getType(), Out);
1337 WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1339 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1349 struct FieldSeparator {
1352 FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1354 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1359 return OS << FS.Sep;
1363 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1364 TypePrinting *TypePrinter,
1365 SlotTracker *Machine,
1366 const Module *Context) {
1371 WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1374 static void writeTag(raw_ostream &Out, FieldSeparator &FS, const DebugNode *N) {
1375 Out << FS << "tag: ";
1376 if (const char *Tag = dwarf::TagString(N->getTag()))
1382 static void writeStringField(raw_ostream &Out, FieldSeparator &FS,
1383 StringRef Name, StringRef Value,
1384 bool ShouldSkipEmpty = true) {
1385 if (ShouldSkipEmpty && Value.empty())
1388 Out << FS << Name << ": \"";
1389 PrintEscapedString(Value, Out);
1393 static void writeGenericDebugNode(raw_ostream &Out, const GenericDebugNode *N,
1394 TypePrinting *TypePrinter,
1395 SlotTracker *Machine, const Module *Context) {
1396 Out << "!GenericDebugNode(";
1398 writeTag(Out, FS, N);
1399 writeStringField(Out, FS, "header", N->getHeader());
1400 if (N->getNumDwarfOperands()) {
1401 Out << FS << "operands: {";
1403 for (auto &I : N->dwarf_operands()) {
1405 writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1412 static void writeMDLocation(raw_ostream &Out, const MDLocation *DL,
1413 TypePrinting *TypePrinter, SlotTracker *Machine,
1414 const Module *Context) {
1415 Out << "!MDLocation(";
1417 // Always output the line, since 0 is a relevant and important value for it.
1418 Out << FS << "line: " << DL->getLine();
1419 if (DL->getColumn())
1420 Out << FS << "column: " << DL->getColumn();
1421 Out << FS << "scope: ";
1422 WriteAsOperandInternal(Out, DL->getScope(), TypePrinter, Machine, Context);
1423 if (DL->getInlinedAt()) {
1424 Out << FS << "inlinedAt: ";
1425 WriteAsOperandInternal(Out, DL->getInlinedAt(), TypePrinter, Machine,
1431 static void writeMDSubrange(raw_ostream &Out, const MDSubrange *N,
1432 TypePrinting *, SlotTracker *, const Module *) {
1433 Out << "!MDSubrange(";
1435 Out << FS << "count: " << N->getCount();
1437 Out << FS << "lowerBound: " << N->getLo();
1441 static void writeMDEnumerator(raw_ostream &Out, const MDEnumerator *N,
1442 TypePrinting *, SlotTracker *, const Module *) {
1443 Out << "!MDEnumerator(";
1445 writeStringField(Out, FS, "name", N->getName(), /* ShouldSkipEmpty */ false);
1446 Out << FS << "value: " << N->getValue();
1450 static void writeMDBasicType(raw_ostream &Out, const MDBasicType *N,
1451 TypePrinting *, SlotTracker *, const Module *) {
1452 Out << "!MDBasicType(";
1454 if (N->getTag() != dwarf::DW_TAG_base_type)
1455 writeTag(Out, FS, N);
1456 writeStringField(Out, FS, "name", N->getName());
1457 if (N->getSizeInBits())
1458 Out << FS << "size: " << N->getSizeInBits();
1459 if (N->getAlignInBits())
1460 Out << FS << "align: " << N->getAlignInBits();
1461 if (unsigned Encoding = N->getEncoding()) {
1462 Out << FS << "encoding: ";
1463 if (const char *S = dwarf::AttributeEncodingString(Encoding))
1471 static void writeDIFlags(raw_ostream &Out, unsigned Flags) {
1472 SmallVector<unsigned, 8> SplitFlags;
1473 unsigned Extra = DIDescriptor::splitFlags(Flags, SplitFlags);
1475 FieldSeparator FS(" | ");
1476 for (unsigned F : SplitFlags) {
1477 const char *StringF = DIDescriptor::getFlagString(F);
1478 assert(StringF && "Expected valid flag");
1479 Out << FS << StringF;
1481 if (Extra || SplitFlags.empty())
1485 static void writeMDDerivedType(raw_ostream &Out, const MDDerivedType *N,
1486 TypePrinting *TypePrinter, SlotTracker *Machine,
1487 const Module *Context) {
1488 Out << "!MDDerivedType(";
1490 writeTag(Out, FS, N);
1491 writeStringField(Out, FS, "name", N->getName());
1492 if (N->getScope()) {
1493 Out << FS << "scope: ";
1494 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1497 Out << FS << "file: ";
1498 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1502 Out << FS << "line: " << N->getLine();
1503 Out << FS << "baseType: ";
1504 writeMetadataAsOperand(Out, N->getBaseType(), TypePrinter, Machine, Context);
1505 if (N->getSizeInBits())
1506 Out << FS << "size: " << N->getSizeInBits();
1507 if (N->getAlignInBits())
1508 Out << FS << "align: " << N->getAlignInBits();
1509 if (N->getOffsetInBits())
1510 Out << FS << "offset: " << N->getOffsetInBits();
1511 if (auto Flags = N->getFlags()) {
1512 Out << FS << "flags: ";
1513 writeDIFlags(Out, Flags);
1515 if (N->getExtraData()) {
1516 Out << FS << "extraData: ";
1517 writeMetadataAsOperand(Out, N->getExtraData(), TypePrinter, Machine,
1523 static void writeMDCompositeType(raw_ostream &Out, const MDCompositeType *N,
1524 TypePrinting *TypePrinter,
1525 SlotTracker *Machine, const Module *Context) {
1526 Out << "!MDCompositeType(";
1528 writeTag(Out, FS, N);
1529 writeStringField(Out, FS, "name", N->getName());
1530 if (N->getScope()) {
1531 Out << FS << "scope: ";
1532 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1535 Out << FS << "file: ";
1536 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1540 Out << FS << "line: " << N->getLine();
1541 if (N->getBaseType()) {
1542 Out << FS << "baseType: ";
1543 writeMetadataAsOperand(Out, N->getBaseType(), TypePrinter, Machine,
1546 if (N->getSizeInBits())
1547 Out << FS << "size: " << N->getSizeInBits();
1548 if (N->getAlignInBits())
1549 Out << FS << "align: " << N->getAlignInBits();
1550 if (N->getOffsetInBits())
1551 Out << FS << "offset: " << N->getOffsetInBits();
1552 if (auto Flags = N->getFlags()) {
1553 Out << FS << "flags: ";
1554 writeDIFlags(Out, Flags);
1556 if (N->getElements()) {
1557 Out << FS << "elements: ";
1558 writeMetadataAsOperand(Out, N->getElements(), TypePrinter, Machine,
1561 if (unsigned Lang = N->getRuntimeLang()) {
1562 Out << FS << "runtimeLang: ";
1563 if (const char *S = dwarf::LanguageString(Lang))
1569 if (N->getVTableHolder()) {
1570 Out << FS << "vtableHolder: ";
1571 writeMetadataAsOperand(Out, N->getVTableHolder(), TypePrinter, Machine,
1574 if (N->getTemplateParams()) {
1575 Out << FS << "templateParams: ";
1576 writeMetadataAsOperand(Out, N->getTemplateParams(), TypePrinter, Machine,
1579 writeStringField(Out, FS, "identifier", N->getIdentifier());
1583 static void writeMDSubroutineType(raw_ostream &Out, const MDSubroutineType *N,
1584 TypePrinting *TypePrinter,
1585 SlotTracker *Machine, const Module *Context) {
1586 Out << "!MDSubroutineType(";
1588 if (auto Flags = N->getFlags()) {
1589 Out << FS << "flags: ";
1590 writeDIFlags(Out, Flags);
1592 Out << FS << "types: ";
1593 writeMetadataAsOperand(Out, N->getTypeArray(), TypePrinter, Machine, Context);
1597 static void writeMDFile(raw_ostream &Out, const MDFile *N, TypePrinting *,
1598 SlotTracker *, const Module *) {
1601 writeStringField(Out, FS, "filename", N->getFilename(),
1602 /* ShouldSkipEmpty */ false);
1603 writeStringField(Out, FS, "directory", N->getDirectory(),
1604 /* ShouldSkipEmpty */ false);
1608 static void writeMDCompileUnit(raw_ostream &Out, const MDCompileUnit *N,
1609 TypePrinting *TypePrinter, SlotTracker *Machine,
1610 const Module *Context) {
1611 Out << "!MDCompileUnit(";
1613 Out << FS << "language: ";
1614 if (const char *Lang = dwarf::LanguageString(N->getSourceLanguage()))
1617 Out << N->getSourceLanguage();
1618 Out << FS << "file: ";
1619 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine, Context);
1620 writeStringField(Out, FS, "producer", N->getProducer());
1621 Out << FS << "isOptimized: " << (N->isOptimized() ? "true" : "false");
1622 writeStringField(Out, FS, "flags", N->getFlags());
1623 Out << FS << "runtimeVersion: " << N->getRuntimeVersion();
1624 writeStringField(Out, FS, "splitDebugFilename", N->getSplitDebugFilename());
1625 Out << FS << "emissionKind: " << N->getEmissionKind();
1626 if (N->getEnumTypes()) {
1627 Out << FS << "enums: ";
1628 writeMetadataAsOperand(Out, N->getEnumTypes(), TypePrinter, Machine,
1631 if (N->getRetainedTypes()) {
1632 Out << FS << "retainedTypes: ";
1633 writeMetadataAsOperand(Out, N->getRetainedTypes(), TypePrinter, Machine,
1636 if (N->getSubprograms()) {
1637 Out << FS << "subprograms: ";
1638 writeMetadataAsOperand(Out, N->getSubprograms(), TypePrinter, Machine,
1641 if (N->getGlobalVariables()) {
1642 Out << FS << "globals: ";
1643 writeMetadataAsOperand(Out, N->getGlobalVariables(), TypePrinter, Machine,
1646 if (N->getImportedEntities()) {
1647 Out << FS << "imports: ";
1648 writeMetadataAsOperand(Out, N->getImportedEntities(), TypePrinter, Machine,
1654 static void writeMDSubprogram(raw_ostream &Out, const MDSubprogram *N,
1655 TypePrinting *TypePrinter, SlotTracker *Machine,
1656 const Module *Context) {
1657 Out << "!MDSubprogram(";
1659 writeStringField(Out, FS, "name", N->getName());
1660 writeStringField(Out, FS, "linkageName", N->getLinkageName());
1661 Out << FS << "scope: ";
1662 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1664 Out << FS << "file: ";
1665 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1669 Out << FS << "line: " << N->getLine();
1671 Out << FS << "type: ";
1672 writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine,
1675 Out << FS << "isLocal: " << (N->isLocalToUnit() ? "true" : "false");
1676 Out << FS << "isDefinition: " << (N->isDefinition() ? "true" : "false");
1677 if (N->getScopeLine())
1678 Out << FS << "scopeLine: " << N->getScopeLine();
1679 if (N->getContainingType()) {
1680 Out << FS << "containingType: ";
1681 writeMetadataAsOperand(Out, N->getContainingType(), TypePrinter, Machine,
1684 if (unsigned V = N->getVirtuality()) {
1685 Out << FS << "virtuality: ";
1686 if (const char *S = dwarf::VirtualityString(V))
1691 if (N->getVirtualIndex())
1692 Out << FS << "virtualIndex: " << N->getVirtualIndex();
1693 if (auto Flags = N->getFlags()) {
1694 Out << FS << "flags: ";
1695 writeDIFlags(Out, Flags);
1697 Out << FS << "isOptimized: " << (N->isOptimized() ? "true" : "false");
1698 if (N->getFunction()) {
1699 Out << FS << "function: ";
1700 writeMetadataAsOperand(Out, N->getFunction(), TypePrinter, Machine,
1703 if (N->getTemplateParams()) {
1704 Out << FS << "templateParams: ";
1705 writeMetadataAsOperand(Out, N->getTemplateParams(), TypePrinter, Machine,
1708 if (N->getDeclaration()) {
1709 Out << FS << "declaration: ";
1710 writeMetadataAsOperand(Out, N->getDeclaration(), TypePrinter, Machine,
1713 if (N->getVariables()) {
1714 Out << FS << "variables: ";
1715 writeMetadataAsOperand(Out, N->getVariables(), TypePrinter, Machine,
1721 static void writeMDLexicalBlock(raw_ostream &Out, const MDLexicalBlock *N,
1722 TypePrinting *TypePrinter, SlotTracker *Machine,
1723 const Module *Context) {
1724 Out << "!MDLexicalBlock(";
1726 Out << FS << "scope: ";
1727 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1729 Out << FS << "file: ";
1730 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1734 Out << FS << "line: " << N->getLine();
1736 Out << FS << "column: " << N->getColumn();
1740 static void writeMDLexicalBlockFile(raw_ostream &Out,
1741 const MDLexicalBlockFile *N,
1742 TypePrinting *TypePrinter,
1743 SlotTracker *Machine,
1744 const Module *Context) {
1745 Out << "!MDLexicalBlockFile(";
1747 Out << FS << "scope: ";
1748 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1750 Out << FS << "file: ";
1751 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1754 Out << FS << "discriminator: " << N->getDiscriminator();
1758 static void writeMDNamespace(raw_ostream &Out, const MDNamespace *N,
1759 TypePrinting *TypePrinter, SlotTracker *Machine,
1760 const Module *Context) {
1761 Out << "!MDNamespace(";
1763 writeStringField(Out, FS, "name", N->getName());
1764 Out << FS << "scope: ";
1765 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1767 Out << FS << "file: ";
1768 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine, Context);
1771 Out << FS << "line: " << N->getLine();
1775 static void writeMDTemplateTypeParameter(raw_ostream &Out,
1776 const MDTemplateTypeParameter *N,
1777 TypePrinting *TypePrinter,
1778 SlotTracker *Machine,
1779 const Module *Context) {
1780 Out << "!MDTemplateTypeParameter(";
1782 writeStringField(Out, FS, "name", N->getName());
1783 Out << FS << "type: ";
1784 writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine, Context);
1788 static void writeMDTemplateValueParameter(raw_ostream &Out,
1789 const MDTemplateValueParameter *N,
1790 TypePrinting *TypePrinter,
1791 SlotTracker *Machine,
1792 const Module *Context) {
1793 Out << "!MDTemplateValueParameter(";
1795 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1796 writeTag(Out, FS, N);
1797 writeStringField(Out, FS, "name", N->getName());
1798 if (auto *Type = N->getType()) {
1799 Out << FS << "type: ";
1800 writeMetadataAsOperand(Out, Type, TypePrinter, Machine, Context);
1802 Out << FS << "value: ";
1803 writeMetadataAsOperand(Out, N->getValue(), TypePrinter, Machine, Context);
1807 static void writeMDGlobalVariable(raw_ostream &Out, const MDGlobalVariable *N,
1808 TypePrinting *TypePrinter,
1809 SlotTracker *Machine, const Module *Context) {
1810 Out << "!MDGlobalVariable(";
1812 writeStringField(Out, FS, "name", N->getName());
1813 writeStringField(Out, FS, "linkageName", N->getLinkageName());
1814 Out << FS << "scope: ";
1815 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1817 Out << FS << "file: ";
1818 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1822 Out << FS << "line: " << N->getLine();
1824 Out << FS << "type: ";
1825 writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine,
1828 Out << FS << "isLocal: " << (N->isLocalToUnit() ? "true" : "false");
1829 Out << FS << "isDefinition: " << (N->isDefinition() ? "true" : "false");
1830 if (N->getVariable()) {
1831 Out << FS << "variable: ";
1832 writeMetadataAsOperand(Out, N->getVariable(), TypePrinter, Machine,
1835 if (N->getStaticDataMemberDeclaration()) {
1836 Out << FS << "declaration: ";
1837 writeMetadataAsOperand(Out, N->getStaticDataMemberDeclaration(),
1838 TypePrinter, Machine, Context);
1843 static void writeMDLocalVariable(raw_ostream &Out, const MDLocalVariable *N,
1844 TypePrinting *TypePrinter,
1845 SlotTracker *Machine, const Module *Context) {
1846 Out << "!MDLocalVariable(";
1848 writeTag(Out, FS, N);
1849 writeStringField(Out, FS, "name", N->getName());
1850 if (N->getTag() == dwarf::DW_TAG_arg_variable || N->getArg())
1851 Out << FS << "arg: " << N->getArg();
1852 Out << FS << "scope: ";
1853 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1855 Out << FS << "file: ";
1856 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine,
1860 Out << FS << "line: " << N->getLine();
1862 Out << FS << "type: ";
1863 writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine,
1866 if (auto Flags = N->getFlags()) {
1867 Out << FS << "flags: ";
1868 writeDIFlags(Out, Flags);
1870 if (N->getInlinedAt()) {
1871 Out << FS << "inlinedAt: ";
1872 writeMetadataAsOperand(Out, N->getInlinedAt(), TypePrinter, Machine,
1878 static void writeMDExpression(raw_ostream &Out, const MDExpression *N,
1879 TypePrinting *TypePrinter, SlotTracker *Machine,
1880 const Module *Context) {
1881 Out << "!MDExpression(";
1884 for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1885 const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1886 assert(OpStr && "Expected valid opcode");
1889 for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1890 Out << FS << I->getArg(A);
1893 for (const auto &I : N->getElements())
1899 static void writeMDObjCProperty(raw_ostream &Out, const MDObjCProperty *N,
1900 TypePrinting *TypePrinter, SlotTracker *Machine,
1901 const Module *Context) {
1902 Out << "!MDObjCProperty(";
1904 writeStringField(Out, FS, "name", N->getName());
1906 Out << FS << "file: ";
1907 writeMetadataAsOperand(Out, N->getFile(), TypePrinter, Machine, Context);
1910 Out << FS << "line: " << N->getLine();
1911 writeStringField(Out, FS, "setter", N->getSetterName());
1912 writeStringField(Out, FS, "getter", N->getGetterName());
1913 if (N->getAttributes())
1914 Out << FS << "attributes: " << N->getAttributes();
1916 Out << FS << "type: ";
1917 writeMetadataAsOperand(Out, N->getType(), TypePrinter, Machine, Context);
1922 static void writeMDImportedEntity(raw_ostream &Out, const MDImportedEntity *N,
1923 TypePrinting *TypePrinter,
1924 SlotTracker *Machine, const Module *Context) {
1925 Out << "!MDImportedEntity(";
1927 writeTag(Out, FS, N);
1928 writeStringField(Out, FS, "name", N->getName());
1929 Out << FS << "scope: ";
1930 writeMetadataAsOperand(Out, N->getScope(), TypePrinter, Machine, Context);
1931 if (N->getEntity()) {
1932 Out << FS << "entity: ";
1933 writeMetadataAsOperand(Out, N->getEntity(), TypePrinter, Machine, Context);
1936 Out << FS << "line: " << N->getLine();
1941 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1942 TypePrinting *TypePrinter,
1943 SlotTracker *Machine,
1944 const Module *Context) {
1945 if (Node->isDistinct())
1947 else if (Node->isTemporary())
1948 Out << "<temporary!> "; // Handle broken code.
1950 switch (Node->getMetadataID()) {
1952 llvm_unreachable("Expected uniquable MDNode");
1953 #define HANDLE_MDNODE_LEAF(CLASS) \
1954 case Metadata::CLASS##Kind: \
1955 write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
1957 #include "llvm/IR/Metadata.def"
1961 // Full implementation of printing a Value as an operand with support for
1962 // TypePrinting, etc.
1963 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1964 TypePrinting *TypePrinter,
1965 SlotTracker *Machine,
1966 const Module *Context) {
1968 PrintLLVMName(Out, V);
1972 const Constant *CV = dyn_cast<Constant>(V);
1973 if (CV && !isa<GlobalValue>(CV)) {
1974 assert(TypePrinter && "Constants require TypePrinting!");
1975 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1979 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1981 if (IA->hasSideEffects())
1982 Out << "sideeffect ";
1983 if (IA->isAlignStack())
1984 Out << "alignstack ";
1985 // We don't emit the AD_ATT dialect as it's the assumed default.
1986 if (IA->getDialect() == InlineAsm::AD_Intel)
1987 Out << "inteldialect ";
1989 PrintEscapedString(IA->getAsmString(), Out);
1991 PrintEscapedString(IA->getConstraintString(), Out);
1996 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1997 WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1998 Context, /* FromValue */ true);
2004 // If we have a SlotTracker, use it.
2006 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2007 Slot = Machine->getGlobalSlot(GV);
2010 Slot = Machine->getLocalSlot(V);
2012 // If the local value didn't succeed, then we may be referring to a value
2013 // from a different function. Translate it, as this can happen when using
2014 // address of blocks.
2016 if ((Machine = createSlotTracker(V))) {
2017 Slot = Machine->getLocalSlot(V);
2021 } else if ((Machine = createSlotTracker(V))) {
2022 // Otherwise, create one to get the # and then destroy it.
2023 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2024 Slot = Machine->getGlobalSlot(GV);
2027 Slot = Machine->getLocalSlot(V);
2036 Out << Prefix << Slot;
2041 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2042 TypePrinting *TypePrinter,
2043 SlotTracker *Machine, const Module *Context,
2045 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2047 Machine = new SlotTracker(Context);
2048 int Slot = Machine->getMetadataSlot(N);
2050 // Give the pointer value instead of "badref", since this comes up all
2051 // the time when debugging.
2052 Out << "<" << N << ">";
2058 if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2060 PrintEscapedString(MDS->getString(), Out);
2065 auto *V = cast<ValueAsMetadata>(MD);
2066 assert(TypePrinter && "TypePrinter required for metadata values");
2067 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2068 "Unexpected function-local metadata outside of value argument");
2070 TypePrinter->print(V->getValue()->getType(), Out);
2072 WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2076 class AssemblyWriter {
2077 formatted_raw_ostream &Out;
2078 const Module *TheModule;
2079 std::unique_ptr<SlotTracker> ModuleSlotTracker;
2080 SlotTracker &Machine;
2081 TypePrinting TypePrinter;
2082 AssemblyAnnotationWriter *AnnotationWriter;
2083 SetVector<const Comdat *> Comdats;
2084 UseListOrderStack UseListOrders;
2087 /// Construct an AssemblyWriter with an external SlotTracker
2088 AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2089 const Module *M, AssemblyAnnotationWriter *AAW);
2091 /// Construct an AssemblyWriter with an internally allocated SlotTracker
2092 AssemblyWriter(formatted_raw_ostream &o, const Module *M,
2093 AssemblyAnnotationWriter *AAW);
2095 void printMDNodeBody(const MDNode *MD);
2096 void printNamedMDNode(const NamedMDNode *NMD);
2098 void printModule(const Module *M);
2100 void writeOperand(const Value *Op, bool PrintType);
2101 void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2102 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2103 void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2104 AtomicOrdering FailureOrdering,
2105 SynchronizationScope SynchScope);
2107 void writeAllMDNodes();
2108 void writeMDNode(unsigned Slot, const MDNode *Node);
2109 void writeAllAttributeGroups();
2111 void printTypeIdentities();
2112 void printGlobal(const GlobalVariable *GV);
2113 void printAlias(const GlobalAlias *GV);
2114 void printComdat(const Comdat *C);
2115 void printFunction(const Function *F);
2116 void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2117 void printBasicBlock(const BasicBlock *BB);
2118 void printInstructionLine(const Instruction &I);
2119 void printInstruction(const Instruction &I);
2121 void printUseListOrder(const UseListOrder &Order);
2122 void printUseLists(const Function *F);
2127 // printInfoComment - Print a little comment after the instruction indicating
2128 // which slot it occupies.
2129 void printInfoComment(const Value &V);
2133 void AssemblyWriter::init() {
2136 TypePrinter.incorporateTypes(*TheModule);
2137 for (const Function &F : *TheModule)
2138 if (const Comdat *C = F.getComdat())
2140 for (const GlobalVariable &GV : TheModule->globals())
2141 if (const Comdat *C = GV.getComdat())
2146 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2148 AssemblyAnnotationWriter *AAW)
2149 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
2153 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
2154 AssemblyAnnotationWriter *AAW)
2155 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
2156 Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
2160 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2162 Out << "<null operand!>";
2166 TypePrinter.print(Operand->getType(), Out);
2169 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2172 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2173 SynchronizationScope SynchScope) {
2174 if (Ordering == NotAtomic)
2177 switch (SynchScope) {
2178 case SingleThread: Out << " singlethread"; break;
2179 case CrossThread: break;
2183 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2184 case Unordered: Out << " unordered"; break;
2185 case Monotonic: Out << " monotonic"; break;
2186 case Acquire: Out << " acquire"; break;
2187 case Release: Out << " release"; break;
2188 case AcquireRelease: Out << " acq_rel"; break;
2189 case SequentiallyConsistent: Out << " seq_cst"; break;
2193 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2194 AtomicOrdering FailureOrdering,
2195 SynchronizationScope SynchScope) {
2196 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2198 switch (SynchScope) {
2199 case SingleThread: Out << " singlethread"; break;
2200 case CrossThread: break;
2203 switch (SuccessOrdering) {
2204 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2205 case Unordered: Out << " unordered"; break;
2206 case Monotonic: Out << " monotonic"; break;
2207 case Acquire: Out << " acquire"; break;
2208 case Release: Out << " release"; break;
2209 case AcquireRelease: Out << " acq_rel"; break;
2210 case SequentiallyConsistent: Out << " seq_cst"; break;
2213 switch (FailureOrdering) {
2214 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2215 case Unordered: Out << " unordered"; break;
2216 case Monotonic: Out << " monotonic"; break;
2217 case Acquire: Out << " acquire"; break;
2218 case Release: Out << " release"; break;
2219 case AcquireRelease: Out << " acq_rel"; break;
2220 case SequentiallyConsistent: Out << " seq_cst"; break;
2224 void AssemblyWriter::writeParamOperand(const Value *Operand,
2225 AttributeSet Attrs, unsigned Idx) {
2227 Out << "<null operand!>";
2232 TypePrinter.print(Operand->getType(), Out);
2233 // Print parameter attributes list
2234 if (Attrs.hasAttributes(Idx))
2235 Out << ' ' << Attrs.getAsString(Idx);
2237 // Print the operand
2238 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2241 void AssemblyWriter::printModule(const Module *M) {
2242 Machine.initialize();
2244 if (shouldPreserveAssemblyUseListOrder())
2245 UseListOrders = predictUseListOrder(M);
2247 if (!M->getModuleIdentifier().empty() &&
2248 // Don't print the ID if it will start a new line (which would
2249 // require a comment char before it).
2250 M->getModuleIdentifier().find('\n') == std::string::npos)
2251 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2253 const std::string &DL = M->getDataLayoutStr();
2255 Out << "target datalayout = \"" << DL << "\"\n";
2256 if (!M->getTargetTriple().empty())
2257 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2259 if (!M->getModuleInlineAsm().empty()) {
2260 // Split the string into lines, to make it easier to read the .ll file.
2261 std::string Asm = M->getModuleInlineAsm();
2263 size_t NewLine = Asm.find_first_of('\n', CurPos);
2265 while (NewLine != std::string::npos) {
2266 // We found a newline, print the portion of the asm string from the
2267 // last newline up to this newline.
2268 Out << "module asm \"";
2269 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
2273 NewLine = Asm.find_first_of('\n', CurPos);
2275 std::string rest(Asm.begin()+CurPos, Asm.end());
2276 if (!rest.empty()) {
2277 Out << "module asm \"";
2278 PrintEscapedString(rest, Out);
2283 printTypeIdentities();
2285 // Output all comdats.
2286 if (!Comdats.empty())
2288 for (const Comdat *C : Comdats) {
2290 if (C != Comdats.back())
2294 // Output all globals.
2295 if (!M->global_empty()) Out << '\n';
2296 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
2298 printGlobal(I); Out << '\n';
2301 // Output all aliases.
2302 if (!M->alias_empty()) Out << "\n";
2303 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
2307 // Output global use-lists.
2308 printUseLists(nullptr);
2310 // Output all of the functions.
2311 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
2313 assert(UseListOrders.empty() && "All use-lists should have been consumed");
2315 // Output all attribute groups.
2316 if (!Machine.as_empty()) {
2318 writeAllAttributeGroups();
2321 // Output named metadata.
2322 if (!M->named_metadata_empty()) Out << '\n';
2324 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
2325 E = M->named_metadata_end(); I != E; ++I)
2326 printNamedMDNode(I);
2329 if (!Machine.mdn_empty()) {
2335 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2337 StringRef Name = NMD->getName();
2339 Out << "<empty name> ";
2341 if (isalpha(static_cast<unsigned char>(Name[0])) ||
2342 Name[0] == '-' || Name[0] == '$' ||
2343 Name[0] == '.' || Name[0] == '_')
2346 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2347 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2348 unsigned char C = Name[i];
2349 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2350 C == '.' || C == '_')
2353 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2357 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2359 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2369 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2370 formatted_raw_ostream &Out) {
2372 case GlobalValue::ExternalLinkage: break;
2373 case GlobalValue::PrivateLinkage: Out << "private "; break;
2374 case GlobalValue::InternalLinkage: Out << "internal "; break;
2375 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
2376 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
2377 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
2378 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
2379 case GlobalValue::CommonLinkage: Out << "common "; break;
2380 case GlobalValue::AppendingLinkage: Out << "appending "; break;
2381 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
2382 case GlobalValue::AvailableExternallyLinkage:
2383 Out << "available_externally ";
2389 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2390 formatted_raw_ostream &Out) {
2392 case GlobalValue::DefaultVisibility: break;
2393 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
2394 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2398 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2399 formatted_raw_ostream &Out) {
2401 case GlobalValue::DefaultStorageClass: break;
2402 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2403 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2407 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2408 formatted_raw_ostream &Out) {
2410 case GlobalVariable::NotThreadLocal:
2412 case GlobalVariable::GeneralDynamicTLSModel:
2413 Out << "thread_local ";
2415 case GlobalVariable::LocalDynamicTLSModel:
2416 Out << "thread_local(localdynamic) ";
2418 case GlobalVariable::InitialExecTLSModel:
2419 Out << "thread_local(initialexec) ";
2421 case GlobalVariable::LocalExecTLSModel:
2422 Out << "thread_local(localexec) ";
2427 static void maybePrintComdat(formatted_raw_ostream &Out,
2428 const GlobalObject &GO) {
2429 const Comdat *C = GO.getComdat();
2433 if (isa<GlobalVariable>(GO))
2437 if (GO.getName() == C->getName())
2441 PrintLLVMName(Out, C->getName(), ComdatPrefix);
2445 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2446 if (GV->isMaterializable())
2447 Out << "; Materializable\n";
2449 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2452 if (!GV->hasInitializer() && GV->hasExternalLinkage())
2455 PrintLinkage(GV->getLinkage(), Out);
2456 PrintVisibility(GV->getVisibility(), Out);
2457 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2458 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2459 if (GV->hasUnnamedAddr())
2460 Out << "unnamed_addr ";
2462 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2463 Out << "addrspace(" << AddressSpace << ") ";
2464 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2465 Out << (GV->isConstant() ? "constant " : "global ");
2466 TypePrinter.print(GV->getType()->getElementType(), Out);
2468 if (GV->hasInitializer()) {
2470 writeOperand(GV->getInitializer(), false);
2473 if (GV->hasSection()) {
2474 Out << ", section \"";
2475 PrintEscapedString(GV->getSection(), Out);
2478 maybePrintComdat(Out, *GV);
2479 if (GV->getAlignment())
2480 Out << ", align " << GV->getAlignment();
2482 printInfoComment(*GV);
2485 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2486 if (GA->isMaterializable())
2487 Out << "; Materializable\n";
2489 // Don't crash when dumping partially built GA
2491 Out << "<<nameless>> = ";
2493 PrintLLVMName(Out, GA);
2496 PrintLinkage(GA->getLinkage(), Out);
2497 PrintVisibility(GA->getVisibility(), Out);
2498 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2499 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2500 if (GA->hasUnnamedAddr())
2501 Out << "unnamed_addr ";
2505 const Constant *Aliasee = GA->getAliasee();
2508 TypePrinter.print(GA->getType(), Out);
2509 Out << " <<NULL ALIASEE>>";
2511 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2514 printInfoComment(*GA);
2518 void AssemblyWriter::printComdat(const Comdat *C) {
2522 void AssemblyWriter::printTypeIdentities() {
2523 if (TypePrinter.NumberedTypes.empty() &&
2524 TypePrinter.NamedTypes.empty())
2529 // We know all the numbers that each type is used and we know that it is a
2530 // dense assignment. Convert the map to an index table.
2531 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2532 for (DenseMap<StructType*, unsigned>::iterator I =
2533 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2535 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2536 NumberedTypes[I->second] = I->first;
2539 // Emit all numbered types.
2540 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2541 Out << '%' << i << " = type ";
2543 // Make sure we print out at least one level of the type structure, so
2544 // that we do not get %2 = type %2
2545 TypePrinter.printStructBody(NumberedTypes[i], Out);
2549 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2550 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2553 // Make sure we print out at least one level of the type structure, so
2554 // that we do not get %FILE = type %FILE
2555 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2560 /// printFunction - Print all aspects of a function.
2562 void AssemblyWriter::printFunction(const Function *F) {
2563 // Print out the return type and name.
2566 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2568 if (F->isMaterializable())
2569 Out << "; Materializable\n";
2571 const AttributeSet &Attrs = F->getAttributes();
2572 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2573 AttributeSet AS = Attrs.getFnAttributes();
2574 std::string AttrStr;
2577 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2578 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2581 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2583 Attribute Attr = *I;
2584 if (!Attr.isStringAttribute()) {
2585 if (!AttrStr.empty()) AttrStr += ' ';
2586 AttrStr += Attr.getAsString();
2590 if (!AttrStr.empty())
2591 Out << "; Function Attrs: " << AttrStr << '\n';
2594 if (F->isDeclaration())
2599 PrintLinkage(F->getLinkage(), Out);
2600 PrintVisibility(F->getVisibility(), Out);
2601 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2603 // Print the calling convention.
2604 if (F->getCallingConv() != CallingConv::C) {
2605 PrintCallingConv(F->getCallingConv(), Out);
2609 FunctionType *FT = F->getFunctionType();
2610 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2611 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2612 TypePrinter.print(F->getReturnType(), Out);
2614 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2616 Machine.incorporateFunction(F);
2618 // Loop over the arguments, printing them...
2621 if (!F->isDeclaration()) {
2622 // If this isn't a declaration, print the argument names as well.
2623 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
2625 // Insert commas as we go... the first arg doesn't get a comma
2626 if (I != F->arg_begin()) Out << ", ";
2627 printArgument(I, Attrs, Idx);
2631 // Otherwise, print the types from the function type.
2632 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2633 // Insert commas as we go... the first arg doesn't get a comma
2637 TypePrinter.print(FT->getParamType(i), Out);
2639 if (Attrs.hasAttributes(i+1))
2640 Out << ' ' << Attrs.getAsString(i+1);
2644 // Finish printing arguments...
2645 if (FT->isVarArg()) {
2646 if (FT->getNumParams()) Out << ", ";
2647 Out << "..."; // Output varargs portion of signature!
2650 if (F->hasUnnamedAddr())
2651 Out << " unnamed_addr";
2652 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2653 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2654 if (F->hasSection()) {
2655 Out << " section \"";
2656 PrintEscapedString(F->getSection(), Out);
2659 maybePrintComdat(Out, *F);
2660 if (F->getAlignment())
2661 Out << " align " << F->getAlignment();
2663 Out << " gc \"" << F->getGC() << '"';
2664 if (F->hasPrefixData()) {
2666 writeOperand(F->getPrefixData(), true);
2668 if (F->hasPrologueData()) {
2669 Out << " prologue ";
2670 writeOperand(F->getPrologueData(), true);
2673 if (F->isDeclaration()) {
2677 // Output all of the function's basic blocks.
2678 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2681 // Output the function's use-lists.
2687 Machine.purgeFunction();
2690 /// printArgument - This member is called for every argument that is passed into
2691 /// the function. Simply print it out
2693 void AssemblyWriter::printArgument(const Argument *Arg,
2694 AttributeSet Attrs, unsigned Idx) {
2696 TypePrinter.print(Arg->getType(), Out);
2698 // Output parameter attributes list
2699 if (Attrs.hasAttributes(Idx))
2700 Out << ' ' << Attrs.getAsString(Idx);
2702 // Output name, if available...
2703 if (Arg->hasName()) {
2705 PrintLLVMName(Out, Arg);
2709 /// printBasicBlock - This member is called for each basic block in a method.
2711 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2712 if (BB->hasName()) { // Print out the label if it exists...
2714 PrintLLVMName(Out, BB->getName(), LabelPrefix);
2716 } else if (!BB->use_empty()) { // Don't print block # of no uses...
2717 Out << "\n; <label>:";
2718 int Slot = Machine.getLocalSlot(BB);
2725 if (!BB->getParent()) {
2726 Out.PadToColumn(50);
2727 Out << "; Error: Block without parent!";
2728 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
2729 // Output predecessors for the block.
2730 Out.PadToColumn(50);
2732 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2735 Out << " No predecessors!";
2738 writeOperand(*PI, false);
2739 for (++PI; PI != PE; ++PI) {
2741 writeOperand(*PI, false);
2748 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2750 // Output all of the instructions in the basic block...
2751 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2752 printInstructionLine(*I);
2755 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2758 /// printInstructionLine - Print an instruction and a newline character.
2759 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2760 printInstruction(I);
2764 /// printInfoComment - Print a little comment after the instruction indicating
2765 /// which slot it occupies.
2767 void AssemblyWriter::printInfoComment(const Value &V) {
2768 if (AnnotationWriter)
2769 AnnotationWriter->printInfoComment(V, Out);
2772 // This member is called for each Instruction in a function..
2773 void AssemblyWriter::printInstruction(const Instruction &I) {
2774 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2776 // Print out indentation for an instruction.
2779 // Print out name if it exists...
2781 PrintLLVMName(Out, &I);
2783 } else if (!I.getType()->isVoidTy()) {
2784 // Print out the def slot taken.
2785 int SlotNum = Machine.getLocalSlot(&I);
2787 Out << "<badref> = ";
2789 Out << '%' << SlotNum << " = ";
2792 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2793 if (CI->isMustTailCall())
2795 else if (CI->isTailCall())
2799 // Print out the opcode...
2800 Out << I.getOpcodeName();
2802 // If this is an atomic load or store, print out the atomic marker.
2803 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
2804 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2807 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2810 // If this is a volatile operation, print out the volatile marker.
2811 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
2812 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2813 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2814 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2817 // Print out optimization information.
2818 WriteOptimizationInfo(Out, &I);
2820 // Print out the compare instruction predicates
2821 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2822 Out << ' ' << getPredicateText(CI->getPredicate());
2824 // Print out the atomicrmw operation
2825 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2826 writeAtomicRMWOperation(Out, RMWI->getOperation());
2828 // Print out the type of the operands...
2829 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2831 // Special case conditional branches to swizzle the condition out to the front
2832 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2833 const BranchInst &BI(cast<BranchInst>(I));
2835 writeOperand(BI.getCondition(), true);
2837 writeOperand(BI.getSuccessor(0), true);
2839 writeOperand(BI.getSuccessor(1), true);
2841 } else if (isa<SwitchInst>(I)) {
2842 const SwitchInst& SI(cast<SwitchInst>(I));
2843 // Special case switch instruction to get formatting nice and correct.
2845 writeOperand(SI.getCondition(), true);
2847 writeOperand(SI.getDefaultDest(), true);
2849 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2852 writeOperand(i.getCaseValue(), true);
2854 writeOperand(i.getCaseSuccessor(), true);
2857 } else if (isa<IndirectBrInst>(I)) {
2858 // Special case indirectbr instruction to get formatting nice and correct.
2860 writeOperand(Operand, true);
2863 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2866 writeOperand(I.getOperand(i), true);
2869 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2871 TypePrinter.print(I.getType(), Out);
2874 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2875 if (op) Out << ", ";
2877 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2878 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2880 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2882 writeOperand(I.getOperand(0), true);
2883 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2885 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2887 writeOperand(I.getOperand(0), true); Out << ", ";
2888 writeOperand(I.getOperand(1), true);
2889 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2891 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2893 TypePrinter.print(I.getType(), Out);
2894 Out << " personality ";
2895 writeOperand(I.getOperand(0), true); Out << '\n';
2897 if (LPI->isCleanup())
2900 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2901 if (i != 0 || LPI->isCleanup()) Out << "\n";
2902 if (LPI->isCatch(i))
2907 writeOperand(LPI->getClause(i), true);
2909 } else if (isa<ReturnInst>(I) && !Operand) {
2911 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2912 // Print the calling convention being used.
2913 if (CI->getCallingConv() != CallingConv::C) {
2915 PrintCallingConv(CI->getCallingConv(), Out);
2918 Operand = CI->getCalledValue();
2919 PointerType *PTy = cast<PointerType>(Operand->getType());
2920 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2921 Type *RetTy = FTy->getReturnType();
2922 const AttributeSet &PAL = CI->getAttributes();
2924 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2925 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2927 // If possible, print out the short form of the call instruction. We can
2928 // only do this if the first argument is a pointer to a nonvararg function,
2929 // and if the return type is not a pointer to a function.
2932 if (!FTy->isVarArg() &&
2933 (!RetTy->isPointerTy() ||
2934 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
2935 TypePrinter.print(RetTy, Out);
2937 writeOperand(Operand, false);
2939 writeOperand(Operand, true);
2942 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2945 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2948 // Emit an ellipsis if this is a musttail call in a vararg function. This
2949 // is only to aid readability, musttail calls forward varargs by default.
2950 if (CI->isMustTailCall() && CI->getParent() &&
2951 CI->getParent()->getParent() &&
2952 CI->getParent()->getParent()->isVarArg())
2956 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2957 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2958 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2959 Operand = II->getCalledValue();
2960 PointerType *PTy = cast<PointerType>(Operand->getType());
2961 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2962 Type *RetTy = FTy->getReturnType();
2963 const AttributeSet &PAL = II->getAttributes();
2965 // Print the calling convention being used.
2966 if (II->getCallingConv() != CallingConv::C) {
2968 PrintCallingConv(II->getCallingConv(), Out);
2971 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2972 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2974 // If possible, print out the short form of the invoke instruction. We can
2975 // only do this if the first argument is a pointer to a nonvararg function,
2976 // and if the return type is not a pointer to a function.
2979 if (!FTy->isVarArg() &&
2980 (!RetTy->isPointerTy() ||
2981 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
2982 TypePrinter.print(RetTy, Out);
2984 writeOperand(Operand, false);
2986 writeOperand(Operand, true);
2989 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2992 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
2996 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2997 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3000 writeOperand(II->getNormalDest(), true);
3002 writeOperand(II->getUnwindDest(), true);
3004 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3006 if (AI->isUsedWithInAlloca())
3008 TypePrinter.print(AI->getAllocatedType(), Out);
3010 // Explicitly write the array size if the code is broken, if it's an array
3011 // allocation, or if the type is not canonical for scalar allocations. The
3012 // latter case prevents the type from mutating when round-tripping through
3014 if (!AI->getArraySize() || AI->isArrayAllocation() ||
3015 !AI->getArraySize()->getType()->isIntegerTy(32)) {
3017 writeOperand(AI->getArraySize(), true);
3019 if (AI->getAlignment()) {
3020 Out << ", align " << AI->getAlignment();
3022 } else if (isa<CastInst>(I)) {
3025 writeOperand(Operand, true); // Work with broken code
3028 TypePrinter.print(I.getType(), Out);
3029 } else if (isa<VAArgInst>(I)) {
3032 writeOperand(Operand, true); // Work with broken code
3035 TypePrinter.print(I.getType(), Out);
3036 } else if (Operand) { // Print the normal way.
3037 if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3039 TypePrinter.print(GEP->getSourceElementType(), Out);
3041 } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3043 TypePrinter.print(LI->getType(), Out);
3047 // PrintAllTypes - Instructions who have operands of all the same type
3048 // omit the type from all but the first operand. If the instruction has
3049 // different type operands (for example br), then they are all printed.
3050 bool PrintAllTypes = false;
3051 Type *TheType = Operand->getType();
3053 // Select, Store and ShuffleVector always print all types.
3054 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3055 || isa<ReturnInst>(I)) {
3056 PrintAllTypes = true;
3058 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3059 Operand = I.getOperand(i);
3060 // note that Operand shouldn't be null, but the test helps make dump()
3061 // more tolerant of malformed IR
3062 if (Operand && Operand->getType() != TheType) {
3063 PrintAllTypes = true; // We have differing types! Print them all!
3069 if (!PrintAllTypes) {
3071 TypePrinter.print(TheType, Out);
3075 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3077 writeOperand(I.getOperand(i), PrintAllTypes);
3081 // Print atomic ordering/alignment for memory operations
3082 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3084 writeAtomic(LI->getOrdering(), LI->getSynchScope());
3085 if (LI->getAlignment())
3086 Out << ", align " << LI->getAlignment();
3087 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3089 writeAtomic(SI->getOrdering(), SI->getSynchScope());
3090 if (SI->getAlignment())
3091 Out << ", align " << SI->getAlignment();
3092 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3093 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3094 CXI->getSynchScope());
3095 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3096 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3097 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3098 writeAtomic(FI->getOrdering(), FI->getSynchScope());
3101 // Print Metadata info.
3102 SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3103 I.getAllMetadata(InstMD);
3104 if (!InstMD.empty()) {
3105 SmallVector<StringRef, 8> MDNames;
3106 I.getType()->getContext().getMDKindNames(MDNames);
3107 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
3108 unsigned Kind = InstMD[i].first;
3109 if (Kind < MDNames.size()) {
3110 Out << ", !" << MDNames[Kind];
3112 Out << ", !<unknown kind #" << Kind << ">";
3115 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
3119 printInfoComment(I);
3122 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3123 Out << '!' << Slot << " = ";
3124 printMDNodeBody(Node);
3128 void AssemblyWriter::writeAllMDNodes() {
3129 SmallVector<const MDNode *, 16> Nodes;
3130 Nodes.resize(Machine.mdn_size());
3131 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3133 Nodes[I->second] = cast<MDNode>(I->first);
3135 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3136 writeMDNode(i, Nodes[i]);
3140 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3141 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3144 void AssemblyWriter::writeAllAttributeGroups() {
3145 std::vector<std::pair<AttributeSet, unsigned> > asVec;
3146 asVec.resize(Machine.as_size());
3148 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3150 asVec[I->second] = *I;
3152 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3153 I = asVec.begin(), E = asVec.end(); I != E; ++I)
3154 Out << "attributes #" << I->second << " = { "
3155 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3158 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3159 bool IsInFunction = Machine.getFunction();
3163 Out << "uselistorder";
3164 if (const BasicBlock *BB =
3165 IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3167 writeOperand(BB->getParent(), false);
3169 writeOperand(BB, false);
3172 writeOperand(Order.V, true);
3176 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3177 Out << Order.Shuffle[0];
3178 for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3179 Out << ", " << Order.Shuffle[I];
3183 void AssemblyWriter::printUseLists(const Function *F) {
3185 [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3190 Out << "\n; uselistorder directives\n";
3192 printUseListOrder(UseListOrders.back());
3193 UseListOrders.pop_back();
3197 //===----------------------------------------------------------------------===//
3198 // External Interface declarations
3199 //===----------------------------------------------------------------------===//
3201 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
3202 SlotTracker SlotTable(this);
3203 formatted_raw_ostream OS(ROS);
3204 AssemblyWriter W(OS, SlotTable, this, AAW);
3205 W.printModule(this);
3208 void NamedMDNode::print(raw_ostream &ROS) const {
3209 SlotTracker SlotTable(getParent());
3210 formatted_raw_ostream OS(ROS);
3211 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
3212 W.printNamedMDNode(this);
3215 void Comdat::print(raw_ostream &ROS) const {
3216 PrintLLVMName(ROS, getName(), ComdatPrefix);
3217 ROS << " = comdat ";
3219 switch (getSelectionKind()) {
3223 case Comdat::ExactMatch:
3224 ROS << "exactmatch";
3226 case Comdat::Largest:
3229 case Comdat::NoDuplicates:
3230 ROS << "noduplicates";
3232 case Comdat::SameSize:
3240 void Type::print(raw_ostream &OS) const {
3242 TP.print(const_cast<Type*>(this), OS);
3244 // If the type is a named struct type, print the body as well.
3245 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3246 if (!STy->isLiteral()) {
3248 TP.printStructBody(STy, OS);
3252 static bool isReferencingMDNode(const Instruction &I) {
3253 if (const auto *CI = dyn_cast<CallInst>(&I))
3254 if (Function *F = CI->getCalledFunction())
3255 if (F->isIntrinsic())
3256 for (auto &Op : I.operands())
3257 if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3258 if (isa<MDNode>(V->getMetadata()))
3263 void Value::print(raw_ostream &ROS) const {
3264 formatted_raw_ostream OS(ROS);
3265 if (const Instruction *I = dyn_cast<Instruction>(this)) {
3266 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
3267 SlotTracker SlotTable(
3269 /* ShouldInitializeAllMetadata */ isReferencingMDNode(*I));
3270 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
3271 W.printInstruction(*I);
3272 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3273 SlotTracker SlotTable(BB->getParent());
3274 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
3275 W.printBasicBlock(BB);
3276 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3277 SlotTracker SlotTable(GV->getParent(),
3278 /* ShouldInitializeAllMetadata */ isa<Function>(GV));
3279 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
3280 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3282 else if (const Function *F = dyn_cast<Function>(GV))
3285 W.printAlias(cast<GlobalAlias>(GV));
3286 } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3287 V->getMetadata()->print(ROS, getModuleFromVal(V));
3288 } else if (const Constant *C = dyn_cast<Constant>(this)) {
3289 TypePrinting TypePrinter;
3290 TypePrinter.print(C->getType(), OS);
3292 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
3293 } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3294 this->printAsOperand(OS);
3296 llvm_unreachable("Unknown value to print out!");
3300 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
3301 // Fast path: Don't construct and populate a TypePrinting object if we
3302 // won't be needing any types printed.
3303 bool IsMetadata = isa<MetadataAsValue>(this);
3304 if (!PrintType && ((!isa<Constant>(this) && !IsMetadata) || hasName() ||
3305 isa<GlobalValue>(this))) {
3306 WriteAsOperandInternal(O, this, nullptr, nullptr, M);
3311 M = getModuleFromVal(this);
3313 TypePrinting TypePrinter;
3315 TypePrinter.incorporateTypes(*M);
3317 TypePrinter.print(getType(), O);
3321 SlotTracker Machine(M, /* ShouldInitializeAllMetadata */ IsMetadata);
3322 WriteAsOperandInternal(O, this, &TypePrinter, &Machine, M);
3325 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3326 const Module *M, bool OnlyAsOperand) {
3327 formatted_raw_ostream OS(ROS);
3329 auto *N = dyn_cast<MDNode>(&MD);
3330 TypePrinting TypePrinter;
3331 SlotTracker Machine(M, /* ShouldInitializeAllMetadata */ N);
3333 TypePrinter.incorporateTypes(*M);
3335 WriteAsOperandInternal(OS, &MD, &TypePrinter, &Machine, M,
3336 /* FromValue */ true);
3337 if (OnlyAsOperand || !N)
3341 WriteMDNodeBodyInternal(OS, N, &TypePrinter, &Machine, M);
3344 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3345 printMetadataImpl(OS, *this, M, /* OnlyAsOperand */ true);
3348 void Metadata::print(raw_ostream &OS, const Module *M) const {
3349 printMetadataImpl(OS, *this, M, /* OnlyAsOperand */ false);
3352 // Value::dump - allow easy printing of Values from the debugger.
3354 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
3356 // Type::dump - allow easy printing of Types from the debugger.
3358 void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
3360 // Module::dump() - Allow printing of Modules from the debugger.
3362 void Module::dump() const { print(dbgs(), nullptr); }
3364 // \brief Allow printing of Comdats from the debugger.
3366 void Comdat::dump() const { print(dbgs()); }
3368 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3370 void NamedMDNode::dump() const { print(dbgs()); }
3373 void Metadata::dump() const { dump(nullptr); }
3376 void Metadata::dump(const Module *M) const {