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/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/TypeSymbolTable.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/FormattedStream.h"
46 EnableDebugInfoComment("enable-debug-info-comment", cl::Hidden,
47 cl::desc("Enable debug info comments"));
50 // Make virtual table appear in this compilation unit.
51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 static const Module *getModuleFromVal(const Value *V) {
58 if (const Argument *MA = dyn_cast<Argument>(V))
59 return MA->getParent() ? MA->getParent()->getParent() : 0;
61 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
62 return BB->getParent() ? BB->getParent()->getParent() : 0;
64 if (const Instruction *I = dyn_cast<Instruction>(V)) {
65 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
66 return M ? M->getParent() : 0;
69 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
70 return GV->getParent();
74 // PrintEscapedString - Print each character of the specified string, escaping
75 // it if it is not printable or if it is an escape char.
76 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
77 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
78 unsigned char C = Name[i];
79 if (isprint(C) && C != '\\' && C != '"')
82 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
93 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
94 /// prefixed with % (if the string only contains simple characters) or is
95 /// surrounded with ""'s (if it has special chars in it). Print it out.
96 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
97 assert(!Name.empty() && "Cannot get empty name!");
99 default: llvm_unreachable("Bad prefix!");
100 case NoPrefix: break;
101 case GlobalPrefix: OS << '@'; break;
102 case LabelPrefix: break;
103 case LocalPrefix: OS << '%'; break;
106 // Scan the name to see if it needs quotes first.
107 bool NeedsQuotes = isdigit(Name[0]);
109 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
111 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
118 // If we didn't need any quotes, just write out the name in one blast.
124 // Okay, we need quotes. Output the quotes and escape any scary characters as
127 PrintEscapedString(Name, OS);
131 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
132 /// prefixed with % (if the string only contains simple characters) or is
133 /// surrounded with ""'s (if it has special chars in it). Print it out.
134 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
135 PrintLLVMName(OS, V->getName(),
136 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
139 //===----------------------------------------------------------------------===//
140 // TypePrinting Class: Type printing machinery
141 //===----------------------------------------------------------------------===//
143 /// TypePrinting - Type printing machinery.
146 DenseMap<const Type *, std::string> TypeNames;
147 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
148 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
157 void print(const Type *Ty, raw_ostream &OS, bool IgnoreTopLevelName = false);
159 void printAtLeastOneLevel(const Type *Ty, raw_ostream &OS) {
163 /// hasTypeName - Return true if the type has a name in TypeNames, false
165 bool hasTypeName(const Type *Ty) const {
166 return TypeNames.count(Ty);
170 /// addTypeName - Add a name for the specified type if it doesn't already have
171 /// one. This name will be printed instead of the structural version of the
172 /// type in order to make the output more concise.
173 void addTypeName(const Type *Ty, const std::string &N) {
174 TypeNames.insert(std::make_pair(Ty, N));
178 void CalcTypeName(const Type *Ty, SmallVectorImpl<const Type *> &TypeStack,
179 raw_ostream &OS, bool IgnoreTopLevelName = false);
181 } // end anonymous namespace.
183 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
184 /// use of type names or up references to shorten the type name where possible.
185 void TypePrinting::CalcTypeName(const Type *Ty,
186 SmallVectorImpl<const Type *> &TypeStack,
187 raw_ostream &OS, bool IgnoreTopLevelName) {
188 // Check to see if the type is named.
189 if (!IgnoreTopLevelName) {
190 DenseMap<const Type *, std::string> &TM = TypeNames;
191 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
198 // Check to see if the Type is already on the stack...
199 unsigned Slot = 0, CurSize = TypeStack.size();
200 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
202 // This is another base case for the recursion. In this case, we know
203 // that we have looped back to a type that we have previously visited.
204 // Generate the appropriate upreference to handle this.
205 if (Slot < CurSize) {
206 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
210 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
212 switch (Ty->getTypeID()) {
213 case Type::VoidTyID: OS << "void"; break;
214 case Type::FloatTyID: OS << "float"; break;
215 case Type::DoubleTyID: OS << "double"; break;
216 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
217 case Type::FP128TyID: OS << "fp128"; break;
218 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
219 case Type::LabelTyID: OS << "label"; break;
220 case Type::MetadataTyID: OS << "metadata"; break;
221 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
222 case Type::IntegerTyID:
223 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
226 case Type::FunctionTyID: {
227 const FunctionType *FTy = cast<FunctionType>(Ty);
228 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
230 for (FunctionType::param_iterator I = FTy->param_begin(),
231 E = FTy->param_end(); I != E; ++I) {
232 if (I != FTy->param_begin())
234 CalcTypeName(*I, TypeStack, OS);
236 if (FTy->isVarArg()) {
237 if (FTy->getNumParams()) OS << ", ";
243 case Type::StructTyID: {
244 const StructType *STy = cast<StructType>(Ty);
248 for (StructType::element_iterator I = STy->element_begin(),
249 E = STy->element_end(); I != E; ++I) {
251 CalcTypeName(*I, TypeStack, OS);
252 if (llvm::next(I) == STy->element_end())
262 case Type::PointerTyID: {
263 const PointerType *PTy = cast<PointerType>(Ty);
264 CalcTypeName(PTy->getElementType(), TypeStack, OS);
265 if (unsigned AddressSpace = PTy->getAddressSpace())
266 OS << " addrspace(" << AddressSpace << ')';
270 case Type::ArrayTyID: {
271 const ArrayType *ATy = cast<ArrayType>(Ty);
272 OS << '[' << ATy->getNumElements() << " x ";
273 CalcTypeName(ATy->getElementType(), TypeStack, OS);
277 case Type::VectorTyID: {
278 const VectorType *PTy = cast<VectorType>(Ty);
279 OS << "<" << PTy->getNumElements() << " x ";
280 CalcTypeName(PTy->getElementType(), TypeStack, OS);
284 case Type::OpaqueTyID:
288 OS << "<unrecognized-type>";
292 TypeStack.pop_back(); // Remove self from stack.
295 /// printTypeInt - The internal guts of printing out a type that has a
296 /// potentially named portion.
298 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
299 bool IgnoreTopLevelName) {
300 // Check to see if the type is named.
301 if (!IgnoreTopLevelName) {
302 DenseMap<const Type*, std::string>::iterator I = TypeNames.find(Ty);
303 if (I != TypeNames.end()) {
309 // Otherwise we have a type that has not been named but is a derived type.
310 // Carefully recurse the type hierarchy to print out any contained symbolic
312 SmallVector<const Type *, 16> TypeStack;
313 std::string TypeName;
315 raw_string_ostream TypeOS(TypeName);
316 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
319 // Cache type name for later use.
320 if (!IgnoreTopLevelName)
321 TypeNames.insert(std::make_pair(Ty, TypeOS.str()));
326 // To avoid walking constant expressions multiple times and other IR
327 // objects, we keep several helper maps.
328 DenseSet<const Value*> VisitedConstants;
329 DenseSet<const Type*> VisitedTypes;
332 std::vector<const Type*> &NumberedTypes;
334 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
335 : TP(tp), NumberedTypes(numberedTypes) {}
337 void Run(const Module &M) {
338 // Get types from the type symbol table. This gets opaque types referened
339 // only through derived named types.
340 const TypeSymbolTable &ST = M.getTypeSymbolTable();
341 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
343 IncorporateType(TI->second);
345 // Get types from global variables.
346 for (Module::const_global_iterator I = M.global_begin(),
347 E = M.global_end(); I != E; ++I) {
348 IncorporateType(I->getType());
349 if (I->hasInitializer())
350 IncorporateValue(I->getInitializer());
353 // Get types from aliases.
354 for (Module::const_alias_iterator I = M.alias_begin(),
355 E = M.alias_end(); I != E; ++I) {
356 IncorporateType(I->getType());
357 IncorporateValue(I->getAliasee());
360 // Get types from functions.
361 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
362 IncorporateType(FI->getType());
364 for (Function::const_iterator BB = FI->begin(), E = FI->end();
366 for (BasicBlock::const_iterator II = BB->begin(),
367 E = BB->end(); II != E; ++II) {
368 const Instruction &I = *II;
369 // Incorporate the type of the instruction and all its operands.
370 IncorporateType(I.getType());
371 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
373 IncorporateValue(*OI);
379 void IncorporateType(const Type *Ty) {
380 // Check to see if we're already visited this type.
381 if (!VisitedTypes.insert(Ty).second)
384 // If this is a structure or opaque type, add a name for the type.
385 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
386 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
387 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
388 NumberedTypes.push_back(Ty);
391 // Recursively walk all contained types.
392 for (Type::subtype_iterator I = Ty->subtype_begin(),
393 E = Ty->subtype_end(); I != E; ++I)
397 /// IncorporateValue - This method is used to walk operand lists finding
398 /// types hiding in constant expressions and other operands that won't be
399 /// walked in other ways. GlobalValues, basic blocks, instructions, and
400 /// inst operands are all explicitly enumerated.
401 void IncorporateValue(const Value *V) {
402 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
405 if (!VisitedConstants.insert(V).second)
409 IncorporateType(V->getType());
411 // Look in operands for types.
412 const Constant *C = cast<Constant>(V);
413 for (Constant::const_op_iterator I = C->op_begin(),
414 E = C->op_end(); I != E;++I)
415 IncorporateValue(*I);
418 } // end anonymous namespace
421 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
422 /// the specified module to the TypePrinter and all numbered types to it and the
423 /// NumberedTypes table.
424 static void AddModuleTypesToPrinter(TypePrinting &TP,
425 std::vector<const Type*> &NumberedTypes,
429 // If the module has a symbol table, take all global types and stuff their
430 // names into the TypeNames map.
431 const TypeSymbolTable &ST = M->getTypeSymbolTable();
432 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
434 const Type *Ty = cast<Type>(TI->second);
436 // As a heuristic, don't insert pointer to primitive types, because
437 // they are used too often to have a single useful name.
438 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
439 const Type *PETy = PTy->getElementType();
440 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
445 // Likewise don't insert primitives either.
446 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
449 // Get the name as a string and insert it into TypeNames.
451 raw_string_ostream NameROS(NameStr);
452 formatted_raw_ostream NameOS(NameROS);
453 PrintLLVMName(NameOS, TI->first, LocalPrefix);
455 TP.addTypeName(Ty, NameStr);
458 // Walk the entire module to find references to unnamed structure and opaque
459 // types. This is required for correctness by opaque types (because multiple
460 // uses of an unnamed opaque type needs to be referred to by the same ID) and
461 // it shrinks complex recursive structure types substantially in some cases.
462 TypeFinder(TP, NumberedTypes).Run(*M);
466 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
467 /// type, iff there is an entry in the modules symbol table for the specified
468 /// type or one of it's component types.
470 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
471 TypePrinting Printer;
472 std::vector<const Type*> NumberedTypes;
473 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
474 Printer.print(Ty, OS);
477 //===----------------------------------------------------------------------===//
478 // SlotTracker Class: Enumerate slot numbers for unnamed values
479 //===----------------------------------------------------------------------===//
483 /// This class provides computation of slot numbers for LLVM Assembly writing.
487 /// ValueMap - A mapping of Values to slot numbers.
488 typedef DenseMap<const Value*, unsigned> ValueMap;
491 /// TheModule - The module for which we are holding slot numbers.
492 const Module* TheModule;
494 /// TheFunction - The function for which we are holding slot numbers.
495 const Function* TheFunction;
496 bool FunctionProcessed;
498 /// mMap - The TypePlanes map for the module level data.
502 /// fMap - The TypePlanes map for the function level data.
506 /// mdnMap - Map for MDNodes.
507 DenseMap<const MDNode*, unsigned> mdnMap;
510 /// Construct from a module
511 explicit SlotTracker(const Module *M);
512 /// Construct from a function, starting out in incorp state.
513 explicit SlotTracker(const Function *F);
515 /// Return the slot number of the specified value in it's type
516 /// plane. If something is not in the SlotTracker, return -1.
517 int getLocalSlot(const Value *V);
518 int getGlobalSlot(const GlobalValue *V);
519 int getMetadataSlot(const MDNode *N);
521 /// If you'd like to deal with a function instead of just a module, use
522 /// this method to get its data into the SlotTracker.
523 void incorporateFunction(const Function *F) {
525 FunctionProcessed = false;
528 /// After calling incorporateFunction, use this method to remove the
529 /// most recently incorporated function from the SlotTracker. This
530 /// will reset the state of the machine back to just the module contents.
531 void purgeFunction();
533 /// MDNode map iterators.
534 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
535 mdn_iterator mdn_begin() { return mdnMap.begin(); }
536 mdn_iterator mdn_end() { return mdnMap.end(); }
537 unsigned mdn_size() const { return mdnMap.size(); }
538 bool mdn_empty() const { return mdnMap.empty(); }
540 /// This function does the actual initialization.
541 inline void initialize();
543 // Implementation Details
545 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
546 void CreateModuleSlot(const GlobalValue *V);
548 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
549 void CreateMetadataSlot(const MDNode *N);
551 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
552 void CreateFunctionSlot(const Value *V);
554 /// Add all of the module level global variables (and their initializers)
555 /// and function declarations, but not the contents of those functions.
556 void processModule();
558 /// Add all of the functions arguments, basic blocks, and instructions.
559 void processFunction();
561 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
562 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
565 } // end anonymous namespace
568 static SlotTracker *createSlotTracker(const Value *V) {
569 if (const Argument *FA = dyn_cast<Argument>(V))
570 return new SlotTracker(FA->getParent());
572 if (const Instruction *I = dyn_cast<Instruction>(V))
573 return new SlotTracker(I->getParent()->getParent());
575 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
576 return new SlotTracker(BB->getParent());
578 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
579 return new SlotTracker(GV->getParent());
581 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
582 return new SlotTracker(GA->getParent());
584 if (const Function *Func = dyn_cast<Function>(V))
585 return new SlotTracker(Func);
587 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
588 if (!MD->isFunctionLocal())
589 return new SlotTracker(MD->getFunction());
591 return new SlotTracker((Function *)0);
598 #define ST_DEBUG(X) dbgs() << X
603 // Module level constructor. Causes the contents of the Module (sans functions)
604 // to be added to the slot table.
605 SlotTracker::SlotTracker(const Module *M)
606 : TheModule(M), TheFunction(0), FunctionProcessed(false),
607 mNext(0), fNext(0), mdnNext(0) {
610 // Function level constructor. Causes the contents of the Module and the one
611 // function provided to be added to the slot table.
612 SlotTracker::SlotTracker(const Function *F)
613 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
614 mNext(0), fNext(0), mdnNext(0) {
617 inline void SlotTracker::initialize() {
620 TheModule = 0; ///< Prevent re-processing next time we're called.
623 if (TheFunction && !FunctionProcessed)
627 // Iterate through all the global variables, functions, and global
628 // variable initializers and create slots for them.
629 void SlotTracker::processModule() {
630 ST_DEBUG("begin processModule!\n");
632 // Add all of the unnamed global variables to the value table.
633 for (Module::const_global_iterator I = TheModule->global_begin(),
634 E = TheModule->global_end(); I != E; ++I) {
639 // Add metadata used by named metadata.
640 for (Module::const_named_metadata_iterator
641 I = TheModule->named_metadata_begin(),
642 E = TheModule->named_metadata_end(); I != E; ++I) {
643 const NamedMDNode *NMD = I;
644 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
645 CreateMetadataSlot(NMD->getOperand(i));
648 // Add all the unnamed functions to the table.
649 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
654 ST_DEBUG("end processModule!\n");
657 // Process the arguments, basic blocks, and instructions of a function.
658 void SlotTracker::processFunction() {
659 ST_DEBUG("begin processFunction!\n");
662 // Add all the function arguments with no names.
663 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
664 AE = TheFunction->arg_end(); AI != AE; ++AI)
666 CreateFunctionSlot(AI);
668 ST_DEBUG("Inserting Instructions:\n");
670 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
672 // Add all of the basic blocks and instructions with no names.
673 for (Function::const_iterator BB = TheFunction->begin(),
674 E = TheFunction->end(); BB != E; ++BB) {
676 CreateFunctionSlot(BB);
678 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
680 if (!I->getType()->isVoidTy() && !I->hasName())
681 CreateFunctionSlot(I);
683 // Intrinsics can directly use metadata. We allow direct calls to any
684 // llvm.foo function here, because the target may not be linked into the
686 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
687 if (Function *F = CI->getCalledFunction())
688 if (F->getName().startswith("llvm."))
689 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
690 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
691 CreateMetadataSlot(N);
694 // Process metadata attached with this instruction.
695 I->getAllMetadata(MDForInst);
696 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
697 CreateMetadataSlot(MDForInst[i].second);
702 FunctionProcessed = true;
704 ST_DEBUG("end processFunction!\n");
707 /// Clean up after incorporating a function. This is the only way to get out of
708 /// the function incorporation state that affects get*Slot/Create*Slot. Function
709 /// incorporation state is indicated by TheFunction != 0.
710 void SlotTracker::purgeFunction() {
711 ST_DEBUG("begin purgeFunction!\n");
712 fMap.clear(); // Simply discard the function level map
714 FunctionProcessed = false;
715 ST_DEBUG("end purgeFunction!\n");
718 /// getGlobalSlot - Get the slot number of a global value.
719 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
720 // Check for uninitialized state and do lazy initialization.
723 // Find the type plane in the module map
724 ValueMap::iterator MI = mMap.find(V);
725 return MI == mMap.end() ? -1 : (int)MI->second;
728 /// getMetadataSlot - Get the slot number of a MDNode.
729 int SlotTracker::getMetadataSlot(const MDNode *N) {
730 // Check for uninitialized state and do lazy initialization.
733 // Find the type plane in the module map
734 mdn_iterator MI = mdnMap.find(N);
735 return MI == mdnMap.end() ? -1 : (int)MI->second;
739 /// getLocalSlot - Get the slot number for a value that is local to a function.
740 int SlotTracker::getLocalSlot(const Value *V) {
741 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
743 // Check for uninitialized state and do lazy initialization.
746 ValueMap::iterator FI = fMap.find(V);
747 return FI == fMap.end() ? -1 : (int)FI->second;
751 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
752 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
753 assert(V && "Can't insert a null Value into SlotTracker!");
754 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
755 assert(!V->hasName() && "Doesn't need a slot!");
757 unsigned DestSlot = mNext++;
760 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
762 // G = Global, F = Function, A = Alias, o = other
763 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
764 (isa<Function>(V) ? 'F' :
765 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
768 /// CreateSlot - Create a new slot for the specified value if it has no name.
769 void SlotTracker::CreateFunctionSlot(const Value *V) {
770 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
772 unsigned DestSlot = fNext++;
775 // G = Global, F = Function, o = other
776 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
777 DestSlot << " [o]\n");
780 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
781 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
782 assert(N && "Can't insert a null Value into SlotTracker!");
784 // Don't insert if N is a function-local metadata, these are always printed
786 if (!N->isFunctionLocal()) {
787 mdn_iterator I = mdnMap.find(N);
788 if (I != mdnMap.end())
791 unsigned DestSlot = mdnNext++;
792 mdnMap[N] = DestSlot;
795 // Recursively add any MDNodes referenced by operands.
796 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
797 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
798 CreateMetadataSlot(Op);
801 //===----------------------------------------------------------------------===//
802 // AsmWriter Implementation
803 //===----------------------------------------------------------------------===//
805 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
806 TypePrinting *TypePrinter,
807 SlotTracker *Machine,
808 const Module *Context);
812 static const char *getPredicateText(unsigned predicate) {
813 const char * pred = "unknown";
815 case FCmpInst::FCMP_FALSE: pred = "false"; break;
816 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
817 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
818 case FCmpInst::FCMP_OGE: pred = "oge"; break;
819 case FCmpInst::FCMP_OLT: pred = "olt"; break;
820 case FCmpInst::FCMP_OLE: pred = "ole"; break;
821 case FCmpInst::FCMP_ONE: pred = "one"; break;
822 case FCmpInst::FCMP_ORD: pred = "ord"; break;
823 case FCmpInst::FCMP_UNO: pred = "uno"; break;
824 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
825 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
826 case FCmpInst::FCMP_UGE: pred = "uge"; break;
827 case FCmpInst::FCMP_ULT: pred = "ult"; break;
828 case FCmpInst::FCMP_ULE: pred = "ule"; break;
829 case FCmpInst::FCMP_UNE: pred = "une"; break;
830 case FCmpInst::FCMP_TRUE: pred = "true"; break;
831 case ICmpInst::ICMP_EQ: pred = "eq"; break;
832 case ICmpInst::ICMP_NE: pred = "ne"; break;
833 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
834 case ICmpInst::ICMP_SGE: pred = "sge"; break;
835 case ICmpInst::ICMP_SLT: pred = "slt"; break;
836 case ICmpInst::ICMP_SLE: pred = "sle"; break;
837 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
838 case ICmpInst::ICMP_UGE: pred = "uge"; break;
839 case ICmpInst::ICMP_ULT: pred = "ult"; break;
840 case ICmpInst::ICMP_ULE: pred = "ule"; break;
846 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
847 if (const OverflowingBinaryOperator *OBO =
848 dyn_cast<OverflowingBinaryOperator>(U)) {
849 if (OBO->hasNoUnsignedWrap())
851 if (OBO->hasNoSignedWrap())
853 } else if (const PossiblyExactOperator *Div =
854 dyn_cast<PossiblyExactOperator>(U)) {
857 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
858 if (GEP->isInBounds())
863 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
864 TypePrinting &TypePrinter,
865 SlotTracker *Machine,
866 const Module *Context) {
867 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
868 if (CI->getType()->isIntegerTy(1)) {
869 Out << (CI->getZExtValue() ? "true" : "false");
872 Out << CI->getValue();
876 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
877 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
878 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
879 // We would like to output the FP constant value in exponential notation,
880 // but we cannot do this if doing so will lose precision. Check here to
881 // make sure that we only output it in exponential format if we can parse
882 // the value back and get the same value.
885 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
886 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
887 CFP->getValueAPF().convertToFloat();
888 SmallString<128> StrVal;
889 raw_svector_ostream(StrVal) << Val;
891 // Check to make sure that the stringized number is not some string like
892 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
893 // that the string matches the "[-+]?[0-9]" regex.
895 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
896 ((StrVal[0] == '-' || StrVal[0] == '+') &&
897 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
898 // Reparse stringized version!
899 if (atof(StrVal.c_str()) == Val) {
904 // Otherwise we could not reparse it to exactly the same value, so we must
905 // output the string in hexadecimal format! Note that loading and storing
906 // floating point types changes the bits of NaNs on some hosts, notably
907 // x86, so we must not use these types.
908 assert(sizeof(double) == sizeof(uint64_t) &&
909 "assuming that double is 64 bits!");
911 APFloat apf = CFP->getValueAPF();
912 // Floats are represented in ASCII IR as double, convert.
914 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
917 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
922 // Some form of long double. These appear as a magic letter identifying
923 // the type, then a fixed number of hex digits.
925 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
927 // api needed to prevent premature destruction
928 APInt api = CFP->getValueAPF().bitcastToAPInt();
929 const uint64_t* p = api.getRawData();
930 uint64_t word = p[1];
932 int width = api.getBitWidth();
933 for (int j=0; j<width; j+=4, shiftcount-=4) {
934 unsigned int nibble = (word>>shiftcount) & 15;
936 Out << (unsigned char)(nibble + '0');
938 Out << (unsigned char)(nibble - 10 + 'A');
939 if (shiftcount == 0 && j+4 < width) {
943 shiftcount = width-j-4;
947 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
949 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
952 llvm_unreachable("Unsupported floating point type");
953 // api needed to prevent premature destruction
954 APInt api = CFP->getValueAPF().bitcastToAPInt();
955 const uint64_t* p = api.getRawData();
958 int width = api.getBitWidth();
959 for (int j=0; j<width; j+=4, shiftcount-=4) {
960 unsigned int nibble = (word>>shiftcount) & 15;
962 Out << (unsigned char)(nibble + '0');
964 Out << (unsigned char)(nibble - 10 + 'A');
965 if (shiftcount == 0 && j+4 < width) {
969 shiftcount = width-j-4;
975 if (isa<ConstantAggregateZero>(CV)) {
976 Out << "zeroinitializer";
980 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
981 Out << "blockaddress(";
982 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
985 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
991 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
992 // As a special case, print the array as a string if it is an array of
993 // i8 with ConstantInt values.
995 const Type *ETy = CA->getType()->getElementType();
996 if (CA->isString()) {
998 PrintEscapedString(CA->getAsString(), Out);
1000 } else { // Cannot output in string format...
1002 if (CA->getNumOperands()) {
1003 TypePrinter.print(ETy, Out);
1005 WriteAsOperandInternal(Out, CA->getOperand(0),
1006 &TypePrinter, Machine,
1008 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1010 TypePrinter.print(ETy, Out);
1012 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1021 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1022 if (CS->getType()->isPacked())
1025 unsigned N = CS->getNumOperands();
1028 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1031 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1034 for (unsigned i = 1; i < N; i++) {
1036 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1039 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1046 if (CS->getType()->isPacked())
1051 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1052 const Type *ETy = CP->getType()->getElementType();
1053 assert(CP->getNumOperands() > 0 &&
1054 "Number of operands for a PackedConst must be > 0");
1056 TypePrinter.print(ETy, Out);
1058 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
1060 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1062 TypePrinter.print(ETy, Out);
1064 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
1071 if (isa<ConstantPointerNull>(CV)) {
1076 if (isa<UndefValue>(CV)) {
1081 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1082 Out << CE->getOpcodeName();
1083 WriteOptimizationInfo(Out, CE);
1084 if (CE->isCompare())
1085 Out << ' ' << getPredicateText(CE->getPredicate());
1088 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1089 TypePrinter.print((*OI)->getType(), Out);
1091 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1092 if (OI+1 != CE->op_end())
1096 if (CE->hasIndices()) {
1097 ArrayRef<unsigned> Indices = CE->getIndices();
1098 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1099 Out << ", " << Indices[i];
1104 TypePrinter.print(CE->getType(), Out);
1111 Out << "<placeholder or erroneous Constant>";
1114 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1115 TypePrinting *TypePrinter,
1116 SlotTracker *Machine,
1117 const Module *Context) {
1119 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1120 const Value *V = Node->getOperand(mi);
1124 TypePrinter->print(V->getType(), Out);
1126 WriteAsOperandInternal(Out, Node->getOperand(mi),
1127 TypePrinter, Machine, Context);
1137 /// WriteAsOperand - Write the name of the specified value out to the specified
1138 /// ostream. This can be useful when you just want to print int %reg126, not
1139 /// the whole instruction that generated it.
1141 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1142 TypePrinting *TypePrinter,
1143 SlotTracker *Machine,
1144 const Module *Context) {
1146 PrintLLVMName(Out, V);
1150 const Constant *CV = dyn_cast<Constant>(V);
1151 if (CV && !isa<GlobalValue>(CV)) {
1152 assert(TypePrinter && "Constants require TypePrinting!");
1153 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1157 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1159 if (IA->hasSideEffects())
1160 Out << "sideeffect ";
1161 if (IA->isAlignStack())
1162 Out << "alignstack ";
1164 PrintEscapedString(IA->getAsmString(), Out);
1166 PrintEscapedString(IA->getConstraintString(), Out);
1171 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1172 if (N->isFunctionLocal()) {
1173 // Print metadata inline, not via slot reference number.
1174 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1179 if (N->isFunctionLocal())
1180 Machine = new SlotTracker(N->getFunction());
1182 Machine = new SlotTracker(Context);
1184 int Slot = Machine->getMetadataSlot(N);
1192 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1194 PrintEscapedString(MDS->getString(), Out);
1199 if (V->getValueID() == Value::PseudoSourceValueVal ||
1200 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1208 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1209 Slot = Machine->getGlobalSlot(GV);
1212 Slot = Machine->getLocalSlot(V);
1215 Machine = createSlotTracker(V);
1217 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1218 Slot = Machine->getGlobalSlot(GV);
1221 Slot = Machine->getLocalSlot(V);
1230 Out << Prefix << Slot;
1235 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1236 bool PrintType, const Module *Context) {
1238 // Fast path: Don't construct and populate a TypePrinting object if we
1239 // won't be needing any types printed.
1241 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1242 V->hasName() || isa<GlobalValue>(V))) {
1243 WriteAsOperandInternal(Out, V, 0, 0, Context);
1247 if (Context == 0) Context = getModuleFromVal(V);
1249 TypePrinting TypePrinter;
1250 std::vector<const Type*> NumberedTypes;
1251 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1253 TypePrinter.print(V->getType(), Out);
1257 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1262 class AssemblyWriter {
1263 formatted_raw_ostream &Out;
1264 SlotTracker &Machine;
1265 const Module *TheModule;
1266 TypePrinting TypePrinter;
1267 AssemblyAnnotationWriter *AnnotationWriter;
1268 std::vector<const Type*> NumberedTypes;
1271 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1273 AssemblyAnnotationWriter *AAW)
1274 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1275 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1278 void printMDNodeBody(const MDNode *MD);
1279 void printNamedMDNode(const NamedMDNode *NMD);
1281 void printModule(const Module *M);
1283 void writeOperand(const Value *Op, bool PrintType);
1284 void writeParamOperand(const Value *Operand, Attributes Attrs);
1286 void writeAllMDNodes();
1288 void printTypeSymbolTable(const TypeSymbolTable &ST);
1289 void printGlobal(const GlobalVariable *GV);
1290 void printAlias(const GlobalAlias *GV);
1291 void printFunction(const Function *F);
1292 void printArgument(const Argument *FA, Attributes Attrs);
1293 void printBasicBlock(const BasicBlock *BB);
1294 void printInstruction(const Instruction &I);
1297 // printInfoComment - Print a little comment after the instruction indicating
1298 // which slot it occupies.
1299 void printInfoComment(const Value &V);
1301 } // end of anonymous namespace
1303 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1305 Out << "<null operand!>";
1309 TypePrinter.print(Operand->getType(), Out);
1312 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1315 void AssemblyWriter::writeParamOperand(const Value *Operand,
1318 Out << "<null operand!>";
1323 TypePrinter.print(Operand->getType(), Out);
1324 // Print parameter attributes list
1325 if (Attrs != Attribute::None)
1326 Out << ' ' << Attribute::getAsString(Attrs);
1328 // Print the operand
1329 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1332 void AssemblyWriter::printModule(const Module *M) {
1333 if (!M->getModuleIdentifier().empty() &&
1334 // Don't print the ID if it will start a new line (which would
1335 // require a comment char before it).
1336 M->getModuleIdentifier().find('\n') == std::string::npos)
1337 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1339 if (!M->getDataLayout().empty())
1340 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1341 if (!M->getTargetTriple().empty())
1342 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1344 if (!M->getModuleInlineAsm().empty()) {
1345 // Split the string into lines, to make it easier to read the .ll file.
1346 std::string Asm = M->getModuleInlineAsm();
1348 size_t NewLine = Asm.find_first_of('\n', CurPos);
1350 while (NewLine != std::string::npos) {
1351 // We found a newline, print the portion of the asm string from the
1352 // last newline up to this newline.
1353 Out << "module asm \"";
1354 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1358 NewLine = Asm.find_first_of('\n', CurPos);
1360 std::string rest(Asm.begin()+CurPos, Asm.end());
1361 if (!rest.empty()) {
1362 Out << "module asm \"";
1363 PrintEscapedString(rest, Out);
1368 // Loop over the dependent libraries and emit them.
1369 Module::lib_iterator LI = M->lib_begin();
1370 Module::lib_iterator LE = M->lib_end();
1373 Out << "deplibs = [ ";
1375 Out << '"' << *LI << '"';
1383 // Loop over the symbol table, emitting all id'd types.
1384 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1385 printTypeSymbolTable(M->getTypeSymbolTable());
1387 // Output all globals.
1388 if (!M->global_empty()) Out << '\n';
1389 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1393 // Output all aliases.
1394 if (!M->alias_empty()) Out << "\n";
1395 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1399 // Output all of the functions.
1400 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1403 // Output named metadata.
1404 if (!M->named_metadata_empty()) Out << '\n';
1406 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1407 E = M->named_metadata_end(); I != E; ++I)
1408 printNamedMDNode(I);
1411 if (!Machine.mdn_empty()) {
1417 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1419 StringRef Name = NMD->getName();
1421 Out << "<empty name> ";
1423 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1424 Name[0] == '.' || Name[0] == '_')
1427 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1428 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1429 unsigned char C = Name[i];
1430 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1433 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1437 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1439 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1449 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1450 formatted_raw_ostream &Out) {
1452 case GlobalValue::ExternalLinkage: break;
1453 case GlobalValue::PrivateLinkage: Out << "private "; break;
1454 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1455 case GlobalValue::LinkerPrivateWeakLinkage:
1456 Out << "linker_private_weak ";
1458 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1459 Out << "linker_private_weak_def_auto ";
1461 case GlobalValue::InternalLinkage: Out << "internal "; break;
1462 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1463 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1464 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1465 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1466 case GlobalValue::CommonLinkage: Out << "common "; break;
1467 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1468 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1469 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1470 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1471 case GlobalValue::AvailableExternallyLinkage:
1472 Out << "available_externally ";
1478 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1479 formatted_raw_ostream &Out) {
1481 case GlobalValue::DefaultVisibility: break;
1482 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1483 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1487 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1488 if (GV->isMaterializable())
1489 Out << "; Materializable\n";
1491 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1494 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1497 PrintLinkage(GV->getLinkage(), Out);
1498 PrintVisibility(GV->getVisibility(), Out);
1500 if (GV->isThreadLocal()) Out << "thread_local ";
1501 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1502 Out << "addrspace(" << AddressSpace << ") ";
1503 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1504 Out << (GV->isConstant() ? "constant " : "global ");
1505 TypePrinter.print(GV->getType()->getElementType(), Out);
1507 if (GV->hasInitializer()) {
1509 writeOperand(GV->getInitializer(), false);
1512 if (GV->hasSection()) {
1513 Out << ", section \"";
1514 PrintEscapedString(GV->getSection(), Out);
1517 if (GV->getAlignment())
1518 Out << ", align " << GV->getAlignment();
1520 printInfoComment(*GV);
1524 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1525 if (GA->isMaterializable())
1526 Out << "; Materializable\n";
1528 // Don't crash when dumping partially built GA
1530 Out << "<<nameless>> = ";
1532 PrintLLVMName(Out, GA);
1535 PrintVisibility(GA->getVisibility(), Out);
1539 PrintLinkage(GA->getLinkage(), Out);
1541 const Constant *Aliasee = GA->getAliasee();
1543 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1544 TypePrinter.print(GV->getType(), Out);
1546 PrintLLVMName(Out, GV);
1547 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1548 TypePrinter.print(F->getFunctionType(), Out);
1551 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1552 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1553 TypePrinter.print(GA->getType(), Out);
1555 PrintLLVMName(Out, GA);
1557 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1558 // The only valid GEP is an all zero GEP.
1559 assert((CE->getOpcode() == Instruction::BitCast ||
1560 CE->getOpcode() == Instruction::GetElementPtr) &&
1561 "Unsupported aliasee");
1562 writeOperand(CE, false);
1565 printInfoComment(*GA);
1569 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1570 // Emit all numbered types.
1571 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1572 Out << '%' << i << " = type ";
1574 // Make sure we print out at least one level of the type structure, so
1575 // that we do not get %2 = type %2
1576 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1580 // Print the named types.
1581 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1583 PrintLLVMName(Out, TI->first, LocalPrefix);
1586 // Make sure we print out at least one level of the type structure, so
1587 // that we do not get %FILE = type %FILE
1588 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1593 /// printFunction - Print all aspects of a function.
1595 void AssemblyWriter::printFunction(const Function *F) {
1596 // Print out the return type and name.
1599 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1601 if (F->isMaterializable())
1602 Out << "; Materializable\n";
1604 if (F->isDeclaration())
1609 PrintLinkage(F->getLinkage(), Out);
1610 PrintVisibility(F->getVisibility(), Out);
1612 // Print the calling convention.
1613 switch (F->getCallingConv()) {
1614 case CallingConv::C: break; // default
1615 case CallingConv::Fast: Out << "fastcc "; break;
1616 case CallingConv::Cold: Out << "coldcc "; break;
1617 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1618 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1619 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1620 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1621 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1622 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1623 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1624 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1625 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1626 default: Out << "cc" << F->getCallingConv() << " "; break;
1629 const FunctionType *FT = F->getFunctionType();
1630 const AttrListPtr &Attrs = F->getAttributes();
1631 Attributes RetAttrs = Attrs.getRetAttributes();
1632 if (RetAttrs != Attribute::None)
1633 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1634 TypePrinter.print(F->getReturnType(), Out);
1636 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1638 Machine.incorporateFunction(F);
1640 // Loop over the arguments, printing them...
1643 if (!F->isDeclaration()) {
1644 // If this isn't a declaration, print the argument names as well.
1645 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1647 // Insert commas as we go... the first arg doesn't get a comma
1648 if (I != F->arg_begin()) Out << ", ";
1649 printArgument(I, Attrs.getParamAttributes(Idx));
1653 // Otherwise, print the types from the function type.
1654 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1655 // Insert commas as we go... the first arg doesn't get a comma
1659 TypePrinter.print(FT->getParamType(i), Out);
1661 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1662 if (ArgAttrs != Attribute::None)
1663 Out << ' ' << Attribute::getAsString(ArgAttrs);
1667 // Finish printing arguments...
1668 if (FT->isVarArg()) {
1669 if (FT->getNumParams()) Out << ", ";
1670 Out << "..."; // Output varargs portion of signature!
1673 if (F->hasUnnamedAddr())
1674 Out << " unnamed_addr";
1675 Attributes FnAttrs = Attrs.getFnAttributes();
1676 if (FnAttrs != Attribute::None)
1677 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1678 if (F->hasSection()) {
1679 Out << " section \"";
1680 PrintEscapedString(F->getSection(), Out);
1683 if (F->getAlignment())
1684 Out << " align " << F->getAlignment();
1686 Out << " gc \"" << F->getGC() << '"';
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,
1707 TypePrinter.print(Arg->getType(), Out);
1709 // Output parameter attributes list
1710 if (Attrs != Attribute::None)
1711 Out << ' ' << Attribute::getAsString(Attrs);
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() == 0) {
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 printInstruction(*I);
1767 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1770 /// printDebugLoc - Print DebugLoc.
1771 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
1772 OS << DL.getLine() << ":" << DL.getCol();
1773 if (MDNode *N = DL.getInlinedAt(getGlobalContext())) {
1774 DebugLoc IDL = DebugLoc::getFromDILocation(N);
1775 if (!IDL.isUnknown()) {
1777 printDebugLoc(IDL,OS);
1782 /// printInfoComment - Print a little comment after the instruction indicating
1783 /// which slot it occupies.
1785 void AssemblyWriter::printInfoComment(const Value &V) {
1786 if (AnnotationWriter) {
1787 AnnotationWriter->printInfoComment(V, Out);
1789 } else if (EnableDebugInfoComment) {
1790 bool Padded = false;
1791 if (const Instruction *I = dyn_cast<Instruction>(&V)) {
1792 const DebugLoc &DL = I->getDebugLoc();
1793 if (!DL.isUnknown()) {
1795 Out.PadToColumn(50);
1799 Out << " [debug line = ";
1800 printDebugLoc(DL,Out);
1803 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
1804 const MDNode *Var = DDI->getVariable();
1806 Out.PadToColumn(50);
1810 if (Var && Var->getNumOperands() >= 2)
1811 if (MDString *MDS = dyn_cast_or_null<MDString>(Var->getOperand(2)))
1812 Out << " [debug variable = " << MDS->getString() << "]";
1814 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
1815 const MDNode *Var = DVI->getVariable();
1817 Out.PadToColumn(50);
1821 if (Var && Var->getNumOperands() >= 2)
1822 if (MDString *MDS = dyn_cast_or_null<MDString>(Var->getOperand(2)))
1823 Out << " [debug variable = " << MDS->getString() << "]";
1829 // This member is called for each Instruction in a function..
1830 void AssemblyWriter::printInstruction(const Instruction &I) {
1831 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1833 // Print out indentation for an instruction.
1836 // Print out name if it exists...
1838 PrintLLVMName(Out, &I);
1840 } else if (!I.getType()->isVoidTy()) {
1841 // Print out the def slot taken.
1842 int SlotNum = Machine.getLocalSlot(&I);
1844 Out << "<badref> = ";
1846 Out << '%' << SlotNum << " = ";
1849 // If this is a volatile load or store, print out the volatile marker.
1850 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1851 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1853 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1854 // If this is a call, check if it's a tail call.
1858 // Print out the opcode...
1859 Out << I.getOpcodeName();
1861 // Print out optimization information.
1862 WriteOptimizationInfo(Out, &I);
1864 // Print out the compare instruction predicates
1865 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1866 Out << ' ' << getPredicateText(CI->getPredicate());
1868 // Print out the type of the operands...
1869 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1871 // Special case conditional branches to swizzle the condition out to the front
1872 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1873 BranchInst &BI(cast<BranchInst>(I));
1875 writeOperand(BI.getCondition(), true);
1877 writeOperand(BI.getSuccessor(0), true);
1879 writeOperand(BI.getSuccessor(1), true);
1881 } else if (isa<SwitchInst>(I)) {
1882 // Special case switch instruction to get formatting nice and correct.
1884 writeOperand(Operand , true);
1886 writeOperand(I.getOperand(1), true);
1889 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1891 writeOperand(I.getOperand(op ), true);
1893 writeOperand(I.getOperand(op+1), true);
1896 } else if (isa<IndirectBrInst>(I)) {
1897 // Special case indirectbr instruction to get formatting nice and correct.
1899 writeOperand(Operand, true);
1902 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1905 writeOperand(I.getOperand(i), true);
1908 } else if (isa<PHINode>(I)) {
1910 TypePrinter.print(I.getType(), Out);
1913 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1914 if (op) Out << ", ";
1916 writeOperand(I.getOperand(op ), false); Out << ", ";
1917 writeOperand(I.getOperand(op+1), false); Out << " ]";
1919 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1921 writeOperand(I.getOperand(0), true);
1922 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1924 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1926 writeOperand(I.getOperand(0), true); Out << ", ";
1927 writeOperand(I.getOperand(1), true);
1928 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1930 } else if (isa<ReturnInst>(I) && !Operand) {
1932 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1933 // Print the calling convention being used.
1934 switch (CI->getCallingConv()) {
1935 case CallingConv::C: break; // default
1936 case CallingConv::Fast: Out << " fastcc"; break;
1937 case CallingConv::Cold: Out << " coldcc"; break;
1938 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1939 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1940 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1941 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1942 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1943 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1944 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1945 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1946 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1947 default: Out << " cc" << CI->getCallingConv(); break;
1950 Operand = CI->getCalledValue();
1951 const PointerType *PTy = cast<PointerType>(Operand->getType());
1952 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1953 const Type *RetTy = FTy->getReturnType();
1954 const AttrListPtr &PAL = CI->getAttributes();
1956 if (PAL.getRetAttributes() != Attribute::None)
1957 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1959 // If possible, print out the short form of the call instruction. We can
1960 // only do this if the first argument is a pointer to a nonvararg function,
1961 // and if the return type is not a pointer to a function.
1964 if (!FTy->isVarArg() &&
1965 (!RetTy->isPointerTy() ||
1966 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1967 TypePrinter.print(RetTy, Out);
1969 writeOperand(Operand, false);
1971 writeOperand(Operand, true);
1974 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1977 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1980 if (PAL.getFnAttributes() != Attribute::None)
1981 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1982 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1983 Operand = II->getCalledValue();
1984 const PointerType *PTy = cast<PointerType>(Operand->getType());
1985 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1986 const Type *RetTy = FTy->getReturnType();
1987 const AttrListPtr &PAL = II->getAttributes();
1989 // Print the calling convention being used.
1990 switch (II->getCallingConv()) {
1991 case CallingConv::C: break; // default
1992 case CallingConv::Fast: Out << " fastcc"; break;
1993 case CallingConv::Cold: Out << " coldcc"; break;
1994 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1995 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1996 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1997 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1998 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1999 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
2000 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
2001 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
2002 case CallingConv::PTX_Device: Out << " ptx_device"; break;
2003 default: Out << " cc" << II->getCallingConv(); break;
2006 if (PAL.getRetAttributes() != Attribute::None)
2007 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
2009 // If possible, print out the short form of the invoke instruction. We can
2010 // only do this if the first argument is a pointer to a nonvararg function,
2011 // and if the return type is not a pointer to a function.
2014 if (!FTy->isVarArg() &&
2015 (!RetTy->isPointerTy() ||
2016 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
2017 TypePrinter.print(RetTy, Out);
2019 writeOperand(Operand, false);
2021 writeOperand(Operand, true);
2024 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
2027 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
2031 if (PAL.getFnAttributes() != Attribute::None)
2032 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
2035 writeOperand(II->getNormalDest(), true);
2037 writeOperand(II->getUnwindDest(), true);
2039 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
2041 TypePrinter.print(AI->getType()->getElementType(), Out);
2042 if (!AI->getArraySize() || AI->isArrayAllocation()) {
2044 writeOperand(AI->getArraySize(), true);
2046 if (AI->getAlignment()) {
2047 Out << ", align " << AI->getAlignment();
2049 } else if (isa<CastInst>(I)) {
2052 writeOperand(Operand, true); // Work with broken code
2055 TypePrinter.print(I.getType(), Out);
2056 } else if (isa<VAArgInst>(I)) {
2059 writeOperand(Operand, true); // Work with broken code
2062 TypePrinter.print(I.getType(), Out);
2063 } else if (Operand) { // Print the normal way.
2065 // PrintAllTypes - Instructions who have operands of all the same type
2066 // omit the type from all but the first operand. If the instruction has
2067 // different type operands (for example br), then they are all printed.
2068 bool PrintAllTypes = false;
2069 const Type *TheType = Operand->getType();
2071 // Select, Store and ShuffleVector always print all types.
2072 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2073 || isa<ReturnInst>(I)) {
2074 PrintAllTypes = true;
2076 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2077 Operand = I.getOperand(i);
2078 // note that Operand shouldn't be null, but the test helps make dump()
2079 // more tolerant of malformed IR
2080 if (Operand && Operand->getType() != TheType) {
2081 PrintAllTypes = true; // We have differing types! Print them all!
2087 if (!PrintAllTypes) {
2089 TypePrinter.print(TheType, Out);
2093 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2095 writeOperand(I.getOperand(i), PrintAllTypes);
2099 // Print post operand alignment for load/store.
2100 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2101 Out << ", align " << cast<LoadInst>(I).getAlignment();
2102 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2103 Out << ", align " << cast<StoreInst>(I).getAlignment();
2106 // Print Metadata info.
2107 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2108 I.getAllMetadata(InstMD);
2109 if (!InstMD.empty()) {
2110 SmallVector<StringRef, 8> MDNames;
2111 I.getType()->getContext().getMDKindNames(MDNames);
2112 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2113 unsigned Kind = InstMD[i].first;
2114 if (Kind < MDNames.size()) {
2115 Out << ", !" << MDNames[Kind];
2117 Out << ", !<unknown kind #" << Kind << ">";
2120 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2124 printInfoComment(I);
2127 static void WriteMDNodeComment(const MDNode *Node,
2128 formatted_raw_ostream &Out) {
2129 if (Node->getNumOperands() < 1)
2131 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2133 APInt Val = CI->getValue();
2134 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2135 if (Val.ult(LLVMDebugVersion))
2138 Out.PadToColumn(50);
2139 if (Tag == dwarf::DW_TAG_user_base)
2140 Out << "; [ DW_TAG_user_base ]";
2141 else if (Tag.isIntN(32)) {
2142 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2143 Out << "; [ " << TagName << " ]";
2147 void AssemblyWriter::writeAllMDNodes() {
2148 SmallVector<const MDNode *, 16> Nodes;
2149 Nodes.resize(Machine.mdn_size());
2150 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2152 Nodes[I->second] = cast<MDNode>(I->first);
2154 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2155 Out << '!' << i << " = metadata ";
2156 printMDNodeBody(Nodes[i]);
2160 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2161 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2162 WriteMDNodeComment(Node, Out);
2166 //===----------------------------------------------------------------------===//
2167 // External Interface declarations
2168 //===----------------------------------------------------------------------===//
2170 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2171 SlotTracker SlotTable(this);
2172 formatted_raw_ostream OS(ROS);
2173 AssemblyWriter W(OS, SlotTable, this, AAW);
2174 W.printModule(this);
2177 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2178 SlotTracker SlotTable(getParent());
2179 formatted_raw_ostream OS(ROS);
2180 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2181 W.printNamedMDNode(this);
2184 void Type::print(raw_ostream &OS) const {
2186 OS << "<null Type>";
2189 TypePrinting().print(this, OS);
2192 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2194 ROS << "printing a <null> value\n";
2197 formatted_raw_ostream OS(ROS);
2198 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2199 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2200 SlotTracker SlotTable(F);
2201 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2202 W.printInstruction(*I);
2203 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2204 SlotTracker SlotTable(BB->getParent());
2205 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2206 W.printBasicBlock(BB);
2207 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2208 SlotTracker SlotTable(GV->getParent());
2209 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2210 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2212 else if (const Function *F = dyn_cast<Function>(GV))
2215 W.printAlias(cast<GlobalAlias>(GV));
2216 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2217 const Function *F = N->getFunction();
2218 SlotTracker SlotTable(F);
2219 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2220 W.printMDNodeBody(N);
2221 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2222 TypePrinting TypePrinter;
2223 TypePrinter.print(C->getType(), OS);
2225 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2226 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2227 isa<Argument>(this)) {
2228 WriteAsOperand(OS, this, true, 0);
2230 // Otherwise we don't know what it is. Call the virtual function to
2231 // allow a subclass to print itself.
2236 // Value::printCustom - subclasses should override this to implement printing.
2237 void Value::printCustom(raw_ostream &OS) const {
2238 llvm_unreachable("Unknown value to print out!");
2241 // Value::dump - allow easy printing of Values from the debugger.
2242 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2244 // Type::dump - allow easy printing of Types from the debugger.
2245 // This one uses type names from the given context module
2246 void Type::dump(const Module *Context) const {
2247 WriteTypeSymbolic(dbgs(), this, Context);
2251 // Type::dump - allow easy printing of Types from the debugger.
2252 void Type::dump() const { dump(0); }
2254 // Module::dump() - Allow printing of Modules from the debugger.
2255 void Module::dump() const { print(dbgs(), 0); }