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);
115 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
116 /// prefixed with % (if the string only contains simple characters) or is
117 /// surrounded with ""'s (if it has special chars in it). Print it out.
118 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
119 assert(!Name.empty() && "Cannot get empty name!");
121 case NoPrefix: break;
122 case GlobalPrefix: OS << '@'; break;
123 case ComdatPrefix: OS << '$'; break;
124 case LabelPrefix: break;
125 case LocalPrefix: OS << '%'; break;
128 // Scan the name to see if it needs quotes first.
129 bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
131 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
132 // By making this unsigned, the value passed in to isalnum will always be
133 // in the range 0-255. This is important when building with MSVC because
134 // its implementation will assert. This situation can arise when dealing
135 // with UTF-8 multibyte characters.
136 unsigned char C = Name[i];
137 if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
145 // If we didn't need any quotes, just write out the name in one blast.
151 // Okay, we need quotes. Output the quotes and escape any scary characters as
154 PrintEscapedString(Name, OS);
158 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
159 /// prefixed with % (if the string only contains simple characters) or is
160 /// surrounded with ""'s (if it has special chars in it). Print it out.
161 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
162 PrintLLVMName(OS, V->getName(),
163 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
169 void TypePrinting::incorporateTypes(const Module &M) {
170 NamedTypes.run(M, false);
172 // The list of struct types we got back includes all the struct types, split
173 // the unnamed ones out to a numbering and remove the anonymous structs.
174 unsigned NextNumber = 0;
176 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
177 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
178 StructType *STy = *I;
180 // Ignore anonymous types.
181 if (STy->isLiteral())
184 if (STy->getName().empty())
185 NumberedTypes[STy] = NextNumber++;
190 NamedTypes.erase(NextToUse, NamedTypes.end());
194 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
195 /// use of type names or up references to shorten the type name where possible.
196 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
197 switch (Ty->getTypeID()) {
198 case Type::VoidTyID: OS << "void"; return;
199 case Type::HalfTyID: OS << "half"; return;
200 case Type::FloatTyID: OS << "float"; return;
201 case Type::DoubleTyID: OS << "double"; return;
202 case Type::X86_FP80TyID: OS << "x86_fp80"; return;
203 case Type::FP128TyID: OS << "fp128"; return;
204 case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
205 case Type::LabelTyID: OS << "label"; return;
206 case Type::MetadataTyID: OS << "metadata"; return;
207 case Type::X86_MMXTyID: OS << "x86_mmx"; return;
208 case Type::IntegerTyID:
209 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
212 case Type::FunctionTyID: {
213 FunctionType *FTy = cast<FunctionType>(Ty);
214 print(FTy->getReturnType(), OS);
216 for (FunctionType::param_iterator I = FTy->param_begin(),
217 E = FTy->param_end(); I != E; ++I) {
218 if (I != FTy->param_begin())
222 if (FTy->isVarArg()) {
223 if (FTy->getNumParams()) OS << ", ";
229 case Type::StructTyID: {
230 StructType *STy = cast<StructType>(Ty);
232 if (STy->isLiteral())
233 return printStructBody(STy, OS);
235 if (!STy->getName().empty())
236 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
238 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
239 if (I != NumberedTypes.end())
240 OS << '%' << I->second;
241 else // Not enumerated, print the hex address.
242 OS << "%\"type " << STy << '\"';
245 case Type::PointerTyID: {
246 PointerType *PTy = cast<PointerType>(Ty);
247 print(PTy->getElementType(), OS);
248 if (unsigned AddressSpace = PTy->getAddressSpace())
249 OS << " addrspace(" << AddressSpace << ')';
253 case Type::ArrayTyID: {
254 ArrayType *ATy = cast<ArrayType>(Ty);
255 OS << '[' << ATy->getNumElements() << " x ";
256 print(ATy->getElementType(), OS);
260 case Type::VectorTyID: {
261 VectorType *PTy = cast<VectorType>(Ty);
262 OS << "<" << PTy->getNumElements() << " x ";
263 print(PTy->getElementType(), OS);
268 llvm_unreachable("Invalid TypeID");
271 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
272 if (STy->isOpaque()) {
280 if (STy->getNumElements() == 0) {
283 StructType::element_iterator I = STy->element_begin();
286 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
297 //===----------------------------------------------------------------------===//
298 // SlotTracker Class: Enumerate slot numbers for unnamed values
299 //===----------------------------------------------------------------------===//
300 /// This class provides computation of slot numbers for LLVM Assembly writing.
304 /// ValueMap - A mapping of Values to slot numbers.
305 typedef DenseMap<const Value*, unsigned> ValueMap;
308 /// TheModule - The module for which we are holding slot numbers.
309 const Module* TheModule;
311 /// TheFunction - The function for which we are holding slot numbers.
312 const Function* TheFunction;
313 bool FunctionProcessed;
315 /// mMap - The slot map for the module level data.
319 /// fMap - The slot map for the function level data.
323 /// mdnMap - Map for MDNodes.
324 DenseMap<const MDNode*, unsigned> mdnMap;
327 /// asMap - The slot map for attribute sets.
328 DenseMap<AttributeSet, unsigned> asMap;
331 /// Construct from a module
332 explicit SlotTracker(const Module *M);
333 /// Construct from a function, starting out in incorp state.
334 explicit SlotTracker(const Function *F);
336 /// Return the slot number of the specified value in it's type
337 /// plane. If something is not in the SlotTracker, return -1.
338 int getLocalSlot(const Value *V);
339 int getGlobalSlot(const GlobalValue *V);
340 int getMetadataSlot(const MDNode *N);
341 int getAttributeGroupSlot(AttributeSet AS);
343 /// If you'd like to deal with a function instead of just a module, use
344 /// this method to get its data into the SlotTracker.
345 void incorporateFunction(const Function *F) {
347 FunctionProcessed = false;
350 /// After calling incorporateFunction, use this method to remove the
351 /// most recently incorporated function from the SlotTracker. This
352 /// will reset the state of the machine back to just the module contents.
353 void purgeFunction();
355 /// MDNode map iterators.
356 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
357 mdn_iterator mdn_begin() { return mdnMap.begin(); }
358 mdn_iterator mdn_end() { return mdnMap.end(); }
359 unsigned mdn_size() const { return mdnMap.size(); }
360 bool mdn_empty() const { return mdnMap.empty(); }
362 /// AttributeSet map iterators.
363 typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
364 as_iterator as_begin() { return asMap.begin(); }
365 as_iterator as_end() { return asMap.end(); }
366 unsigned as_size() const { return asMap.size(); }
367 bool as_empty() const { return asMap.empty(); }
369 /// This function does the actual initialization.
370 inline void initialize();
372 // Implementation Details
374 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
375 void CreateModuleSlot(const GlobalValue *V);
377 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
378 void CreateMetadataSlot(const MDNode *N);
380 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
381 void CreateFunctionSlot(const Value *V);
383 /// \brief Insert the specified AttributeSet into the slot table.
384 void CreateAttributeSetSlot(AttributeSet AS);
386 /// Add all of the module level global variables (and their initializers)
387 /// and function declarations, but not the contents of those functions.
388 void processModule();
390 /// Add all of the functions arguments, basic blocks, and instructions.
391 void processFunction();
393 SlotTracker(const SlotTracker &) LLVM_DELETED_FUNCTION;
394 void operator=(const SlotTracker &) LLVM_DELETED_FUNCTION;
397 SlotTracker *createSlotTracker(const Module *M) {
398 return new SlotTracker(M);
401 static SlotTracker *createSlotTracker(const Value *V) {
402 if (const Argument *FA = dyn_cast<Argument>(V))
403 return new SlotTracker(FA->getParent());
405 if (const Instruction *I = dyn_cast<Instruction>(V))
407 return new SlotTracker(I->getParent()->getParent());
409 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
410 return new SlotTracker(BB->getParent());
412 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
413 return new SlotTracker(GV->getParent());
415 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
416 return new SlotTracker(GA->getParent());
418 if (const Function *Func = dyn_cast<Function>(V))
419 return new SlotTracker(Func);
421 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
422 if (!MD->isFunctionLocal())
423 return new SlotTracker(MD->getFunction());
425 return new SlotTracker((Function *)nullptr);
432 #define ST_DEBUG(X) dbgs() << X
437 // Module level constructor. Causes the contents of the Module (sans functions)
438 // to be added to the slot table.
439 SlotTracker::SlotTracker(const Module *M)
440 : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
441 mNext(0), fNext(0), mdnNext(0), asNext(0) {
444 // Function level constructor. Causes the contents of the Module and the one
445 // function provided to be added to the slot table.
446 SlotTracker::SlotTracker(const Function *F)
447 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
448 FunctionProcessed(false), mNext(0), fNext(0), mdnNext(0), asNext(0) {
451 inline void SlotTracker::initialize() {
454 TheModule = nullptr; ///< Prevent re-processing next time we're called.
457 if (TheFunction && !FunctionProcessed)
461 // Iterate through all the global variables, functions, and global
462 // variable initializers and create slots for them.
463 void SlotTracker::processModule() {
464 ST_DEBUG("begin processModule!\n");
466 // Add all of the unnamed global variables to the value table.
467 for (Module::const_global_iterator I = TheModule->global_begin(),
468 E = TheModule->global_end(); I != E; ++I) {
473 // Add metadata used by named metadata.
474 for (Module::const_named_metadata_iterator
475 I = TheModule->named_metadata_begin(),
476 E = TheModule->named_metadata_end(); I != E; ++I) {
477 const NamedMDNode *NMD = I;
478 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
479 CreateMetadataSlot(NMD->getOperand(i));
482 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
485 // Add all the unnamed functions to the table.
488 // Add all the function attributes to the table.
489 // FIXME: Add attributes of other objects?
490 AttributeSet FnAttrs = I->getAttributes().getFnAttributes();
491 if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
492 CreateAttributeSetSlot(FnAttrs);
495 ST_DEBUG("end processModule!\n");
498 // Process the arguments, basic blocks, and instructions of a function.
499 void SlotTracker::processFunction() {
500 ST_DEBUG("begin processFunction!\n");
503 // Add all the function arguments with no names.
504 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
505 AE = TheFunction->arg_end(); AI != AE; ++AI)
507 CreateFunctionSlot(AI);
509 ST_DEBUG("Inserting Instructions:\n");
511 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
513 // Add all of the basic blocks and instructions with no names.
514 for (Function::const_iterator BB = TheFunction->begin(),
515 E = TheFunction->end(); BB != E; ++BB) {
517 CreateFunctionSlot(BB);
519 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
521 if (!I->getType()->isVoidTy() && !I->hasName())
522 CreateFunctionSlot(I);
524 // Intrinsics can directly use metadata. We allow direct calls to any
525 // llvm.foo function here, because the target may not be linked into the
527 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
528 if (Function *F = CI->getCalledFunction())
529 if (F->isIntrinsic())
530 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
531 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
532 CreateMetadataSlot(N);
534 // Add all the call attributes to the table.
535 AttributeSet Attrs = CI->getAttributes().getFnAttributes();
536 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
537 CreateAttributeSetSlot(Attrs);
538 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) {
539 // Add all the call attributes to the table.
540 AttributeSet Attrs = II->getAttributes().getFnAttributes();
541 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
542 CreateAttributeSetSlot(Attrs);
545 // Process metadata attached with this instruction.
546 I->getAllMetadata(MDForInst);
547 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
548 CreateMetadataSlot(MDForInst[i].second);
553 FunctionProcessed = true;
555 ST_DEBUG("end processFunction!\n");
558 /// Clean up after incorporating a function. This is the only way to get out of
559 /// the function incorporation state that affects get*Slot/Create*Slot. Function
560 /// incorporation state is indicated by TheFunction != 0.
561 void SlotTracker::purgeFunction() {
562 ST_DEBUG("begin purgeFunction!\n");
563 fMap.clear(); // Simply discard the function level map
564 TheFunction = nullptr;
565 FunctionProcessed = false;
566 ST_DEBUG("end purgeFunction!\n");
569 /// getGlobalSlot - Get the slot number of a global value.
570 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
571 // Check for uninitialized state and do lazy initialization.
574 // Find the value in the module map
575 ValueMap::iterator MI = mMap.find(V);
576 return MI == mMap.end() ? -1 : (int)MI->second;
579 /// getMetadataSlot - Get the slot number of a MDNode.
580 int SlotTracker::getMetadataSlot(const MDNode *N) {
581 // Check for uninitialized state and do lazy initialization.
584 // Find the MDNode in the module map
585 mdn_iterator MI = mdnMap.find(N);
586 return MI == mdnMap.end() ? -1 : (int)MI->second;
590 /// getLocalSlot - Get the slot number for a value that is local to a function.
591 int SlotTracker::getLocalSlot(const Value *V) {
592 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
594 // Check for uninitialized state and do lazy initialization.
597 ValueMap::iterator FI = fMap.find(V);
598 return FI == fMap.end() ? -1 : (int)FI->second;
601 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
602 // Check for uninitialized state and do lazy initialization.
605 // Find the AttributeSet in the module map.
606 as_iterator AI = asMap.find(AS);
607 return AI == asMap.end() ? -1 : (int)AI->second;
610 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
611 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
612 assert(V && "Can't insert a null Value into SlotTracker!");
613 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
614 assert(!V->hasName() && "Doesn't need a slot!");
616 unsigned DestSlot = mNext++;
619 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
621 // G = Global, F = Function, A = Alias, o = other
622 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
623 (isa<Function>(V) ? 'F' :
624 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
627 /// CreateSlot - Create a new slot for the specified value if it has no name.
628 void SlotTracker::CreateFunctionSlot(const Value *V) {
629 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
631 unsigned DestSlot = fNext++;
634 // G = Global, F = Function, o = other
635 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
636 DestSlot << " [o]\n");
639 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
640 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
641 assert(N && "Can't insert a null Value into SlotTracker!");
643 // Don't insert if N is a function-local metadata, these are always printed
645 if (!N->isFunctionLocal()) {
646 mdn_iterator I = mdnMap.find(N);
647 if (I != mdnMap.end())
650 unsigned DestSlot = mdnNext++;
651 mdnMap[N] = DestSlot;
654 // Recursively add any MDNodes referenced by operands.
655 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
656 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
657 CreateMetadataSlot(Op);
660 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
661 assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
662 "Doesn't need a slot!");
664 as_iterator I = asMap.find(AS);
665 if (I != asMap.end())
668 unsigned DestSlot = asNext++;
669 asMap[AS] = DestSlot;
672 //===----------------------------------------------------------------------===//
673 // AsmWriter Implementation
674 //===----------------------------------------------------------------------===//
676 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
677 TypePrinting *TypePrinter,
678 SlotTracker *Machine,
679 const Module *Context);
681 static const char *getPredicateText(unsigned predicate) {
682 const char * pred = "unknown";
684 case FCmpInst::FCMP_FALSE: pred = "false"; break;
685 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
686 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
687 case FCmpInst::FCMP_OGE: pred = "oge"; break;
688 case FCmpInst::FCMP_OLT: pred = "olt"; break;
689 case FCmpInst::FCMP_OLE: pred = "ole"; break;
690 case FCmpInst::FCMP_ONE: pred = "one"; break;
691 case FCmpInst::FCMP_ORD: pred = "ord"; break;
692 case FCmpInst::FCMP_UNO: pred = "uno"; break;
693 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
694 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
695 case FCmpInst::FCMP_UGE: pred = "uge"; break;
696 case FCmpInst::FCMP_ULT: pred = "ult"; break;
697 case FCmpInst::FCMP_ULE: pred = "ule"; break;
698 case FCmpInst::FCMP_UNE: pred = "une"; break;
699 case FCmpInst::FCMP_TRUE: pred = "true"; break;
700 case ICmpInst::ICMP_EQ: pred = "eq"; break;
701 case ICmpInst::ICMP_NE: pred = "ne"; break;
702 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
703 case ICmpInst::ICMP_SGE: pred = "sge"; break;
704 case ICmpInst::ICMP_SLT: pred = "slt"; break;
705 case ICmpInst::ICMP_SLE: pred = "sle"; break;
706 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
707 case ICmpInst::ICMP_UGE: pred = "uge"; break;
708 case ICmpInst::ICMP_ULT: pred = "ult"; break;
709 case ICmpInst::ICMP_ULE: pred = "ule"; break;
714 static void writeAtomicRMWOperation(raw_ostream &Out,
715 AtomicRMWInst::BinOp Op) {
717 default: Out << " <unknown operation " << Op << ">"; break;
718 case AtomicRMWInst::Xchg: Out << " xchg"; break;
719 case AtomicRMWInst::Add: Out << " add"; break;
720 case AtomicRMWInst::Sub: Out << " sub"; break;
721 case AtomicRMWInst::And: Out << " and"; break;
722 case AtomicRMWInst::Nand: Out << " nand"; break;
723 case AtomicRMWInst::Or: Out << " or"; break;
724 case AtomicRMWInst::Xor: Out << " xor"; break;
725 case AtomicRMWInst::Max: Out << " max"; break;
726 case AtomicRMWInst::Min: Out << " min"; break;
727 case AtomicRMWInst::UMax: Out << " umax"; break;
728 case AtomicRMWInst::UMin: Out << " umin"; break;
732 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
733 if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
734 // Unsafe algebra implies all the others, no need to write them all out
735 if (FPO->hasUnsafeAlgebra())
738 if (FPO->hasNoNaNs())
740 if (FPO->hasNoInfs())
742 if (FPO->hasNoSignedZeros())
744 if (FPO->hasAllowReciprocal())
749 if (const OverflowingBinaryOperator *OBO =
750 dyn_cast<OverflowingBinaryOperator>(U)) {
751 if (OBO->hasNoUnsignedWrap())
753 if (OBO->hasNoSignedWrap())
755 } else if (const PossiblyExactOperator *Div =
756 dyn_cast<PossiblyExactOperator>(U)) {
759 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
760 if (GEP->isInBounds())
765 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
766 TypePrinting &TypePrinter,
767 SlotTracker *Machine,
768 const Module *Context) {
769 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
770 if (CI->getType()->isIntegerTy(1)) {
771 Out << (CI->getZExtValue() ? "true" : "false");
774 Out << CI->getValue();
778 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
779 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
780 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
781 // We would like to output the FP constant value in exponential notation,
782 // but we cannot do this if doing so will lose precision. Check here to
783 // make sure that we only output it in exponential format if we can parse
784 // the value back and get the same value.
787 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
788 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
789 bool isInf = CFP->getValueAPF().isInfinity();
790 bool isNaN = CFP->getValueAPF().isNaN();
791 if (!isHalf && !isInf && !isNaN) {
792 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
793 CFP->getValueAPF().convertToFloat();
794 SmallString<128> StrVal;
795 raw_svector_ostream(StrVal) << Val;
797 // Check to make sure that the stringized number is not some string like
798 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
799 // that the string matches the "[-+]?[0-9]" regex.
801 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
802 ((StrVal[0] == '-' || StrVal[0] == '+') &&
803 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
804 // Reparse stringized version!
805 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
811 // Otherwise we could not reparse it to exactly the same value, so we must
812 // output the string in hexadecimal format! Note that loading and storing
813 // floating point types changes the bits of NaNs on some hosts, notably
814 // x86, so we must not use these types.
815 static_assert(sizeof(double) == sizeof(uint64_t),
816 "assuming that double is 64 bits!");
818 APFloat apf = CFP->getValueAPF();
819 // Halves and floats are represented in ASCII IR as double, convert.
821 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
824 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
829 // Either half, or some form of long double.
830 // These appear as a magic letter identifying the type, then a
831 // fixed number of hex digits.
833 // Bit position, in the current word, of the next nibble to print.
836 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
838 // api needed to prevent premature destruction
839 APInt api = CFP->getValueAPF().bitcastToAPInt();
840 const uint64_t* p = api.getRawData();
841 uint64_t word = p[1];
843 int width = api.getBitWidth();
844 for (int j=0; j<width; j+=4, shiftcount-=4) {
845 unsigned int nibble = (word>>shiftcount) & 15;
847 Out << (unsigned char)(nibble + '0');
849 Out << (unsigned char)(nibble - 10 + 'A');
850 if (shiftcount == 0 && j+4 < width) {
854 shiftcount = width-j-4;
858 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
861 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
864 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
868 llvm_unreachable("Unsupported floating point type");
869 // api needed to prevent premature destruction
870 APInt api = CFP->getValueAPF().bitcastToAPInt();
871 const uint64_t* p = api.getRawData();
873 int width = api.getBitWidth();
874 for (int j=0; j<width; j+=4, shiftcount-=4) {
875 unsigned int nibble = (word>>shiftcount) & 15;
877 Out << (unsigned char)(nibble + '0');
879 Out << (unsigned char)(nibble - 10 + 'A');
880 if (shiftcount == 0 && j+4 < width) {
884 shiftcount = width-j-4;
890 if (isa<ConstantAggregateZero>(CV)) {
891 Out << "zeroinitializer";
895 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
896 Out << "blockaddress(";
897 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
900 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
906 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
907 Type *ETy = CA->getType()->getElementType();
909 TypePrinter.print(ETy, Out);
911 WriteAsOperandInternal(Out, CA->getOperand(0),
912 &TypePrinter, Machine,
914 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
916 TypePrinter.print(ETy, Out);
918 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
925 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
926 // As a special case, print the array as a string if it is an array of
927 // i8 with ConstantInt values.
928 if (CA->isString()) {
930 PrintEscapedString(CA->getAsString(), Out);
935 Type *ETy = CA->getType()->getElementType();
937 TypePrinter.print(ETy, Out);
939 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
940 &TypePrinter, Machine,
942 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
944 TypePrinter.print(ETy, Out);
946 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
954 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
955 if (CS->getType()->isPacked())
958 unsigned N = CS->getNumOperands();
961 TypePrinter.print(CS->getOperand(0)->getType(), Out);
964 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
967 for (unsigned i = 1; i < N; i++) {
969 TypePrinter.print(CS->getOperand(i)->getType(), Out);
972 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
979 if (CS->getType()->isPacked())
984 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
985 Type *ETy = CV->getType()->getVectorElementType();
987 TypePrinter.print(ETy, Out);
989 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
991 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
993 TypePrinter.print(ETy, Out);
995 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1002 if (isa<ConstantPointerNull>(CV)) {
1007 if (isa<UndefValue>(CV)) {
1012 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1013 Out << CE->getOpcodeName();
1014 WriteOptimizationInfo(Out, CE);
1015 if (CE->isCompare())
1016 Out << ' ' << getPredicateText(CE->getPredicate());
1019 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1020 TypePrinter.print((*OI)->getType(), Out);
1022 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1023 if (OI+1 != CE->op_end())
1027 if (CE->hasIndices()) {
1028 ArrayRef<unsigned> Indices = CE->getIndices();
1029 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1030 Out << ", " << Indices[i];
1035 TypePrinter.print(CE->getType(), Out);
1042 Out << "<placeholder or erroneous Constant>";
1045 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1046 TypePrinting *TypePrinter,
1047 SlotTracker *Machine,
1048 const Module *Context) {
1050 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1051 const Value *V = Node->getOperand(mi);
1055 TypePrinter->print(V->getType(), Out);
1057 WriteAsOperandInternal(Out, Node->getOperand(mi),
1058 TypePrinter, Machine, Context);
1067 // Full implementation of printing a Value as an operand with support for
1068 // TypePrinting, etc.
1069 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1070 TypePrinting *TypePrinter,
1071 SlotTracker *Machine,
1072 const Module *Context) {
1074 PrintLLVMName(Out, V);
1078 const Constant *CV = dyn_cast<Constant>(V);
1079 if (CV && !isa<GlobalValue>(CV)) {
1080 assert(TypePrinter && "Constants require TypePrinting!");
1081 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1085 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1087 if (IA->hasSideEffects())
1088 Out << "sideeffect ";
1089 if (IA->isAlignStack())
1090 Out << "alignstack ";
1091 // We don't emit the AD_ATT dialect as it's the assumed default.
1092 if (IA->getDialect() == InlineAsm::AD_Intel)
1093 Out << "inteldialect ";
1095 PrintEscapedString(IA->getAsmString(), Out);
1097 PrintEscapedString(IA->getConstraintString(), Out);
1102 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1103 if (N->isFunctionLocal()) {
1104 // Print metadata inline, not via slot reference number.
1105 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1110 if (N->isFunctionLocal())
1111 Machine = new SlotTracker(N->getFunction());
1113 Machine = new SlotTracker(Context);
1115 int Slot = Machine->getMetadataSlot(N);
1123 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1125 PrintEscapedString(MDS->getString(), Out);
1132 // If we have a SlotTracker, use it.
1134 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1135 Slot = Machine->getGlobalSlot(GV);
1138 Slot = Machine->getLocalSlot(V);
1140 // If the local value didn't succeed, then we may be referring to a value
1141 // from a different function. Translate it, as this can happen when using
1142 // address of blocks.
1144 if ((Machine = createSlotTracker(V))) {
1145 Slot = Machine->getLocalSlot(V);
1149 } else if ((Machine = createSlotTracker(V))) {
1150 // Otherwise, create one to get the # and then destroy it.
1151 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1152 Slot = Machine->getGlobalSlot(GV);
1155 Slot = Machine->getLocalSlot(V);
1164 Out << Prefix << Slot;
1169 void AssemblyWriter::init() {
1172 TypePrinter.incorporateTypes(*TheModule);
1173 for (const Function &F : *TheModule)
1174 if (const Comdat *C = F.getComdat())
1176 for (const GlobalVariable &GV : TheModule->globals())
1177 if (const Comdat *C = GV.getComdat())
1182 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1184 AssemblyAnnotationWriter *AAW)
1185 : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW) {
1189 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
1190 AssemblyAnnotationWriter *AAW)
1191 : Out(o), TheModule(M), ModuleSlotTracker(createSlotTracker(M)),
1192 Machine(*ModuleSlotTracker), AnnotationWriter(AAW) {
1196 AssemblyWriter::~AssemblyWriter() { }
1198 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1200 Out << "<null operand!>";
1204 TypePrinter.print(Operand->getType(), Out);
1207 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1210 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1211 SynchronizationScope SynchScope) {
1212 if (Ordering == NotAtomic)
1215 switch (SynchScope) {
1216 case SingleThread: Out << " singlethread"; break;
1217 case CrossThread: break;
1221 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1222 case Unordered: Out << " unordered"; break;
1223 case Monotonic: Out << " monotonic"; break;
1224 case Acquire: Out << " acquire"; break;
1225 case Release: Out << " release"; break;
1226 case AcquireRelease: Out << " acq_rel"; break;
1227 case SequentiallyConsistent: Out << " seq_cst"; break;
1231 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
1232 AtomicOrdering FailureOrdering,
1233 SynchronizationScope SynchScope) {
1234 assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
1236 switch (SynchScope) {
1237 case SingleThread: Out << " singlethread"; break;
1238 case CrossThread: break;
1241 switch (SuccessOrdering) {
1242 default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
1243 case Unordered: Out << " unordered"; break;
1244 case Monotonic: Out << " monotonic"; break;
1245 case Acquire: Out << " acquire"; break;
1246 case Release: Out << " release"; break;
1247 case AcquireRelease: Out << " acq_rel"; break;
1248 case SequentiallyConsistent: Out << " seq_cst"; break;
1251 switch (FailureOrdering) {
1252 default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
1253 case Unordered: Out << " unordered"; break;
1254 case Monotonic: Out << " monotonic"; break;
1255 case Acquire: Out << " acquire"; break;
1256 case Release: Out << " release"; break;
1257 case AcquireRelease: Out << " acq_rel"; break;
1258 case SequentiallyConsistent: Out << " seq_cst"; break;
1262 void AssemblyWriter::writeParamOperand(const Value *Operand,
1263 AttributeSet Attrs, unsigned Idx) {
1265 Out << "<null operand!>";
1270 TypePrinter.print(Operand->getType(), Out);
1271 // Print parameter attributes list
1272 if (Attrs.hasAttributes(Idx))
1273 Out << ' ' << Attrs.getAsString(Idx);
1275 // Print the operand
1276 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1279 void AssemblyWriter::printModule(const Module *M) {
1280 Machine.initialize();
1282 if (!M->getModuleIdentifier().empty() &&
1283 // Don't print the ID if it will start a new line (which would
1284 // require a comment char before it).
1285 M->getModuleIdentifier().find('\n') == std::string::npos)
1286 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1288 const std::string &DL = M->getDataLayoutStr();
1290 Out << "target datalayout = \"" << DL << "\"\n";
1291 if (!M->getTargetTriple().empty())
1292 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1294 if (!M->getModuleInlineAsm().empty()) {
1295 // Split the string into lines, to make it easier to read the .ll file.
1296 std::string Asm = M->getModuleInlineAsm();
1298 size_t NewLine = Asm.find_first_of('\n', CurPos);
1300 while (NewLine != std::string::npos) {
1301 // We found a newline, print the portion of the asm string from the
1302 // last newline up to this newline.
1303 Out << "module asm \"";
1304 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1308 NewLine = Asm.find_first_of('\n', CurPos);
1310 std::string rest(Asm.begin()+CurPos, Asm.end());
1311 if (!rest.empty()) {
1312 Out << "module asm \"";
1313 PrintEscapedString(rest, Out);
1318 printTypeIdentities();
1320 // Output all comdats.
1321 if (!Comdats.empty())
1323 for (const Comdat *C : Comdats) {
1325 if (C != Comdats.back())
1329 // Output all globals.
1330 if (!M->global_empty()) Out << '\n';
1331 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1333 printGlobal(I); Out << '\n';
1336 // Output all aliases.
1337 if (!M->alias_empty()) Out << "\n";
1338 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1342 // Output all of the functions.
1343 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1346 // Output all attribute groups.
1347 if (!Machine.as_empty()) {
1349 writeAllAttributeGroups();
1352 // Output named metadata.
1353 if (!M->named_metadata_empty()) Out << '\n';
1355 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1356 E = M->named_metadata_end(); I != E; ++I)
1357 printNamedMDNode(I);
1360 if (!Machine.mdn_empty()) {
1366 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1368 StringRef Name = NMD->getName();
1370 Out << "<empty name> ";
1372 if (isalpha(static_cast<unsigned char>(Name[0])) ||
1373 Name[0] == '-' || Name[0] == '$' ||
1374 Name[0] == '.' || Name[0] == '_')
1377 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1378 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1379 unsigned char C = Name[i];
1380 if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
1381 C == '.' || C == '_')
1384 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1388 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1390 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1400 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1401 formatted_raw_ostream &Out) {
1403 case GlobalValue::ExternalLinkage: break;
1404 case GlobalValue::PrivateLinkage: Out << "private "; break;
1405 case GlobalValue::InternalLinkage: Out << "internal "; break;
1406 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1407 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1408 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1409 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1410 case GlobalValue::CommonLinkage: Out << "common "; break;
1411 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1412 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1413 case GlobalValue::AvailableExternallyLinkage:
1414 Out << "available_externally ";
1420 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1421 formatted_raw_ostream &Out) {
1423 case GlobalValue::DefaultVisibility: break;
1424 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1425 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1429 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
1430 formatted_raw_ostream &Out) {
1432 case GlobalValue::DefaultStorageClass: break;
1433 case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
1434 case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
1438 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1439 formatted_raw_ostream &Out) {
1441 case GlobalVariable::NotThreadLocal:
1443 case GlobalVariable::GeneralDynamicTLSModel:
1444 Out << "thread_local ";
1446 case GlobalVariable::LocalDynamicTLSModel:
1447 Out << "thread_local(localdynamic) ";
1449 case GlobalVariable::InitialExecTLSModel:
1450 Out << "thread_local(initialexec) ";
1452 case GlobalVariable::LocalExecTLSModel:
1453 Out << "thread_local(localexec) ";
1458 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1459 if (GV->isMaterializable())
1460 Out << "; Materializable\n";
1462 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1465 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1468 PrintLinkage(GV->getLinkage(), Out);
1469 PrintVisibility(GV->getVisibility(), Out);
1470 PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
1471 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1472 if (GV->hasUnnamedAddr())
1473 Out << "unnamed_addr ";
1475 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1476 Out << "addrspace(" << AddressSpace << ") ";
1477 if (GV->isExternallyInitialized()) Out << "externally_initialized ";
1478 Out << (GV->isConstant() ? "constant " : "global ");
1479 TypePrinter.print(GV->getType()->getElementType(), Out);
1481 if (GV->hasInitializer()) {
1483 writeOperand(GV->getInitializer(), false);
1486 if (GV->hasSection()) {
1487 Out << ", section \"";
1488 PrintEscapedString(GV->getSection(), Out);
1491 if (GV->hasComdat()) {
1493 PrintLLVMName(Out, GV->getComdat()->getName(), ComdatPrefix);
1495 if (GV->getAlignment())
1496 Out << ", align " << GV->getAlignment();
1498 printInfoComment(*GV);
1501 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1502 if (GA->isMaterializable())
1503 Out << "; Materializable\n";
1505 // Don't crash when dumping partially built GA
1507 Out << "<<nameless>> = ";
1509 PrintLLVMName(Out, GA);
1512 PrintLinkage(GA->getLinkage(), Out);
1513 PrintVisibility(GA->getVisibility(), Out);
1514 PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
1515 PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
1516 if (GA->hasUnnamedAddr())
1517 Out << "unnamed_addr ";
1521 const Constant *Aliasee = GA->getAliasee();
1524 TypePrinter.print(GA->getType(), Out);
1525 Out << " <<NULL ALIASEE>>";
1527 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1530 printInfoComment(*GA);
1534 void AssemblyWriter::printComdat(const Comdat *C) {
1538 void AssemblyWriter::printTypeIdentities() {
1539 if (TypePrinter.NumberedTypes.empty() &&
1540 TypePrinter.NamedTypes.empty())
1545 // We know all the numbers that each type is used and we know that it is a
1546 // dense assignment. Convert the map to an index table.
1547 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1548 for (DenseMap<StructType*, unsigned>::iterator I =
1549 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1551 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1552 NumberedTypes[I->second] = I->first;
1555 // Emit all numbered types.
1556 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1557 Out << '%' << i << " = type ";
1559 // Make sure we print out at least one level of the type structure, so
1560 // that we do not get %2 = type %2
1561 TypePrinter.printStructBody(NumberedTypes[i], Out);
1565 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1566 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1569 // Make sure we print out at least one level of the type structure, so
1570 // that we do not get %FILE = type %FILE
1571 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1576 /// printFunction - Print all aspects of a function.
1578 void AssemblyWriter::printFunction(const Function *F) {
1579 // Print out the return type and name.
1582 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1584 if (F->isMaterializable())
1585 Out << "; Materializable\n";
1587 const AttributeSet &Attrs = F->getAttributes();
1588 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
1589 AttributeSet AS = Attrs.getFnAttributes();
1590 std::string AttrStr;
1593 for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
1594 if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
1597 for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
1599 Attribute Attr = *I;
1600 if (!Attr.isStringAttribute()) {
1601 if (!AttrStr.empty()) AttrStr += ' ';
1602 AttrStr += Attr.getAsString();
1606 if (!AttrStr.empty())
1607 Out << "; Function Attrs: " << AttrStr << '\n';
1610 if (F->isDeclaration())
1615 PrintLinkage(F->getLinkage(), Out);
1616 PrintVisibility(F->getVisibility(), Out);
1617 PrintDLLStorageClass(F->getDLLStorageClass(), Out);
1619 // Print the calling convention.
1620 if (F->getCallingConv() != CallingConv::C) {
1621 PrintCallingConv(F->getCallingConv(), Out);
1625 FunctionType *FT = F->getFunctionType();
1626 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1627 Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
1628 TypePrinter.print(F->getReturnType(), Out);
1630 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1632 Machine.incorporateFunction(F);
1634 // Loop over the arguments, printing them...
1637 if (!F->isDeclaration()) {
1638 // If this isn't a declaration, print the argument names as well.
1639 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1641 // Insert commas as we go... the first arg doesn't get a comma
1642 if (I != F->arg_begin()) Out << ", ";
1643 printArgument(I, Attrs, Idx);
1647 // Otherwise, print the types from the function type.
1648 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1649 // Insert commas as we go... the first arg doesn't get a comma
1653 TypePrinter.print(FT->getParamType(i), Out);
1655 if (Attrs.hasAttributes(i+1))
1656 Out << ' ' << Attrs.getAsString(i+1);
1660 // Finish printing arguments...
1661 if (FT->isVarArg()) {
1662 if (FT->getNumParams()) Out << ", ";
1663 Out << "..."; // Output varargs portion of signature!
1666 if (F->hasUnnamedAddr())
1667 Out << " unnamed_addr";
1668 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1669 Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
1670 if (F->hasSection()) {
1671 Out << " section \"";
1672 PrintEscapedString(F->getSection(), Out);
1675 if (F->hasComdat()) {
1677 PrintLLVMName(Out, F->getComdat()->getName(), ComdatPrefix);
1679 if (F->getAlignment())
1680 Out << " align " << F->getAlignment();
1682 Out << " gc \"" << F->getGC() << '"';
1683 if (F->hasPrefixData()) {
1685 writeOperand(F->getPrefixData(), true);
1687 if (F->isDeclaration()) {
1691 // Output all of the function's basic blocks.
1692 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1698 Machine.purgeFunction();
1701 /// printArgument - This member is called for every argument that is passed into
1702 /// the function. Simply print it out
1704 void AssemblyWriter::printArgument(const Argument *Arg,
1705 AttributeSet Attrs, unsigned Idx) {
1707 TypePrinter.print(Arg->getType(), Out);
1709 // Output parameter attributes list
1710 if (Attrs.hasAttributes(Idx))
1711 Out << ' ' << Attrs.getAsString(Idx);
1713 // Output name, if available...
1714 if (Arg->hasName()) {
1716 PrintLLVMName(Out, Arg);
1720 /// printBasicBlock - This member is called for each basic block in a method.
1722 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1723 if (BB->hasName()) { // Print out the label if it exists...
1725 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1727 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1728 Out << "\n; <label>:";
1729 int Slot = Machine.getLocalSlot(BB);
1736 if (!BB->getParent()) {
1737 Out.PadToColumn(50);
1738 Out << "; Error: Block without parent!";
1739 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1740 // Output predecessors for the block.
1741 Out.PadToColumn(50);
1743 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1746 Out << " No predecessors!";
1749 writeOperand(*PI, false);
1750 for (++PI; PI != PE; ++PI) {
1752 writeOperand(*PI, false);
1759 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1761 // Output all of the instructions in the basic block...
1762 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1763 printInstructionLine(*I);
1766 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1769 /// printInstructionLine - Print an instruction and a newline character.
1770 void AssemblyWriter::printInstructionLine(const Instruction &I) {
1771 printInstruction(I);
1775 /// printInfoComment - Print a little comment after the instruction indicating
1776 /// which slot it occupies.
1778 void AssemblyWriter::printInfoComment(const Value &V) {
1779 if (AnnotationWriter)
1780 AnnotationWriter->printInfoComment(V, Out);
1783 // This member is called for each Instruction in a function..
1784 void AssemblyWriter::printInstruction(const Instruction &I) {
1785 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1787 // Print out indentation for an instruction.
1790 // Print out name if it exists...
1792 PrintLLVMName(Out, &I);
1794 } else if (!I.getType()->isVoidTy()) {
1795 // Print out the def slot taken.
1796 int SlotNum = Machine.getLocalSlot(&I);
1798 Out << "<badref> = ";
1800 Out << '%' << SlotNum << " = ";
1803 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1804 if (CI->isMustTailCall())
1806 else if (CI->isTailCall())
1810 // Print out the opcode...
1811 Out << I.getOpcodeName();
1813 // If this is an atomic load or store, print out the atomic marker.
1814 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1815 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1818 if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
1821 // If this is a volatile operation, print out the volatile marker.
1822 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1823 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1824 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1825 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1828 // Print out optimization information.
1829 WriteOptimizationInfo(Out, &I);
1831 // Print out the compare instruction predicates
1832 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1833 Out << ' ' << getPredicateText(CI->getPredicate());
1835 // Print out the atomicrmw operation
1836 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1837 writeAtomicRMWOperation(Out, RMWI->getOperation());
1839 // Print out the type of the operands...
1840 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
1842 // Special case conditional branches to swizzle the condition out to the front
1843 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1844 const BranchInst &BI(cast<BranchInst>(I));
1846 writeOperand(BI.getCondition(), true);
1848 writeOperand(BI.getSuccessor(0), true);
1850 writeOperand(BI.getSuccessor(1), true);
1852 } else if (isa<SwitchInst>(I)) {
1853 const SwitchInst& SI(cast<SwitchInst>(I));
1854 // Special case switch instruction to get formatting nice and correct.
1856 writeOperand(SI.getCondition(), true);
1858 writeOperand(SI.getDefaultDest(), true);
1860 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1863 writeOperand(i.getCaseValue(), true);
1865 writeOperand(i.getCaseSuccessor(), true);
1868 } else if (isa<IndirectBrInst>(I)) {
1869 // Special case indirectbr instruction to get formatting nice and correct.
1871 writeOperand(Operand, true);
1874 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1877 writeOperand(I.getOperand(i), true);
1880 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1882 TypePrinter.print(I.getType(), Out);
1885 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1886 if (op) Out << ", ";
1888 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1889 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1891 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1893 writeOperand(I.getOperand(0), true);
1894 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1896 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1898 writeOperand(I.getOperand(0), true); Out << ", ";
1899 writeOperand(I.getOperand(1), true);
1900 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1902 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1904 TypePrinter.print(I.getType(), Out);
1905 Out << " personality ";
1906 writeOperand(I.getOperand(0), true); Out << '\n';
1908 if (LPI->isCleanup())
1911 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1912 if (i != 0 || LPI->isCleanup()) Out << "\n";
1913 if (LPI->isCatch(i))
1918 writeOperand(LPI->getClause(i), true);
1920 } else if (isa<ReturnInst>(I) && !Operand) {
1922 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1923 // Print the calling convention being used.
1924 if (CI->getCallingConv() != CallingConv::C) {
1926 PrintCallingConv(CI->getCallingConv(), Out);
1929 Operand = CI->getCalledValue();
1930 PointerType *PTy = cast<PointerType>(Operand->getType());
1931 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1932 Type *RetTy = FTy->getReturnType();
1933 const AttributeSet &PAL = CI->getAttributes();
1935 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1936 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1938 // If possible, print out the short form of the call instruction. We can
1939 // only do this if the first argument is a pointer to a nonvararg function,
1940 // and if the return type is not a pointer to a function.
1943 if (!FTy->isVarArg() &&
1944 (!RetTy->isPointerTy() ||
1945 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1946 TypePrinter.print(RetTy, Out);
1948 writeOperand(Operand, false);
1950 writeOperand(Operand, true);
1953 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1956 writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
1959 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
1960 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
1961 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1962 Operand = II->getCalledValue();
1963 PointerType *PTy = cast<PointerType>(Operand->getType());
1964 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1965 Type *RetTy = FTy->getReturnType();
1966 const AttributeSet &PAL = II->getAttributes();
1968 // Print the calling convention being used.
1969 if (II->getCallingConv() != CallingConv::C) {
1971 PrintCallingConv(II->getCallingConv(), Out);
1974 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
1975 Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
1977 // If possible, print out the short form of the invoke instruction. We can
1978 // only do this if the first argument is a pointer to a nonvararg function,
1979 // and if the return type is not a pointer to a function.
1982 if (!FTy->isVarArg() &&
1983 (!RetTy->isPointerTy() ||
1984 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1985 TypePrinter.print(RetTy, Out);
1987 writeOperand(Operand, false);
1989 writeOperand(Operand, true);
1992 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1995 writeParamOperand(II->getArgOperand(op), PAL, op + 1);
1999 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2000 Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2003 writeOperand(II->getNormalDest(), true);
2005 writeOperand(II->getUnwindDest(), true);
2007 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
2009 if (AI->isUsedWithInAlloca())
2011 TypePrinter.print(AI->getAllocatedType(), Out);
2012 if (!AI->getArraySize() || AI->isArrayAllocation()) {
2014 writeOperand(AI->getArraySize(), true);
2016 if (AI->getAlignment()) {
2017 Out << ", align " << AI->getAlignment();
2019 } else if (isa<CastInst>(I)) {
2022 writeOperand(Operand, true); // Work with broken code
2025 TypePrinter.print(I.getType(), Out);
2026 } else if (isa<VAArgInst>(I)) {
2029 writeOperand(Operand, true); // Work with broken code
2032 TypePrinter.print(I.getType(), Out);
2033 } else if (Operand) { // Print the normal way.
2035 // PrintAllTypes - Instructions who have operands of all the same type
2036 // omit the type from all but the first operand. If the instruction has
2037 // different type operands (for example br), then they are all printed.
2038 bool PrintAllTypes = false;
2039 Type *TheType = Operand->getType();
2041 // Select, Store and ShuffleVector always print all types.
2042 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2043 || isa<ReturnInst>(I)) {
2044 PrintAllTypes = true;
2046 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2047 Operand = I.getOperand(i);
2048 // note that Operand shouldn't be null, but the test helps make dump()
2049 // more tolerant of malformed IR
2050 if (Operand && Operand->getType() != TheType) {
2051 PrintAllTypes = true; // We have differing types! Print them all!
2057 if (!PrintAllTypes) {
2059 TypePrinter.print(TheType, Out);
2063 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2065 writeOperand(I.getOperand(i), PrintAllTypes);
2069 // Print atomic ordering/alignment for memory operations
2070 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2072 writeAtomic(LI->getOrdering(), LI->getSynchScope());
2073 if (LI->getAlignment())
2074 Out << ", align " << LI->getAlignment();
2075 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2077 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2078 if (SI->getAlignment())
2079 Out << ", align " << SI->getAlignment();
2080 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2081 writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
2082 CXI->getSynchScope());
2083 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2084 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2085 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2086 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2089 // Print Metadata info.
2090 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2091 I.getAllMetadata(InstMD);
2092 if (!InstMD.empty()) {
2093 SmallVector<StringRef, 8> MDNames;
2094 I.getType()->getContext().getMDKindNames(MDNames);
2095 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2096 unsigned Kind = InstMD[i].first;
2097 if (Kind < MDNames.size()) {
2098 Out << ", !" << MDNames[Kind];
2100 Out << ", !<unknown kind #" << Kind << ">";
2103 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2107 printInfoComment(I);
2110 static void WriteMDNodeComment(const MDNode *Node,
2111 formatted_raw_ostream &Out) {
2112 if (Node->getNumOperands() < 1)
2115 Value *Op = Node->getOperand(0);
2116 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2119 DIDescriptor Desc(Node);
2123 unsigned Tag = Desc.getTag();
2124 Out.PadToColumn(50);
2125 if (dwarf::TagString(Tag)) {
2128 } else if (Tag == dwarf::DW_TAG_user_base) {
2129 Out << "; [ DW_TAG_user_base ]";
2133 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
2134 Out << '!' << Slot << " = metadata ";
2135 printMDNodeBody(Node);
2138 void AssemblyWriter::writeAllMDNodes() {
2139 SmallVector<const MDNode *, 16> Nodes;
2140 Nodes.resize(Machine.mdn_size());
2141 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2143 Nodes[I->second] = cast<MDNode>(I->first);
2145 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2146 writeMDNode(i, Nodes[i]);
2150 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2151 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2152 WriteMDNodeComment(Node, Out);
2156 void AssemblyWriter::writeAllAttributeGroups() {
2157 std::vector<std::pair<AttributeSet, unsigned> > asVec;
2158 asVec.resize(Machine.as_size());
2160 for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
2162 asVec[I->second] = *I;
2164 for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
2165 I = asVec.begin(), E = asVec.end(); I != E; ++I)
2166 Out << "attributes #" << I->second << " = { "
2167 << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
2172 //===----------------------------------------------------------------------===//
2173 // External Interface declarations
2174 //===----------------------------------------------------------------------===//
2176 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2177 SlotTracker SlotTable(this);
2178 formatted_raw_ostream OS(ROS);
2179 AssemblyWriter W(OS, SlotTable, this, AAW);
2180 W.printModule(this);
2183 void NamedMDNode::print(raw_ostream &ROS) const {
2184 SlotTracker SlotTable(getParent());
2185 formatted_raw_ostream OS(ROS);
2186 AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
2187 W.printNamedMDNode(this);
2190 void Comdat::print(raw_ostream &ROS) const {
2191 PrintLLVMName(ROS, getName(), ComdatPrefix);
2192 ROS << " = comdat ";
2194 switch (getSelectionKind()) {
2198 case Comdat::ExactMatch:
2199 ROS << "exactmatch";
2201 case Comdat::Largest:
2204 case Comdat::NoDuplicates:
2205 ROS << "noduplicates";
2207 case Comdat::SameSize:
2215 void Type::print(raw_ostream &OS) const {
2217 TP.print(const_cast<Type*>(this), OS);
2219 // If the type is a named struct type, print the body as well.
2220 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2221 if (!STy->isLiteral()) {
2223 TP.printStructBody(STy, OS);
2227 void Value::print(raw_ostream &ROS) const {
2228 formatted_raw_ostream OS(ROS);
2229 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2230 const Function *F = I->getParent() ? I->getParent()->getParent() : nullptr;
2231 SlotTracker SlotTable(F);
2232 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
2233 W.printInstruction(*I);
2234 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2235 SlotTracker SlotTable(BB->getParent());
2236 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
2237 W.printBasicBlock(BB);
2238 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2239 SlotTracker SlotTable(GV->getParent());
2240 AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
2241 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2243 else if (const Function *F = dyn_cast<Function>(GV))
2246 W.printAlias(cast<GlobalAlias>(GV));
2247 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2248 const Function *F = N->getFunction();
2249 SlotTracker SlotTable(F);
2250 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : nullptr, nullptr);
2251 W.printMDNodeBody(N);
2252 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2253 TypePrinting TypePrinter;
2254 TypePrinter.print(C->getType(), OS);
2256 WriteConstantInternal(OS, C, TypePrinter, nullptr, nullptr);
2257 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2258 isa<Argument>(this)) {
2259 this->printAsOperand(OS);
2261 llvm_unreachable("Unknown value to print out!");
2265 void Value::printAsOperand(raw_ostream &O, bool PrintType, const Module *M) const {
2266 // Fast path: Don't construct and populate a TypePrinting object if we
2267 // won't be needing any types printed.
2269 ((!isa<Constant>(this) && !isa<MDNode>(this)) ||
2270 hasName() || isa<GlobalValue>(this))) {
2271 WriteAsOperandInternal(O, this, nullptr, nullptr, M);
2276 M = getModuleFromVal(this);
2278 TypePrinting TypePrinter;
2280 TypePrinter.incorporateTypes(*M);
2282 TypePrinter.print(getType(), O);
2286 WriteAsOperandInternal(O, this, &TypePrinter, nullptr, M);
2289 // Value::dump - allow easy printing of Values from the debugger.
2290 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2292 // Type::dump - allow easy printing of Types from the debugger.
2293 void Type::dump() const { print(dbgs()); }
2295 // Module::dump() - Allow printing of Modules from the debugger.
2296 void Module::dump() const { print(dbgs(), nullptr); }
2298 // \brief Allow printing of Comdats from the debugger.
2299 void Comdat::dump() const { print(dbgs()); }
2301 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2302 void NamedMDNode::dump() const { print(dbgs()); }