Introduce MetadataBase, a base class for MDString and MDNode.
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
11 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
39 #include <algorithm>
40 #include <cctype>
41 #include <map>
42 using namespace llvm;
43
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
46
47 //===----------------------------------------------------------------------===//
48 // Helper Functions
49 //===----------------------------------------------------------------------===//
50
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;
54   
55   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56     return BB->getParent() ? BB->getParent()->getParent() : 0;
57   
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;
61   }
62   
63   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64     return GV->getParent();
65   return 0;
66 }
67
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,
71                                raw_ostream &Out) {
72   for (unsigned i = 0; i != Length; ++i) {
73     unsigned char C = Str[i];
74     if (isprint(C) && C != '\\' && C != '"')
75       Out << C;
76     else
77       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
78   }
79 }
80
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);
85 }
86
87 enum PrefixType {
88   GlobalPrefix,
89   LabelPrefix,
90   LocalPrefix,
91   NoPrefix
92 };
93
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!");
100   switch (Prefix) {
101   default: llvm_unreachable("Bad prefix!");
102   case NoPrefix: break;
103   case GlobalPrefix: OS << '@'; break;
104   case LabelPrefix:  break;
105   case LocalPrefix:  OS << '%'; break;
106   }
107   
108   // Scan the name to see if it needs quotes first.
109   bool NeedsQuotes = isdigit(NameStr[0]);
110   if (!NeedsQuotes) {
111     for (unsigned i = 0; i != NameLen; ++i) {
112       char C = NameStr[i];
113       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
114         NeedsQuotes = true;
115         break;
116       }
117     }
118   }
119   
120   // If we didn't need any quotes, just write out the name in one blast.
121   if (!NeedsQuotes) {
122     OS.write(NameStr, NameLen);
123     return;
124   }
125   
126   // Okay, we need quotes.  Output the quotes and escape any scary characters as
127   // needed.
128   OS << '"';
129   PrintEscapedString(NameStr, NameLen, OS);
130   OS << '"';
131 }
132
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);
139 }
140
141 //===----------------------------------------------------------------------===//
142 // TypePrinting Class: Type printing machinery
143 //===----------------------------------------------------------------------===//
144
145 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
146   return *static_cast<DenseMap<const Type *, std::string>*>(M);
147 }
148
149 void TypePrinting::clear() {
150   getTypeNamesMap(TypeNames).clear();
151 }
152
153 bool TypePrinting::hasTypeName(const Type *Ty) const {
154   return getTypeNamesMap(TypeNames).count(Ty);
155 }
156
157 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
158   getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
159 }
160
161
162 TypePrinting::TypePrinting() {
163   TypeNames = new DenseMap<const Type *, std::string>();
164 }
165
166 TypePrinting::~TypePrinting() {
167   delete &getTypeNamesMap(TypeNames);
168 }
169
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);
179     if (I != TM.end()) {
180       OS << I->second;
181       return;
182     }
183   }
184   
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
188   
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
194     return;
195   }
196   
197   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
198   
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();
210     break;
211       
212   case Type::FunctionTyID: {
213     const FunctionType *FTy = cast<FunctionType>(Ty);
214     CalcTypeName(FTy->getReturnType(), TypeStack, OS);
215     OS << " (";
216     for (FunctionType::param_iterator I = FTy->param_begin(),
217          E = FTy->param_end(); I != E; ++I) {
218       if (I != FTy->param_begin())
219         OS << ", ";
220       CalcTypeName(*I, TypeStack, OS);
221     }
222     if (FTy->isVarArg()) {
223       if (FTy->getNumParams()) OS << ", ";
224       OS << "...";
225     }
226     OS << ')';
227     break;
228   }
229   case Type::StructTyID: {
230     const StructType *STy = cast<StructType>(Ty);
231     if (STy->isPacked())
232       OS << '<';
233     OS << "{ ";
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())
238         OS << ',';
239       OS << ' ';
240     }
241     OS << '}';
242     if (STy->isPacked())
243       OS << '>';
244     break;
245   }
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 << ')';
251     OS << '*';
252     break;
253   }
254   case Type::ArrayTyID: {
255     const ArrayType *ATy = cast<ArrayType>(Ty);
256     OS << '[' << ATy->getNumElements() << " x ";
257     CalcTypeName(ATy->getElementType(), TypeStack, OS);
258     OS << ']';
259     break;
260   }
261   case Type::VectorTyID: {
262     const VectorType *PTy = cast<VectorType>(Ty);
263     OS << "<" << PTy->getNumElements() << " x ";
264     CalcTypeName(PTy->getElementType(), TypeStack, OS);
265     OS << '>';
266     break;
267   }
268   case Type::OpaqueTyID:
269     OS << "opaque";
270     break;
271   default:
272     OS << "<unrecognized-type>";
273     break;
274   }
275   
276   TypeStack.pop_back();       // Remove self from stack.
277 }
278
279 /// printTypeInt - The internal guts of printing out a type that has a
280 /// potentially named portion.
281 ///
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);
288     if (I != TM.end()) {
289       OS << I->second;
290       return;
291     }
292   }
293   
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
296   // names.
297   SmallVector<const Type *, 16> TypeStack;
298   std::string TypeName;
299   
300   raw_string_ostream TypeOS(TypeName);
301   CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
302   OS << TypeOS.str();
303
304   // Cache type name for later use.
305   if (!IgnoreTopLevelName)
306     TM.insert(std::make_pair(Ty, TypeOS.str()));
307 }
308
309 namespace {
310   class TypeFinder {
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;
315     
316     TypePrinting &TP;
317     std::vector<const Type*> &NumberedTypes;
318   public:
319     TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
320       : TP(tp), NumberedTypes(numberedTypes) {}
321     
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();
327            TI != E; ++TI)
328         IncorporateType(TI->second);
329       
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());
336       }
337       
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());
343       }
344       
345       // Get types from functions.
346       for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
347         IncorporateType(FI->getType());
348         
349         for (Function::const_iterator BB = FI->begin(), E = FI->end();
350              BB != E;++BB)
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();
357                  OI != OE; ++OI)
358               IncorporateValue(*OI);
359           }
360       }
361     }
362     
363   private:
364     void IncorporateType(const Type *Ty) {
365       // Check to see if we're already visited this type.
366       if (!VisitedTypes.insert(Ty).second)
367         return;
368       
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);
374       }
375       
376       // Recursively walk all contained types.
377       for (Type::subtype_iterator I = Ty->subtype_begin(),
378            E = Ty->subtype_end(); I != E; ++I)
379         IncorporateType(*I);      
380     }
381     
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;
388       
389       // Already visited?
390       if (!VisitedConstants.insert(V).second)
391         return;
392       
393       // Check this type.
394       IncorporateType(V->getType());
395       
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);
401     }
402   };
403 } // end anonymous namespace
404
405
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,
411                                     const Module *M) {
412   if (M == 0) return;
413   
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();
418        TI != E; ++TI) {
419     const Type *Ty = cast<Type>(TI->second);
420     
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))
427         continue;
428     }
429     
430     // Likewise don't insert primitives either.
431     if (Ty->isInteger() || Ty->isPrimitiveType())
432       continue;
433     
434     // Get the name as a string and insert it into TypeNames.
435     std::string NameStr;
436     raw_string_ostream NameOS(NameStr);
437     PrintLLVMName(NameOS, TI->first.c_str(), TI->first.length(), LocalPrefix);
438     TP.addTypeName(Ty, NameOS.str());
439   }
440   
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);
446 }
447
448
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.
452 ///
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);
458 }
459
460 //===----------------------------------------------------------------------===//
461 // SlotTracker Class: Enumerate slot numbers for unnamed values
462 //===----------------------------------------------------------------------===//
463
464 namespace {
465
466 /// This class provides computation of slot numbers for LLVM Assembly writing.
467 ///
468 class SlotTracker {
469 public:
470   /// ValueMap - A mapping of Values to slot numbers.
471   typedef DenseMap<const Value*, unsigned> ValueMap;
472   
473 private:  
474   /// TheModule - The module for which we are holding slot numbers.
475   const Module* TheModule;
476   
477   /// TheFunction - The function for which we are holding slot numbers.
478   const Function* TheFunction;
479   bool FunctionProcessed;
480   
481   /// TheMDNode - The MDNode for which we are holding slot numbers.
482   const MDNode *TheMDNode;
483
484   /// mMap - The TypePlanes map for the module level data.
485   ValueMap mMap;
486   unsigned mNext;
487   
488   /// fMap - The TypePlanes map for the function level data.
489   ValueMap fMap;
490   unsigned fNext;
491   
492   /// mdnMap - Map for MDNodes.
493   ValueMap mdnMap;
494   unsigned mdnNext;
495 public:
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);
502
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);
508
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) {
512     TheFunction = F;
513     FunctionProcessed = false;
514   }
515
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();
520
521   /// MDNode map iterators.
522   ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
523   ValueMap::iterator mdnEnd() { return mdnMap.end(); }
524   unsigned mdnSize() { return mdnMap.size(); }
525
526   /// This function does the actual initialization.
527   inline void initialize();
528
529   // Implementation Details
530 private:
531   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
532   void CreateModuleSlot(const GlobalValue *V);
533
534   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
535   void CreateMetadataSlot(const MDNode *N);
536
537   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
538   void CreateFunctionSlot(const Value *V);
539
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();
543
544   /// Add all of the functions arguments, basic blocks, and instructions.
545   void processFunction();
546
547   /// Add all MDNode operands.
548   void processMDNode();
549
550   SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
551   void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
552 };
553
554 }  // end anonymous namespace
555
556
557 static SlotTracker *createSlotTracker(const Value *V) {
558   if (const Argument *FA = dyn_cast<Argument>(V))
559     return new SlotTracker(FA->getParent());
560   
561   if (const Instruction *I = dyn_cast<Instruction>(V))
562     return new SlotTracker(I->getParent()->getParent());
563   
564   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
565     return new SlotTracker(BB->getParent());
566   
567   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
568     return new SlotTracker(GV->getParent());
569   
570   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
571     return new SlotTracker(GA->getParent());    
572   
573   if (const Function *Func = dyn_cast<Function>(V))
574     return new SlotTracker(Func);
575   
576   return 0;
577 }
578
579 #if 0
580 #define ST_DEBUG(X) cerr << X
581 #else
582 #define ST_DEBUG(X)
583 #endif
584
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) {
590 }
591
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) {
597 }
598
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) {
603 }
604
605 inline void SlotTracker::initialize() {
606   if (TheModule) {
607     processModule();
608     TheModule = 0; ///< Prevent re-processing next time we're called.
609   }
610   
611   if (TheFunction && !FunctionProcessed)
612     processFunction();
613
614   if (TheMDNode)
615     processMDNode();
616 }
617
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");
622   
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) {
626     if (!I->hasName()) 
627       CreateModuleSlot(I);
628     if (I->hasInitializer()) {
629       if (MDNode *N = dyn_cast<MDNode>(I->getInitializer())) 
630         CreateMetadataSlot(N);
631     }
632   }
633   
634   // Add all the unnamed functions to the table.
635   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
636        I != E; ++I)
637     if (!I->hasName())
638       CreateModuleSlot(I);
639   
640   ST_DEBUG("end processModule!\n");
641 }
642
643 // Process the arguments, basic blocks, and instructions  of a function.
644 void SlotTracker::processFunction() {
645   ST_DEBUG("begin processFunction!\n");
646   fNext = 0;
647   
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)
651     if (!AI->hasName())
652       CreateFunctionSlot(AI);
653   
654   ST_DEBUG("Inserting Instructions:\n");
655   
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) {
659     if (!BB->hasName())
660       CreateFunctionSlot(BB);
661     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 
662          ++I) {
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);
668     }
669   }
670   
671   FunctionProcessed = true;
672   
673   ST_DEBUG("end processFunction!\n");
674 }
675
676 /// processMDNode - Process TheMDNode.
677 void SlotTracker::processMDNode() {
678   ST_DEBUG("begin processMDNode!\n");
679   mdnNext = 0;
680   CreateMetadataSlot(TheMDNode);
681   TheMDNode = 0;
682   ST_DEBUG("end processMDNode!\n");
683 }
684
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
691   TheFunction = 0;
692   FunctionProcessed = false;
693   ST_DEBUG("end purgeFunction!\n");
694 }
695
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.
699   initialize();
700   
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;
704 }
705
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.
709   initialize();
710   
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;
714 }
715
716
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!");
720   
721   // Check for uninitialized state and do lazy initialization.
722   initialize();
723   
724   ValueMap::iterator FI = fMap.find(V);
725   return FI == fMap.end() ? -1 : (int)FI->second;
726 }
727
728
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!");
734   
735   unsigned DestSlot = mNext++;
736   mMap[V] = DestSlot;
737   
738   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
739            DestSlot << " [");
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");
744 }
745
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!");
750   
751   unsigned DestSlot = fNext++;
752   fMap[V] = DestSlot;
753   
754   // G = Global, F = Function, o = other
755   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
756            DestSlot << " [o]\n");
757 }  
758
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!");
762   
763   ValueMap::iterator I = mdnMap.find(N);
764   if (I != mdnMap.end())
765     return;
766
767   unsigned DestSlot = mdnNext++;
768   mdnMap[N] = DestSlot;
769
770   for (MDNode::const_elem_iterator MDI = N->elem_begin(), 
771          MDE = N->elem_end(); MDI != MDE; ++MDI) {
772     const Value *TV = *MDI;
773     if (TV)
774       if (const MDNode *N2 = dyn_cast<MDNode>(TV)) 
775         CreateMetadataSlot(N2);
776   }
777 }
778
779 //===----------------------------------------------------------------------===//
780 // AsmWriter Implementation
781 //===----------------------------------------------------------------------===//
782
783 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
784                                    TypePrinting &TypePrinter,
785                                    SlotTracker *Machine);
786
787
788
789 static const char *getPredicateText(unsigned predicate) {
790   const char * pred = "unknown";
791   switch (predicate) {
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;
818   }
819   return pred;
820 }
821
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);
829
830   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
831     Out << '!' << i << " = metadata ";
832     const MDNode *Node = Nodes[i];
833     Out << "!{";
834     for (MDNode::const_elem_iterator NI = Node->elem_begin(), 
835            NE = Node->elem_end(); NI != NE;) {
836       const Value *V = *NI;
837       if (!V)
838         Out << "null";
839       else if (const MDNode *N = dyn_cast<MDNode>(V)) {
840         Out << "metadata ";
841         Out << '!' << Machine.getMetadataSlot(N);
842       }
843       else {
844         TypePrinter.print((*NI)->getType(), Out);
845         Out << ' ';
846         WriteAsOperandInternal(Out, *NI, TypePrinter, &Machine);
847       }
848       if (++NI != NE)
849         Out << ", ";
850     }
851     Out << "}\n";
852   }
853 }
854
855 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
856   if (const OverflowingBinaryOperator *OBO =
857         dyn_cast<OverflowingBinaryOperator>(U)) {
858     if (OBO->hasNoUnsignedOverflow())
859       Out << "unsigned ";
860     if (OBO->hasNoSignedOverflow())
861       Out << "signed ";
862   } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
863     if (Div->isExact())
864       Out << "exact ";
865   }
866 }
867
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");
873       return;
874     }
875     Out << CI->getValue();
876     return;
877   }
878   
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.
886       //
887       bool ignored;
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());
892
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.
896       //
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) {
902           Out << StrVal;
903           return;
904         }
905       }
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!");
912       char Buffer[40];
913       APFloat apf = CFP->getValueAPF();
914       // Floats are represented in ASCII IR as double, convert.
915       if (!isDouble)
916         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 
917                           &ignored);
918       Out << "0x" << 
919               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 
920                             Buffer+40);
921       return;
922     }
923     
924     // Some form of long double.  These appear as a magic letter identifying
925     // the type, then a fixed number of hex digits.
926     Out << "0x";
927     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
928       Out << 'K';
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];
933       int shiftcount=12;
934       int width = api.getBitWidth();
935       for (int j=0; j<width; j+=4, shiftcount-=4) {
936         unsigned int nibble = (word>>shiftcount) & 15;
937         if (nibble < 10)
938           Out << (unsigned char)(nibble + '0');
939         else
940           Out << (unsigned char)(nibble - 10 + 'A');
941         if (shiftcount == 0 && j+4 < width) {
942           word = *p;
943           shiftcount = 64;
944           if (width-j-4 < 64)
945             shiftcount = width-j-4;
946         }
947       }
948       return;
949     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
950       Out << 'L';
951     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
952       Out << 'M';
953     else
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();
958     uint64_t word = *p;
959     int shiftcount=60;
960     int width = api.getBitWidth();
961     for (int j=0; j<width; j+=4, shiftcount-=4) {
962       unsigned int nibble = (word>>shiftcount) & 15;
963       if (nibble < 10)
964         Out << (unsigned char)(nibble + '0');
965       else
966         Out << (unsigned char)(nibble - 10 + 'A');
967       if (shiftcount == 0 && j+4 < width) {
968         word = *(++p);
969         shiftcount = 64;
970         if (width-j-4 < 64)
971           shiftcount = width-j-4;
972       }
973     }
974     return;
975   }
976   
977   if (isa<ConstantAggregateZero>(CV)) {
978     Out << "zeroinitializer";
979     return;
980   }
981   
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.
985     //
986     const Type *ETy = CA->getType()->getElementType();
987     if (CA->isString()) {
988       Out << "c\"";
989       PrintEscapedString(CA->getAsString(), Out);
990       Out << '"';
991     } else {                // Cannot output in string format...
992       Out << '[';
993       if (CA->getNumOperands()) {
994         TypePrinter.print(ETy, Out);
995         Out << ' ';
996         WriteAsOperandInternal(Out, CA->getOperand(0),
997                                TypePrinter, Machine);
998         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
999           Out << ", ";
1000           TypePrinter.print(ETy, Out);
1001           Out << ' ';
1002           WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
1003         }
1004       }
1005       Out << ']';
1006     }
1007     return;
1008   }
1009   
1010   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1011     if (CS->getType()->isPacked())
1012       Out << '<';
1013     Out << '{';
1014     unsigned N = CS->getNumOperands();
1015     if (N) {
1016       Out << ' ';
1017       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1018       Out << ' ';
1019
1020       WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
1021
1022       for (unsigned i = 1; i < N; i++) {
1023         Out << ", ";
1024         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1025         Out << ' ';
1026
1027         WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
1028       }
1029       Out << ' ';
1030     }
1031  
1032     Out << '}';
1033     if (CS->getType()->isPacked())
1034       Out << '>';
1035     return;
1036   }
1037   
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");
1042     Out << '<';
1043     TypePrinter.print(ETy, Out);
1044     Out << ' ';
1045     WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
1046     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1047       Out << ", ";
1048       TypePrinter.print(ETy, Out);
1049       Out << ' ';
1050       WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
1051     }
1052     Out << '>';
1053     return;
1054   }
1055   
1056   if (isa<ConstantPointerNull>(CV)) {
1057     Out << "null";
1058     return;
1059   }
1060   
1061   if (isa<UndefValue>(CV)) {
1062     Out << "undef";
1063     return;
1064   }
1065   
1066   if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1067     Out << "!" << Machine->getMetadataSlot(Node);
1068     return;
1069   }
1070
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());
1076     Out << " (";
1077
1078     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1079       TypePrinter.print((*OI)->getType(), Out);
1080       Out << ' ';
1081       WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
1082       if (OI+1 != CE->op_end())
1083         Out << ", ";
1084     }
1085
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];
1090     }
1091
1092     if (CE->isCast()) {
1093       Out << " to ";
1094       TypePrinter.print(CE->getType(), Out);
1095     }
1096
1097     Out << ')';
1098     return;
1099   }
1100   
1101   Out << "<placeholder or erroneous Constant>";
1102 }
1103
1104
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.
1108 ///
1109 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1110                                    TypePrinting &TypePrinter,
1111                                    SlotTracker *Machine) {
1112   if (V->hasName()) {
1113     PrintLLVMName(Out, V);
1114     return;
1115   }
1116   
1117   const Constant *CV = dyn_cast<Constant>(V);
1118   if (CV && !isa<GlobalValue>(CV)) {
1119     WriteConstantInt(Out, CV, TypePrinter, Machine);
1120     return;
1121   }
1122   
1123   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1124     Out << "asm ";
1125     if (IA->hasSideEffects())
1126       Out << "sideeffect ";
1127     Out << '"';
1128     PrintEscapedString(IA->getAsmString(), Out);
1129     Out << "\", \"";
1130     PrintEscapedString(IA->getConstraintString(), Out);
1131     Out << '"';
1132     return;
1133   }
1134
1135   if (const MDString *MDS = dyn_cast<MDString>(V)) {
1136     TypePrinter.print(MDS->getType(), Out);
1137     Out << ' ';
1138     Out << "!\"";
1139     PrintEscapedString(MDS->begin(), MDS->size(), Out);
1140     Out << '"';
1141     return;
1142   }
1143
1144   char Prefix = '%';
1145   int Slot;
1146   if (Machine) {
1147     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1148       Slot = Machine->getGlobalSlot(GV);
1149       Prefix = '@';
1150     } else {
1151       Slot = Machine->getLocalSlot(V);
1152     }
1153   } else {
1154     Machine = createSlotTracker(V);
1155     if (Machine) {
1156       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1157         Slot = Machine->getGlobalSlot(GV);
1158         Prefix = '@';
1159       } else {
1160         Slot = Machine->getLocalSlot(V);
1161       }
1162     } else {
1163       Slot = -1;
1164     }
1165     delete Machine;
1166   }
1167   
1168   if (Slot != -1)
1169     Out << Prefix << Slot;
1170   else
1171     Out << "<badref>";
1172 }
1173
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.
1177 ///
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);
1182 }
1183
1184 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1185                           const Module *Context) {
1186   if (Context == 0) Context = getModuleFromVal(V);
1187
1188   TypePrinting TypePrinter;
1189   std::vector<const Type*> NumberedTypes;
1190   AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1191   if (PrintType) {
1192     TypePrinter.print(V->getType(), Out);
1193     Out << ' ';
1194   }
1195
1196   WriteAsOperandInternal(Out, V, TypePrinter, 0);
1197 }
1198
1199
1200 namespace {
1201
1202 class AssemblyWriter {
1203   raw_ostream &Out;
1204   SlotTracker &Machine;
1205   const Module *TheModule;
1206   TypePrinting TypePrinter;
1207   AssemblyAnnotationWriter *AnnotationWriter;
1208   std::vector<const Type*> NumberedTypes;
1209
1210   // Each MDNode is assigned unique MetadataIDNo.
1211   std::map<const MDNode *, unsigned> MDNodes;
1212   unsigned MetadataIDNo;
1213 public:
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);
1218   }
1219
1220   void write(const Module *M) { printModule(M); }
1221   
1222   void write(const GlobalValue *G) {
1223     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1224       printGlobal(GV);
1225     else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1226       printAlias(GA);
1227     else if (const Function *F = dyn_cast<Function>(G))
1228       printFunction(F);
1229     else
1230       llvm_unreachable("Unknown global");
1231   }
1232   
1233   void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
1234   void write(const Instruction *I)    { printInstruction(*I); }
1235
1236   void writeOperand(const Value *Op, bool PrintType);
1237   void writeParamOperand(const Value *Operand, Attributes Attrs);
1238
1239   const Module* getModule() { return TheModule; }
1240
1241 private:
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);
1250
1251   // printInfoComment - Print a little comment after the instruction indicating
1252   // which slot it occupies.
1253   void printInfoComment(const Value &V);
1254 };
1255 }  // end of anonymous namespace
1256
1257
1258 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1259   if (Operand == 0) {
1260     Out << "<null operand!>";
1261   } else {
1262     if (PrintType) {
1263       TypePrinter.print(Operand->getType(), Out);
1264       Out << ' ';
1265     }
1266     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1267   }
1268 }
1269
1270 void AssemblyWriter::writeParamOperand(const Value *Operand, 
1271                                        Attributes Attrs) {
1272   if (Operand == 0) {
1273     Out << "<null operand!>";
1274   } else {
1275     // Print the type
1276     TypePrinter.print(Operand->getType(), Out);
1277     // Print parameter attributes list
1278     if (Attrs != Attribute::None)
1279       Out << ' ' << Attribute::getAsString(Attrs);
1280     Out << ' ';
1281     // Print the operand
1282     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1283   }
1284 }
1285
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";
1292
1293   if (!M->getDataLayout().empty())
1294     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1295   if (!M->getTargetTriple().empty())
1296     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1297
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();
1301     size_t CurPos = 0;
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),
1308                          Out);
1309       Out << "\"\n";
1310       CurPos = NewLine+1;
1311       NewLine = Asm.find_first_of('\n', CurPos);
1312     }
1313     Out << "module asm \"";
1314     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1315     Out << "\"\n";
1316   }
1317   
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();
1321   if (LI != LE) {
1322     Out << "deplibs = [ ";
1323     while (LI != LE) {
1324       Out << '"' << *LI << '"';
1325       ++LI;
1326       if (LI != LE)
1327         Out << ", ";
1328     }
1329     Out << " ]\n";
1330   }
1331
1332   // Loop over the symbol table, emitting all id'd types.
1333   printTypeSymbolTable(M->getTypeSymbolTable());
1334
1335   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1336        I != E; ++I)
1337     printGlobal(I);
1338   
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();
1342        I != E; ++I)
1343     printAlias(I);
1344
1345   // Output all of the functions.
1346   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1347     printFunction(I);
1348
1349   WriteMDNodes(Out, TypePrinter, Machine);
1350 }
1351
1352 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1353   switch (LT) {
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 ";
1369     break;
1370   case GlobalValue::GhostLinkage:
1371     llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1372   }
1373 }
1374
1375
1376 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1377                             raw_ostream &Out) {
1378   switch (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;
1383   }
1384 }
1385
1386 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1387   if (GV->hasName()) {
1388     PrintLLVMName(Out, GV);
1389     Out << " = ";
1390   }
1391
1392   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1393     Out << "external ";
1394   
1395   PrintLinkage(GV->getLinkage(), Out);
1396   PrintVisibility(GV->getVisibility(), Out);
1397
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);
1403
1404   if (GV->hasInitializer()) {
1405     Out << ' ';
1406     writeOperand(GV->getInitializer(), false);
1407   }
1408     
1409   if (GV->hasSection())
1410     Out << ", section \"" << GV->getSection() << '"';
1411   if (GV->getAlignment())
1412     Out << ", align " << GV->getAlignment();
1413
1414   printInfoComment(*GV);
1415   Out << '\n';
1416 }
1417
1418 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1419   // Don't crash when dumping partially built GA
1420   if (!GA->hasName())
1421     Out << "<<nameless>> = ";
1422   else {
1423     PrintLLVMName(Out, GA);
1424     Out << " = ";
1425   }
1426   PrintVisibility(GA->getVisibility(), Out);
1427
1428   Out << "alias ";
1429
1430   PrintLinkage(GA->getLinkage(), Out);
1431   
1432   const Constant *Aliasee = GA->getAliasee();
1433     
1434   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1435     TypePrinter.print(GV->getType(), Out);
1436     Out << ' ';
1437     PrintLLVMName(Out, GV);
1438   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1439     TypePrinter.print(F->getFunctionType(), Out);
1440     Out << "* ";
1441
1442     WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1443   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1444     TypePrinter.print(GA->getType(), Out);
1445     Out << ' ';
1446     PrintLLVMName(Out, GA);
1447   } else {
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);
1454   }
1455   
1456   printInfoComment(*GA);
1457   Out << '\n';
1458 }
1459
1460 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1461   // Emit all numbered types.
1462   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1463     Out << "\ttype ";
1464     
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';
1469   }
1470   
1471   // Print the named types.
1472   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1473        TI != TE; ++TI) {
1474     Out << '\t';
1475     PrintLLVMName(Out, &TI->first[0], TI->first.size(), LocalPrefix);
1476     Out << " = type ";
1477
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);
1481     Out << '\n';
1482   }
1483 }
1484
1485 /// printFunction - Print all aspects of a function.
1486 ///
1487 void AssemblyWriter::printFunction(const Function *F) {
1488   // Print out the return type and name.
1489   Out << '\n';
1490
1491   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1492
1493   if (F->isDeclaration())
1494     Out << "declare ";
1495   else
1496     Out << "define ";
1497   
1498   PrintLinkage(F->getLinkage(), Out);
1499   PrintVisibility(F->getVisibility(), Out);
1500
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;
1512   }
1513
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);
1520   Out << ' ';
1521   WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1522   Out << '(';
1523   Machine.incorporateFunction(F);
1524
1525   // Loop over the arguments, printing them...
1526
1527   unsigned Idx = 1;
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();
1531          I != E; ++I) {
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));
1535       Idx++;
1536     }
1537   } else {
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
1541       if (i) Out << ", ";
1542       
1543       // Output type...
1544       TypePrinter.print(FT->getParamType(i), Out);
1545       
1546       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1547       if (ArgAttrs != Attribute::None)
1548         Out << ' ' << Attribute::getAsString(ArgAttrs);
1549     }
1550   }
1551
1552   // Finish printing arguments...
1553   if (FT->isVarArg()) {
1554     if (FT->getNumParams()) Out << ", ";
1555     Out << "...";  // Output varargs portion of signature!
1556   }
1557   Out << ')';
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();
1565   if (F->hasGC())
1566     Out << " gc \"" << F->getGC() << '"';
1567   if (F->isDeclaration()) {
1568     Out << "\n";
1569   } else {
1570     Out << " {";
1571
1572     // Output all of its basic blocks... for the function
1573     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1574       printBasicBlock(I);
1575
1576     Out << "}\n";
1577   }
1578
1579   Machine.purgeFunction();
1580 }
1581
1582 /// printArgument - This member is called for every argument that is passed into
1583 /// the function.  Simply print it out
1584 ///
1585 void AssemblyWriter::printArgument(const Argument *Arg, 
1586                                    Attributes Attrs) {
1587   // Output type...
1588   TypePrinter.print(Arg->getType(), Out);
1589
1590   // Output parameter attributes list
1591   if (Attrs != Attribute::None)
1592     Out << ' ' << Attribute::getAsString(Attrs);
1593
1594   // Output name, if available...
1595   if (Arg->hasName()) {
1596     Out << ' ';
1597     PrintLLVMName(Out, Arg);
1598   }
1599 }
1600
1601 /// printBasicBlock - This member is called for each basic block in a method.
1602 ///
1603 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1604   if (BB->hasName()) {              // Print out the label if it exists...
1605     Out << "\n";
1606     PrintLLVMName(Out, BB->getNameStart(), BB->getNameLen(), LabelPrefix);
1607     Out << ':';
1608   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1609     Out << "\n; <label>:";
1610     int Slot = Machine.getLocalSlot(BB);
1611     if (Slot != -1)
1612       Out << Slot;
1613     else
1614       Out << "<badref>";
1615   }
1616
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...
1621     Out << "\t\t;";
1622     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1623     
1624     if (PI == PE) {
1625       Out << " No predecessors!";
1626     } else {
1627       Out << " preds = ";
1628       writeOperand(*PI, false);
1629       for (++PI; PI != PE; ++PI) {
1630         Out << ", ";
1631         writeOperand(*PI, false);
1632       }
1633     }
1634   }
1635
1636   Out << "\n";
1637
1638   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1639
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);
1643     Out << '\n';
1644   }
1645
1646   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1647 }
1648
1649
1650 /// printInfoComment - Print a little comment after the instruction indicating
1651 /// which slot it occupies.
1652 ///
1653 void AssemblyWriter::printInfoComment(const Value &V) {
1654   if (V.getType() != Type::VoidTy) {
1655     Out << "\t\t; <";
1656     TypePrinter.print(V.getType(), Out);
1657     Out << '>';
1658
1659     if (!V.hasName() && !isa<Instruction>(V)) {
1660       int SlotNum;
1661       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1662         SlotNum = Machine.getGlobalSlot(GV);
1663       else
1664         SlotNum = Machine.getLocalSlot(&V);
1665       if (SlotNum == -1)
1666         Out << ":<badref>";
1667       else
1668         Out << ':' << SlotNum; // Print out the def slot taken.
1669     }
1670     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1671   }
1672 }
1673
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);
1677
1678   Out << '\t';
1679
1680   // Print out name if it exists...
1681   if (I.hasName()) {
1682     PrintLLVMName(Out, &I);
1683     Out << " = ";
1684   } else if (I.getType() != Type::VoidTy) {
1685     // Print out the def slot taken.
1686     int SlotNum = Machine.getLocalSlot(&I);
1687     if (SlotNum == -1)
1688       Out << "<badref> = ";
1689     else
1690       Out << '%' << SlotNum << " = ";
1691   }
1692
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())) {
1696       Out << "volatile ";
1697   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1698     // If this is a call, check if it's a tail call.
1699     Out << "tail ";
1700   }
1701
1702   // Print out optimization information.
1703   WriteOptimizationInfo(Out, &I);
1704
1705   // Print out the opcode...
1706   Out << I.getOpcodeName();
1707
1708   // Print out the compare instruction predicates
1709   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1710     Out << ' ' << getPredicateText(CI->getPredicate());
1711
1712   // Print out the type of the operands...
1713   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1714
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));
1718     Out << ' ';
1719     writeOperand(BI.getCondition(), true);
1720     Out << ", ";
1721     writeOperand(BI.getSuccessor(0), true);
1722     Out << ", ";
1723     writeOperand(BI.getSuccessor(1), true);
1724
1725   } else if (isa<SwitchInst>(I)) {
1726     // Special case switch statement to get formatting nice and correct...
1727     Out << ' ';
1728     writeOperand(Operand        , true);
1729     Out << ", ";
1730     writeOperand(I.getOperand(1), true);
1731     Out << " [";
1732
1733     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1734       Out << "\n\t\t";
1735       writeOperand(I.getOperand(op  ), true);
1736       Out << ", ";
1737       writeOperand(I.getOperand(op+1), true);
1738     }
1739     Out << "\n\t]";
1740   } else if (isa<PHINode>(I)) {
1741     Out << ' ';
1742     TypePrinter.print(I.getType(), Out);
1743     Out << ' ';
1744
1745     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1746       if (op) Out << ", ";
1747       Out << "[ ";
1748       writeOperand(I.getOperand(op  ), false); Out << ", ";
1749       writeOperand(I.getOperand(op+1), false); Out << " ]";
1750     }
1751   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1752     Out << ' ';
1753     writeOperand(I.getOperand(0), true);
1754     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1755       Out << ", " << *i;
1756   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1757     Out << ' ';
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)
1761       Out << ", " << *i;
1762   } else if (isa<ReturnInst>(I) && !Operand) {
1763     Out << " void";
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;
1776     }
1777
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();
1782
1783     if (PAL.getRetAttributes() != Attribute::None)
1784       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1785
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.
1789     //
1790     Out << ' ';
1791     if (!FTy->isVarArg() &&
1792         (!isa<PointerType>(RetTy) ||
1793          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1794       TypePrinter.print(RetTy, Out);
1795       Out << ' ';
1796       writeOperand(Operand, false);
1797     } else {
1798       writeOperand(Operand, true);
1799     }
1800     Out << '(';
1801     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1802       if (op > 1)
1803         Out << ", ";
1804       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1805     }
1806     Out << ')';
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();
1814
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;
1826     }
1827
1828     if (PAL.getRetAttributes() != Attribute::None)
1829       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1830
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.
1834     //
1835     Out << ' ';
1836     if (!FTy->isVarArg() &&
1837         (!isa<PointerType>(RetTy) ||
1838          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1839       TypePrinter.print(RetTy, Out);
1840       Out << ' ';
1841       writeOperand(Operand, false);
1842     } else {
1843       writeOperand(Operand, true);
1844     }
1845     Out << '(';
1846     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1847       if (op > 3)
1848         Out << ", ";
1849       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1850     }
1851
1852     Out << ')';
1853     if (PAL.getFnAttributes() != Attribute::None)
1854       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1855
1856     Out << "\n\t\t\tto ";
1857     writeOperand(II->getNormalDest(), true);
1858     Out << " unwind ";
1859     writeOperand(II->getUnwindDest(), true);
1860
1861   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1862     Out << ' ';
1863     TypePrinter.print(AI->getType()->getElementType(), Out);
1864     if (AI->isArrayAllocation()) {
1865       Out << ", ";
1866       writeOperand(AI->getArraySize(), true);
1867     }
1868     if (AI->getAlignment()) {
1869       Out << ", align " << AI->getAlignment();
1870     }
1871   } else if (isa<CastInst>(I)) {
1872     if (Operand) {
1873       Out << ' ';
1874       writeOperand(Operand, true);   // Work with broken code
1875     }
1876     Out << " to ";
1877     TypePrinter.print(I.getType(), Out);
1878   } else if (isa<VAArgInst>(I)) {
1879     if (Operand) {
1880       Out << ' ';
1881       writeOperand(Operand, true);   // Work with broken code
1882     }
1883     Out << ", ";
1884     TypePrinter.print(I.getType(), Out);
1885   } else if (Operand) {   // Print the normal way.
1886
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();
1892
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;
1897     } else {
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!
1904           break;
1905         }
1906       }
1907     }
1908
1909     if (!PrintAllTypes) {
1910       Out << ' ';
1911       TypePrinter.print(TheType, Out);
1912     }
1913
1914     Out << ' ';
1915     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1916       if (i) Out << ", ";
1917       writeOperand(I.getOperand(i), PrintAllTypes);
1918     }
1919   }
1920   
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();
1926   }
1927
1928   printInfoComment(I);
1929 }
1930
1931
1932 //===----------------------------------------------------------------------===//
1933 //                       External Interface declarations
1934 //===----------------------------------------------------------------------===//
1935
1936 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1937   raw_os_ostream OS(o);
1938   print(OS, AAW);
1939 }
1940 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1941   SlotTracker SlotTable(this);
1942   AssemblyWriter W(OS, SlotTable, this, AAW);
1943   W.write(this);
1944 }
1945
1946 void Type::print(std::ostream &o) const {
1947   raw_os_ostream OS(o);
1948   print(OS);
1949 }
1950
1951 void Type::print(raw_ostream &OS) const {
1952   if (this == 0) {
1953     OS << "<null Type>";
1954     return;
1955   }
1956   TypePrinting().print(this, OS);
1957 }
1958
1959 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1960   if (this == 0) {
1961     OS << "printing a <null> value\n";
1962     return;
1963   }
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);
1968     W.write(I);
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);
1973     W.write(BB);
1974   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1975     SlotTracker SlotTable(GV->getParent());
1976     AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
1977     W.write(GV);
1978   } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
1979     TypePrinting TypePrinter;
1980     TypePrinter.print(MDS->getType(), OS);
1981     OS << ' ';
1982     OS << "!\"";
1983     PrintEscapedString(MDS->begin(), MDS->size(), OS);
1984     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);
1993     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);
2000   } else {
2001     llvm_unreachable("Unknown value to print out!");
2002   }
2003 }
2004
2005 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
2006   raw_os_ostream OS(O);
2007   print(OS, AAW);
2008 }
2009
2010 // Value::dump - allow easy printing of Values from the debugger.
2011 void Value::dump() const { print(errs()); errs() << '\n'; }
2012
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);
2017   errs() << '\n';
2018 }
2019
2020 // Type::dump - allow easy printing of Types from the debugger.
2021 void Type::dump() const { dump(0); }
2022
2023 // Module::dump() - Allow printing of Modules from the debugger.
2024 void Module::dump() const { print(errs(), 0); }