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/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Operator.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/FormattedStream.h"
42 // Make virtual table appear in this compilation unit.
43 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 static const Module *getModuleFromVal(const Value *V) {
50 if (const Argument *MA = dyn_cast<Argument>(V))
51 return MA->getParent() ? MA->getParent()->getParent() : 0;
53 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
54 return BB->getParent() ? BB->getParent()->getParent() : 0;
56 if (const Instruction *I = dyn_cast<Instruction>(V)) {
57 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
58 return M ? M->getParent() : 0;
61 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
62 return GV->getParent();
63 if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
64 return NMD->getParent();
68 // PrintEscapedString - Print each character of the specified string, escaping
69 // it if it is not printable or if it is an escape char.
70 static void PrintEscapedString(const StringRef &Name,
72 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
73 unsigned char C = Name[i];
74 if (isprint(C) && C != '\\' && C != '"')
77 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
88 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
89 /// prefixed with % (if the string only contains simple characters) or is
90 /// surrounded with ""'s (if it has special chars in it). Print it out.
91 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
93 assert(Name.data() && "Cannot get empty name!");
95 default: llvm_unreachable("Bad prefix!");
97 case GlobalPrefix: OS << '@'; break;
98 case LabelPrefix: break;
99 case LocalPrefix: OS << '%'; break;
102 // Scan the name to see if it needs quotes first.
103 bool NeedsQuotes = isdigit(Name[0]);
105 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
107 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
114 // If we didn't need any quotes, just write out the name in one blast.
120 // Okay, we need quotes. Output the quotes and escape any scary characters as
123 PrintEscapedString(Name, OS);
127 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
128 /// prefixed with % (if the string only contains simple characters) or is
129 /// surrounded with ""'s (if it has special chars in it). Print it out.
130 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
131 PrintLLVMName(OS, V->getName(),
132 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
135 //===----------------------------------------------------------------------===//
136 // TypePrinting Class: Type printing machinery
137 //===----------------------------------------------------------------------===//
139 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
140 return *static_cast<DenseMap<const Type *, std::string>*>(M);
143 void TypePrinting::clear() {
144 getTypeNamesMap(TypeNames).clear();
147 bool TypePrinting::hasTypeName(const Type *Ty) const {
148 return getTypeNamesMap(TypeNames).count(Ty);
151 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
152 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
156 TypePrinting::TypePrinting() {
157 TypeNames = new DenseMap<const Type *, std::string>();
160 TypePrinting::~TypePrinting() {
161 delete &getTypeNamesMap(TypeNames);
164 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
165 /// use of type names or up references to shorten the type name where possible.
166 void TypePrinting::CalcTypeName(const Type *Ty,
167 SmallVectorImpl<const Type *> &TypeStack,
168 raw_ostream &OS, bool IgnoreTopLevelName) {
169 // Check to see if the type is named.
170 if (!IgnoreTopLevelName) {
171 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
172 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
179 // Check to see if the Type is already on the stack...
180 unsigned Slot = 0, CurSize = TypeStack.size();
181 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
183 // This is another base case for the recursion. In this case, we know
184 // that we have looped back to a type that we have previously visited.
185 // Generate the appropriate upreference to handle this.
186 if (Slot < CurSize) {
187 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
191 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
193 switch (Ty->getTypeID()) {
194 case Type::VoidTyID: OS << "void"; break;
195 case Type::FloatTyID: OS << "float"; break;
196 case Type::DoubleTyID: OS << "double"; break;
197 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
198 case Type::FP128TyID: OS << "fp128"; break;
199 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
200 case Type::LabelTyID: OS << "label"; break;
201 case Type::MetadataTyID: OS << "metadata"; break;
202 case Type::IntegerTyID:
203 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
206 case Type::FunctionTyID: {
207 const FunctionType *FTy = cast<FunctionType>(Ty);
208 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
210 for (FunctionType::param_iterator I = FTy->param_begin(),
211 E = FTy->param_end(); I != E; ++I) {
212 if (I != FTy->param_begin())
214 CalcTypeName(*I, TypeStack, OS);
216 if (FTy->isVarArg()) {
217 if (FTy->getNumParams()) OS << ", ";
223 case Type::StructTyID: {
224 const StructType *STy = cast<StructType>(Ty);
228 for (StructType::element_iterator I = STy->element_begin(),
229 E = STy->element_end(); I != E; ++I) {
230 CalcTypeName(*I, TypeStack, OS);
231 if (next(I) != STy->element_end())
240 case Type::PointerTyID: {
241 const PointerType *PTy = cast<PointerType>(Ty);
242 CalcTypeName(PTy->getElementType(), TypeStack, OS);
243 if (unsigned AddressSpace = PTy->getAddressSpace())
244 OS << " addrspace(" << AddressSpace << ')';
248 case Type::ArrayTyID: {
249 const ArrayType *ATy = cast<ArrayType>(Ty);
250 OS << '[' << ATy->getNumElements() << " x ";
251 CalcTypeName(ATy->getElementType(), TypeStack, OS);
255 case Type::VectorTyID: {
256 const VectorType *PTy = cast<VectorType>(Ty);
257 OS << "<" << PTy->getNumElements() << " x ";
258 CalcTypeName(PTy->getElementType(), TypeStack, OS);
262 case Type::OpaqueTyID:
266 OS << "<unrecognized-type>";
270 TypeStack.pop_back(); // Remove self from stack.
273 /// printTypeInt - The internal guts of printing out a type that has a
274 /// potentially named portion.
276 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
277 bool IgnoreTopLevelName) {
278 // Check to see if the type is named.
279 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
280 if (!IgnoreTopLevelName) {
281 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
288 // Otherwise we have a type that has not been named but is a derived type.
289 // Carefully recurse the type hierarchy to print out any contained symbolic
291 SmallVector<const Type *, 16> TypeStack;
292 std::string TypeName;
294 raw_string_ostream TypeOS(TypeName);
295 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
298 // Cache type name for later use.
299 if (!IgnoreTopLevelName)
300 TM.insert(std::make_pair(Ty, TypeOS.str()));
305 // To avoid walking constant expressions multiple times and other IR
306 // objects, we keep several helper maps.
307 DenseSet<const Value*> VisitedConstants;
308 DenseSet<const Type*> VisitedTypes;
311 std::vector<const Type*> &NumberedTypes;
313 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
314 : TP(tp), NumberedTypes(numberedTypes) {}
316 void Run(const Module &M) {
317 // Get types from the type symbol table. This gets opaque types referened
318 // only through derived named types.
319 const TypeSymbolTable &ST = M.getTypeSymbolTable();
320 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
322 IncorporateType(TI->second);
324 // Get types from global variables.
325 for (Module::const_global_iterator I = M.global_begin(),
326 E = M.global_end(); I != E; ++I) {
327 IncorporateType(I->getType());
328 if (I->hasInitializer())
329 IncorporateValue(I->getInitializer());
332 // Get types from aliases.
333 for (Module::const_alias_iterator I = M.alias_begin(),
334 E = M.alias_end(); I != E; ++I) {
335 IncorporateType(I->getType());
336 IncorporateValue(I->getAliasee());
339 // Get types from functions.
340 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
341 IncorporateType(FI->getType());
343 for (Function::const_iterator BB = FI->begin(), E = FI->end();
345 for (BasicBlock::const_iterator II = BB->begin(),
346 E = BB->end(); II != E; ++II) {
347 const Instruction &I = *II;
348 // Incorporate the type of the instruction and all its operands.
349 IncorporateType(I.getType());
350 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
352 IncorporateValue(*OI);
358 void IncorporateType(const Type *Ty) {
359 // Check to see if we're already visited this type.
360 if (!VisitedTypes.insert(Ty).second)
363 // If this is a structure or opaque type, add a name for the type.
364 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
365 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
366 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
367 NumberedTypes.push_back(Ty);
370 // Recursively walk all contained types.
371 for (Type::subtype_iterator I = Ty->subtype_begin(),
372 E = Ty->subtype_end(); I != E; ++I)
376 /// IncorporateValue - This method is used to walk operand lists finding
377 /// types hiding in constant expressions and other operands that won't be
378 /// walked in other ways. GlobalValues, basic blocks, instructions, and
379 /// inst operands are all explicitly enumerated.
380 void IncorporateValue(const Value *V) {
381 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
384 if (!VisitedConstants.insert(V).second)
388 IncorporateType(V->getType());
390 // Look in operands for types.
391 const Constant *C = cast<Constant>(V);
392 for (Constant::const_op_iterator I = C->op_begin(),
393 E = C->op_end(); I != E;++I)
394 IncorporateValue(*I);
397 } // end anonymous namespace
400 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
401 /// the specified module to the TypePrinter and all numbered types to it and the
402 /// NumberedTypes table.
403 static void AddModuleTypesToPrinter(TypePrinting &TP,
404 std::vector<const Type*> &NumberedTypes,
408 // If the module has a symbol table, take all global types and stuff their
409 // names into the TypeNames map.
410 const TypeSymbolTable &ST = M->getTypeSymbolTable();
411 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
413 const Type *Ty = cast<Type>(TI->second);
415 // As a heuristic, don't insert pointer to primitive types, because
416 // they are used too often to have a single useful name.
417 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
418 const Type *PETy = PTy->getElementType();
419 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
420 !isa<OpaqueType>(PETy))
424 // Likewise don't insert primitives either.
425 if (Ty->isInteger() || Ty->isPrimitiveType())
428 // Get the name as a string and insert it into TypeNames.
430 raw_string_ostream NameROS(NameStr);
431 formatted_raw_ostream NameOS(NameROS);
432 PrintLLVMName(NameOS, TI->first, LocalPrefix);
434 TP.addTypeName(Ty, NameStr);
437 // Walk the entire module to find references to unnamed structure and opaque
438 // types. This is required for correctness by opaque types (because multiple
439 // uses of an unnamed opaque type needs to be referred to by the same ID) and
440 // it shrinks complex recursive structure types substantially in some cases.
441 TypeFinder(TP, NumberedTypes).Run(*M);
445 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
446 /// type, iff there is an entry in the modules symbol table for the specified
447 /// type or one of it's component types.
449 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
450 TypePrinting Printer;
451 std::vector<const Type*> NumberedTypes;
452 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
453 Printer.print(Ty, OS);
456 //===----------------------------------------------------------------------===//
457 // SlotTracker Class: Enumerate slot numbers for unnamed values
458 //===----------------------------------------------------------------------===//
462 /// This class provides computation of slot numbers for LLVM Assembly writing.
466 /// ValueMap - A mapping of Values to slot numbers.
467 typedef DenseMap<const Value*, unsigned> ValueMap;
470 /// TheModule - The module for which we are holding slot numbers.
471 const Module* TheModule;
473 /// TheFunction - The function for which we are holding slot numbers.
474 const Function* TheFunction;
475 bool FunctionProcessed;
477 /// mMap - The TypePlanes map for the module level data.
481 /// fMap - The TypePlanes map for the function level data.
485 /// mdnMap - Map for MDNodes.
489 /// Construct from a module
490 explicit SlotTracker(const Module *M);
491 /// Construct from a function, starting out in incorp state.
492 explicit SlotTracker(const Function *F);
494 /// Return the slot number of the specified value in it's type
495 /// plane. If something is not in the SlotTracker, return -1.
496 int getLocalSlot(const Value *V);
497 int getGlobalSlot(const GlobalValue *V);
498 int getMetadataSlot(const MDNode *N);
500 /// If you'd like to deal with a function instead of just a module, use
501 /// this method to get its data into the SlotTracker.
502 void incorporateFunction(const Function *F) {
504 FunctionProcessed = false;
507 /// After calling incorporateFunction, use this method to remove the
508 /// most recently incorporated function from the SlotTracker. This
509 /// will reset the state of the machine back to just the module contents.
510 void purgeFunction();
512 /// MDNode map iterators.
513 ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
514 ValueMap::iterator mdnEnd() { return mdnMap.end(); }
515 unsigned mdnSize() const { return mdnMap.size(); }
516 bool mdnEmpty() const { return mdnMap.empty(); }
518 /// This function does the actual initialization.
519 inline void initialize();
521 // Implementation Details
523 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
524 void CreateModuleSlot(const GlobalValue *V);
526 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
527 void CreateMetadataSlot(const MDNode *N);
529 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
530 void CreateFunctionSlot(const Value *V);
532 /// Add all of the module level global variables (and their initializers)
533 /// and function declarations, but not the contents of those functions.
534 void processModule();
536 /// Add all of the functions arguments, basic blocks, and instructions.
537 void processFunction();
539 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
540 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
543 } // end anonymous namespace
546 static SlotTracker *createSlotTracker(const Value *V) {
547 if (const Argument *FA = dyn_cast<Argument>(V))
548 return new SlotTracker(FA->getParent());
550 if (const Instruction *I = dyn_cast<Instruction>(V))
551 return new SlotTracker(I->getParent()->getParent());
553 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
554 return new SlotTracker(BB->getParent());
556 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
557 return new SlotTracker(GV->getParent());
559 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
560 return new SlotTracker(GA->getParent());
562 if (const Function *Func = dyn_cast<Function>(V))
563 return new SlotTracker(Func);
569 #define ST_DEBUG(X) errs() << X
574 // Module level constructor. Causes the contents of the Module (sans functions)
575 // to be added to the slot table.
576 SlotTracker::SlotTracker(const Module *M)
577 : TheModule(M), TheFunction(0), FunctionProcessed(false),
578 mNext(0), fNext(0), mdnNext(0) {
581 // Function level constructor. Causes the contents of the Module and the one
582 // function provided to be added to the slot table.
583 SlotTracker::SlotTracker(const Function *F)
584 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
585 mNext(0), fNext(0), mdnNext(0) {
588 inline void SlotTracker::initialize() {
591 TheModule = 0; ///< Prevent re-processing next time we're called.
594 if (TheFunction && !FunctionProcessed)
598 // Iterate through all the global variables, functions, and global
599 // variable initializers and create slots for them.
600 void SlotTracker::processModule() {
601 ST_DEBUG("begin processModule!\n");
603 // Add all of the unnamed global variables to the value table.
604 for (Module::const_global_iterator I = TheModule->global_begin(),
605 E = TheModule->global_end(); I != E; ++I) {
610 // Add metadata used by named metadata.
611 for (Module::const_named_metadata_iterator
612 I = TheModule->named_metadata_begin(),
613 E = TheModule->named_metadata_end(); I != E; ++I) {
614 const NamedMDNode *NMD = I;
615 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
616 // FIXME: Change accessor to be type safe.
617 if (MDNode *MD = cast_or_null<MDNode>(NMD->getOperand(i)))
618 CreateMetadataSlot(MD);
622 // Add all the unnamed functions to the table.
623 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
628 ST_DEBUG("end processModule!\n");
631 // Process the arguments, basic blocks, and instructions of a function.
632 void SlotTracker::processFunction() {
633 ST_DEBUG("begin processFunction!\n");
636 // Add all the function arguments with no names.
637 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
638 AE = TheFunction->arg_end(); AI != AE; ++AI)
640 CreateFunctionSlot(AI);
642 ST_DEBUG("Inserting Instructions:\n");
644 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
646 // Add all of the basic blocks and instructions with no names.
647 for (Function::const_iterator BB = TheFunction->begin(),
648 E = TheFunction->end(); BB != E; ++BB) {
650 CreateFunctionSlot(BB);
652 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
654 if (!I->getType()->isVoidTy() && !I->hasName())
655 CreateFunctionSlot(I);
657 // Intrinsics can directly use metadata.
658 if (isa<IntrinsicInst>(I))
659 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
660 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
661 CreateMetadataSlot(N);
663 // Process metadata attached with this instruction.
664 I->getAllMetadata(MDForInst);
665 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
666 CreateMetadataSlot(MDForInst[i].second);
671 FunctionProcessed = true;
673 ST_DEBUG("end processFunction!\n");
676 /// Clean up after incorporating a function. This is the only way to get out of
677 /// the function incorporation state that affects get*Slot/Create*Slot. Function
678 /// incorporation state is indicated by TheFunction != 0.
679 void SlotTracker::purgeFunction() {
680 ST_DEBUG("begin purgeFunction!\n");
681 fMap.clear(); // Simply discard the function level map
683 FunctionProcessed = false;
684 ST_DEBUG("end purgeFunction!\n");
687 /// getGlobalSlot - Get the slot number of a global value.
688 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
689 // Check for uninitialized state and do lazy initialization.
692 // Find the type plane in the module map
693 ValueMap::iterator MI = mMap.find(V);
694 return MI == mMap.end() ? -1 : (int)MI->second;
697 /// getGlobalSlot - Get the slot number of a MDNode.
698 int SlotTracker::getMetadataSlot(const MDNode *N) {
699 // Check for uninitialized state and do lazy initialization.
702 // Find the type plane in the module map
703 ValueMap::iterator MI = mdnMap.find(N);
704 return MI == mdnMap.end() ? -1 : (int)MI->second;
708 /// getLocalSlot - Get the slot number for a value that is local to a function.
709 int SlotTracker::getLocalSlot(const Value *V) {
710 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
712 // Check for uninitialized state and do lazy initialization.
715 ValueMap::iterator FI = fMap.find(V);
716 return FI == fMap.end() ? -1 : (int)FI->second;
720 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
721 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
722 assert(V && "Can't insert a null Value into SlotTracker!");
723 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
724 assert(!V->hasName() && "Doesn't need a slot!");
726 unsigned DestSlot = mNext++;
729 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
731 // G = Global, F = Function, A = Alias, o = other
732 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
733 (isa<Function>(V) ? 'F' :
734 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
737 /// CreateSlot - Create a new slot for the specified value if it has no name.
738 void SlotTracker::CreateFunctionSlot(const Value *V) {
739 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
741 unsigned DestSlot = fNext++;
744 // G = Global, F = Function, o = other
745 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
746 DestSlot << " [o]\n");
749 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
750 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
751 assert(N && "Can't insert a null Value into SlotTracker!");
753 // Don't insert if N is a function-local metadata.
754 if (N->isFunctionLocal())
757 ValueMap::iterator I = mdnMap.find(N);
758 if (I != mdnMap.end())
761 unsigned DestSlot = mdnNext++;
762 mdnMap[N] = DestSlot;
764 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
765 const Value *TV = N->getOperand(i);
767 if (const MDNode *N2 = dyn_cast<MDNode>(TV))
768 CreateMetadataSlot(N2);
772 //===----------------------------------------------------------------------===//
773 // AsmWriter Implementation
774 //===----------------------------------------------------------------------===//
776 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
777 TypePrinting *TypePrinter,
778 SlotTracker *Machine);
782 static const char *getPredicateText(unsigned predicate) {
783 const char * pred = "unknown";
785 case FCmpInst::FCMP_FALSE: pred = "false"; break;
786 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
787 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
788 case FCmpInst::FCMP_OGE: pred = "oge"; break;
789 case FCmpInst::FCMP_OLT: pred = "olt"; break;
790 case FCmpInst::FCMP_OLE: pred = "ole"; break;
791 case FCmpInst::FCMP_ONE: pred = "one"; break;
792 case FCmpInst::FCMP_ORD: pred = "ord"; break;
793 case FCmpInst::FCMP_UNO: pred = "uno"; break;
794 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
795 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
796 case FCmpInst::FCMP_UGE: pred = "uge"; break;
797 case FCmpInst::FCMP_ULT: pred = "ult"; break;
798 case FCmpInst::FCMP_ULE: pred = "ule"; break;
799 case FCmpInst::FCMP_UNE: pred = "une"; break;
800 case FCmpInst::FCMP_TRUE: pred = "true"; break;
801 case ICmpInst::ICMP_EQ: pred = "eq"; break;
802 case ICmpInst::ICMP_NE: pred = "ne"; break;
803 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
804 case ICmpInst::ICMP_SGE: pred = "sge"; break;
805 case ICmpInst::ICMP_SLT: pred = "slt"; break;
806 case ICmpInst::ICMP_SLE: pred = "sle"; break;
807 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
808 case ICmpInst::ICMP_UGE: pred = "uge"; break;
809 case ICmpInst::ICMP_ULT: pred = "ult"; break;
810 case ICmpInst::ICMP_ULE: pred = "ule"; break;
816 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
817 if (const OverflowingBinaryOperator *OBO =
818 dyn_cast<OverflowingBinaryOperator>(U)) {
819 if (OBO->hasNoUnsignedWrap())
821 if (OBO->hasNoSignedWrap())
823 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
826 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
827 if (GEP->isInBounds())
832 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
833 TypePrinting &TypePrinter, SlotTracker *Machine) {
834 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
835 if (CI->getType() == Type::getInt1Ty(CV->getContext())) {
836 Out << (CI->getZExtValue() ? "true" : "false");
839 Out << CI->getValue();
843 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
844 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
845 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
846 // We would like to output the FP constant value in exponential notation,
847 // but we cannot do this if doing so will lose precision. Check here to
848 // make sure that we only output it in exponential format if we can parse
849 // the value back and get the same value.
852 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
853 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
854 CFP->getValueAPF().convertToFloat();
855 std::string StrVal = ftostr(CFP->getValueAPF());
857 // Check to make sure that the stringized number is not some string like
858 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
859 // that the string matches the "[-+]?[0-9]" regex.
861 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
862 ((StrVal[0] == '-' || StrVal[0] == '+') &&
863 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
864 // Reparse stringized version!
865 if (atof(StrVal.c_str()) == Val) {
870 // Otherwise we could not reparse it to exactly the same value, so we must
871 // output the string in hexadecimal format! Note that loading and storing
872 // floating point types changes the bits of NaNs on some hosts, notably
873 // x86, so we must not use these types.
874 assert(sizeof(double) == sizeof(uint64_t) &&
875 "assuming that double is 64 bits!");
877 APFloat apf = CFP->getValueAPF();
878 // Floats are represented in ASCII IR as double, convert.
880 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
883 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
888 // Some form of long double. These appear as a magic letter identifying
889 // the type, then a fixed number of hex digits.
891 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
893 // api needed to prevent premature destruction
894 APInt api = CFP->getValueAPF().bitcastToAPInt();
895 const uint64_t* p = api.getRawData();
896 uint64_t word = p[1];
898 int width = api.getBitWidth();
899 for (int j=0; j<width; j+=4, shiftcount-=4) {
900 unsigned int nibble = (word>>shiftcount) & 15;
902 Out << (unsigned char)(nibble + '0');
904 Out << (unsigned char)(nibble - 10 + 'A');
905 if (shiftcount == 0 && j+4 < width) {
909 shiftcount = width-j-4;
913 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
915 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
918 llvm_unreachable("Unsupported floating point type");
919 // api needed to prevent premature destruction
920 APInt api = CFP->getValueAPF().bitcastToAPInt();
921 const uint64_t* p = api.getRawData();
924 int width = api.getBitWidth();
925 for (int j=0; j<width; j+=4, shiftcount-=4) {
926 unsigned int nibble = (word>>shiftcount) & 15;
928 Out << (unsigned char)(nibble + '0');
930 Out << (unsigned char)(nibble - 10 + 'A');
931 if (shiftcount == 0 && j+4 < width) {
935 shiftcount = width-j-4;
941 if (isa<ConstantAggregateZero>(CV)) {
942 Out << "zeroinitializer";
946 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
947 Out << "blockaddress(";
948 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
950 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
955 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
956 // As a special case, print the array as a string if it is an array of
957 // i8 with ConstantInt values.
959 const Type *ETy = CA->getType()->getElementType();
960 if (CA->isString()) {
962 PrintEscapedString(CA->getAsString(), Out);
964 } else { // Cannot output in string format...
966 if (CA->getNumOperands()) {
967 TypePrinter.print(ETy, Out);
969 WriteAsOperandInternal(Out, CA->getOperand(0),
970 &TypePrinter, Machine);
971 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
973 TypePrinter.print(ETy, Out);
975 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
983 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
984 if (CS->getType()->isPacked())
987 unsigned N = CS->getNumOperands();
990 TypePrinter.print(CS->getOperand(0)->getType(), Out);
993 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
995 for (unsigned i = 1; i < N; i++) {
997 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1000 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1006 if (CS->getType()->isPacked())
1011 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1012 const Type *ETy = CP->getType()->getElementType();
1013 assert(CP->getNumOperands() > 0 &&
1014 "Number of operands for a PackedConst must be > 0");
1016 TypePrinter.print(ETy, Out);
1018 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1019 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1021 TypePrinter.print(ETy, Out);
1023 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1029 if (isa<ConstantPointerNull>(CV)) {
1034 if (isa<UndefValue>(CV)) {
1039 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1040 Out << "!" << Machine->getMetadataSlot(Node);
1044 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1045 Out << CE->getOpcodeName();
1046 WriteOptimizationInfo(Out, CE);
1047 if (CE->isCompare())
1048 Out << ' ' << getPredicateText(CE->getPredicate());
1051 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1052 TypePrinter.print((*OI)->getType(), Out);
1054 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1055 if (OI+1 != CE->op_end())
1059 if (CE->hasIndices()) {
1060 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1061 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1062 Out << ", " << Indices[i];
1067 TypePrinter.print(CE->getType(), Out);
1074 Out << "<placeholder or erroneous Constant>";
1078 /// WriteAsOperand - Write the name of the specified value out to the specified
1079 /// ostream. This can be useful when you just want to print int %reg126, not
1080 /// the whole instruction that generated it.
1082 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1083 TypePrinting *TypePrinter,
1084 SlotTracker *Machine) {
1086 PrintLLVMName(Out, V);
1090 const Constant *CV = dyn_cast<Constant>(V);
1091 if (CV && !isa<GlobalValue>(CV)) {
1092 assert(TypePrinter && "Constants require TypePrinting!");
1093 WriteConstantInt(Out, CV, *TypePrinter, Machine);
1097 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1099 if (IA->hasSideEffects())
1100 Out << "sideeffect ";
1101 if (IA->isAlignStack())
1102 Out << "alignstack ";
1104 PrintEscapedString(IA->getAsmString(), Out);
1106 PrintEscapedString(IA->getConstraintString(), Out);
1111 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1112 if (N->isFunctionLocal()) {
1113 // Print metadata inline, not via slot reference number.
1115 for (unsigned mi = 0, me = N->getNumOperands(); mi != me; ++mi) {
1116 const Value *Val = N->getOperand(mi);
1120 TypePrinter->print(N->getOperand(mi)->getType(), Out);
1122 WriteAsOperandInternal(Out, N->getOperand(mi), TypePrinter, Machine);
1131 Out << '!' << Machine->getMetadataSlot(N);
1135 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1137 PrintEscapedString(MDS->getString(), Out);
1142 if (V->getValueID() == Value::PseudoSourceValueVal ||
1143 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1151 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1152 Slot = Machine->getGlobalSlot(GV);
1155 Slot = Machine->getLocalSlot(V);
1158 Machine = createSlotTracker(V);
1160 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1161 Slot = Machine->getGlobalSlot(GV);
1164 Slot = Machine->getLocalSlot(V);
1173 Out << Prefix << Slot;
1178 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1179 bool PrintType, const Module *Context) {
1181 // Fast path: Don't construct and populate a TypePrinting object if we
1182 // won't be needing any types printed.
1184 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1185 WriteAsOperandInternal(Out, V, 0, 0);
1189 if (Context == 0) Context = getModuleFromVal(V);
1191 TypePrinting TypePrinter;
1192 std::vector<const Type*> NumberedTypes;
1193 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1195 TypePrinter.print(V->getType(), Out);
1199 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1204 class AssemblyWriter {
1205 formatted_raw_ostream &Out;
1206 SlotTracker &Machine;
1207 const Module *TheModule;
1208 TypePrinting TypePrinter;
1209 AssemblyAnnotationWriter *AnnotationWriter;
1210 std::vector<const Type*> NumberedTypes;
1211 SmallVector<StringRef, 8> MDNames;
1214 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1216 AssemblyAnnotationWriter *AAW)
1217 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1218 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1219 // FIXME: Provide MDPrinter
1221 M->getMDKindNames(MDNames);
1224 void printMDNodeBody(const MDNode *MD);
1225 void printNamedMDNode(const NamedMDNode *NMD);
1227 void write(const Module *M) { printModule(M); }
1229 void write(const GlobalValue *G) {
1230 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1232 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1234 else if (const Function *F = dyn_cast<Function>(G))
1237 llvm_unreachable("Unknown global");
1240 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1241 void write(const Instruction *I) { printInstruction(*I); }
1243 void writeOperand(const Value *Op, bool PrintType);
1244 void writeParamOperand(const Value *Operand, Attributes Attrs);
1246 void writeAllMDNodes();
1249 void printModule(const Module *M);
1250 void printTypeSymbolTable(const TypeSymbolTable &ST);
1251 void printGlobal(const GlobalVariable *GV);
1252 void printAlias(const GlobalAlias *GV);
1253 void printFunction(const Function *F);
1254 void printArgument(const Argument *FA, Attributes Attrs);
1255 void printBasicBlock(const BasicBlock *BB);
1256 void printInstruction(const Instruction &I);
1258 // printInfoComment - Print a little comment after the instruction indicating
1259 // which slot it occupies.
1260 void printInfoComment(const Value &V);
1262 } // end of anonymous namespace
1265 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1267 Out << "<null operand!>";
1270 TypePrinter.print(Operand->getType(), Out);
1273 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1277 void AssemblyWriter::writeParamOperand(const Value *Operand,
1280 Out << "<null operand!>";
1283 TypePrinter.print(Operand->getType(), Out);
1284 // Print parameter attributes list
1285 if (Attrs != Attribute::None)
1286 Out << ' ' << Attribute::getAsString(Attrs);
1288 // Print the operand
1289 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1293 void AssemblyWriter::printModule(const Module *M) {
1294 if (!M->getModuleIdentifier().empty() &&
1295 // Don't print the ID if it will start a new line (which would
1296 // require a comment char before it).
1297 M->getModuleIdentifier().find('\n') == std::string::npos)
1298 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1300 if (!M->getDataLayout().empty())
1301 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1302 if (!M->getTargetTriple().empty())
1303 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1305 if (!M->getModuleInlineAsm().empty()) {
1306 // Split the string into lines, to make it easier to read the .ll file.
1307 std::string Asm = M->getModuleInlineAsm();
1309 size_t NewLine = Asm.find_first_of('\n', CurPos);
1311 while (NewLine != std::string::npos) {
1312 // We found a newline, print the portion of the asm string from the
1313 // last newline up to this newline.
1314 Out << "module asm \"";
1315 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1319 NewLine = Asm.find_first_of('\n', CurPos);
1321 Out << "module asm \"";
1322 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1326 // Loop over the dependent libraries and emit them.
1327 Module::lib_iterator LI = M->lib_begin();
1328 Module::lib_iterator LE = M->lib_end();
1331 Out << "deplibs = [ ";
1333 Out << '"' << *LI << '"';
1341 // Loop over the symbol table, emitting all id'd types.
1342 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1343 printTypeSymbolTable(M->getTypeSymbolTable());
1345 // Output all globals.
1346 if (!M->global_empty()) Out << '\n';
1347 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1351 // Output all aliases.
1352 if (!M->alias_empty()) Out << "\n";
1353 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1357 // Output all of the functions.
1358 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1361 // Output named metadata.
1362 if (!M->named_metadata_empty()) Out << '\n';
1364 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1365 E = M->named_metadata_end(); I != E; ++I)
1366 printNamedMDNode(I);
1369 if (!Machine.mdnEmpty()) {
1375 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1376 Out << "!" << NMD->getName() << " = !{";
1377 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1379 // FIXME: Change accessor to be typesafe.
1380 // FIXME: This doesn't handle null??
1381 MDNode *MD = cast_or_null<MDNode>(NMD->getOperand(i));
1382 Out << '!' << Machine.getMetadataSlot(MD);
1388 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1389 formatted_raw_ostream &Out) {
1391 case GlobalValue::ExternalLinkage: break;
1392 case GlobalValue::PrivateLinkage: Out << "private "; break;
1393 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1394 case GlobalValue::InternalLinkage: Out << "internal "; break;
1395 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1396 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1397 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1398 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1399 case GlobalValue::CommonLinkage: Out << "common "; break;
1400 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1401 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1402 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1403 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1404 case GlobalValue::AvailableExternallyLinkage:
1405 Out << "available_externally ";
1407 // This is invalid syntax and just a debugging aid.
1408 case GlobalValue::GhostLinkage: Out << "ghost "; break;
1413 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1414 formatted_raw_ostream &Out) {
1416 case GlobalValue::DefaultVisibility: break;
1417 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1418 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1422 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1423 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1426 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1429 PrintLinkage(GV->getLinkage(), Out);
1430 PrintVisibility(GV->getVisibility(), Out);
1432 if (GV->isThreadLocal()) Out << "thread_local ";
1433 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1434 Out << "addrspace(" << AddressSpace << ") ";
1435 Out << (GV->isConstant() ? "constant " : "global ");
1436 TypePrinter.print(GV->getType()->getElementType(), Out);
1438 if (GV->hasInitializer()) {
1440 writeOperand(GV->getInitializer(), false);
1443 if (GV->hasSection())
1444 Out << ", section \"" << GV->getSection() << '"';
1445 if (GV->getAlignment())
1446 Out << ", align " << GV->getAlignment();
1448 printInfoComment(*GV);
1452 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1453 // Don't crash when dumping partially built GA
1455 Out << "<<nameless>> = ";
1457 PrintLLVMName(Out, GA);
1460 PrintVisibility(GA->getVisibility(), Out);
1464 PrintLinkage(GA->getLinkage(), Out);
1466 const Constant *Aliasee = GA->getAliasee();
1468 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1469 TypePrinter.print(GV->getType(), Out);
1471 PrintLLVMName(Out, GV);
1472 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1473 TypePrinter.print(F->getFunctionType(), Out);
1476 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1477 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1478 TypePrinter.print(GA->getType(), Out);
1480 PrintLLVMName(Out, GA);
1482 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1483 // The only valid GEP is an all zero GEP.
1484 assert((CE->getOpcode() == Instruction::BitCast ||
1485 CE->getOpcode() == Instruction::GetElementPtr) &&
1486 "Unsupported aliasee");
1487 writeOperand(CE, false);
1490 printInfoComment(*GA);
1494 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1495 // Emit all numbered types.
1496 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1497 Out << '%' << i << " = type ";
1499 // Make sure we print out at least one level of the type structure, so
1500 // that we do not get %2 = type %2
1501 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1505 // Print the named types.
1506 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1508 PrintLLVMName(Out, TI->first, LocalPrefix);
1511 // Make sure we print out at least one level of the type structure, so
1512 // that we do not get %FILE = type %FILE
1513 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1518 /// printFunction - Print all aspects of a function.
1520 void AssemblyWriter::printFunction(const Function *F) {
1521 // Print out the return type and name.
1524 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1526 if (F->isDeclaration())
1531 PrintLinkage(F->getLinkage(), Out);
1532 PrintVisibility(F->getVisibility(), Out);
1534 // Print the calling convention.
1535 switch (F->getCallingConv()) {
1536 case CallingConv::C: break; // default
1537 case CallingConv::Fast: Out << "fastcc "; break;
1538 case CallingConv::Cold: Out << "coldcc "; break;
1539 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1540 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1541 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1542 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1543 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1544 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1545 default: Out << "cc" << F->getCallingConv() << " "; break;
1548 const FunctionType *FT = F->getFunctionType();
1549 const AttrListPtr &Attrs = F->getAttributes();
1550 Attributes RetAttrs = Attrs.getRetAttributes();
1551 if (RetAttrs != Attribute::None)
1552 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1553 TypePrinter.print(F->getReturnType(), Out);
1555 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1557 Machine.incorporateFunction(F);
1559 // Loop over the arguments, printing them...
1562 if (!F->isDeclaration()) {
1563 // If this isn't a declaration, print the argument names as well.
1564 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1566 // Insert commas as we go... the first arg doesn't get a comma
1567 if (I != F->arg_begin()) Out << ", ";
1568 printArgument(I, Attrs.getParamAttributes(Idx));
1572 // Otherwise, print the types from the function type.
1573 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1574 // Insert commas as we go... the first arg doesn't get a comma
1578 TypePrinter.print(FT->getParamType(i), Out);
1580 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1581 if (ArgAttrs != Attribute::None)
1582 Out << ' ' << Attribute::getAsString(ArgAttrs);
1586 // Finish printing arguments...
1587 if (FT->isVarArg()) {
1588 if (FT->getNumParams()) Out << ", ";
1589 Out << "..."; // Output varargs portion of signature!
1592 Attributes FnAttrs = Attrs.getFnAttributes();
1593 if (FnAttrs != Attribute::None)
1594 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1595 if (F->hasSection())
1596 Out << " section \"" << F->getSection() << '"';
1597 if (F->getAlignment())
1598 Out << " align " << F->getAlignment();
1600 Out << " gc \"" << F->getGC() << '"';
1601 if (F->isDeclaration()) {
1606 // Output all of its basic blocks... for the function
1607 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1613 Machine.purgeFunction();
1616 /// printArgument - This member is called for every argument that is passed into
1617 /// the function. Simply print it out
1619 void AssemblyWriter::printArgument(const Argument *Arg,
1622 TypePrinter.print(Arg->getType(), Out);
1624 // Output parameter attributes list
1625 if (Attrs != Attribute::None)
1626 Out << ' ' << Attribute::getAsString(Attrs);
1628 // Output name, if available...
1629 if (Arg->hasName()) {
1631 PrintLLVMName(Out, Arg);
1635 /// printBasicBlock - This member is called for each basic block in a method.
1637 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1638 if (BB->hasName()) { // Print out the label if it exists...
1640 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1642 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1643 Out << "\n; <label>:";
1644 int Slot = Machine.getLocalSlot(BB);
1651 if (BB->getParent() == 0) {
1652 Out.PadToColumn(50);
1653 Out << "; Error: Block without parent!";
1654 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1655 // Output predecessors for the block...
1656 Out.PadToColumn(50);
1658 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1661 Out << " No predecessors!";
1664 writeOperand(*PI, false);
1665 for (++PI; PI != PE; ++PI) {
1667 writeOperand(*PI, false);
1674 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1676 // Output all of the instructions in the basic block...
1677 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1678 printInstruction(*I);
1682 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1686 /// printInfoComment - Print a little comment after the instruction indicating
1687 /// which slot it occupies.
1689 void AssemblyWriter::printInfoComment(const Value &V) {
1690 if (V.getType()->isVoidTy()) return;
1692 Out.PadToColumn(50);
1694 TypePrinter.print(V.getType(), Out);
1695 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1698 // This member is called for each Instruction in a function..
1699 void AssemblyWriter::printInstruction(const Instruction &I) {
1700 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1702 // Print out indentation for an instruction.
1705 // Print out name if it exists...
1707 PrintLLVMName(Out, &I);
1709 } else if (!I.getType()->isVoidTy()) {
1710 // Print out the def slot taken.
1711 int SlotNum = Machine.getLocalSlot(&I);
1713 Out << "<badref> = ";
1715 Out << '%' << SlotNum << " = ";
1718 // If this is a volatile load or store, print out the volatile marker.
1719 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1720 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1722 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1723 // If this is a call, check if it's a tail call.
1727 // Print out the opcode...
1728 Out << I.getOpcodeName();
1730 // Print out optimization information.
1731 WriteOptimizationInfo(Out, &I);
1733 // Print out the compare instruction predicates
1734 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1735 Out << ' ' << getPredicateText(CI->getPredicate());
1737 // Print out the type of the operands...
1738 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1740 // Special case conditional branches to swizzle the condition out to the front
1741 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1742 BranchInst &BI(cast<BranchInst>(I));
1744 writeOperand(BI.getCondition(), true);
1746 writeOperand(BI.getSuccessor(0), true);
1748 writeOperand(BI.getSuccessor(1), true);
1750 } else if (isa<SwitchInst>(I)) {
1751 // Special case switch instruction to get formatting nice and correct.
1753 writeOperand(Operand , true);
1755 writeOperand(I.getOperand(1), true);
1758 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1760 writeOperand(I.getOperand(op ), true);
1762 writeOperand(I.getOperand(op+1), true);
1765 } else if (isa<IndirectBrInst>(I)) {
1766 // Special case indirectbr instruction to get formatting nice and correct.
1768 writeOperand(Operand, true);
1771 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1774 writeOperand(I.getOperand(i), true);
1777 } else if (isa<PHINode>(I)) {
1779 TypePrinter.print(I.getType(), Out);
1782 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1783 if (op) Out << ", ";
1785 writeOperand(I.getOperand(op ), false); Out << ", ";
1786 writeOperand(I.getOperand(op+1), false); Out << " ]";
1788 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1790 writeOperand(I.getOperand(0), true);
1791 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1793 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1795 writeOperand(I.getOperand(0), true); Out << ", ";
1796 writeOperand(I.getOperand(1), true);
1797 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1799 } else if (isa<ReturnInst>(I) && !Operand) {
1801 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1802 // Print the calling convention being used.
1803 switch (CI->getCallingConv()) {
1804 case CallingConv::C: break; // default
1805 case CallingConv::Fast: Out << " fastcc"; break;
1806 case CallingConv::Cold: Out << " coldcc"; break;
1807 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1808 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1809 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1810 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1811 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1812 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1813 default: Out << " cc" << CI->getCallingConv(); break;
1816 const PointerType *PTy = cast<PointerType>(Operand->getType());
1817 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1818 const Type *RetTy = FTy->getReturnType();
1819 const AttrListPtr &PAL = CI->getAttributes();
1821 if (PAL.getRetAttributes() != Attribute::None)
1822 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1824 // If possible, print out the short form of the call instruction. We can
1825 // only do this if the first argument is a pointer to a nonvararg function,
1826 // and if the return type is not a pointer to a function.
1829 if (!FTy->isVarArg() &&
1830 (!isa<PointerType>(RetTy) ||
1831 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1832 TypePrinter.print(RetTy, Out);
1834 writeOperand(Operand, false);
1836 writeOperand(Operand, true);
1839 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1842 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1845 if (PAL.getFnAttributes() != Attribute::None)
1846 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1847 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1848 const PointerType *PTy = cast<PointerType>(Operand->getType());
1849 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1850 const Type *RetTy = FTy->getReturnType();
1851 const AttrListPtr &PAL = II->getAttributes();
1853 // Print the calling convention being used.
1854 switch (II->getCallingConv()) {
1855 case CallingConv::C: break; // default
1856 case CallingConv::Fast: Out << " fastcc"; break;
1857 case CallingConv::Cold: Out << " coldcc"; break;
1858 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1859 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1860 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1861 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1862 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1863 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1864 default: Out << " cc" << II->getCallingConv(); break;
1867 if (PAL.getRetAttributes() != Attribute::None)
1868 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1870 // If possible, print out the short form of the invoke instruction. We can
1871 // only do this if the first argument is a pointer to a nonvararg function,
1872 // and if the return type is not a pointer to a function.
1875 if (!FTy->isVarArg() &&
1876 (!isa<PointerType>(RetTy) ||
1877 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1878 TypePrinter.print(RetTy, Out);
1880 writeOperand(Operand, false);
1882 writeOperand(Operand, true);
1885 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1888 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1892 if (PAL.getFnAttributes() != Attribute::None)
1893 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1896 writeOperand(II->getNormalDest(), true);
1898 writeOperand(II->getUnwindDest(), true);
1900 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1902 TypePrinter.print(AI->getType()->getElementType(), Out);
1903 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1905 writeOperand(AI->getArraySize(), true);
1907 if (AI->getAlignment()) {
1908 Out << ", align " << AI->getAlignment();
1910 } else if (isa<CastInst>(I)) {
1913 writeOperand(Operand, true); // Work with broken code
1916 TypePrinter.print(I.getType(), Out);
1917 } else if (isa<VAArgInst>(I)) {
1920 writeOperand(Operand, true); // Work with broken code
1923 TypePrinter.print(I.getType(), Out);
1924 } else if (Operand) { // Print the normal way.
1926 // PrintAllTypes - Instructions who have operands of all the same type
1927 // omit the type from all but the first operand. If the instruction has
1928 // different type operands (for example br), then they are all printed.
1929 bool PrintAllTypes = false;
1930 const Type *TheType = Operand->getType();
1932 // Select, Store and ShuffleVector always print all types.
1933 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1934 || isa<ReturnInst>(I)) {
1935 PrintAllTypes = true;
1937 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1938 Operand = I.getOperand(i);
1939 // note that Operand shouldn't be null, but the test helps make dump()
1940 // more tolerant of malformed IR
1941 if (Operand && Operand->getType() != TheType) {
1942 PrintAllTypes = true; // We have differing types! Print them all!
1948 if (!PrintAllTypes) {
1950 TypePrinter.print(TheType, Out);
1954 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1956 writeOperand(I.getOperand(i), PrintAllTypes);
1960 // Print post operand alignment for load/store.
1961 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1962 Out << ", align " << cast<LoadInst>(I).getAlignment();
1963 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1964 Out << ", align " << cast<StoreInst>(I).getAlignment();
1967 // Print Metadata info.
1968 if (!MDNames.empty()) {
1969 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1970 I.getAllMetadata(InstMD);
1971 for (unsigned i = 0, e = InstMD.size(); i != e; ++i)
1972 Out << ", !" << MDNames[InstMD[i].first]
1973 << " !" << Machine.getMetadataSlot(InstMD[i].second);
1975 printInfoComment(I);
1978 static void WriteMDNodeComment(const MDNode *Node,
1979 formatted_raw_ostream &Out) {
1980 if (Node->getNumOperands() < 1)
1982 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1984 unsigned Val = CI->getZExtValue();
1985 unsigned Tag = Val & ~LLVMDebugVersionMask;
1986 if (Val < LLVMDebugVersion)
1989 Out.PadToColumn(50);
1990 if (Tag == dwarf::DW_TAG_auto_variable)
1991 Out << "; [ DW_TAG_auto_variable ]";
1992 else if (Tag == dwarf::DW_TAG_arg_variable)
1993 Out << "; [ DW_TAG_arg_variable ]";
1994 else if (Tag == dwarf::DW_TAG_return_variable)
1995 Out << "; [ DW_TAG_return_variable ]";
1996 else if (Tag == dwarf::DW_TAG_vector_type)
1997 Out << "; [ DW_TAG_vector_type ]";
1998 else if (Tag == dwarf::DW_TAG_user_base)
1999 Out << "; [ DW_TAG_user_base ]";
2000 else if (const char *TagName = dwarf::TagString(Tag))
2001 Out << "; [ " << TagName << " ]";
2004 void AssemblyWriter::writeAllMDNodes() {
2005 SmallVector<const MDNode *, 16> Nodes;
2006 Nodes.resize(Machine.mdnSize());
2007 for (SlotTracker::ValueMap::iterator I =
2008 Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I)
2009 Nodes[I->second] = cast<MDNode>(I->first);
2011 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2012 Out << '!' << i << " = metadata ";
2013 const MDNode *Node = Nodes[i];
2014 printMDNodeBody(Node);
2018 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2020 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
2021 const Value *V = Node->getOperand(mi);
2024 else if (const MDNode *N = dyn_cast<MDNode>(V)) {
2025 Out << "metadata !" << Machine.getMetadataSlot(N);
2027 TypePrinter.print(V->getType(), Out);
2029 WriteAsOperandInternal(Out, Node->getOperand(mi),
2030 &TypePrinter, &Machine);
2037 WriteMDNodeComment(Node, Out);
2041 //===----------------------------------------------------------------------===//
2042 // External Interface declarations
2043 //===----------------------------------------------------------------------===//
2045 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2046 SlotTracker SlotTable(this);
2047 formatted_raw_ostream OS(ROS);
2048 AssemblyWriter W(OS, SlotTable, this, AAW);
2052 void Type::print(raw_ostream &OS) const {
2054 OS << "<null Type>";
2057 TypePrinting().print(this, OS);
2060 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2062 ROS << "printing a <null> value\n";
2065 formatted_raw_ostream OS(ROS);
2066 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2067 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2068 SlotTracker SlotTable(F);
2069 AssemblyWriter W(OS, SlotTable, getModuleFromVal(F), AAW);
2071 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2072 SlotTracker SlotTable(BB->getParent());
2073 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2075 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2076 SlotTracker SlotTable(GV->getParent());
2077 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2079 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2080 SlotTracker SlotTable((Function*)0);
2081 AssemblyWriter W(OS, SlotTable, 0, AAW);
2082 W.printMDNodeBody(N);
2083 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2084 SlotTracker SlotTable(N->getParent());
2085 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2086 W.printNamedMDNode(N);
2087 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2088 TypePrinting TypePrinter;
2089 TypePrinter.print(C->getType(), OS);
2091 WriteConstantInt(OS, C, TypePrinter, 0);
2092 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2093 isa<Argument>(this)) {
2094 WriteAsOperand(OS, this, true, 0);
2096 // Otherwise we don't know what it is. Call the virtual function to
2097 // allow a subclass to print itself.
2102 // Value::printCustom - subclasses should override this to implement printing.
2103 void Value::printCustom(raw_ostream &OS) const {
2104 llvm_unreachable("Unknown value to print out!");
2107 // Value::dump - allow easy printing of Values from the debugger.
2108 void Value::dump() const { print(errs()); errs() << '\n'; }
2110 // Type::dump - allow easy printing of Types from the debugger.
2111 // This one uses type names from the given context module
2112 void Type::dump(const Module *Context) const {
2113 WriteTypeSymbolic(errs(), this, Context);
2117 // Type::dump - allow easy printing of Types from the debugger.
2118 void Type::dump() const { dump(0); }
2120 // Module::dump() - Allow printing of Modules from the debugger.
2121 void Module::dump() const { print(errs(), 0); }