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 MDString *MDS = dyn_cast<MDString>(V)) {
1136 TypePrinter.print(MDS->getType(), Out);
1139 PrintEscapedString(MDS->begin(), MDS->size(), Out);
1147 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1148 Slot = Machine->getGlobalSlot(GV);
1151 Slot = Machine->getLocalSlot(V);
1154 Machine = createSlotTracker(V);
1156 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1157 Slot = Machine->getGlobalSlot(GV);
1160 Slot = Machine->getLocalSlot(V);
1169 Out << Prefix << Slot;
1174 /// WriteAsOperand - Write the name of the specified value out to the specified
1175 /// ostream. This can be useful when you just want to print int %reg126, not
1176 /// the whole instruction that generated it.
1178 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1179 const Module *Context) {
1180 raw_os_ostream OS(Out);
1181 WriteAsOperand(OS, V, PrintType, Context);
1184 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1185 const Module *Context) {
1186 if (Context == 0) Context = getModuleFromVal(V);
1188 TypePrinting TypePrinter;
1189 std::vector<const Type*> NumberedTypes;
1190 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1192 TypePrinter.print(V->getType(), Out);
1196 WriteAsOperandInternal(Out, V, TypePrinter, 0);
1202 class AssemblyWriter {
1204 SlotTracker &Machine;
1205 const Module *TheModule;
1206 TypePrinting TypePrinter;
1207 AssemblyAnnotationWriter *AnnotationWriter;
1208 std::vector<const Type*> NumberedTypes;
1210 // Each MDNode is assigned unique MetadataIDNo.
1211 std::map<const MDNode *, unsigned> MDNodes;
1212 unsigned MetadataIDNo;
1214 inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1215 AssemblyAnnotationWriter *AAW)
1216 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1217 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1220 void write(const Module *M) { printModule(M); }
1222 void write(const GlobalValue *G) {
1223 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1225 else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1227 else if (const Function *F = dyn_cast<Function>(G))
1230 llvm_unreachable("Unknown global");
1233 void write(const BasicBlock *BB) { printBasicBlock(BB); }
1234 void write(const Instruction *I) { printInstruction(*I); }
1236 void writeOperand(const Value *Op, bool PrintType);
1237 void writeParamOperand(const Value *Operand, Attributes Attrs);
1239 const Module* getModule() { return TheModule; }
1242 void printModule(const Module *M);
1243 void printTypeSymbolTable(const TypeSymbolTable &ST);
1244 void printGlobal(const GlobalVariable *GV);
1245 void printAlias(const GlobalAlias *GV);
1246 void printFunction(const Function *F);
1247 void printArgument(const Argument *FA, Attributes Attrs);
1248 void printBasicBlock(const BasicBlock *BB);
1249 void printInstruction(const Instruction &I);
1251 // printInfoComment - Print a little comment after the instruction indicating
1252 // which slot it occupies.
1253 void printInfoComment(const Value &V);
1255 } // end of anonymous namespace
1258 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1260 Out << "<null operand!>";
1263 TypePrinter.print(Operand->getType(), Out);
1266 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1270 void AssemblyWriter::writeParamOperand(const Value *Operand,
1273 Out << "<null operand!>";
1276 TypePrinter.print(Operand->getType(), Out);
1277 // Print parameter attributes list
1278 if (Attrs != Attribute::None)
1279 Out << ' ' << Attribute::getAsString(Attrs);
1281 // Print the operand
1282 WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1286 void AssemblyWriter::printModule(const Module *M) {
1287 if (!M->getModuleIdentifier().empty() &&
1288 // Don't print the ID if it will start a new line (which would
1289 // require a comment char before it).
1290 M->getModuleIdentifier().find('\n') == std::string::npos)
1291 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1293 if (!M->getDataLayout().empty())
1294 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1295 if (!M->getTargetTriple().empty())
1296 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1298 if (!M->getModuleInlineAsm().empty()) {
1299 // Split the string into lines, to make it easier to read the .ll file.
1300 std::string Asm = M->getModuleInlineAsm();
1302 size_t NewLine = Asm.find_first_of('\n', CurPos);
1303 while (NewLine != std::string::npos) {
1304 // We found a newline, print the portion of the asm string from the
1305 // last newline up to this newline.
1306 Out << "module asm \"";
1307 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1311 NewLine = Asm.find_first_of('\n', CurPos);
1313 Out << "module asm \"";
1314 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1318 // Loop over the dependent libraries and emit them.
1319 Module::lib_iterator LI = M->lib_begin();
1320 Module::lib_iterator LE = M->lib_end();
1322 Out << "deplibs = [ ";
1324 Out << '"' << *LI << '"';
1332 // Loop over the symbol table, emitting all id'd types.
1333 printTypeSymbolTable(M->getTypeSymbolTable());
1335 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1339 // Output all aliases.
1340 if (!M->alias_empty()) Out << "\n";
1341 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1345 // Output all of the functions.
1346 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1349 WriteMDNodes(Out, TypePrinter, Machine);
1352 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1354 case GlobalValue::ExternalLinkage: break;
1355 case GlobalValue::PrivateLinkage: Out << "private "; break;
1356 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1357 case GlobalValue::InternalLinkage: Out << "internal "; break;
1358 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1359 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1360 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1361 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1362 case GlobalValue::CommonLinkage: Out << "common "; break;
1363 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1364 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1365 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1366 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1367 case GlobalValue::AvailableExternallyLinkage:
1368 Out << "available_externally ";
1370 case GlobalValue::GhostLinkage:
1371 llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1376 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1379 default: llvm_unreachable("Invalid visibility style!");
1380 case GlobalValue::DefaultVisibility: break;
1381 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1382 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1386 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1387 if (GV->hasName()) {
1388 PrintLLVMName(Out, GV);
1392 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1395 PrintLinkage(GV->getLinkage(), Out);
1396 PrintVisibility(GV->getVisibility(), Out);
1398 if (GV->isThreadLocal()) Out << "thread_local ";
1399 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1400 Out << "addrspace(" << AddressSpace << ") ";
1401 Out << (GV->isConstant() ? "constant " : "global ");
1402 TypePrinter.print(GV->getType()->getElementType(), Out);
1404 if (GV->hasInitializer()) {
1406 writeOperand(GV->getInitializer(), false);
1409 if (GV->hasSection())
1410 Out << ", section \"" << GV->getSection() << '"';
1411 if (GV->getAlignment())
1412 Out << ", align " << GV->getAlignment();
1414 printInfoComment(*GV);
1418 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1419 // Don't crash when dumping partially built GA
1421 Out << "<<nameless>> = ";
1423 PrintLLVMName(Out, GA);
1426 PrintVisibility(GA->getVisibility(), Out);
1430 PrintLinkage(GA->getLinkage(), Out);
1432 const Constant *Aliasee = GA->getAliasee();
1434 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1435 TypePrinter.print(GV->getType(), Out);
1437 PrintLLVMName(Out, GV);
1438 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1439 TypePrinter.print(F->getFunctionType(), Out);
1442 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1443 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1444 TypePrinter.print(GA->getType(), Out);
1446 PrintLLVMName(Out, GA);
1448 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1449 // The only valid GEP is an all zero GEP.
1450 assert((CE->getOpcode() == Instruction::BitCast ||
1451 CE->getOpcode() == Instruction::GetElementPtr) &&
1452 "Unsupported aliasee");
1453 writeOperand(CE, false);
1456 printInfoComment(*GA);
1460 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1461 // Emit all numbered types.
1462 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1465 // Make sure we print out at least one level of the type structure, so
1466 // that we do not get %2 = type %2
1467 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1468 Out << "\t\t; type %" << i << '\n';
1471 // Print the named types.
1472 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1475 PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1478 // Make sure we print out at least one level of the type structure, so
1479 // that we do not get %FILE = type %FILE
1480 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1485 /// printFunction - Print all aspects of a function.
1487 void AssemblyWriter::printFunction(const Function *F) {
1488 // Print out the return type and name.
1491 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1493 if (F->isDeclaration())
1498 PrintLinkage(F->getLinkage(), Out);
1499 PrintVisibility(F->getVisibility(), Out);
1501 // Print the calling convention.
1502 switch (F->getCallingConv()) {
1503 case CallingConv::C: break; // default
1504 case CallingConv::Fast: Out << "fastcc "; break;
1505 case CallingConv::Cold: Out << "coldcc "; break;
1506 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1507 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1508 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1509 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1510 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1511 default: Out << "cc" << F->getCallingConv() << " "; break;
1514 const FunctionType *FT = F->getFunctionType();
1515 const AttrListPtr &Attrs = F->getAttributes();
1516 Attributes RetAttrs = Attrs.getRetAttributes();
1517 if (RetAttrs != Attribute::None)
1518 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1519 TypePrinter.print(F->getReturnType(), Out);
1521 WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1523 Machine.incorporateFunction(F);
1525 // Loop over the arguments, printing them...
1528 if (!F->isDeclaration()) {
1529 // If this isn't a declaration, print the argument names as well.
1530 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1532 // Insert commas as we go... the first arg doesn't get a comma
1533 if (I != F->arg_begin()) Out << ", ";
1534 printArgument(I, Attrs.getParamAttributes(Idx));
1538 // Otherwise, print the types from the function type.
1539 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1540 // Insert commas as we go... the first arg doesn't get a comma
1544 TypePrinter.print(FT->getParamType(i), Out);
1546 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1547 if (ArgAttrs != Attribute::None)
1548 Out << ' ' << Attribute::getAsString(ArgAttrs);
1552 // Finish printing arguments...
1553 if (FT->isVarArg()) {
1554 if (FT->getNumParams()) Out << ", ";
1555 Out << "..."; // Output varargs portion of signature!
1558 Attributes FnAttrs = Attrs.getFnAttributes();
1559 if (FnAttrs != Attribute::None)
1560 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1561 if (F->hasSection())
1562 Out << " section \"" << F->getSection() << '"';
1563 if (F->getAlignment())
1564 Out << " align " << F->getAlignment();
1566 Out << " gc \"" << F->getGC() << '"';
1567 if (F->isDeclaration()) {
1572 // Output all of its basic blocks... for the function
1573 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1579 Machine.purgeFunction();
1582 /// printArgument - This member is called for every argument that is passed into
1583 /// the function. Simply print it out
1585 void AssemblyWriter::printArgument(const Argument *Arg,
1588 TypePrinter.print(Arg->getType(), Out);
1590 // Output parameter attributes list
1591 if (Attrs != Attribute::None)
1592 Out << ' ' << Attribute::getAsString(Attrs);
1594 // Output name, if available...
1595 if (Arg->hasName()) {
1597 PrintLLVMName(Out, Arg);
1601 /// printBasicBlock - This member is called for each basic block in a method.
1603 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1604 if (BB->hasName()) { // Print out the label if it exists...
1606 PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1608 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1609 Out << "\n; <label>:";
1610 int Slot = Machine.getLocalSlot(BB);
1617 if (BB->getParent() == 0)
1618 Out << "\t\t; Error: Block without parent!";
1619 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1620 // Output predecessors for the block...
1622 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1625 Out << " No predecessors!";
1628 writeOperand(*PI, false);
1629 for (++PI; PI != PE; ++PI) {
1631 writeOperand(*PI, false);
1638 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1640 // Output all of the instructions in the basic block...
1641 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1642 printInstruction(*I);
1646 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1650 /// printInfoComment - Print a little comment after the instruction indicating
1651 /// which slot it occupies.
1653 void AssemblyWriter::printInfoComment(const Value &V) {
1654 if (V.getType() != Type::VoidTy) {
1656 TypePrinter.print(V.getType(), Out);
1659 if (!V.hasName() && !isa<Instruction>(V)) {
1661 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1662 SlotNum = Machine.getGlobalSlot(GV);
1664 SlotNum = Machine.getLocalSlot(&V);
1668 Out << ':' << SlotNum; // Print out the def slot taken.
1670 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1674 // This member is called for each Instruction in a function..
1675 void AssemblyWriter::printInstruction(const Instruction &I) {
1676 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1680 // Print out name if it exists...
1682 PrintLLVMName(Out, &I);
1684 } else if (I.getType() != Type::VoidTy) {
1685 // Print out the def slot taken.
1686 int SlotNum = Machine.getLocalSlot(&I);
1688 Out << "<badref> = ";
1690 Out << '%' << SlotNum << " = ";
1693 // If this is a volatile load or store, print out the volatile marker.
1694 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1695 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1697 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1698 // If this is a call, check if it's a tail call.
1702 // Print out optimization information.
1703 WriteOptimizationInfo(Out, &I);
1705 // Print out the opcode...
1706 Out << I.getOpcodeName();
1708 // Print out the compare instruction predicates
1709 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1710 Out << ' ' << getPredicateText(CI->getPredicate());
1712 // Print out the type of the operands...
1713 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1715 // Special case conditional branches to swizzle the condition out to the front
1716 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1717 BranchInst &BI(cast<BranchInst>(I));
1719 writeOperand(BI.getCondition(), true);
1721 writeOperand(BI.getSuccessor(0), true);
1723 writeOperand(BI.getSuccessor(1), true);
1725 } else if (isa<SwitchInst>(I)) {
1726 // Special case switch statement to get formatting nice and correct...
1728 writeOperand(Operand , true);
1730 writeOperand(I.getOperand(1), true);
1733 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1735 writeOperand(I.getOperand(op ), true);
1737 writeOperand(I.getOperand(op+1), true);
1740 } else if (isa<PHINode>(I)) {
1742 TypePrinter.print(I.getType(), Out);
1745 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1746 if (op) Out << ", ";
1748 writeOperand(I.getOperand(op ), false); Out << ", ";
1749 writeOperand(I.getOperand(op+1), false); Out << " ]";
1751 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1753 writeOperand(I.getOperand(0), true);
1754 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1756 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1758 writeOperand(I.getOperand(0), true); Out << ", ";
1759 writeOperand(I.getOperand(1), true);
1760 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1762 } else if (isa<ReturnInst>(I) && !Operand) {
1764 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1765 // Print the calling convention being used.
1766 switch (CI->getCallingConv()) {
1767 case CallingConv::C: break; // default
1768 case CallingConv::Fast: Out << " fastcc"; break;
1769 case CallingConv::Cold: Out << " coldcc"; break;
1770 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1771 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1772 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1773 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1774 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1775 default: Out << " cc" << CI->getCallingConv(); break;
1778 const PointerType *PTy = cast<PointerType>(Operand->getType());
1779 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1780 const Type *RetTy = FTy->getReturnType();
1781 const AttrListPtr &PAL = CI->getAttributes();
1783 if (PAL.getRetAttributes() != Attribute::None)
1784 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1786 // If possible, print out the short form of the call instruction. We can
1787 // only do this if the first argument is a pointer to a nonvararg function,
1788 // and if the return type is not a pointer to a function.
1791 if (!FTy->isVarArg() &&
1792 (!isa<PointerType>(RetTy) ||
1793 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1794 TypePrinter.print(RetTy, Out);
1796 writeOperand(Operand, false);
1798 writeOperand(Operand, true);
1801 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1804 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1807 if (PAL.getFnAttributes() != Attribute::None)
1808 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1809 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1810 const PointerType *PTy = cast<PointerType>(Operand->getType());
1811 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1812 const Type *RetTy = FTy->getReturnType();
1813 const AttrListPtr &PAL = II->getAttributes();
1815 // Print the calling convention being used.
1816 switch (II->getCallingConv()) {
1817 case CallingConv::C: break; // default
1818 case CallingConv::Fast: Out << " fastcc"; break;
1819 case CallingConv::Cold: Out << " coldcc"; break;
1820 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1821 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1822 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1823 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1824 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1825 default: Out << " cc" << II->getCallingConv(); break;
1828 if (PAL.getRetAttributes() != Attribute::None)
1829 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1831 // If possible, print out the short form of the invoke instruction. We can
1832 // only do this if the first argument is a pointer to a nonvararg function,
1833 // and if the return type is not a pointer to a function.
1836 if (!FTy->isVarArg() &&
1837 (!isa<PointerType>(RetTy) ||
1838 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1839 TypePrinter.print(RetTy, Out);
1841 writeOperand(Operand, false);
1843 writeOperand(Operand, true);
1846 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1849 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1853 if (PAL.getFnAttributes() != Attribute::None)
1854 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1856 Out << "\n\t\t\tto ";
1857 writeOperand(II->getNormalDest(), true);
1859 writeOperand(II->getUnwindDest(), true);
1861 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1863 TypePrinter.print(AI->getType()->getElementType(), Out);
1864 if (AI->isArrayAllocation()) {
1866 writeOperand(AI->getArraySize(), true);
1868 if (AI->getAlignment()) {
1869 Out << ", align " << AI->getAlignment();
1871 } else if (isa<CastInst>(I)) {
1874 writeOperand(Operand, true); // Work with broken code
1877 TypePrinter.print(I.getType(), Out);
1878 } else if (isa<VAArgInst>(I)) {
1881 writeOperand(Operand, true); // Work with broken code
1884 TypePrinter.print(I.getType(), Out);
1885 } else if (Operand) { // Print the normal way.
1887 // PrintAllTypes - Instructions who have operands of all the same type
1888 // omit the type from all but the first operand. If the instruction has
1889 // different type operands (for example br), then they are all printed.
1890 bool PrintAllTypes = false;
1891 const Type *TheType = Operand->getType();
1893 // Select, Store and ShuffleVector always print all types.
1894 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1895 || isa<ReturnInst>(I)) {
1896 PrintAllTypes = true;
1898 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1899 Operand = I.getOperand(i);
1900 // note that Operand shouldn't be null, but the test helps make dump()
1901 // more tolerant of malformed IR
1902 if (Operand && Operand->getType() != TheType) {
1903 PrintAllTypes = true; // We have differing types! Print them all!
1909 if (!PrintAllTypes) {
1911 TypePrinter.print(TheType, Out);
1915 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1917 writeOperand(I.getOperand(i), PrintAllTypes);
1921 // Print post operand alignment for load/store
1922 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1923 Out << ", align " << cast<LoadInst>(I).getAlignment();
1924 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1925 Out << ", align " << cast<StoreInst>(I).getAlignment();
1928 printInfoComment(I);
1932 //===----------------------------------------------------------------------===//
1933 // External Interface declarations
1934 //===----------------------------------------------------------------------===//
1936 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1937 raw_os_ostream OS(o);
1940 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1941 SlotTracker SlotTable(this);
1942 AssemblyWriter W(OS, SlotTable, this, AAW);
1946 void Type::print(std::ostream &o) const {
1947 raw_os_ostream OS(o);
1951 void Type::print(raw_ostream &OS) const {
1953 OS << "<null Type>";
1956 TypePrinting().print(this, OS);
1959 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1961 OS << "printing a <null> value\n";
1964 if (const Instruction *I = dyn_cast<Instruction>(this)) {
1965 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1966 SlotTracker SlotTable(F);
1967 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1969 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1970 SlotTracker SlotTable(BB->getParent());
1971 AssemblyWriter W(OS, SlotTable,
1972 BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1974 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1975 SlotTracker SlotTable(GV->getParent());
1976 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1978 } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
1979 TypePrinting TypePrinter;
1980 TypePrinter.print(MDS->getType(), OS);
1983 PrintEscapedString(MDS->begin(), MDS->size(), OS);
1985 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
1986 SlotTracker SlotTable(N);
1987 TypePrinting TypePrinter;
1988 SlotTable.initialize();
1989 WriteMDNodes(OS, TypePrinter, SlotTable);
1990 } else if (const Constant *C = dyn_cast<Constant>(this)) {
1991 TypePrinting TypePrinter;
1992 TypePrinter.print(C->getType(), OS);
1994 WriteConstantInt(OS, C, TypePrinter, 0);
1995 } else if (const Argument *A = dyn_cast<Argument>(this)) {
1996 WriteAsOperand(OS, this, true,
1997 A->getParent() ? A->getParent()->getParent() : 0);
1998 } else if (isa<InlineAsm>(this)) {
1999 WriteAsOperand(OS, this, true, 0);
2001 llvm_unreachable("Unknown value to print out!");
2005 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
2006 raw_os_ostream OS(O);
2010 // Value::dump - allow easy printing of Values from the debugger.
2011 void Value::dump() const { print(errs()); errs() << '\n'; }
2013 // Type::dump - allow easy printing of Types from the debugger.
2014 // This one uses type names from the given context module
2015 void Type::dump(const Module *Context) const {
2016 WriteTypeSymbolic(errs(), this, Context);
2020 // Type::dump - allow easy printing of Types from the debugger.
2021 void Type::dump() const { dump(0); }
2023 // Module::dump() - Allow printing of Modules from the debugger.
2024 void Module::dump() const { print(errs(), 0); }