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/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Operator.h"
27 #include "llvm/MDNode.h"
28 #include "llvm/Module.h"
29 #include "llvm/ValueSymbolTable.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Streams.h"
38 #include "llvm/Support/raw_ostream.h"
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast<Argument>(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
55 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
58 if (const Instruction *I = dyn_cast<Instruction>(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
63 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return GV->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 char *Str, unsigned Length,
72 for (unsigned i = 0; i != Length; ++i) {
73 unsigned char C = Str[i];
74 if (isprint(C) && C != '\\' && C != '"')
77 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
81 // PrintEscapedString - Print each character of the specified string, escaping
82 // it if it is not printable or if it is an escape char.
83 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
84 PrintEscapedString(Str.c_str(), Str.size(), Out);
94 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
95 /// prefixed with % (if the string only contains simple characters) or is
96 /// surrounded with ""'s (if it has special chars in it). Print it out.
97 static void PrintLLVMName(raw_ostream &OS, const char *NameStr,
98 unsigned NameLen, PrefixType Prefix) {
99 assert(NameStr && "Cannot get empty name!");
101 default: llvm_unreachable("Bad prefix!");
102 case NoPrefix: break;
103 case GlobalPrefix: OS << '@'; break;
104 case LabelPrefix: break;
105 case LocalPrefix: OS << '%'; break;
108 // Scan the name to see if it needs quotes first.
109 bool NeedsQuotes = isdigit(NameStr[0]);
111 for (unsigned i = 0; i != NameLen; ++i) {
113 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
120 // If we didn't need any quotes, just write out the name in one blast.
122 OS.write(NameStr, NameLen);
126 // Okay, we need quotes. Output the quotes and escape any scary characters as
129 PrintEscapedString(NameStr, NameLen, OS);
133 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
134 /// prefixed with % (if the string only contains simple characters) or is
135 /// surrounded with ""'s (if it has special chars in it). Print it out.
136 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
137 PrintLLVMName(OS, V->getNameStart(), V->getNameLen(),
138 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
141 //===----------------------------------------------------------------------===//
142 // TypePrinting Class: Type printing machinery
143 //===----------------------------------------------------------------------===//
145 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
146 return *static_cast<DenseMap<const Type *, std::string>*>(M);
149 void TypePrinting::clear() {
150 getTypeNamesMap(TypeNames).clear();
153 bool TypePrinting::hasTypeName(const Type *Ty) const {
154 return getTypeNamesMap(TypeNames).count(Ty);
157 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
158 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
162 TypePrinting::TypePrinting() {
163 TypeNames = new DenseMap<const Type *, std::string>();
166 TypePrinting::~TypePrinting() {
167 delete &getTypeNamesMap(TypeNames);
170 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
171 /// use of type names or up references to shorten the type name where possible.
172 void TypePrinting::CalcTypeName(const Type *Ty,
173 SmallVectorImpl<const Type *> &TypeStack,
174 raw_ostream &OS, bool IgnoreTopLevelName) {
175 // Check to see if the type is named.
176 if (!IgnoreTopLevelName) {
177 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
178 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
185 // Check to see if the Type is already on the stack...
186 unsigned Slot = 0, CurSize = TypeStack.size();
187 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
189 // This is another base case for the recursion. In this case, we know
190 // that we have looped back to a type that we have previously visited.
191 // Generate the appropriate upreference to handle this.
192 if (Slot < CurSize) {
193 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
197 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
199 switch (Ty->getTypeID()) {
200 case Type::VoidTyID: OS << "void"; break;
201 case Type::FloatTyID: OS << "float"; break;
202 case Type::DoubleTyID: OS << "double"; break;
203 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
204 case Type::FP128TyID: OS << "fp128"; break;
205 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
206 case Type::LabelTyID: OS << "label"; break;
207 case Type::MetadataTyID: OS << "metadata"; break;
208 case Type::IntegerTyID:
209 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
212 case Type::FunctionTyID: {
213 const FunctionType *FTy = cast<FunctionType>(Ty);
214 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
216 for (FunctionType::param_iterator I = FTy->param_begin(),
217 E = FTy->param_end(); I != E; ++I) {
218 if (I != FTy->param_begin())
220 CalcTypeName(*I, TypeStack, OS);
222 if (FTy->isVarArg()) {
223 if (FTy->getNumParams()) OS << ", ";
229 case Type::StructTyID: {
230 const StructType *STy = cast<StructType>(Ty);
234 for (StructType::element_iterator I = STy->element_begin(),
235 E = STy->element_end(); I != E; ++I) {
236 CalcTypeName(*I, TypeStack, OS);
237 if (next(I) != STy->element_end())
246 case Type::PointerTyID: {
247 const PointerType *PTy = cast<PointerType>(Ty);
248 CalcTypeName(PTy->getElementType(), TypeStack, OS);
249 if (unsigned AddressSpace = PTy->getAddressSpace())
250 OS << " addrspace(" << AddressSpace << ')';
254 case Type::ArrayTyID: {
255 const ArrayType *ATy = cast<ArrayType>(Ty);
256 OS << '[' << ATy->getNumElements() << " x ";
257 CalcTypeName(ATy->getElementType(), TypeStack, OS);
261 case Type::VectorTyID: {
262 const VectorType *PTy = cast<VectorType>(Ty);
263 OS << "<" << PTy->getNumElements() << " x ";
264 CalcTypeName(PTy->getElementType(), TypeStack, OS);
268 case Type::OpaqueTyID:
272 OS << "<unrecognized-type>";
276 TypeStack.pop_back(); // Remove self from stack.
279 /// printTypeInt - The internal guts of printing out a type that has a
280 /// potentially named portion.
282 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
283 bool IgnoreTopLevelName) {
284 // Check to see if the type is named.
285 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
286 if (!IgnoreTopLevelName) {
287 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
294 // Otherwise we have a type that has not been named but is a derived type.
295 // Carefully recurse the type hierarchy to print out any contained symbolic
297 SmallVector<const Type *, 16> TypeStack;
298 std::string TypeName;
300 raw_string_ostream TypeOS(TypeName);
301 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
304 // Cache type name for later use.
305 if (!IgnoreTopLevelName)
306 TM.insert(std::make_pair(Ty, TypeOS.str()));
311 // To avoid walking constant expressions multiple times and other IR
312 // objects, we keep several helper maps.
313 DenseSet<const Value*> VisitedConstants;
314 DenseSet<const Type*> VisitedTypes;
317 std::vector<const Type*> &NumberedTypes;
319 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
320 : TP(tp), NumberedTypes(numberedTypes) {}
322 void Run(const Module &M) {
323 // Get types from the type symbol table. This gets opaque types referened
324 // only through derived named types.
325 const TypeSymbolTable &ST = M.getTypeSymbolTable();
326 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
328 IncorporateType(TI->second);
330 // Get types from global variables.
331 for (Module::const_global_iterator I = M.global_begin(),
332 E = M.global_end(); I != E; ++I) {
333 IncorporateType(I->getType());
334 if (I->hasInitializer())
335 IncorporateValue(I->getInitializer());
338 // Get types from aliases.
339 for (Module::const_alias_iterator I = M.alias_begin(),
340 E = M.alias_end(); I != E; ++I) {
341 IncorporateType(I->getType());
342 IncorporateValue(I->getAliasee());
345 // Get types from functions.
346 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
347 IncorporateType(FI->getType());
349 for (Function::const_iterator BB = FI->begin(), E = FI->end();
351 for (BasicBlock::const_iterator II = BB->begin(),
352 E = BB->end(); II != E; ++II) {
353 const Instruction &I = *II;
354 // Incorporate the type of the instruction and all its operands.
355 IncorporateType(I.getType());
356 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
358 IncorporateValue(*OI);
364 void IncorporateType(const Type *Ty) {
365 // Check to see if we're already visited this type.
366 if (!VisitedTypes.insert(Ty).second)
369 // If this is a structure or opaque type, add a name for the type.
370 if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
371 || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
372 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
373 NumberedTypes.push_back(Ty);
376 // Recursively walk all contained types.
377 for (Type::subtype_iterator I = Ty->subtype_begin(),
378 E = Ty->subtype_end(); I != E; ++I)
382 /// IncorporateValue - This method is used to walk operand lists finding
383 /// types hiding in constant expressions and other operands that won't be
384 /// walked in other ways. GlobalValues, basic blocks, instructions, and
385 /// inst operands are all explicitly enumerated.
386 void IncorporateValue(const Value *V) {
387 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
390 if (!VisitedConstants.insert(V).second)
394 IncorporateType(V->getType());
396 // Look in operands for types.
397 const Constant *C = cast<Constant>(V);
398 for (Constant::const_op_iterator I = C->op_begin(),
399 E = C->op_end(); I != E;++I)
400 IncorporateValue(*I);
403 } // end anonymous namespace
406 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
407 /// the specified module to the TypePrinter and all numbered types to it and the
408 /// NumberedTypes table.
409 static void AddModuleTypesToPrinter(TypePrinting &TP,
410 std::vector<const Type*> &NumberedTypes,
414 // If the module has a symbol table, take all global types and stuff their
415 // names into the TypeNames map.
416 const TypeSymbolTable &ST = M->getTypeSymbolTable();
417 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
419 const Type *Ty = cast<Type>(TI->second);
421 // As a heuristic, don't insert pointer to primitive types, because
422 // they are used too often to have a single useful name.
423 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
424 const Type *PETy = PTy->getElementType();
425 if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
426 !isa<OpaqueType>(PETy))
430 // Likewise don't insert primitives either.
431 if (Ty->isInteger() || Ty->isPrimitiveType())
434 // Get the name as a string and insert it into TypeNames.
436 raw_string_ostream NameOS(NameStr);
437 PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
438 TP.addTypeName(Ty, NameOS.str());
441 // Walk the entire module to find references to unnamed structure and opaque
442 // types. This is required for correctness by opaque types (because multiple
443 // uses of an unnamed opaque type needs to be referred to by the same ID) and
444 // it shrinks complex recursive structure types substantially in some cases.
445 TypeFinder(TP, NumberedTypes).Run(*M);
449 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
450 /// type, iff there is an entry in the modules symbol table for the specified
451 /// type or one of it's component types.
453 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
454 TypePrinting Printer;
455 std::vector<const Type*> NumberedTypes;
456 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
457 Printer.print(Ty, OS);
460 //===----------------------------------------------------------------------===//
461 // SlotTracker Class: Enumerate slot numbers for unnamed values
462 //===----------------------------------------------------------------------===//
466 /// This class provides computation of slot numbers for LLVM Assembly writing.
470 /// ValueMap - A mapping of Values to slot numbers.
471 typedef DenseMap<const Value*, unsigned> ValueMap;
474 /// TheModule - The module for which we are holding slot numbers.
475 const Module* TheModule;
477 /// TheFunction - The function for which we are holding slot numbers.
478 const Function* TheFunction;
479 bool FunctionProcessed;
481 /// TheMDNode - The MDNode for which we are holding slot numbers.
482 const MDNode *TheMDNode;
484 /// mMap - The TypePlanes map for the module level data.
488 /// fMap - The TypePlanes map for the function level data.
492 /// mdnMap - Map for MDNodes.
496 /// Construct from a module
497 explicit SlotTracker(const Module *M);
498 /// Construct from a function, starting out in incorp state.
499 explicit SlotTracker(const Function *F);
500 /// Construct from a mdnode.
501 explicit SlotTracker(const MDNode *N);
503 /// Return the slot number of the specified value in it's type
504 /// plane. If something is not in the SlotTracker, return -1.
505 int getLocalSlot(const Value *V);
506 int getGlobalSlot(const GlobalValue *V);
507 int getMetadataSlot(const MDNode *N);
509 /// If you'd like to deal with a function instead of just a module, use
510 /// this method to get its data into the SlotTracker.
511 void incorporateFunction(const Function *F) {
513 FunctionProcessed = false;
516 /// After calling incorporateFunction, use this method to remove the
517 /// most recently incorporated function from the SlotTracker. This
518 /// will reset the state of the machine back to just the module contents.
519 void purgeFunction();
521 /// MDNode map iterators.
522 ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
523 ValueMap::iterator mdnEnd() { return mdnMap.end(); }
524 unsigned mdnSize() { return mdnMap.size(); }
526 /// This function does the actual initialization.
527 inline void initialize();
529 // Implementation Details
531 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
532 void CreateModuleSlot(const GlobalValue *V);
534 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
535 void CreateMetadataSlot(const MDNode *N);
537 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
538 void CreateFunctionSlot(const Value *V);
540 /// Add all of the module level global variables (and their initializers)
541 /// and function declarations, but not the contents of those functions.
542 void processModule();
544 /// Add all of the functions arguments, basic blocks, and instructions.
545 void processFunction();
547 /// Add all MDNode operands.
548 void processMDNode();
550 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
551 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
554 } // end anonymous namespace
557 static SlotTracker *createSlotTracker(const Value *V) {
558 if (const Argument *FA = dyn_cast<Argument>(V))
559 return new SlotTracker(FA->getParent());
561 if (const Instruction *I = dyn_cast<Instruction>(V))
562 return new SlotTracker(I->getParent()->getParent());
564 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
565 return new SlotTracker(BB->getParent());
567 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
568 return new SlotTracker(GV->getParent());
570 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
571 return new SlotTracker(GA->getParent());
573 if (const Function *Func = dyn_cast<Function>(V))
574 return new SlotTracker(Func);
580 #define ST_DEBUG(X) cerr << X
585 // Module level constructor. Causes the contents of the Module (sans functions)
586 // to be added to the slot table.
587 SlotTracker::SlotTracker(const Module *M)
588 : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
589 mNext(0), fNext(0), mdnNext(0) {
592 // Function level constructor. Causes the contents of the Module and the one
593 // function provided to be added to the slot table.
594 SlotTracker::SlotTracker(const Function *F)
595 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
596 TheMDNode(0), mNext(0), fNext(0) {
599 // Constructor to handle single MDNode.
600 SlotTracker::SlotTracker(const MDNode *C)
601 : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C),
602 mNext(0), fNext(0), mdnNext(0) {
605 inline void SlotTracker::initialize() {
608 TheModule = 0; ///< Prevent re-processing next time we're called.
611 if (TheFunction && !FunctionProcessed)
618 // Iterate through all the global variables, functions, and global
619 // variable initializers and create slots for them.
620 void SlotTracker::processModule() {
621 ST_DEBUG("begin processModule!\n");
623 // Add all of the unnamed global variables to the value table.
624 for (Module::const_global_iterator I = TheModule->global_begin(),
625 E = TheModule->global_end(); I != E; ++I) {
628 if (I->hasInitializer()) {
629 if (MDNode *N = dyn_cast<MDNode>(I->getInitializer()))
630 CreateMetadataSlot(N);
634 // Add all the unnamed functions to the table.
635 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
640 ST_DEBUG("end processModule!\n");
643 // Process the arguments, basic blocks, and instructions of a function.
644 void SlotTracker::processFunction() {
645 ST_DEBUG("begin processFunction!\n");
648 // Add all the function arguments with no names.
649 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
650 AE = TheFunction->arg_end(); AI != AE; ++AI)
652 CreateFunctionSlot(AI);
654 ST_DEBUG("Inserting Instructions:\n");
656 // Add all of the basic blocks and instructions with no names.
657 for (Function::const_iterator BB = TheFunction->begin(),
658 E = TheFunction->end(); BB != E; ++BB) {
660 CreateFunctionSlot(BB);
661 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
663 if (I->getType() != Type::VoidTy && !I->hasName())
664 CreateFunctionSlot(I);
665 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
666 if (MDNode *N = dyn_cast<MDNode>(I->getOperand(i)))
667 CreateMetadataSlot(N);
671 FunctionProcessed = true;
673 ST_DEBUG("end processFunction!\n");
676 /// processMDNode - Process TheMDNode.
677 void SlotTracker::processMDNode() {
678 ST_DEBUG("begin processMDNode!\n");
680 CreateMetadataSlot(TheMDNode);
682 ST_DEBUG("end processMDNode!\n");
685 /// Clean up after incorporating a function. This is the only way to get out of
686 /// the function incorporation state that affects get*Slot/Create*Slot. Function
687 /// incorporation state is indicated by TheFunction != 0.
688 void SlotTracker::purgeFunction() {
689 ST_DEBUG("begin purgeFunction!\n");
690 fMap.clear(); // Simply discard the function level map
692 FunctionProcessed = false;
693 ST_DEBUG("end purgeFunction!\n");
696 /// getGlobalSlot - Get the slot number of a global value.
697 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
698 // Check for uninitialized state and do lazy initialization.
701 // Find the type plane in the module map
702 ValueMap::iterator MI = mMap.find(V);
703 return MI == mMap.end() ? -1 : (int)MI->second;
706 /// getGlobalSlot - Get the slot number of a MDNode.
707 int SlotTracker::getMetadataSlot(const MDNode *N) {
708 // Check for uninitialized state and do lazy initialization.
711 // Find the type plane in the module map
712 ValueMap::iterator MI = mdnMap.find(N);
713 return MI == mdnMap.end() ? -1 : (int)MI->second;
717 /// getLocalSlot - Get the slot number for a value that is local to a function.
718 int SlotTracker::getLocalSlot(const Value *V) {
719 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
721 // Check for uninitialized state and do lazy initialization.
724 ValueMap::iterator FI = fMap.find(V);
725 return FI == fMap.end() ? -1 : (int)FI->second;
729 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
730 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
731 assert(V && "Can't insert a null Value into SlotTracker!");
732 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
733 assert(!V->hasName() && "Doesn't need a slot!");
735 unsigned DestSlot = mNext++;
738 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
740 // G = Global, F = Function, A = Alias, o = other
741 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
742 (isa<Function>(V) ? 'F' :
743 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
746 /// CreateSlot - Create a new slot for the specified value if it has no name.
747 void SlotTracker::CreateFunctionSlot(const Value *V) {
748 assert(V->getType() != Type::VoidTy && !V->hasName() &&
749 "Doesn't need a slot!");
751 unsigned DestSlot = fNext++;
754 // G = Global, F = Function, o = other
755 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
756 DestSlot << " [o]\n");
759 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
760 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
761 assert(N && "Can't insert a null Value into SlotTracker!");
763 ValueMap::iterator I = mdnMap.find(N);
764 if (I != mdnMap.end())
767 unsigned DestSlot = mdnNext++;
768 mdnMap[N] = DestSlot;
770 for (MDNode::const_elem_iterator MDI = N->elem_begin(),
771 MDE = N->elem_end(); MDI != MDE; ++MDI) {
772 const Value *TV = *MDI;
774 if (const MDNode *N2 = dyn_cast<MDNode>(TV))
775 CreateMetadataSlot(N2);
779 //===----------------------------------------------------------------------===//
780 // AsmWriter Implementation
781 //===----------------------------------------------------------------------===//
783 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
784 TypePrinting &TypePrinter,
785 SlotTracker *Machine);
789 static const char *getPredicateText(unsigned predicate) {
790 const char * pred = "unknown";
792 case FCmpInst::FCMP_FALSE: pred = "false"; break;
793 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
794 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
795 case FCmpInst::FCMP_OGE: pred = "oge"; break;
796 case FCmpInst::FCMP_OLT: pred = "olt"; break;
797 case FCmpInst::FCMP_OLE: pred = "ole"; break;
798 case FCmpInst::FCMP_ONE: pred = "one"; break;
799 case FCmpInst::FCMP_ORD: pred = "ord"; break;
800 case FCmpInst::FCMP_UNO: pred = "uno"; break;
801 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
802 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
803 case FCmpInst::FCMP_UGE: pred = "uge"; break;
804 case FCmpInst::FCMP_ULT: pred = "ult"; break;
805 case FCmpInst::FCMP_ULE: pred = "ule"; break;
806 case FCmpInst::FCMP_UNE: pred = "une"; break;
807 case FCmpInst::FCMP_TRUE: pred = "true"; break;
808 case ICmpInst::ICMP_EQ: pred = "eq"; break;
809 case ICmpInst::ICMP_NE: pred = "ne"; break;
810 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
811 case ICmpInst::ICMP_SGE: pred = "sge"; break;
812 case ICmpInst::ICMP_SLT: pred = "slt"; break;
813 case ICmpInst::ICMP_SLE: pred = "sle"; break;
814 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
815 case ICmpInst::ICMP_UGE: pred = "uge"; break;
816 case ICmpInst::ICMP_ULT: pred = "ult"; break;
817 case ICmpInst::ICMP_ULE: pred = "ule"; break;
822 static void WriteMDNodes(raw_ostream &Out, TypePrinting &TypePrinter,
823 SlotTracker &Machine) {
824 SmallVector<const MDNode *, 16> Nodes;
825 Nodes.resize(Machine.mdnSize());
826 for (SlotTracker::ValueMap::iterator I =
827 Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I)
828 Nodes[I->second] = cast<MDNode>(I->first);
830 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
831 Out << '!' << i << " = metadata ";
832 const MDNode *Node = Nodes[i];
834 for (MDNode::const_elem_iterator NI = Node->elem_begin(),
835 NE = Node->elem_end(); NI != NE;) {
836 const Value *V = *NI;
839 else if (const MDNode *N = dyn_cast<MDNode>(V)) {
841 Out << '!' << Machine.getMetadataSlot(N);
844 TypePrinter.print((*NI)->getType(), Out);
846 WriteAsOperandInternal(Out, *NI, TypePrinter, &Machine);
855 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
856 if (const OverflowingBinaryOperator *OBO =
857 dyn_cast<OverflowingBinaryOperator>(U)) {
858 if (OBO->hasNoUnsignedOverflow())
860 if (OBO->hasNoSignedOverflow())
862 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
868 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
869 TypePrinting &TypePrinter, SlotTracker *Machine) {
870 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
871 if (CI->getType() == Type::Int1Ty) {
872 Out << (CI->getZExtValue() ? "true" : "false");
875 Out << CI->getValue();
879 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
880 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
881 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
882 // We would like to output the FP constant value in exponential notation,
883 // but we cannot do this if doing so will lose precision. Check here to
884 // make sure that we only output it in exponential format if we can parse
885 // the value back and get the same value.
888 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
889 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
890 CFP->getValueAPF().convertToFloat();
891 std::string StrVal = ftostr(CFP->getValueAPF());
893 // Check to make sure that the stringized number is not some string like
894 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
895 // that the string matches the "[-+]?[0-9]" regex.
897 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
898 ((StrVal[0] == '-' || StrVal[0] == '+') &&
899 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
900 // Reparse stringized version!
901 if (atof(StrVal.c_str()) == Val) {
906 // Otherwise we could not reparse it to exactly the same value, so we must
907 // output the string in hexadecimal format! Note that loading and storing
908 // floating point types changes the bits of NaNs on some hosts, notably
909 // x86, so we must not use these types.
910 assert(sizeof(double) == sizeof(uint64_t) &&
911 "assuming that double is 64 bits!");
913 APFloat apf = CFP->getValueAPF();
914 // Floats are represented in ASCII IR as double, convert.
916 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
919 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
924 // Some form of long double. These appear as a magic letter identifying
925 // the type, then a fixed number of hex digits.
927 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
929 // api needed to prevent premature destruction
930 APInt api = CFP->getValueAPF().bitcastToAPInt();
931 const uint64_t* p = api.getRawData();
932 uint64_t word = p[1];
934 int width = api.getBitWidth();
935 for (int j=0; j<width; j+=4, shiftcount-=4) {
936 unsigned int nibble = (word>>shiftcount) & 15;
938 Out << (unsigned char)(nibble + '0');
940 Out << (unsigned char)(nibble - 10 + 'A');
941 if (shiftcount == 0 && j+4 < width) {
945 shiftcount = width-j-4;
949 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
951 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
954 llvm_unreachable("Unsupported floating point type");
955 // api needed to prevent premature destruction
956 APInt api = CFP->getValueAPF().bitcastToAPInt();
957 const uint64_t* p = api.getRawData();
960 int width = api.getBitWidth();
961 for (int j=0; j<width; j+=4, shiftcount-=4) {
962 unsigned int nibble = (word>>shiftcount) & 15;
964 Out << (unsigned char)(nibble + '0');
966 Out << (unsigned char)(nibble - 10 + 'A');
967 if (shiftcount == 0 && j+4 < width) {
971 shiftcount = width-j-4;
977 if (isa<ConstantAggregateZero>(CV)) {
978 Out << "zeroinitializer";
982 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
983 // As a special case, print the array as a string if it is an array of
984 // i8 with ConstantInt values.
986 const Type *ETy = CA->getType()->getElementType();
987 if (CA->isString()) {
989 PrintEscapedString(CA->getAsString(), Out);
991 } else { // Cannot output in string format...
993 if (CA->getNumOperands()) {
994 TypePrinter.print(ETy, Out);
996 WriteAsOperandInternal(Out, CA->getOperand(0),
997 TypePrinter, Machine);
998 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1000 TypePrinter.print(ETy, Out);
1002 WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
1010 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1011 if (CS->getType()->isPacked())
1014 unsigned N = CS->getNumOperands();
1017 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1020 WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
1022 for (unsigned i = 1; i < N; i++) {
1024 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1027 WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
1033 if (CS->getType()->isPacked())
1038 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1039 const Type *ETy = CP->getType()->getElementType();
1040 assert(CP->getNumOperands() > 0 &&
1041 "Number of operands for a PackedConst must be > 0");
1043 TypePrinter.print(ETy, Out);
1045 WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
1046 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1048 TypePrinter.print(ETy, Out);
1050 WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
1056 if (isa<ConstantPointerNull>(CV)) {
1061 if (isa<UndefValue>(CV)) {
1066 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1067 Out << "!" << Machine->getMetadataSlot(Node);
1071 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1072 WriteOptimizationInfo(Out, CE);
1073 Out << CE->getOpcodeName();
1074 if (CE->isCompare())
1075 Out << ' ' << getPredicateText(CE->getPredicate());
1078 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1079 TypePrinter.print((*OI)->getType(), Out);
1081 WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
1082 if (OI+1 != CE->op_end())
1086 if (CE->hasIndices()) {
1087 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1088 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1089 Out << ", " << Indices[i];
1094 TypePrinter.print(CE->getType(), Out);
1101 Out << "<placeholder or erroneous Constant>";
1105 /// WriteAsOperand - Write the name of the specified value out to the specified
1106 /// ostream. This can be useful when you just want to print int %reg126, not
1107 /// the whole instruction that generated it.
1109 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1110 TypePrinting &TypePrinter,
1111 SlotTracker *Machine) {
1113 PrintLLVMName(Out, V);
1117 const Constant *CV = dyn_cast<Constant>(V);
1118 if (CV && !isa<GlobalValue>(CV)) {
1119 WriteConstantInt(Out, CV, TypePrinter, Machine);
1123 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1125 if (IA->hasSideEffects())
1126 Out << "sideeffect ";
1128 PrintEscapedString(IA->getAsmString(), Out);
1130 PrintEscapedString(IA->getConstraintString(), Out);
1135 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1136 Out << '!' << Machine->getMetadataSlot(N);
1140 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1142 PrintEscapedString(MDS->begin(), MDS->length(), Out);
1150 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1151 Slot = Machine->getGlobalSlot(GV);
1154 Slot = Machine->getLocalSlot(V);
1157 Machine = createSlotTracker(V);
1159 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1160 Slot = Machine->getGlobalSlot(GV);
1163 Slot = Machine->getLocalSlot(V);
1172 Out << Prefix << Slot;
1177 /// WriteAsOperand - Write the name of the specified value out to the specified
1178 /// ostream. This can be useful when you just want to print int %reg126, not
1179 /// the whole instruction that generated it.
1181 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1182 const Module *Context) {
1183 raw_os_ostream OS(Out);
1184 WriteAsOperand(OS, V, PrintType, Context);
1187 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1188 const Module *Context) {
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);
1205 class AssemblyWriter {
1207 SlotTracker &Machine;
1208 const Module *TheModule;
1209 TypePrinting TypePrinter;
1210 AssemblyAnnotationWriter *AnnotationWriter;
1211 std::vector<const Type*> NumberedTypes;
1213 // Each MDNode is assigned unique MetadataIDNo.
1214 std::map<const MDNode *, unsigned> MDNodes;
1215 unsigned MetadataIDNo;
1217 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1218 AssemblyAnnotationWriter *AAW)
1219 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1220 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1223 void write(const Module *M) { printModule(M); }
1225 void write(const GlobalValue *G) {
1226 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1228 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1230 else if (const Function *F = dyn_cast<Function>(G))
1233 llvm_unreachable("Unknown global");
1236 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1237 void write(const Instruction *I) { printInstruction(*I); }
1239 void writeOperand(const Value *Op, bool PrintType);
1240 void writeParamOperand(const Value *Operand, Attributes Attrs);
1242 const Module* getModule() { return TheModule; }
1245 void printModule(const Module *M);
1246 void printTypeSymbolTable(const TypeSymbolTable &ST);
1247 void printGlobal(const GlobalVariable *GV);
1248 void printAlias(const GlobalAlias *GV);
1249 void printFunction(const Function *F);
1250 void printArgument(const Argument *FA, Attributes Attrs);
1251 void printBasicBlock(const BasicBlock *BB);
1252 void printInstruction(const Instruction &I);
1254 // printInfoComment - Print a little comment after the instruction indicating
1255 // which slot it occupies.
1256 void printInfoComment(const Value &V);
1258 } // end of anonymous namespace
1261 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1263 Out << "<null operand!>";
1266 TypePrinter.print(Operand->getType(), Out);
1269 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1273 void AssemblyWriter::writeParamOperand(const Value *Operand,
1276 Out << "<null operand!>";
1279 TypePrinter.print(Operand->getType(), Out);
1280 // Print parameter attributes list
1281 if (Attrs != Attribute::None)
1282 Out << ' ' << Attribute::getAsString(Attrs);
1284 // Print the operand
1285 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1289 void AssemblyWriter::printModule(const Module *M) {
1290 if (!M->getModuleIdentifier().empty() &&
1291 // Don't print the ID if it will start a new line (which would
1292 // require a comment char before it).
1293 M->getModuleIdentifier().find('\n') == std::string::npos)
1294 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1296 if (!M->getDataLayout().empty())
1297 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1298 if (!M->getTargetTriple().empty())
1299 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1301 if (!M->getModuleInlineAsm().empty()) {
1302 // Split the string into lines, to make it easier to read the .ll file.
1303 std::string Asm = M->getModuleInlineAsm();
1305 size_t NewLine = Asm.find_first_of('\n', CurPos);
1306 while (NewLine != std::string::npos) {
1307 // We found a newline, print the portion of the asm string from the
1308 // last newline up to this newline.
1309 Out << "module asm \"";
1310 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1314 NewLine = Asm.find_first_of('\n', CurPos);
1316 Out << "module asm \"";
1317 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1321 // Loop over the dependent libraries and emit them.
1322 Module::lib_iterator LI = M->lib_begin();
1323 Module::lib_iterator LE = M->lib_end();
1325 Out << "deplibs = [ ";
1327 Out << '"' << *LI << '"';
1335 // Loop over the symbol table, emitting all id'd types.
1336 printTypeSymbolTable(M->getTypeSymbolTable());
1338 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1342 // Output all aliases.
1343 if (!M->alias_empty()) Out << "\n";
1344 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1348 // Output all of the functions.
1349 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1352 WriteMDNodes(Out, TypePrinter, Machine);
1355 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1357 case GlobalValue::ExternalLinkage: break;
1358 case GlobalValue::PrivateLinkage: Out << "private "; break;
1359 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1360 case GlobalValue::InternalLinkage: Out << "internal "; break;
1361 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1362 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1363 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1364 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1365 case GlobalValue::CommonLinkage: Out << "common "; break;
1366 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1367 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1368 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1369 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1370 case GlobalValue::AvailableExternallyLinkage:
1371 Out << "available_externally ";
1373 case GlobalValue::GhostLinkage:
1374 llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1379 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1382 default: llvm_unreachable("Invalid visibility style!");
1383 case GlobalValue::DefaultVisibility: break;
1384 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1385 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1389 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1390 if (GV->hasName()) {
1391 PrintLLVMName(Out, GV);
1395 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1398 PrintLinkage(GV->getLinkage(), Out);
1399 PrintVisibility(GV->getVisibility(), Out);
1401 if (GV->isThreadLocal()) Out << "thread_local ";
1402 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1403 Out << "addrspace(" << AddressSpace << ") ";
1404 Out << (GV->isConstant() ? "constant " : "global ");
1405 TypePrinter.print(GV->getType()->getElementType(), Out);
1407 if (GV->hasInitializer()) {
1409 writeOperand(GV->getInitializer(), false);
1412 if (GV->hasSection())
1413 Out << ", section \"" << GV->getSection() << '"';
1414 if (GV->getAlignment())
1415 Out << ", align " << GV->getAlignment();
1417 printInfoComment(*GV);
1421 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1422 // Don't crash when dumping partially built GA
1424 Out << "<<nameless>> = ";
1426 PrintLLVMName(Out, GA);
1429 PrintVisibility(GA->getVisibility(), Out);
1433 PrintLinkage(GA->getLinkage(), Out);
1435 const Constant *Aliasee = GA->getAliasee();
1437 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1438 TypePrinter.print(GV->getType(), Out);
1440 PrintLLVMName(Out, GV);
1441 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1442 TypePrinter.print(F->getFunctionType(), Out);
1445 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1446 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1447 TypePrinter.print(GA->getType(), Out);
1449 PrintLLVMName(Out, GA);
1451 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1452 // The only valid GEP is an all zero GEP.
1453 assert((CE->getOpcode() == Instruction::BitCast ||
1454 CE->getOpcode() == Instruction::GetElementPtr) &&
1455 "Unsupported aliasee");
1456 writeOperand(CE, false);
1459 printInfoComment(*GA);
1463 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1464 // Emit all numbered types.
1465 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1468 // Make sure we print out at least one level of the type structure, so
1469 // that we do not get %2 = type %2
1470 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1471 Out << "\t\t; type %" << i << '\n';
1474 // Print the named types.
1475 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1478 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1481 // Make sure we print out at least one level of the type structure, so
1482 // that we do not get %FILE = type %FILE
1483 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1488 /// printFunction - Print all aspects of a function.
1490 void AssemblyWriter::printFunction(const Function *F) {
1491 // Print out the return type and name.
1494 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1496 if (F->isDeclaration())
1501 PrintLinkage(F->getLinkage(), Out);
1502 PrintVisibility(F->getVisibility(), Out);
1504 // Print the calling convention.
1505 switch (F->getCallingConv()) {
1506 case CallingConv::C: break; // default
1507 case CallingConv::Fast: Out << "fastcc "; break;
1508 case CallingConv::Cold: Out << "coldcc "; break;
1509 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1510 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1511 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1512 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1513 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1514 default: Out << "cc" << F->getCallingConv() << " "; break;
1517 const FunctionType *FT = F->getFunctionType();
1518 const AttrListPtr &Attrs = F->getAttributes();
1519 Attributes RetAttrs = Attrs.getRetAttributes();
1520 if (RetAttrs != Attribute::None)
1521 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1522 TypePrinter.print(F->getReturnType(), Out);
1524 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1526 Machine.incorporateFunction(F);
1528 // Loop over the arguments, printing them...
1531 if (!F->isDeclaration()) {
1532 // If this isn't a declaration, print the argument names as well.
1533 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1535 // Insert commas as we go... the first arg doesn't get a comma
1536 if (I != F->arg_begin()) Out << ", ";
1537 printArgument(I, Attrs.getParamAttributes(Idx));
1541 // Otherwise, print the types from the function type.
1542 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1543 // Insert commas as we go... the first arg doesn't get a comma
1547 TypePrinter.print(FT->getParamType(i), Out);
1549 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1550 if (ArgAttrs != Attribute::None)
1551 Out << ' ' << Attribute::getAsString(ArgAttrs);
1555 // Finish printing arguments...
1556 if (FT->isVarArg()) {
1557 if (FT->getNumParams()) Out << ", ";
1558 Out << "..."; // Output varargs portion of signature!
1561 Attributes FnAttrs = Attrs.getFnAttributes();
1562 if (FnAttrs != Attribute::None)
1563 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1564 if (F->hasSection())
1565 Out << " section \"" << F->getSection() << '"';
1566 if (F->getAlignment())
1567 Out << " align " << F->getAlignment();
1569 Out << " gc \"" << F->getGC() << '"';
1570 if (F->isDeclaration()) {
1575 // Output all of its basic blocks... for the function
1576 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1582 Machine.purgeFunction();
1585 /// printArgument - This member is called for every argument that is passed into
1586 /// the function. Simply print it out
1588 void AssemblyWriter::printArgument(const Argument *Arg,
1591 TypePrinter.print(Arg->getType(), Out);
1593 // Output parameter attributes list
1594 if (Attrs != Attribute::None)
1595 Out << ' ' << Attribute::getAsString(Attrs);
1597 // Output name, if available...
1598 if (Arg->hasName()) {
1600 PrintLLVMName(Out, Arg);
1604 /// printBasicBlock - This member is called for each basic block in a method.
1606 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1607 if (BB->hasName()) { // Print out the label if it exists...
1609 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1611 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1612 Out << "\n; <label>:";
1613 int Slot = Machine.getLocalSlot(BB);
1620 if (BB->getParent() == 0)
1621 Out << "\t\t; Error: Block without parent!";
1622 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1623 // Output predecessors for the block...
1625 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1628 Out << " No predecessors!";
1631 writeOperand(*PI, false);
1632 for (++PI; PI != PE; ++PI) {
1634 writeOperand(*PI, false);
1641 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1643 // Output all of the instructions in the basic block...
1644 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1645 printInstruction(*I);
1649 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1653 /// printInfoComment - Print a little comment after the instruction indicating
1654 /// which slot it occupies.
1656 void AssemblyWriter::printInfoComment(const Value &V) {
1657 if (V.getType() != Type::VoidTy) {
1659 TypePrinter.print(V.getType(), Out);
1662 if (!V.hasName() && !isa<Instruction>(V)) {
1664 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1665 SlotNum = Machine.getGlobalSlot(GV);
1667 SlotNum = Machine.getLocalSlot(&V);
1671 Out << ':' << SlotNum; // Print out the def slot taken.
1673 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1677 // This member is called for each Instruction in a function..
1678 void AssemblyWriter::printInstruction(const Instruction &I) {
1679 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1683 // Print out name if it exists...
1685 PrintLLVMName(Out, &I);
1687 } else if (I.getType() != Type::VoidTy) {
1688 // Print out the def slot taken.
1689 int SlotNum = Machine.getLocalSlot(&I);
1691 Out << "<badref> = ";
1693 Out << '%' << SlotNum << " = ";
1696 // If this is a volatile load or store, print out the volatile marker.
1697 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1698 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1700 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1701 // If this is a call, check if it's a tail call.
1705 // Print out optimization information.
1706 WriteOptimizationInfo(Out, &I);
1708 // Print out the opcode...
1709 Out << I.getOpcodeName();
1711 // Print out the compare instruction predicates
1712 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1713 Out << ' ' << getPredicateText(CI->getPredicate());
1715 // Print out the type of the operands...
1716 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1718 // Special case conditional branches to swizzle the condition out to the front
1719 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1720 BranchInst &BI(cast<BranchInst>(I));
1722 writeOperand(BI.getCondition(), true);
1724 writeOperand(BI.getSuccessor(0), true);
1726 writeOperand(BI.getSuccessor(1), true);
1728 } else if (isa<SwitchInst>(I)) {
1729 // Special case switch statement to get formatting nice and correct...
1731 writeOperand(Operand , true);
1733 writeOperand(I.getOperand(1), true);
1736 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1738 writeOperand(I.getOperand(op ), true);
1740 writeOperand(I.getOperand(op+1), true);
1743 } else if (isa<PHINode>(I)) {
1745 TypePrinter.print(I.getType(), Out);
1748 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1749 if (op) Out << ", ";
1751 writeOperand(I.getOperand(op ), false); Out << ", ";
1752 writeOperand(I.getOperand(op+1), false); Out << " ]";
1754 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1756 writeOperand(I.getOperand(0), true);
1757 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1759 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1761 writeOperand(I.getOperand(0), true); Out << ", ";
1762 writeOperand(I.getOperand(1), true);
1763 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1765 } else if (isa<ReturnInst>(I) && !Operand) {
1767 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1768 // Print the calling convention being used.
1769 switch (CI->getCallingConv()) {
1770 case CallingConv::C: break; // default
1771 case CallingConv::Fast: Out << " fastcc"; break;
1772 case CallingConv::Cold: Out << " coldcc"; break;
1773 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1774 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1775 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1776 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1777 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1778 default: Out << " cc" << CI->getCallingConv(); break;
1781 const PointerType *PTy = cast<PointerType>(Operand->getType());
1782 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1783 const Type *RetTy = FTy->getReturnType();
1784 const AttrListPtr &PAL = CI->getAttributes();
1786 if (PAL.getRetAttributes() != Attribute::None)
1787 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1789 // If possible, print out the short form of the call instruction. We can
1790 // only do this if the first argument is a pointer to a nonvararg function,
1791 // and if the return type is not a pointer to a function.
1794 if (!FTy->isVarArg() &&
1795 (!isa<PointerType>(RetTy) ||
1796 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1797 TypePrinter.print(RetTy, Out);
1799 writeOperand(Operand, false);
1801 writeOperand(Operand, true);
1804 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1807 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1810 if (PAL.getFnAttributes() != Attribute::None)
1811 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1812 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1813 const PointerType *PTy = cast<PointerType>(Operand->getType());
1814 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1815 const Type *RetTy = FTy->getReturnType();
1816 const AttrListPtr &PAL = II->getAttributes();
1818 // Print the calling convention being used.
1819 switch (II->getCallingConv()) {
1820 case CallingConv::C: break; // default
1821 case CallingConv::Fast: Out << " fastcc"; break;
1822 case CallingConv::Cold: Out << " coldcc"; break;
1823 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1824 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1825 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1826 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1827 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1828 default: Out << " cc" << II->getCallingConv(); break;
1831 if (PAL.getRetAttributes() != Attribute::None)
1832 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1834 // If possible, print out the short form of the invoke instruction. We can
1835 // only do this if the first argument is a pointer to a nonvararg function,
1836 // and if the return type is not a pointer to a function.
1839 if (!FTy->isVarArg() &&
1840 (!isa<PointerType>(RetTy) ||
1841 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1842 TypePrinter.print(RetTy, Out);
1844 writeOperand(Operand, false);
1846 writeOperand(Operand, true);
1849 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1852 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1856 if (PAL.getFnAttributes() != Attribute::None)
1857 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1859 Out << "\n\t\t\tto ";
1860 writeOperand(II->getNormalDest(), true);
1862 writeOperand(II->getUnwindDest(), true);
1864 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1866 TypePrinter.print(AI->getType()->getElementType(), Out);
1867 if (AI->isArrayAllocation()) {
1869 writeOperand(AI->getArraySize(), true);
1871 if (AI->getAlignment()) {
1872 Out << ", align " << AI->getAlignment();
1874 } else if (isa<CastInst>(I)) {
1877 writeOperand(Operand, true); // Work with broken code
1880 TypePrinter.print(I.getType(), Out);
1881 } else if (isa<VAArgInst>(I)) {
1884 writeOperand(Operand, true); // Work with broken code
1887 TypePrinter.print(I.getType(), Out);
1888 } else if (Operand) { // Print the normal way.
1890 // PrintAllTypes - Instructions who have operands of all the same type
1891 // omit the type from all but the first operand. If the instruction has
1892 // different type operands (for example br), then they are all printed.
1893 bool PrintAllTypes = false;
1894 const Type *TheType = Operand->getType();
1896 // Select, Store and ShuffleVector always print all types.
1897 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1898 || isa<ReturnInst>(I)) {
1899 PrintAllTypes = true;
1901 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1902 Operand = I.getOperand(i);
1903 // note that Operand shouldn't be null, but the test helps make dump()
1904 // more tolerant of malformed IR
1905 if (Operand && Operand->getType() != TheType) {
1906 PrintAllTypes = true; // We have differing types! Print them all!
1912 if (!PrintAllTypes) {
1914 TypePrinter.print(TheType, Out);
1918 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1920 writeOperand(I.getOperand(i), PrintAllTypes);
1924 // Print post operand alignment for load/store
1925 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1926 Out << ", align " << cast<LoadInst>(I).getAlignment();
1927 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1928 Out << ", align " << cast<StoreInst>(I).getAlignment();
1931 printInfoComment(I);
1935 //===----------------------------------------------------------------------===//
1936 // External Interface declarations
1937 //===----------------------------------------------------------------------===//
1939 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1940 raw_os_ostream OS(o);
1943 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1944 SlotTracker SlotTable(this);
1945 AssemblyWriter W(OS, SlotTable, this, AAW);
1949 void Type::print(std::ostream &o) const {
1950 raw_os_ostream OS(o);
1954 void Type::print(raw_ostream &OS) const {
1956 OS << "<null Type>";
1959 TypePrinting().print(this, OS);
1962 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1964 OS << "printing a <null> value\n";
1967 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1968 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1969 SlotTracker SlotTable(F);
1970 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1972 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1973 SlotTracker SlotTable(BB->getParent());
1974 AssemblyWriter W(OS, SlotTable,
1975 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1977 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1978 SlotTracker SlotTable(GV->getParent());
1979 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1981 } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
1982 TypePrinting TypePrinter;
1983 TypePrinter.print(MDS->getType(), OS);
1986 PrintEscapedString(MDS->begin(), MDS->length(), OS);
1988 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
1989 SlotTracker SlotTable(N);
1990 TypePrinting TypePrinter;
1991 SlotTable.initialize();
1992 WriteMDNodes(OS, TypePrinter, SlotTable);
1993 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1994 TypePrinting TypePrinter;
1995 TypePrinter.print(C->getType(), OS);
1997 WriteConstantInt(OS, C, TypePrinter, 0);
1998 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1999 WriteAsOperand(OS, this, true,
2000 A->getParent() ? A->getParent()->getParent() : 0);
2001 } else if (isa<InlineAsm>(this)) {
2002 WriteAsOperand(OS, this, true, 0);
2004 llvm_unreachable("Unknown value to print out!");
2008 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
2009 raw_os_ostream OS(O);
2013 // Value::dump - allow easy printing of Values from the debugger.
2014 void Value::dump() const { print(errs()); errs() << '\n'; }
2016 // Type::dump - allow easy printing of Types from the debugger.
2017 // This one uses type names from the given context module
2018 void Type::dump(const Module *Context) const {
2019 WriteTypeSymbolic(errs(), this, Context);
2023 // Type::dump - allow easy printing of Types from the debugger.
2024 void Type::dump() const { dump(0); }
2026 // Module::dump() - Allow printing of Modules from the debugger.
2027 void Module::dump() const { print(errs(), 0); }