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 "AsmWriter.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.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/ValueSymbolTable.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/MathExtras.h"
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static const Module *getModuleFromVal(const Value *V) {
53 if (const Argument *MA = dyn_cast<Argument>(V))
54 return MA->getParent() ? MA->getParent()->getParent() : nullptr;
56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57 return BB->getParent() ? BB->getParent()->getParent() : nullptr;
59 if (const Instruction *I = dyn_cast<Instruction>(V)) {
60 const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
61 return M ? M->getParent() : nullptr;
64 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65 return GV->getParent();
69 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
71 default: Out << "cc" << cc; break;
72 case CallingConv::Fast: Out << "fastcc"; break;
73 case CallingConv::Cold: Out << "coldcc"; break;
74 case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
75 case CallingConv::AnyReg: Out << "anyregcc"; break;
76 case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
77 case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
78 case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
79 case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
80 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
81 case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
82 case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
83 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
84 case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
85 case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
86 case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
87 case CallingConv::PTX_Device: Out << "ptx_device"; break;
88 case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
89 case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
90 case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
91 case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
95 // PrintEscapedString - Print each character of the specified string, escaping
96 // it if it is not printable or if it is an escape char.
97 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
98 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
99 unsigned char C = Name[i];
100 if (isprint(C) && C != '\\' && C != '"')
103 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
114 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
115 /// prefixed with % (if the string only contains simple characters) or is
116 /// surrounded with ""'s (if it has special chars in it). Print it out.
117 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
118 assert(!Name.empty() && "Cannot get empty name!");
120 case NoPrefix: break;
121 case GlobalPrefix: OS << '@'; break;
122 case LabelPrefix: break;
123 case LocalPrefix: OS << '%'; break;
126 // Scan the name to see if it needs quotes first.
127 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
129 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
130 // By making this unsigned, the value passed in to isalnum will always be
131 // in the range 0-255. This is important when building with MSVC because
132 // its implementation will assert. This situation can arise when dealing
133 // with UTF-8 multibyte characters.
134 unsigned char C = Name[i];
135 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
143 // If we didn't need any quotes, just write out the name in one blast.
149 // Okay, we need quotes. Output the quotes and escape any scary characters as
152 PrintEscapedString(Name, OS);
156 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
157 /// prefixed with % (if the string only contains simple characters) or is
158 /// surrounded with ""'s (if it has special chars in it). Print it out.
159 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
160 PrintLLVMName(OS, V->getName(),
161 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
167 void TypePrinting::incorporateTypes(const Module &M) {
168 NamedTypes.run(M, false);
170 // The list of struct types we got back includes all the struct types, split
171 // the unnamed ones out to a numbering and remove the anonymous structs.
172 unsigned NextNumber = 0;
174 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
175 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
176 StructType *STy = *I;
178 // Ignore anonymous types.
179 if (STy->isLiteral())
182 if (STy->getName().empty())
183 NumberedTypes[STy] = NextNumber++;
188 NamedTypes.erase(NextToUse, NamedTypes.end());
192 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
193 /// use of type names or up references to shorten the type name where possible.
194 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
195 switch (Ty->getTypeID()) {
196 case Type::VoidTyID: OS << "void"; return;
197 case Type::HalfTyID: OS << "half"; return;
198 case Type::FloatTyID: OS << "float"; return;
199 case Type::DoubleTyID: OS << "double"; return;
200 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
201 case Type::FP128TyID: OS << "fp128"; return;
202 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
203 case Type::LabelTyID: OS << "label"; return;
204 case Type::MetadataTyID: OS << "metadata"; return;
205 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
206 case Type::IntegerTyID:
207 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
210 case Type::FunctionTyID: {
211 FunctionType *FTy = cast<FunctionType>(Ty);
212 print(FTy->getReturnType(), OS);
214 for (FunctionType::param_iterator I = FTy->param_begin(),
215 E = FTy->param_end(); I != E; ++I) {
216 if (I != FTy->param_begin())
220 if (FTy->isVarArg()) {
221 if (FTy->getNumParams()) OS << ", ";
227 case Type::StructTyID: {
228 StructType *STy = cast<StructType>(Ty);
230 if (STy->isLiteral())
231 return printStructBody(STy, OS);
233 if (!STy->getName().empty())
234 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
236 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
237 if (I != NumberedTypes.end())
238 OS << '%' << I->second;
239 else // Not enumerated, print the hex address.
240 OS << "%\"type " << STy << '\"';
243 case Type::PointerTyID: {
244 PointerType *PTy = cast<PointerType>(Ty);
245 print(PTy->getElementType(), OS);
246 if (unsigned AddressSpace = PTy->getAddressSpace())
247 OS << " addrspace(" << AddressSpace << ')';
251 case Type::ArrayTyID: {
252 ArrayType *ATy = cast<ArrayType>(Ty);
253 OS << '[' << ATy->getNumElements() << " x ";
254 print(ATy->getElementType(), OS);
258 case Type::VectorTyID: {
259 VectorType *PTy = cast<VectorType>(Ty);
260 OS << "<" << PTy->getNumElements() << " x ";
261 print(PTy->getElementType(), OS);
266 llvm_unreachable("Invalid TypeID");
269 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
270 if (STy->isOpaque()) {
278 if (STy->getNumElements() == 0) {
281 StructType::element_iterator I = STy->element_begin();
284 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
295 //===----------------------------------------------------------------------===//
296 // SlotTracker Class: Enumerate slot numbers for unnamed values
297 //===----------------------------------------------------------------------===//
298 /// This class provides computation of slot numbers for LLVM Assembly writing.
302 /// ValueMap - A mapping of Values to slot numbers.
303 typedef DenseMap<const Value*, unsigned> ValueMap;
306 /// TheModule - The module for which we are holding slot numbers.
307 const Module* TheModule;
309 /// TheFunction - The function for which we are holding slot numbers.
310 const Function* TheFunction;
311 bool FunctionProcessed;
313 /// mMap - The slot map for the module level data.
317 /// fMap - The slot map for the function level data.
321 /// mdnMap - Map for MDNodes.
322 DenseMap<const MDNode*, unsigned> mdnMap;
325 /// asMap - The slot map for attribute sets.
326 DenseMap<AttributeSet, unsigned> asMap;
329 /// Construct from a module
330 explicit SlotTracker(const Module *M);
331 /// Construct from a function, starting out in incorp state.
332 explicit SlotTracker(const Function *F);
334 /// Return the slot number of the specified value in it's type
335 /// plane. If something is not in the SlotTracker, return -1.
336 int getLocalSlot(const Value *V);
337 int getGlobalSlot(const GlobalValue *V);
338 int getMetadataSlot(const MDNode *N);
339 int getAttributeGroupSlot(AttributeSet AS);
341 /// If you'd like to deal with a function instead of just a module, use
342 /// this method to get its data into the SlotTracker.
343 void incorporateFunction(const Function *F) {
345 FunctionProcessed = false;
348 /// After calling incorporateFunction, use this method to remove the
349 /// most recently incorporated function from the SlotTracker. This
350 /// will reset the state of the machine back to just the module contents.
351 void purgeFunction();
353 /// MDNode map iterators.
354 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
355 mdn_iterator mdn_begin() { return mdnMap.begin(); }
356 mdn_iterator mdn_end() { return mdnMap.end(); }
357 unsigned mdn_size() const { return mdnMap.size(); }
358 bool mdn_empty() const { return mdnMap.empty(); }
360 /// AttributeSet map iterators.
361 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
362 as_iterator as_begin() { return asMap.begin(); }
363 as_iterator as_end() { return asMap.end(); }
364 unsigned as_size() const { return asMap.size(); }
365 bool as_empty() const { return asMap.empty(); }
367 /// This function does the actual initialization.
368 inline void initialize();
370 // Implementation Details
372 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
373 void CreateModuleSlot(const GlobalValue *V);
375 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
376 void CreateMetadataSlot(const MDNode *N);
378 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
379 void CreateFunctionSlot(const Value *V);
381 /// \brief Insert the specified AttributeSet into the slot table.
382 void CreateAttributeSetSlot(AttributeSet AS);
384 /// Add all of the module level global variables (and their initializers)
385 /// and function declarations, but not the contents of those functions.
386 void processModule();
388 /// Add all of the functions arguments, basic blocks, and instructions.
389 void processFunction();
391 SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
392 void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
395 SlotTracker *createSlotTracker(const Module *M) {
396 return new SlotTracker(M);
399 static SlotTracker *createSlotTracker(const Value *V) {
400 if (const Argument *FA = dyn_cast<Argument>(V))
401 return new SlotTracker(FA->getParent());
403 if (const Instruction *I = dyn_cast<Instruction>(V))
405 return new SlotTracker(I->getParent()->getParent());
407 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
408 return new SlotTracker(BB->getParent());
410 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
411 return new SlotTracker(GV->getParent());
413 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
414 return new SlotTracker(GA->getParent());
416 if (const Function *Func = dyn_cast<Function>(V))
417 return new SlotTracker(Func);
419 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
420 if (!MD->isFunctionLocal())
421 return new SlotTracker(MD->getFunction());
423 return new SlotTracker((Function *)nullptr);
430 #define ST_DEBUG(X) dbgs() << X
435 // Module level constructor. Causes the contents of the Module (sans functions)
436 // to be added to the slot table.
437 SlotTracker::SlotTracker(const Module *M)
438 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
439 mNext(0), fNext(0), mdnNext(0), asNext(0) {
442 // Function level constructor. Causes the contents of the Module and the one
443 // function provided to be added to the slot table.
444 SlotTracker::SlotTracker(const Function *F)
445 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
446 FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {
449 inline void SlotTracker::initialize() {
452 TheModule = nullptr; ///< Prevent re-processing next time we're called.
455 if (TheFunction && !FunctionProcessed)
459 // Iterate through all the global variables, functions, and global
460 // variable initializers and create slots for them.
461 void SlotTracker::processModule() {
462 ST_DEBUG("begin processModule!\n");
464 // Add all of the unnamed global variables to the value table.
465 for (Module::const_global_iterator I = TheModule->global_begin(),
466 E = TheModule->global_end(); I != E; ++I) {
471 // Add metadata used by named metadata.
472 for (Module::const_named_metadata_iterator
473 I = TheModule->named_metadata_begin(),
474 E = TheModule->named_metadata_end(); I != E; ++I) {
475 const NamedMDNode *NMD = I;
476 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
477 CreateMetadataSlot(NMD->getOperand(i));
480 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
483 // Add all the unnamed functions to the table.
486 // Add all the function attributes to the table.
487 // FIXME: Add attributes of other objects?
488 AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
489 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
490 CreateAttributeSetSlot(FnAttrs);
493 ST_DEBUG("end processModule!\n");
496 // Process the arguments, basic blocks, and instructions of a function.
497 void SlotTracker::processFunction() {
498 ST_DEBUG("begin processFunction!\n");
501 // Add all the function arguments with no names.
502 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
503 AE = TheFunction->arg_end(); AI != AE; ++AI)
505 CreateFunctionSlot(AI);
507 ST_DEBUG("Inserting Instructions:\n");
509 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
511 // Add all of the basic blocks and instructions with no names.
512 for (Function::const_iterator BB = TheFunction->begin(),
513 E = TheFunction->end(); BB != E; ++BB) {
515 CreateFunctionSlot(BB);
517 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
519 if (!I->getType()->isVoidTy() && !I->hasName())
520 CreateFunctionSlot(I);
522 // Intrinsics can directly use metadata. We allow direct calls to any
523 // llvm.foo function here, because the target may not be linked into the
525 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
526 if (Function *F = CI->getCalledFunction())
527 if (F->isIntrinsic())
528 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
529 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
530 CreateMetadataSlot(N);
532 // Add all the call attributes to the table.
533 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
534 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
535 CreateAttributeSetSlot(Attrs);
536 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
537 // Add all the call attributes to the table.
538 AttributeSet Attrs = II->getAttributes().getFnAttributes();
539 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
540 CreateAttributeSetSlot(Attrs);
543 // Process metadata attached with this instruction.
544 I->getAllMetadata(MDForInst);
545 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
546 CreateMetadataSlot(MDForInst[i].second);
551 FunctionProcessed = true;
553 ST_DEBUG("end processFunction!\n");
556 /// Clean up after incorporating a function. This is the only way to get out of
557 /// the function incorporation state that affects get*Slot/Create*Slot. Function
558 /// incorporation state is indicated by TheFunction != 0.
559 void SlotTracker::purgeFunction() {
560 ST_DEBUG("begin purgeFunction!\n");
561 fMap.clear(); // Simply discard the function level map
562 TheFunction = nullptr;
563 FunctionProcessed = false;
564 ST_DEBUG("end purgeFunction!\n");
567 /// getGlobalSlot - Get the slot number of a global value.
568 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
569 // Check for uninitialized state and do lazy initialization.
572 // Find the value in the module map
573 ValueMap::iterator MI = mMap.find(V);
574 return MI == mMap.end() ? -1 : (int)MI->second;
577 /// getMetadataSlot - Get the slot number of a MDNode.
578 int SlotTracker::getMetadataSlot(const MDNode *N) {
579 // Check for uninitialized state and do lazy initialization.
582 // Find the MDNode in the module map
583 mdn_iterator MI = mdnMap.find(N);
584 return MI == mdnMap.end() ? -1 : (int)MI->second;
588 /// getLocalSlot - Get the slot number for a value that is local to a function.
589 int SlotTracker::getLocalSlot(const Value *V) {
590 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
592 // Check for uninitialized state and do lazy initialization.
595 ValueMap::iterator FI = fMap.find(V);
596 return FI == fMap.end() ? -1 : (int)FI->second;
599 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
600 // Check for uninitialized state and do lazy initialization.
603 // Find the AttributeSet in the module map.
604 as_iterator AI = asMap.find(AS);
605 return AI == asMap.end() ? -1 : (int)AI->second;
608 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
609 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
610 assert(V && "Can't insert a null Value into SlotTracker!");
611 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
612 assert(!V->hasName() && "Doesn't need a slot!");
614 unsigned DestSlot = mNext++;
617 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
619 // G = Global, F = Function, A = Alias, o = other
620 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
621 (isa<Function>(V) ? 'F' :
622 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
625 /// CreateSlot - Create a new slot for the specified value if it has no name.
626 void SlotTracker::CreateFunctionSlot(const Value *V) {
627 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
629 unsigned DestSlot = fNext++;
632 // G = Global, F = Function, o = other
633 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
634 DestSlot << " [o]\n");
637 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
638 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
639 assert(N && "Can't insert a null Value into SlotTracker!");
641 // Don't insert if N is a function-local metadata, these are always printed
643 if (!N->isFunctionLocal()) {
644 mdn_iterator I = mdnMap.find(N);
645 if (I != mdnMap.end())
648 unsigned DestSlot = mdnNext++;
649 mdnMap[N] = DestSlot;
652 // Recursively add any MDNodes referenced by operands.
653 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
654 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
655 CreateMetadataSlot(Op);
658 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
659 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
660 "Doesn't need a slot!");
662 as_iterator I = asMap.find(AS);
663 if (I != asMap.end())
666 unsigned DestSlot = asNext++;
667 asMap[AS] = DestSlot;
670 //===----------------------------------------------------------------------===//
671 // AsmWriter Implementation
672 //===----------------------------------------------------------------------===//
674 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
675 TypePrinting *TypePrinter,
676 SlotTracker *Machine,
677 const Module *Context);
679 static const char *getPredicateText(unsigned predicate) {
680 const char * pred = "unknown";
682 case FCmpInst::FCMP_FALSE: pred = "false"; break;
683 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
684 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
685 case FCmpInst::FCMP_OGE: pred = "oge"; break;
686 case FCmpInst::FCMP_OLT: pred = "olt"; break;
687 case FCmpInst::FCMP_OLE: pred = "ole"; break;
688 case FCmpInst::FCMP_ONE: pred = "one"; break;
689 case FCmpInst::FCMP_ORD: pred = "ord"; break;
690 case FCmpInst::FCMP_UNO: pred = "uno"; break;
691 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
692 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
693 case FCmpInst::FCMP_UGE: pred = "uge"; break;
694 case FCmpInst::FCMP_ULT: pred = "ult"; break;
695 case FCmpInst::FCMP_ULE: pred = "ule"; break;
696 case FCmpInst::FCMP_UNE: pred = "une"; break;
697 case FCmpInst::FCMP_TRUE: pred = "true"; break;
698 case ICmpInst::ICMP_EQ: pred = "eq"; break;
699 case ICmpInst::ICMP_NE: pred = "ne"; break;
700 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
701 case ICmpInst::ICMP_SGE: pred = "sge"; break;
702 case ICmpInst::ICMP_SLT: pred = "slt"; break;
703 case ICmpInst::ICMP_SLE: pred = "sle"; break;
704 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
705 case ICmpInst::ICMP_UGE: pred = "uge"; break;
706 case ICmpInst::ICMP_ULT: pred = "ult"; break;
707 case ICmpInst::ICMP_ULE: pred = "ule"; break;
712 static void writeAtomicRMWOperation(raw_ostream &Out,
713 AtomicRMWInst::BinOp Op) {
715 default: Out << " <unknown operation " << Op << ">"; break;
716 case AtomicRMWInst::Xchg: Out << " xchg"; break;
717 case AtomicRMWInst::Add: Out << " add"; break;
718 case AtomicRMWInst::Sub: Out << " sub"; break;
719 case AtomicRMWInst::And: Out << " and"; break;
720 case AtomicRMWInst::Nand: Out << " nand"; break;
721 case AtomicRMWInst::Or: Out << " or"; break;
722 case AtomicRMWInst::Xor: Out << " xor"; break;
723 case AtomicRMWInst::Max: Out << " max"; break;
724 case AtomicRMWInst::Min: Out << " min"; break;
725 case AtomicRMWInst::UMax: Out << " umax"; break;
726 case AtomicRMWInst::UMin: Out << " umin"; break;
730 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
731 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
732 // Unsafe algebra implies all the others, no need to write them all out
733 if (FPO->hasUnsafeAlgebra())
736 if (FPO->hasNoNaNs())
738 if (FPO->hasNoInfs())
740 if (FPO->hasNoSignedZeros())
742 if (FPO->hasAllowReciprocal())
747 if (const OverflowingBinaryOperator *OBO =
748 dyn_cast<OverflowingBinaryOperator>(U)) {
749 if (OBO->hasNoUnsignedWrap())
751 if (OBO->hasNoSignedWrap())
753 } else if (const PossiblyExactOperator *Div =
754 dyn_cast<PossiblyExactOperator>(U)) {
757 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
758 if (GEP->isInBounds())
763 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
764 TypePrinting &TypePrinter,
765 SlotTracker *Machine,
766 const Module *Context) {
767 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
768 if (CI->getType()->isIntegerTy(1)) {
769 Out << (CI->getZExtValue() ? "true" : "false");
772 Out << CI->getValue();
776 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
777 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
778 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
779 // We would like to output the FP constant value in exponential notation,
780 // but we cannot do this if doing so will lose precision. Check here to
781 // make sure that we only output it in exponential format if we can parse
782 // the value back and get the same value.
785 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
786 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
787 bool isInf = CFP->getValueAPF().isInfinity();
788 bool isNaN = CFP->getValueAPF().isNaN();
789 if (!isHalf && !isInf && !isNaN) {
790 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
791 CFP->getValueAPF().convertToFloat();
792 SmallString<128> StrVal;
793 raw_svector_ostream(StrVal) << Val;
795 // Check to make sure that the stringized number is not some string like
796 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
797 // that the string matches the "[-+]?[0-9]" regex.
799 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
800 ((StrVal[0] == '-' || StrVal[0] == '+') &&
801 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
802 // Reparse stringized version!
803 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
809 // Otherwise we could not reparse it to exactly the same value, so we must
810 // output the string in hexadecimal format! Note that loading and storing
811 // floating point types changes the bits of NaNs on some hosts, notably
812 // x86, so we must not use these types.
813 static_assert(sizeof(double) == sizeof(uint64_t),
814 "assuming that double is 64 bits!");
816 APFloat apf = CFP->getValueAPF();
817 // Halves and floats are represented in ASCII IR as double, convert.
819 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
822 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
827 // Either half, or some form of long double.
828 // These appear as a magic letter identifying the type, then a
829 // fixed number of hex digits.
831 // Bit position, in the current word, of the next nibble to print.
834 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
836 // api needed to prevent premature destruction
837 APInt api = CFP->getValueAPF().bitcastToAPInt();
838 const uint64_t* p = api.getRawData();
839 uint64_t word = p[1];
841 int width = api.getBitWidth();
842 for (int j=0; j<width; j+=4, shiftcount-=4) {
843 unsigned int nibble = (word>>shiftcount) & 15;
845 Out << (unsigned char)(nibble + '0');
847 Out << (unsigned char)(nibble - 10 + 'A');
848 if (shiftcount == 0 && j+4 < width) {
852 shiftcount = width-j-4;
856 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
859 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
862 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
866 llvm_unreachable("Unsupported floating point type");
867 // api needed to prevent premature destruction
868 APInt api = CFP->getValueAPF().bitcastToAPInt();
869 const uint64_t* p = api.getRawData();
871 int width = api.getBitWidth();
872 for (int j=0; j<width; j+=4, shiftcount-=4) {
873 unsigned int nibble = (word>>shiftcount) & 15;
875 Out << (unsigned char)(nibble + '0');
877 Out << (unsigned char)(nibble - 10 + 'A');
878 if (shiftcount == 0 && j+4 < width) {
882 shiftcount = width-j-4;
888 if (isa<ConstantAggregateZero>(CV)) {
889 Out << "zeroinitializer";
893 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
894 Out << "blockaddress(";
895 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
898 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
904 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
905 Type *ETy = CA->getType()->getElementType();
907 TypePrinter.print(ETy, Out);
909 WriteAsOperandInternal(Out, CA->getOperand(0),
910 &TypePrinter, Machine,
912 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
914 TypePrinter.print(ETy, Out);
916 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
923 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
924 // As a special case, print the array as a string if it is an array of
925 // i8 with ConstantInt values.
926 if (CA->isString()) {
928 PrintEscapedString(CA->getAsString(), Out);
933 Type *ETy = CA->getType()->getElementType();
935 TypePrinter.print(ETy, Out);
937 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
938 &TypePrinter, Machine,
940 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
942 TypePrinter.print(ETy, Out);
944 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
952 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
953 if (CS->getType()->isPacked())
956 unsigned N = CS->getNumOperands();
959 TypePrinter.print(CS->getOperand(0)->getType(), Out);
962 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
965 for (unsigned i = 1; i < N; i++) {
967 TypePrinter.print(CS->getOperand(i)->getType(), Out);
970 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
977 if (CS->getType()->isPacked())
982 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
983 Type *ETy = CV->getType()->getVectorElementType();
985 TypePrinter.print(ETy, Out);
987 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
989 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
991 TypePrinter.print(ETy, Out);
993 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1000 if (isa<ConstantPointerNull>(CV)) {
1005 if (isa<UndefValue>(CV)) {
1010 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1011 Out << CE->getOpcodeName();
1012 WriteOptimizationInfo(Out, CE);
1013 if (CE->isCompare())
1014 Out << ' ' << getPredicateText(CE->getPredicate());
1017 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1018 TypePrinter.print((*OI)->getType(), Out);
1020 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1021 if (OI+1 != CE->op_end())
1025 if (CE->hasIndices()) {
1026 ArrayRef<unsigned> Indices = CE->getIndices();
1027 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1028 Out << ", " << Indices[i];
1033 TypePrinter.print(CE->getType(), Out);
1040 Out << "<placeholder or erroneous Constant>";
1043 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1044 TypePrinting *TypePrinter,
1045 SlotTracker *Machine,
1046 const Module *Context) {
1048 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1049 const Value *V = Node->getOperand(mi);
1053 TypePrinter->print(V->getType(), Out);
1055 WriteAsOperandInternal(Out, Node->getOperand(mi),
1056 TypePrinter, Machine, Context);
1065 // Full implementation of printing a Value as an operand with support for
1066 // TypePrinting, etc.
1067 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1068 TypePrinting *TypePrinter,
1069 SlotTracker *Machine,
1070 const Module *Context) {
1072 PrintLLVMName(Out, V);
1076 const Constant *CV = dyn_cast<Constant>(V);
1077 if (CV && !isa<GlobalValue>(CV)) {
1078 assert(TypePrinter && "Constants require TypePrinting!");
1079 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1083 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1085 if (IA->hasSideEffects())
1086 Out << "sideeffect ";
1087 if (IA->isAlignStack())
1088 Out << "alignstack ";
1089 // We don't emit the AD_ATT dialect as it's the assumed default.
1090 if (IA->getDialect() == InlineAsm::AD_Intel)
1091 Out << "inteldialect ";
1093 PrintEscapedString(IA->getAsmString(), Out);
1095 PrintEscapedString(IA->getConstraintString(), Out);
1100 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1101 if (N->isFunctionLocal()) {
1102 // Print metadata inline, not via slot reference number.
1103 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1108 if (N->isFunctionLocal())
1109 Machine = new SlotTracker(N->getFunction());
1111 Machine = new SlotTracker(Context);
1113 int Slot = Machine->getMetadataSlot(N);
1121 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1123 PrintEscapedString(MDS->getString(), Out);
1130 // If we have a SlotTracker, use it.
1132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1133 Slot = Machine->getGlobalSlot(GV);
1136 Slot = Machine->getLocalSlot(V);
1138 // If the local value didn't succeed, then we may be referring to a value
1139 // from a different function. Translate it, as this can happen when using
1140 // address of blocks.
1142 if ((Machine = createSlotTracker(V))) {
1143 Slot = Machine->getLocalSlot(V);
1147 } else if ((Machine = createSlotTracker(V))) {
1148 // Otherwise, create one to get the # and then destroy it.
1149 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1150 Slot = Machine->getGlobalSlot(GV);
1153 Slot = Machine->getLocalSlot(V);
1162 Out << Prefix << Slot;
1167 void AssemblyWriter::init() {
1169 TypePrinter.incorporateTypes(*TheModule);
1173 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1175 AssemblyAnnotationWriter *AAW)
1176 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
1180 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
1181 AssemblyAnnotationWriter *AAW)
1182 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
1183 Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
1187 AssemblyWriter::~AssemblyWriter() { }
1189 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1191 Out << "<null operand!>";
1195 TypePrinter.print(Operand->getType(), Out);
1198 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1201 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1202 SynchronizationScope SynchScope) {
1203 if (Ordering == NotAtomic)
1206 switch (SynchScope) {
1207 case SingleThread: Out << " singlethread"; break;
1208 case CrossThread: break;
1212 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1213 case Unordered: Out << " unordered"; break;
1214 case Monotonic: Out << " monotonic"; break;
1215 case Acquire: Out << " acquire"; break;
1216 case Release: Out << " release"; break;
1217 case AcquireRelease: Out << " acq_rel"; break;
1218 case SequentiallyConsistent: Out << " seq_cst"; break;
1222 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
1223 AtomicOrdering FailureOrdering,
1224 SynchronizationScope SynchScope) {
1225 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
1227 switch (SynchScope) {
1228 case SingleThread: Out << " singlethread"; break;
1229 case CrossThread: break;
1232 switch (SuccessOrdering) {
1233 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
1234 case Unordered: Out << " unordered"; break;
1235 case Monotonic: Out << " monotonic"; break;
1236 case Acquire: Out << " acquire"; break;
1237 case Release: Out << " release"; break;
1238 case AcquireRelease: Out << " acq_rel"; break;
1239 case SequentiallyConsistent: Out << " seq_cst"; break;
1242 switch (FailureOrdering) {
1243 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
1244 case Unordered: Out << " unordered"; break;
1245 case Monotonic: Out << " monotonic"; break;
1246 case Acquire: Out << " acquire"; break;
1247 case Release: Out << " release"; break;
1248 case AcquireRelease: Out << " acq_rel"; break;
1249 case SequentiallyConsistent: Out << " seq_cst"; break;
1253 void AssemblyWriter::writeParamOperand(const Value *Operand,
1254 AttributeSet Attrs, unsigned Idx) {
1256 Out << "<null operand!>";
1261 TypePrinter.print(Operand->getType(), Out);
1262 // Print parameter attributes list
1263 if (Attrs.hasAttributes(Idx))
1264 Out << ' ' << Attrs.getAsString(Idx);
1266 // Print the operand
1267 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1270 void AssemblyWriter::printModule(const Module *M) {
1271 Machine.initialize();
1273 if (!M->getModuleIdentifier().empty() &&
1274 // Don't print the ID if it will start a new line (which would
1275 // require a comment char before it).
1276 M->getModuleIdentifier().find('\n') == std::string::npos)
1277 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1279 const std::string &DL = M->getDataLayoutStr();
1281 Out << "target datalayout = \"" << DL << "\"\n";
1282 if (!M->getTargetTriple().empty())
1283 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1285 if (!M->getModuleInlineAsm().empty()) {
1286 // Split the string into lines, to make it easier to read the .ll file.
1287 std::string Asm = M->getModuleInlineAsm();
1289 size_t NewLine = Asm.find_first_of('\n', CurPos);
1291 while (NewLine != std::string::npos) {
1292 // We found a newline, print the portion of the asm string from the
1293 // last newline up to this newline.
1294 Out << "module asm \"";
1295 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1299 NewLine = Asm.find_first_of('\n', CurPos);
1301 std::string rest(Asm.begin()+CurPos, Asm.end());
1302 if (!rest.empty()) {
1303 Out << "module asm \"";
1304 PrintEscapedString(rest, Out);
1309 printTypeIdentities();
1311 // Output all globals.
1312 if (!M->global_empty()) Out << '\n';
1313 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1315 printGlobal(I); Out << '\n';
1318 // Output all aliases.
1319 if (!M->alias_empty()) Out << "\n";
1320 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1324 // Output all of the functions.
1325 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1328 // Output all attribute groups.
1329 if (!Machine.as_empty()) {
1331 writeAllAttributeGroups();
1334 // Output named metadata.
1335 if (!M->named_metadata_empty()) Out << '\n';
1337 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1338 E = M->named_metadata_end(); I != E; ++I)
1339 printNamedMDNode(I);
1342 if (!Machine.mdn_empty()) {
1348 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1350 StringRef Name = NMD->getName();
1352 Out << "<empty name> ";
1354 if (isalpha(static_cast<unsigned char>(Name[0])) ||
1355 Name[0] == '-' || Name[0] == '$' ||
1356 Name[0] == '.' || Name[0] == '_')
1359 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1360 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1361 unsigned char C = Name[i];
1362 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
1363 C == '.' || C == '_')
1366 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1370 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1372 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1382 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1383 formatted_raw_ostream &Out) {
1385 case GlobalValue::ExternalLinkage: break;
1386 case GlobalValue::PrivateLinkage: Out << "private "; break;
1387 case GlobalValue::InternalLinkage: Out << "internal "; break;
1388 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1389 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1390 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1391 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1392 case GlobalValue::CommonLinkage: Out << "common "; break;
1393 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1394 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1395 case GlobalValue::AvailableExternallyLinkage:
1396 Out << "available_externally ";
1402 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1403 formatted_raw_ostream &Out) {
1405 case GlobalValue::DefaultVisibility: break;
1406 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1407 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1411 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
1412 formatted_raw_ostream &Out) {
1414 case GlobalValue::DefaultStorageClass: break;
1415 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
1416 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
1420 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1421 formatted_raw_ostream &Out) {
1423 case GlobalVariable::NotThreadLocal:
1425 case GlobalVariable::GeneralDynamicTLSModel:
1426 Out << "thread_local ";
1428 case GlobalVariable::LocalDynamicTLSModel:
1429 Out << "thread_local(localdynamic) ";
1431 case GlobalVariable::InitialExecTLSModel:
1432 Out << "thread_local(initialexec) ";
1434 case GlobalVariable::LocalExecTLSModel:
1435 Out << "thread_local(localexec) ";
1440 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1441 if (GV->isMaterializable())
1442 Out << "; Materializable\n";
1444 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1447 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1450 PrintLinkage(GV->getLinkage(), Out);
1451 PrintVisibility(GV->getVisibility(), Out);
1452 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
1453 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1454 if (GV->hasUnnamedAddr())
1455 Out << "unnamed_addr ";
1457 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1458 Out << "addrspace(" << AddressSpace << ") ";
1459 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
1460 Out << (GV->isConstant() ? "constant " : "global ");
1461 TypePrinter.print(GV->getType()->getElementType(), Out);
1463 if (GV->hasInitializer()) {
1465 writeOperand(GV->getInitializer(), false);
1468 if (GV->hasSection()) {
1469 Out << ", section \"";
1470 PrintEscapedString(GV->getSection(), Out);
1473 if (GV->getAlignment())
1474 Out << ", align " << GV->getAlignment();
1476 printInfoComment(*GV);
1479 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1480 if (GA->isMaterializable())
1481 Out << "; Materializable\n";
1483 // Don't crash when dumping partially built GA
1485 Out << "<<nameless>> = ";
1487 PrintLLVMName(Out, GA);
1490 PrintVisibility(GA->getVisibility(), Out);
1491 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
1492 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
1493 if (GA->hasUnnamedAddr())
1494 Out << "unnamed_addr ";
1498 PrintLinkage(GA->getLinkage(), Out);
1500 const Constant *Aliasee = GA->getAliasee();
1503 TypePrinter.print(GA->getType(), Out);
1504 Out << " <<NULL ALIASEE>>";
1506 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1509 printInfoComment(*GA);
1513 void AssemblyWriter::printTypeIdentities() {
1514 if (TypePrinter.NumberedTypes.empty() &&
1515 TypePrinter.NamedTypes.empty())
1520 // We know all the numbers that each type is used and we know that it is a
1521 // dense assignment. Convert the map to an index table.
1522 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1523 for (DenseMap<StructType*, unsigned>::iterator I =
1524 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1526 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1527 NumberedTypes[I->second] = I->first;
1530 // Emit all numbered types.
1531 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1532 Out << '%' << i << " = type ";
1534 // Make sure we print out at least one level of the type structure, so
1535 // that we do not get %2 = type %2
1536 TypePrinter.printStructBody(NumberedTypes[i], Out);
1540 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1541 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1544 // Make sure we print out at least one level of the type structure, so
1545 // that we do not get %FILE = type %FILE
1546 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1551 /// printFunction - Print all aspects of a function.
1553 void AssemblyWriter::printFunction(const Function *F) {
1554 // Print out the return type and name.
1557 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1559 if (F->isMaterializable())
1560 Out << "; Materializable\n";
1562 const AttributeSet &Attrs = F->getAttributes();
1563 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
1564 AttributeSet AS = Attrs.getFnAttributes();
1565 std::string AttrStr;
1568 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
1569 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
1572 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
1574 Attribute Attr = *I;
1575 if (!Attr.isStringAttribute()) {
1576 if (!AttrStr.empty()) AttrStr += ' ';
1577 AttrStr += Attr.getAsString();
1581 if (!AttrStr.empty())
1582 Out << "; Function Attrs: " << AttrStr << '\n';
1585 if (F->isDeclaration())
1590 PrintLinkage(F->getLinkage(), Out);
1591 PrintVisibility(F->getVisibility(), Out);
1592 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
1594 // Print the calling convention.
1595 if (F->getCallingConv() != CallingConv::C) {
1596 PrintCallingConv(F->getCallingConv(), Out);
1600 FunctionType *FT = F->getFunctionType();
1601 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1602 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
1603 TypePrinter.print(F->getReturnType(), Out);
1605 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1607 Machine.incorporateFunction(F);
1609 // Loop over the arguments, printing them...
1612 if (!F->isDeclaration()) {
1613 // If this isn't a declaration, print the argument names as well.
1614 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1616 // Insert commas as we go... the first arg doesn't get a comma
1617 if (I != F->arg_begin()) Out << ", ";
1618 printArgument(I, Attrs, Idx);
1622 // Otherwise, print the types from the function type.
1623 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1624 // Insert commas as we go... the first arg doesn't get a comma
1628 TypePrinter.print(FT->getParamType(i), Out);
1630 if (Attrs.hasAttributes(i+1))
1631 Out << ' ' << Attrs.getAsString(i+1);
1635 // Finish printing arguments...
1636 if (FT->isVarArg()) {
1637 if (FT->getNumParams()) Out << ", ";
1638 Out << "..."; // Output varargs portion of signature!
1641 if (F->hasUnnamedAddr())
1642 Out << " unnamed_addr";
1643 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1644 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
1645 if (F->hasSection()) {
1646 Out << " section \"";
1647 PrintEscapedString(F->getSection(), Out);
1650 if (F->getAlignment())
1651 Out << " align " << F->getAlignment();
1653 Out << " gc \"" << F->getGC() << '"';
1654 if (F->hasPrefixData()) {
1656 writeOperand(F->getPrefixData(), true);
1658 if (F->isDeclaration()) {
1662 // Output all of the function's basic blocks.
1663 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1669 Machine.purgeFunction();
1672 /// printArgument - This member is called for every argument that is passed into
1673 /// the function. Simply print it out
1675 void AssemblyWriter::printArgument(const Argument *Arg,
1676 AttributeSet Attrs, unsigned Idx) {
1678 TypePrinter.print(Arg->getType(), Out);
1680 // Output parameter attributes list
1681 if (Attrs.hasAttributes(Idx))
1682 Out << ' ' << Attrs.getAsString(Idx);
1684 // Output name, if available...
1685 if (Arg->hasName()) {
1687 PrintLLVMName(Out, Arg);
1691 /// printBasicBlock - This member is called for each basic block in a method.
1693 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1694 if (BB->hasName()) { // Print out the label if it exists...
1696 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1698 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1699 Out << "\n; <label>:";
1700 int Slot = Machine.getLocalSlot(BB);
1707 if (!BB->getParent()) {
1708 Out.PadToColumn(50);
1709 Out << "; Error: Block without parent!";
1710 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1711 // Output predecessors for the block.
1712 Out.PadToColumn(50);
1714 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1717 Out << " No predecessors!";
1720 writeOperand(*PI, false);
1721 for (++PI; PI != PE; ++PI) {
1723 writeOperand(*PI, false);
1730 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1732 // Output all of the instructions in the basic block...
1733 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1734 printInstructionLine(*I);
1737 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1740 /// printInstructionLine - Print an instruction and a newline character.
1741 void AssemblyWriter::printInstructionLine(const Instruction &I) {
1742 printInstruction(I);
1746 /// printInfoComment - Print a little comment after the instruction indicating
1747 /// which slot it occupies.
1749 void AssemblyWriter::printInfoComment(const Value &V) {
1750 if (AnnotationWriter)
1751 AnnotationWriter->printInfoComment(V, Out);
1754 // This member is called for each Instruction in a function..
1755 void AssemblyWriter::printInstruction(const Instruction &I) {
1756 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1758 // Print out indentation for an instruction.
1761 // Print out name if it exists...
1763 PrintLLVMName(Out, &I);
1765 } else if (!I.getType()->isVoidTy()) {
1766 // Print out the def slot taken.
1767 int SlotNum = Machine.getLocalSlot(&I);
1769 Out << "<badref> = ";
1771 Out << '%' << SlotNum << " = ";
1774 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1775 if (CI->isMustTailCall())
1777 else if (CI->isTailCall())
1781 // Print out the opcode...
1782 Out << I.getOpcodeName();
1784 // If this is an atomic load or store, print out the atomic marker.
1785 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1786 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1789 // If this is a volatile operation, print out the volatile marker.
1790 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1791 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1792 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1793 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1796 // Print out optimization information.
1797 WriteOptimizationInfo(Out, &I);
1799 // Print out the compare instruction predicates
1800 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1801 Out << ' ' << getPredicateText(CI->getPredicate());
1803 // Print out the atomicrmw operation
1804 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1805 writeAtomicRMWOperation(Out, RMWI->getOperation());
1807 // Print out the type of the operands...
1808 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
1810 // Special case conditional branches to swizzle the condition out to the front
1811 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1812 const BranchInst &BI(cast<BranchInst>(I));
1814 writeOperand(BI.getCondition(), true);
1816 writeOperand(BI.getSuccessor(0), true);
1818 writeOperand(BI.getSuccessor(1), true);
1820 } else if (isa<SwitchInst>(I)) {
1821 const SwitchInst& SI(cast<SwitchInst>(I));
1822 // Special case switch instruction to get formatting nice and correct.
1824 writeOperand(SI.getCondition(), true);
1826 writeOperand(SI.getDefaultDest(), true);
1828 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1831 writeOperand(i.getCaseValue(), true);
1833 writeOperand(i.getCaseSuccessor(), true);
1836 } else if (isa<IndirectBrInst>(I)) {
1837 // Special case indirectbr instruction to get formatting nice and correct.
1839 writeOperand(Operand, true);
1842 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1845 writeOperand(I.getOperand(i), true);
1848 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1850 TypePrinter.print(I.getType(), Out);
1853 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1854 if (op) Out << ", ";
1856 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1857 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1859 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1861 writeOperand(I.getOperand(0), true);
1862 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1864 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1866 writeOperand(I.getOperand(0), true); Out << ", ";
1867 writeOperand(I.getOperand(1), true);
1868 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1870 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1872 TypePrinter.print(I.getType(), Out);
1873 Out << " personality ";
1874 writeOperand(I.getOperand(0), true); Out << '\n';
1876 if (LPI->isCleanup())
1879 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1880 if (i != 0 || LPI->isCleanup()) Out << "\n";
1881 if (LPI->isCatch(i))
1886 writeOperand(LPI->getClause(i), true);
1888 } else if (isa<ReturnInst>(I) && !Operand) {
1890 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1891 // Print the calling convention being used.
1892 if (CI->getCallingConv() != CallingConv::C) {
1894 PrintCallingConv(CI->getCallingConv(), Out);
1897 Operand = CI->getCalledValue();
1898 PointerType *PTy = cast<PointerType>(Operand->getType());
1899 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1900 Type *RetTy = FTy->getReturnType();
1901 const AttributeSet &PAL = CI->getAttributes();
1903 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1904 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1906 // If possible, print out the short form of the call instruction. We can
1907 // only do this if the first argument is a pointer to a nonvararg function,
1908 // and if the return type is not a pointer to a function.
1911 if (!FTy->isVarArg() &&
1912 (!RetTy->isPointerTy() ||
1913 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1914 TypePrinter.print(RetTy, Out);
1916 writeOperand(Operand, false);
1918 writeOperand(Operand, true);
1921 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1924 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
1927 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1928 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1929 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1930 Operand = II->getCalledValue();
1931 PointerType *PTy = cast<PointerType>(Operand->getType());
1932 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1933 Type *RetTy = FTy->getReturnType();
1934 const AttributeSet &PAL = II->getAttributes();
1936 // Print the calling convention being used.
1937 if (II->getCallingConv() != CallingConv::C) {
1939 PrintCallingConv(II->getCallingConv(), Out);
1942 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1943 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1945 // If possible, print out the short form of the invoke instruction. We can
1946 // only do this if the first argument is a pointer to a nonvararg function,
1947 // and if the return type is not a pointer to a function.
1950 if (!FTy->isVarArg() &&
1951 (!RetTy->isPointerTy() ||
1952 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1953 TypePrinter.print(RetTy, Out);
1955 writeOperand(Operand, false);
1957 writeOperand(Operand, true);
1960 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1963 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
1967 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1968 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1971 writeOperand(II->getNormalDest(), true);
1973 writeOperand(II->getUnwindDest(), true);
1975 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1977 if (AI->isUsedWithInAlloca())
1979 TypePrinter.print(AI->getAllocatedType(), Out);
1980 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1982 writeOperand(AI->getArraySize(), true);
1984 if (AI->getAlignment()) {
1985 Out << ", align " << AI->getAlignment();
1987 } else if (isa<CastInst>(I)) {
1990 writeOperand(Operand, true); // Work with broken code
1993 TypePrinter.print(I.getType(), Out);
1994 } else if (isa<VAArgInst>(I)) {
1997 writeOperand(Operand, true); // Work with broken code
2000 TypePrinter.print(I.getType(), Out);
2001 } else if (Operand) { // Print the normal way.
2003 // PrintAllTypes - Instructions who have operands of all the same type
2004 // omit the type from all but the first operand. If the instruction has
2005 // different type operands (for example br), then they are all printed.
2006 bool PrintAllTypes = false;
2007 Type *TheType = Operand->getType();
2009 // Select, Store and ShuffleVector always print all types.
2010 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2011 || isa<ReturnInst>(I)) {
2012 PrintAllTypes = true;
2014 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2015 Operand = I.getOperand(i);
2016 // note that Operand shouldn't be null, but the test helps make dump()
2017 // more tolerant of malformed IR
2018 if (Operand && Operand->getType() != TheType) {
2019 PrintAllTypes = true; // We have differing types! Print them all!
2025 if (!PrintAllTypes) {
2027 TypePrinter.print(TheType, Out);
2031 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2033 writeOperand(I.getOperand(i), PrintAllTypes);
2037 // Print atomic ordering/alignment for memory operations
2038 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2040 writeAtomic(LI->getOrdering(), LI->getSynchScope());
2041 if (LI->getAlignment())
2042 Out << ", align " << LI->getAlignment();
2043 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2045 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2046 if (SI->getAlignment())
2047 Out << ", align " << SI->getAlignment();
2048 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2049 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
2050 CXI->getSynchScope());
2051 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2052 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2053 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2054 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2057 // Print Metadata info.
2058 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2059 I.getAllMetadata(InstMD);
2060 if (!InstMD.empty()) {
2061 SmallVector<StringRef, 8> MDNames;
2062 I.getType()->getContext().getMDKindNames(MDNames);
2063 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2064 unsigned Kind = InstMD[i].first;
2065 if (Kind < MDNames.size()) {
2066 Out << ", !" << MDNames[Kind];
2068 Out << ", !<unknown kind #" << Kind << ">";
2071 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2075 printInfoComment(I);
2078 static void WriteMDNodeComment(const MDNode *Node,
2079 formatted_raw_ostream &Out) {
2080 if (Node->getNumOperands() < 1)
2083 Value *Op = Node->getOperand(0);
2084 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2087 DIDescriptor Desc(Node);
2091 unsigned Tag = Desc.getTag();
2092 Out.PadToColumn(50);
2093 if (dwarf::TagString(Tag)) {
2096 } else if (Tag == dwarf::DW_TAG_user_base) {
2097 Out << "; [ DW_TAG_user_base ]";
2101 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
2102 Out << '!' << Slot << " = metadata ";
2103 printMDNodeBody(Node);
2106 void AssemblyWriter::writeAllMDNodes() {
2107 SmallVector<const MDNode *, 16> Nodes;
2108 Nodes.resize(Machine.mdn_size());
2109 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2111 Nodes[I->second] = cast<MDNode>(I->first);
2113 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2114 writeMDNode(i, Nodes[i]);
2118 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2119 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2120 WriteMDNodeComment(Node, Out);
2124 void AssemblyWriter::writeAllAttributeGroups() {
2125 std::vector<std::pair<AttributeSet, unsigned> > asVec;
2126 asVec.resize(Machine.as_size());
2128 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
2130 asVec[I->second] = *I;
2132 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
2133 I = asVec.begin(), E = asVec.end(); I != E; ++I)
2134 Out << "attributes #" << I->second << " = { "
2135 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
2140 //===----------------------------------------------------------------------===//
2141 // External Interface declarations
2142 //===----------------------------------------------------------------------===//
2144 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2145 SlotTracker SlotTable(this);
2146 formatted_raw_ostream OS(ROS);
2147 AssemblyWriter W(OS, SlotTable, this, AAW);
2148 W.printModule(this);
2151 void NamedMDNode::print(raw_ostream &ROS) const {
2152 SlotTracker SlotTable(getParent());
2153 formatted_raw_ostream OS(ROS);
2154 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
2155 W.printNamedMDNode(this);
2158 void Type::print(raw_ostream &OS) const {
2160 TP.print(const_cast<Type*>(this), OS);
2162 // If the type is a named struct type, print the body as well.
2163 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2164 if (!STy->isLiteral()) {
2166 TP.printStructBody(STy, OS);
2170 void Value::print(raw_ostream &ROS) const {
2171 formatted_raw_ostream OS(ROS);
2172 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2173 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
2174 SlotTracker SlotTable(F);
2175 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
2176 W.printInstruction(*I);
2177 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2178 SlotTracker SlotTable(BB->getParent());
2179 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
2180 W.printBasicBlock(BB);
2181 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2182 SlotTracker SlotTable(GV->getParent());
2183 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
2184 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2186 else if (const Function *F = dyn_cast<Function>(GV))
2189 W.printAlias(cast<GlobalAlias>(GV));
2190 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2191 const Function *F = N->getFunction();
2192 SlotTracker SlotTable(F);
2193 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr);
2194 W.printMDNodeBody(N);
2195 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2196 TypePrinting TypePrinter;
2197 TypePrinter.print(C->getType(), OS);
2199 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
2200 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2201 isa<Argument>(this)) {
2202 this->printAsOperand(OS);
2204 llvm_unreachable("Unknown value to print out!");
2208 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
2209 // Fast path: Don't construct and populate a TypePrinting object if we
2210 // won't be needing any types printed.
2212 ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
2213 hasName() || isa<GlobalValue>(this))) {
2214 WriteAsOperandInternal(O, this, nullptr, nullptr, M);
2219 M = getModuleFromVal(this);
2221 TypePrinting TypePrinter;
2223 TypePrinter.incorporateTypes(*M);
2225 TypePrinter.print(getType(), O);
2229 WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
2232 // Value::dump - allow easy printing of Values from the debugger.
2233 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2235 // Type::dump - allow easy printing of Types from the debugger.
2236 void Type::dump() const { print(dbgs()); }
2238 // Module::dump() - Allow printing of Modules from the debugger.
2239 void Module::dump() const { print(dbgs(), nullptr); }
2241 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2242 void NamedMDNode::dump() const { print(dbgs()); }