Print named metadata.
[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/Metadata.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/raw_ostream.h"
38 #include <algorithm>
39 #include <cctype>
40 #include <map>
41 using namespace llvm;
42
43 // Make virtual table appear in this compilation unit.
44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45
46 //===----------------------------------------------------------------------===//
47 // Helper Functions
48 //===----------------------------------------------------------------------===//
49
50 static const Module *getModuleFromVal(const Value *V) {
51   if (const Argument *MA = dyn_cast<Argument>(V))
52     return MA->getParent() ? MA->getParent()->getParent() : 0;
53   
54   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55     return BB->getParent() ? BB->getParent()->getParent() : 0;
56   
57   if (const Instruction *I = dyn_cast<Instruction>(V)) {
58     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59     return M ? M->getParent() : 0;
60   }
61   
62   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63     return GV->getParent();
64   return 0;
65 }
66
67 // PrintEscapedString - Print each character of the specified string, escaping
68 // it if it is not printable or if it is an escape char.
69 static void PrintEscapedString(const StringRef &Name, raw_ostream &Out) {
70   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71     unsigned char C = Name[i];
72     if (isprint(C) && C != '\\' && C != '"')
73       Out << C;
74     else
75       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76   }
77 }
78
79 enum PrefixType {
80   GlobalPrefix,
81   LabelPrefix,
82   LocalPrefix,
83   NoPrefix
84 };
85
86 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87 /// prefixed with % (if the string only contains simple characters) or is
88 /// surrounded with ""'s (if it has special chars in it).  Print it out.
89 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
90                           PrefixType Prefix) {
91   assert(Name.data() && "Cannot get empty name!");
92   switch (Prefix) {
93   default: llvm_unreachable("Bad prefix!");
94   case NoPrefix: break;
95   case GlobalPrefix: OS << '@'; break;
96   case LabelPrefix:  break;
97   case LocalPrefix:  OS << '%'; break;
98   }
99   
100   // Scan the name to see if it needs quotes first.
101   bool NeedsQuotes = isdigit(Name[0]);
102   if (!NeedsQuotes) {
103     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
104       char C = Name[i];
105       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
106         NeedsQuotes = true;
107         break;
108       }
109     }
110   }
111   
112   // If we didn't need any quotes, just write out the name in one blast.
113   if (!NeedsQuotes) {
114     OS << Name;
115     return;
116   }
117   
118   // Okay, we need quotes.  Output the quotes and escape any scary characters as
119   // needed.
120   OS << '"';
121   PrintEscapedString(Name, OS);
122   OS << '"';
123 }
124
125 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
126 /// prefixed with % (if the string only contains simple characters) or is
127 /// surrounded with ""'s (if it has special chars in it).  Print it out.
128 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
129   PrintLLVMName(OS, V->getName(), 
130                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
131 }
132
133 //===----------------------------------------------------------------------===//
134 // TypePrinting Class: Type printing machinery
135 //===----------------------------------------------------------------------===//
136
137 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
138   return *static_cast<DenseMap<const Type *, std::string>*>(M);
139 }
140
141 void TypePrinting::clear() {
142   getTypeNamesMap(TypeNames).clear();
143 }
144
145 bool TypePrinting::hasTypeName(const Type *Ty) const {
146   return getTypeNamesMap(TypeNames).count(Ty);
147 }
148
149 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
150   getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
151 }
152
153
154 TypePrinting::TypePrinting() {
155   TypeNames = new DenseMap<const Type *, std::string>();
156 }
157
158 TypePrinting::~TypePrinting() {
159   delete &getTypeNamesMap(TypeNames);
160 }
161
162 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
163 /// use of type names or up references to shorten the type name where possible.
164 void TypePrinting::CalcTypeName(const Type *Ty,
165                                 SmallVectorImpl<const Type *> &TypeStack,
166                                 raw_ostream &OS, bool IgnoreTopLevelName) {
167   // Check to see if the type is named.
168   if (!IgnoreTopLevelName) {
169     DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
170     DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
171     if (I != TM.end()) {
172       OS << I->second;
173       return;
174     }
175   }
176   
177   // Check to see if the Type is already on the stack...
178   unsigned Slot = 0, CurSize = TypeStack.size();
179   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
180   
181   // This is another base case for the recursion.  In this case, we know
182   // that we have looped back to a type that we have previously visited.
183   // Generate the appropriate upreference to handle this.
184   if (Slot < CurSize) {
185     OS << '\\' << unsigned(CurSize-Slot);     // Here's the upreference
186     return;
187   }
188   
189   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
190   
191   switch (Ty->getTypeID()) {
192   case Type::VoidTyID:      OS << "void"; break;
193   case Type::FloatTyID:     OS << "float"; break;
194   case Type::DoubleTyID:    OS << "double"; break;
195   case Type::X86_FP80TyID:  OS << "x86_fp80"; break;
196   case Type::FP128TyID:     OS << "fp128"; break;
197   case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
198   case Type::LabelTyID:     OS << "label"; break;
199   case Type::MetadataTyID:  OS << "metadata"; break;
200   case Type::IntegerTyID:
201     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
202     break;
203       
204   case Type::FunctionTyID: {
205     const FunctionType *FTy = cast<FunctionType>(Ty);
206     CalcTypeName(FTy->getReturnType(), TypeStack, OS);
207     OS << " (";
208     for (FunctionType::param_iterator I = FTy->param_begin(),
209          E = FTy->param_end(); I != E; ++I) {
210       if (I != FTy->param_begin())
211         OS << ", ";
212       CalcTypeName(*I, TypeStack, OS);
213     }
214     if (FTy->isVarArg()) {
215       if (FTy->getNumParams()) OS << ", ";
216       OS << "...";
217     }
218     OS << ')';
219     break;
220   }
221   case Type::StructTyID: {
222     const StructType *STy = cast<StructType>(Ty);
223     if (STy->isPacked())
224       OS << '<';
225     OS << "{ ";
226     for (StructType::element_iterator I = STy->element_begin(),
227          E = STy->element_end(); I != E; ++I) {
228       CalcTypeName(*I, TypeStack, OS);
229       if (next(I) != STy->element_end())
230         OS << ',';
231       OS << ' ';
232     }
233     OS << '}';
234     if (STy->isPacked())
235       OS << '>';
236     break;
237   }
238   case Type::PointerTyID: {
239     const PointerType *PTy = cast<PointerType>(Ty);
240     CalcTypeName(PTy->getElementType(), TypeStack, OS);
241     if (unsigned AddressSpace = PTy->getAddressSpace())
242       OS << " addrspace(" << AddressSpace << ')';
243     OS << '*';
244     break;
245   }
246   case Type::ArrayTyID: {
247     const ArrayType *ATy = cast<ArrayType>(Ty);
248     OS << '[' << ATy->getNumElements() << " x ";
249     CalcTypeName(ATy->getElementType(), TypeStack, OS);
250     OS << ']';
251     break;
252   }
253   case Type::VectorTyID: {
254     const VectorType *PTy = cast<VectorType>(Ty);
255     OS << "<" << PTy->getNumElements() << " x ";
256     CalcTypeName(PTy->getElementType(), TypeStack, OS);
257     OS << '>';
258     break;
259   }
260   case Type::OpaqueTyID:
261     OS << "opaque";
262     break;
263   default:
264     OS << "<unrecognized-type>";
265     break;
266   }
267   
268   TypeStack.pop_back();       // Remove self from stack.
269 }
270
271 /// printTypeInt - The internal guts of printing out a type that has a
272 /// potentially named portion.
273 ///
274 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
275                          bool IgnoreTopLevelName) {
276   // Check to see if the type is named.
277   DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
278   if (!IgnoreTopLevelName) {
279     DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
280     if (I != TM.end()) {
281       OS << I->second;
282       return;
283     }
284   }
285   
286   // Otherwise we have a type that has not been named but is a derived type.
287   // Carefully recurse the type hierarchy to print out any contained symbolic
288   // names.
289   SmallVector<const Type *, 16> TypeStack;
290   std::string TypeName;
291   
292   raw_string_ostream TypeOS(TypeName);
293   CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
294   OS << TypeOS.str();
295
296   // Cache type name for later use.
297   if (!IgnoreTopLevelName)
298     TM.insert(std::make_pair(Ty, TypeOS.str()));
299 }
300
301 namespace {
302   class TypeFinder {
303     // To avoid walking constant expressions multiple times and other IR
304     // objects, we keep several helper maps.
305     DenseSet<const Value*> VisitedConstants;
306     DenseSet<const Type*> VisitedTypes;
307     
308     TypePrinting &TP;
309     std::vector<const Type*> &NumberedTypes;
310   public:
311     TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
312       : TP(tp), NumberedTypes(numberedTypes) {}
313     
314     void Run(const Module &M) {
315       // Get types from the type symbol table.  This gets opaque types referened
316       // only through derived named types.
317       const TypeSymbolTable &ST = M.getTypeSymbolTable();
318       for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
319            TI != E; ++TI)
320         IncorporateType(TI->second);
321       
322       // Get types from global variables.
323       for (Module::const_global_iterator I = M.global_begin(),
324            E = M.global_end(); I != E; ++I) {
325         IncorporateType(I->getType());
326         if (I->hasInitializer())
327           IncorporateValue(I->getInitializer());
328       }
329       
330       // Get types from aliases.
331       for (Module::const_alias_iterator I = M.alias_begin(),
332            E = M.alias_end(); I != E; ++I) {
333         IncorporateType(I->getType());
334         IncorporateValue(I->getAliasee());
335       }
336       
337       // Get types from functions.
338       for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
339         IncorporateType(FI->getType());
340         
341         for (Function::const_iterator BB = FI->begin(), E = FI->end();
342              BB != E;++BB)
343           for (BasicBlock::const_iterator II = BB->begin(),
344                E = BB->end(); II != E; ++II) {
345             const Instruction &I = *II;
346             // Incorporate the type of the instruction and all its operands.
347             IncorporateType(I.getType());
348             for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
349                  OI != OE; ++OI)
350               IncorporateValue(*OI);
351           }
352       }
353     }
354     
355   private:
356     void IncorporateType(const Type *Ty) {
357       // Check to see if we're already visited this type.
358       if (!VisitedTypes.insert(Ty).second)
359         return;
360       
361       // If this is a structure or opaque type, add a name for the type.
362       if (((isa<StructType>(Ty) && cast<StructType>(Ty)->getNumElements())
363             || isa<OpaqueType>(Ty)) && !TP.hasTypeName(Ty)) {
364         TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
365         NumberedTypes.push_back(Ty);
366       }
367       
368       // Recursively walk all contained types.
369       for (Type::subtype_iterator I = Ty->subtype_begin(),
370            E = Ty->subtype_end(); I != E; ++I)
371         IncorporateType(*I);      
372     }
373     
374     /// IncorporateValue - This method is used to walk operand lists finding
375     /// types hiding in constant expressions and other operands that won't be
376     /// walked in other ways.  GlobalValues, basic blocks, instructions, and
377     /// inst operands are all explicitly enumerated.
378     void IncorporateValue(const Value *V) {
379       if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
380       
381       // Already visited?
382       if (!VisitedConstants.insert(V).second)
383         return;
384       
385       // Check this type.
386       IncorporateType(V->getType());
387       
388       // Look in operands for types.
389       const Constant *C = cast<Constant>(V);
390       for (Constant::const_op_iterator I = C->op_begin(),
391            E = C->op_end(); I != E;++I)
392         IncorporateValue(*I);
393     }
394   };
395 } // end anonymous namespace
396
397
398 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
399 /// the specified module to the TypePrinter and all numbered types to it and the
400 /// NumberedTypes table.
401 static void AddModuleTypesToPrinter(TypePrinting &TP, 
402                                     std::vector<const Type*> &NumberedTypes,
403                                     const Module *M) {
404   if (M == 0) return;
405   
406   // If the module has a symbol table, take all global types and stuff their
407   // names into the TypeNames map.
408   const TypeSymbolTable &ST = M->getTypeSymbolTable();
409   for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
410        TI != E; ++TI) {
411     const Type *Ty = cast<Type>(TI->second);
412     
413     // As a heuristic, don't insert pointer to primitive types, because
414     // they are used too often to have a single useful name.
415     if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
416       const Type *PETy = PTy->getElementType();
417       if ((PETy->isPrimitiveType() || PETy->isInteger()) &&
418           !isa<OpaqueType>(PETy))
419         continue;
420     }
421     
422     // Likewise don't insert primitives either.
423     if (Ty->isInteger() || Ty->isPrimitiveType())
424       continue;
425     
426     // Get the name as a string and insert it into TypeNames.
427     std::string NameStr;
428     raw_string_ostream NameOS(NameStr);
429     PrintLLVMName(NameOS, TI->first, LocalPrefix);
430     TP.addTypeName(Ty, NameOS.str());
431   }
432   
433   // Walk the entire module to find references to unnamed structure and opaque
434   // types.  This is required for correctness by opaque types (because multiple
435   // uses of an unnamed opaque type needs to be referred to by the same ID) and
436   // it shrinks complex recursive structure types substantially in some cases.
437   TypeFinder(TP, NumberedTypes).Run(*M);
438 }
439
440
441 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
442 /// type, iff there is an entry in the modules symbol table for the specified
443 /// type or one of it's component types.
444 ///
445 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
446   TypePrinting Printer;
447   std::vector<const Type*> NumberedTypes;
448   AddModuleTypesToPrinter(Printer, NumberedTypes, M);
449   Printer.print(Ty, OS);
450 }
451
452 //===----------------------------------------------------------------------===//
453 // SlotTracker Class: Enumerate slot numbers for unnamed values
454 //===----------------------------------------------------------------------===//
455
456 namespace {
457
458 /// This class provides computation of slot numbers for LLVM Assembly writing.
459 ///
460 class SlotTracker {
461 public:
462   /// ValueMap - A mapping of Values to slot numbers.
463   typedef DenseMap<const Value*, unsigned> ValueMap;
464   
465 private:  
466   /// TheModule - The module for which we are holding slot numbers.
467   const Module* TheModule;
468   
469   /// TheFunction - The function for which we are holding slot numbers.
470   const Function* TheFunction;
471   bool FunctionProcessed;
472   
473   /// TheMDNode - The MDNode for which we are holding slot numbers.
474   const MDNode *TheMDNode;
475
476   /// mMap - The TypePlanes map for the module level data.
477   ValueMap mMap;
478   unsigned mNext;
479   
480   /// fMap - The TypePlanes map for the function level data.
481   ValueMap fMap;
482   unsigned fNext;
483   
484   /// mdnMap - Map for MDNodes.
485   ValueMap mdnMap;
486   unsigned mdnNext;
487 public:
488   /// Construct from a module
489   explicit SlotTracker(const Module *M);
490   /// Construct from a function, starting out in incorp state.
491   explicit SlotTracker(const Function *F);
492   /// Construct from a mdnode.
493   explicit SlotTracker(const MDNode *N);
494
495   /// Return the slot number of the specified value in it's type
496   /// plane.  If something is not in the SlotTracker, return -1.
497   int getLocalSlot(const Value *V);
498   int getGlobalSlot(const GlobalValue *V);
499   int getMetadataSlot(const MDNode *N);
500
501   /// If you'd like to deal with a function instead of just a module, use
502   /// this method to get its data into the SlotTracker.
503   void incorporateFunction(const Function *F) {
504     TheFunction = F;
505     FunctionProcessed = false;
506   }
507
508   /// After calling incorporateFunction, use this method to remove the
509   /// most recently incorporated function from the SlotTracker. This
510   /// will reset the state of the machine back to just the module contents.
511   void purgeFunction();
512
513   /// MDNode map iterators.
514   ValueMap::iterator mdnBegin() { return mdnMap.begin(); }
515   ValueMap::iterator mdnEnd() { return mdnMap.end(); }
516   unsigned mdnSize() { return mdnMap.size(); }
517
518   /// This function does the actual initialization.
519   inline void initialize();
520
521   // Implementation Details
522 private:
523   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
524   void CreateModuleSlot(const GlobalValue *V);
525
526   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
527   void CreateMetadataSlot(const MDNode *N);
528
529   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
530   void CreateFunctionSlot(const Value *V);
531
532   /// Add all of the module level global variables (and their initializers)
533   /// and function declarations, but not the contents of those functions.
534   void processModule();
535
536   /// Add all of the functions arguments, basic blocks, and instructions.
537   void processFunction();
538
539   /// Add all MDNode operands.
540   void processMDNode();
541
542   SlotTracker(const SlotTracker &);  // DO NOT IMPLEMENT
543   void operator=(const SlotTracker &);  // DO NOT IMPLEMENT
544 };
545
546 }  // end anonymous namespace
547
548
549 static SlotTracker *createSlotTracker(const Value *V) {
550   if (const Argument *FA = dyn_cast<Argument>(V))
551     return new SlotTracker(FA->getParent());
552   
553   if (const Instruction *I = dyn_cast<Instruction>(V))
554     return new SlotTracker(I->getParent()->getParent());
555   
556   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
557     return new SlotTracker(BB->getParent());
558   
559   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
560     return new SlotTracker(GV->getParent());
561   
562   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
563     return new SlotTracker(GA->getParent());    
564   
565   if (const Function *Func = dyn_cast<Function>(V))
566     return new SlotTracker(Func);
567   
568   return 0;
569 }
570
571 #if 0
572 #define ST_DEBUG(X) errs() << X
573 #else
574 #define ST_DEBUG(X)
575 #endif
576
577 // Module level constructor. Causes the contents of the Module (sans functions)
578 // to be added to the slot table.
579 SlotTracker::SlotTracker(const Module *M)
580   : TheModule(M), TheFunction(0), FunctionProcessed(false), TheMDNode(0),
581     mNext(0), fNext(0),  mdnNext(0) {
582 }
583
584 // Function level constructor. Causes the contents of the Module and the one
585 // function provided to be added to the slot table.
586 SlotTracker::SlotTracker(const Function *F)
587   : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
588     TheMDNode(0), mNext(0), fNext(0), mdnNext(0) {
589 }
590
591 // Constructor to handle single MDNode.
592 SlotTracker::SlotTracker(const MDNode *C)
593   : TheModule(0), TheFunction(0), FunctionProcessed(false), TheMDNode(C),
594     mNext(0), fNext(0),  mdnNext(0) {
595 }
596
597 inline void SlotTracker::initialize() {
598   if (TheModule) {
599     processModule();
600     TheModule = 0; ///< Prevent re-processing next time we're called.
601   }
602   
603   if (TheFunction && !FunctionProcessed)
604     processFunction();
605
606   if (TheMDNode)
607     processMDNode();
608 }
609
610 // Iterate through all the global variables, functions, and global
611 // variable initializers and create slots for them.
612 void SlotTracker::processModule() {
613   ST_DEBUG("begin processModule!\n");
614   
615   // Add all of the unnamed global variables to the value table.
616   for (Module::const_global_iterator I = TheModule->global_begin(),
617          E = TheModule->global_end(); I != E; ++I) {
618     if (!I->hasName()) 
619       CreateModuleSlot(I);
620     if (I->hasInitializer()) {
621       if (MDNode *N = dyn_cast<MDNode>(I->getInitializer())) 
622         CreateMetadataSlot(N);
623     }
624   }
625   
626   // Add metadata used by named metadata.
627   for (Module::const_named_metadata_iterator 
628          I = TheModule->named_metadata_begin(),
629          E = TheModule->named_metadata_end(); I != E; ++I) {
630     const NamedMDNode *NMD = I;
631     for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
632       MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i));
633       CreateMetadataSlot(MD);
634     }
635   }
636
637   // Add all the unnamed functions to the table.
638   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
639        I != E; ++I)
640     if (!I->hasName())
641       CreateModuleSlot(I);
642   
643   ST_DEBUG("end processModule!\n");
644 }
645
646 // Process the arguments, basic blocks, and instructions  of a function.
647 void SlotTracker::processFunction() {
648   ST_DEBUG("begin processFunction!\n");
649   fNext = 0;
650   
651   // Add all the function arguments with no names.
652   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
653       AE = TheFunction->arg_end(); AI != AE; ++AI)
654     if (!AI->hasName())
655       CreateFunctionSlot(AI);
656   
657   ST_DEBUG("Inserting Instructions:\n");
658   
659   // Add all of the basic blocks and instructions with no names.
660   for (Function::const_iterator BB = TheFunction->begin(),
661        E = TheFunction->end(); BB != E; ++BB) {
662     if (!BB->hasName())
663       CreateFunctionSlot(BB);
664     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; 
665          ++I) {
666       if (I->getType() != Type::VoidTy && !I->hasName())
667         CreateFunctionSlot(I);
668       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 
669         if (MDNode *N = dyn_cast<MDNode>(I->getOperand(i))) 
670           CreateMetadataSlot(N);
671     }
672   }
673   
674   FunctionProcessed = true;
675   
676   ST_DEBUG("end processFunction!\n");
677 }
678
679 /// processMDNode - Process TheMDNode.
680 void SlotTracker::processMDNode() {
681   ST_DEBUG("begin processMDNode!\n");
682   mdnNext = 0;
683   CreateMetadataSlot(TheMDNode);
684   TheMDNode = 0;
685   ST_DEBUG("end processMDNode!\n");
686 }
687
688 /// Clean up after incorporating a function. This is the only way to get out of
689 /// the function incorporation state that affects get*Slot/Create*Slot. Function
690 /// incorporation state is indicated by TheFunction != 0.
691 void SlotTracker::purgeFunction() {
692   ST_DEBUG("begin purgeFunction!\n");
693   fMap.clear(); // Simply discard the function level map
694   TheFunction = 0;
695   FunctionProcessed = false;
696   ST_DEBUG("end purgeFunction!\n");
697 }
698
699 /// getGlobalSlot - Get the slot number of a global value.
700 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
701   // Check for uninitialized state and do lazy initialization.
702   initialize();
703   
704   // Find the type plane in the module map
705   ValueMap::iterator MI = mMap.find(V);
706   return MI == mMap.end() ? -1 : (int)MI->second;
707 }
708
709 /// getGlobalSlot - Get the slot number of a MDNode.
710 int SlotTracker::getMetadataSlot(const MDNode *N) {
711   // Check for uninitialized state and do lazy initialization.
712   initialize();
713   
714   // Find the type plane in the module map
715   ValueMap::iterator MI = mdnMap.find(N);
716   return MI == mdnMap.end() ? -1 : (int)MI->second;
717 }
718
719
720 /// getLocalSlot - Get the slot number for a value that is local to a function.
721 int SlotTracker::getLocalSlot(const Value *V) {
722   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
723   
724   // Check for uninitialized state and do lazy initialization.
725   initialize();
726   
727   ValueMap::iterator FI = fMap.find(V);
728   return FI == fMap.end() ? -1 : (int)FI->second;
729 }
730
731
732 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
733 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
734   assert(V && "Can't insert a null Value into SlotTracker!");
735   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
736   assert(!V->hasName() && "Doesn't need a slot!");
737   
738   unsigned DestSlot = mNext++;
739   mMap[V] = DestSlot;
740   
741   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
742            DestSlot << " [");
743   // G = Global, F = Function, A = Alias, o = other
744   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
745             (isa<Function>(V) ? 'F' :
746              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
747 }
748
749 /// CreateSlot - Create a new slot for the specified value if it has no name.
750 void SlotTracker::CreateFunctionSlot(const Value *V) {
751   assert(V->getType() != Type::VoidTy && !V->hasName() &&
752          "Doesn't need a slot!");
753   
754   unsigned DestSlot = fNext++;
755   fMap[V] = DestSlot;
756   
757   // G = Global, F = Function, o = other
758   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
759            DestSlot << " [o]\n");
760 }  
761
762 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
763 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
764   assert(N && "Can't insert a null Value into SlotTracker!");
765   
766   ValueMap::iterator I = mdnMap.find(N);
767   if (I != mdnMap.end())
768     return;
769
770   unsigned DestSlot = mdnNext++;
771   mdnMap[N] = DestSlot;
772
773   for (MDNode::const_elem_iterator MDI = N->elem_begin(), 
774          MDE = N->elem_end(); MDI != MDE; ++MDI) {
775     const Value *TV = *MDI;
776     if (TV)
777       if (const MDNode *N2 = dyn_cast<MDNode>(TV)) 
778         CreateMetadataSlot(N2);
779   }
780 }
781
782 //===----------------------------------------------------------------------===//
783 // AsmWriter Implementation
784 //===----------------------------------------------------------------------===//
785
786 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
787                                    TypePrinting &TypePrinter,
788                                    SlotTracker *Machine);
789
790
791
792 static const char *getPredicateText(unsigned predicate) {
793   const char * pred = "unknown";
794   switch (predicate) {
795     case FCmpInst::FCMP_FALSE: pred = "false"; break;
796     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
797     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
798     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
799     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
800     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
801     case FCmpInst::FCMP_ONE:   pred = "one"; break;
802     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
803     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
804     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
805     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
806     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
807     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
808     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
809     case FCmpInst::FCMP_UNE:   pred = "une"; break;
810     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
811     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
812     case ICmpInst::ICMP_NE:    pred = "ne"; break;
813     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
814     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
815     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
816     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
817     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
818     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
819     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
820     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
821   }
822   return pred;
823 }
824
825 static void WriteMDNodes(raw_ostream &Out, TypePrinting &TypePrinter,
826                          SlotTracker &Machine) {
827   SmallVector<const MDNode *, 16> Nodes;
828   Nodes.resize(Machine.mdnSize());
829   for (SlotTracker::ValueMap::iterator I = 
830          Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) 
831     Nodes[I->second] = cast<MDNode>(I->first);
832
833   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
834     Out << '!' << i << " = metadata ";
835     const MDNode *Node = Nodes[i];
836     Out << "!{";
837     for (MDNode::const_elem_iterator NI = Node->elem_begin(), 
838            NE = Node->elem_end(); NI != NE;) {
839       const Value *V = *NI;
840       if (!V)
841         Out << "null";
842       else if (const MDNode *N = dyn_cast<MDNode>(V)) {
843         Out << "metadata ";
844         Out << '!' << Machine.getMetadataSlot(N);
845       }
846       else {
847         TypePrinter.print((*NI)->getType(), Out);
848         Out << ' ';
849         WriteAsOperandInternal(Out, *NI, TypePrinter, &Machine);
850       }
851       if (++NI != NE)
852         Out << ", ";
853     }
854     Out << "}\n";
855   }
856 }
857
858 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
859   if (const OverflowingBinaryOperator *OBO =
860         dyn_cast<OverflowingBinaryOperator>(U)) {
861     if (OBO->hasNoUnsignedOverflow())
862       Out << " nuw";
863     if (OBO->hasNoSignedOverflow())
864       Out << " nsw";
865   } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
866     if (Div->isExact())
867       Out << " exact";
868   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
869     if (GEP->isInBounds())
870       Out << " inbounds";
871   }
872 }
873
874 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
875                              TypePrinting &TypePrinter, SlotTracker *Machine) {
876   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
877     if (CI->getType() == Type::Int1Ty) {
878       Out << (CI->getZExtValue() ? "true" : "false");
879       return;
880     }
881     Out << CI->getValue();
882     return;
883   }
884   
885   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
886     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
887         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
888       // We would like to output the FP constant value in exponential notation,
889       // but we cannot do this if doing so will lose precision.  Check here to
890       // make sure that we only output it in exponential format if we can parse
891       // the value back and get the same value.
892       //
893       bool ignored;
894       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
895       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
896                               CFP->getValueAPF().convertToFloat();
897       std::string StrVal = ftostr(CFP->getValueAPF());
898
899       // Check to make sure that the stringized number is not some string like
900       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
901       // that the string matches the "[-+]?[0-9]" regex.
902       //
903       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
904           ((StrVal[0] == '-' || StrVal[0] == '+') &&
905            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
906         // Reparse stringized version!
907         if (atof(StrVal.c_str()) == Val) {
908           Out << StrVal;
909           return;
910         }
911       }
912       // Otherwise we could not reparse it to exactly the same value, so we must
913       // output the string in hexadecimal format!  Note that loading and storing
914       // floating point types changes the bits of NaNs on some hosts, notably
915       // x86, so we must not use these types.
916       assert(sizeof(double) == sizeof(uint64_t) &&
917              "assuming that double is 64 bits!");
918       char Buffer[40];
919       APFloat apf = CFP->getValueAPF();
920       // Floats are represented in ASCII IR as double, convert.
921       if (!isDouble)
922         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 
923                           &ignored);
924       Out << "0x" << 
925               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 
926                             Buffer+40);
927       return;
928     }
929     
930     // Some form of long double.  These appear as a magic letter identifying
931     // the type, then a fixed number of hex digits.
932     Out << "0x";
933     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
934       Out << 'K';
935       // api needed to prevent premature destruction
936       APInt api = CFP->getValueAPF().bitcastToAPInt();
937       const uint64_t* p = api.getRawData();
938       uint64_t word = p[1];
939       int shiftcount=12;
940       int width = api.getBitWidth();
941       for (int j=0; j<width; j+=4, shiftcount-=4) {
942         unsigned int nibble = (word>>shiftcount) & 15;
943         if (nibble < 10)
944           Out << (unsigned char)(nibble + '0');
945         else
946           Out << (unsigned char)(nibble - 10 + 'A');
947         if (shiftcount == 0 && j+4 < width) {
948           word = *p;
949           shiftcount = 64;
950           if (width-j-4 < 64)
951             shiftcount = width-j-4;
952         }
953       }
954       return;
955     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
956       Out << 'L';
957     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
958       Out << 'M';
959     else
960       llvm_unreachable("Unsupported floating point type");
961     // api needed to prevent premature destruction
962     APInt api = CFP->getValueAPF().bitcastToAPInt();
963     const uint64_t* p = api.getRawData();
964     uint64_t word = *p;
965     int shiftcount=60;
966     int width = api.getBitWidth();
967     for (int j=0; j<width; j+=4, shiftcount-=4) {
968       unsigned int nibble = (word>>shiftcount) & 15;
969       if (nibble < 10)
970         Out << (unsigned char)(nibble + '0');
971       else
972         Out << (unsigned char)(nibble - 10 + 'A');
973       if (shiftcount == 0 && j+4 < width) {
974         word = *(++p);
975         shiftcount = 64;
976         if (width-j-4 < 64)
977           shiftcount = width-j-4;
978       }
979     }
980     return;
981   }
982   
983   if (isa<ConstantAggregateZero>(CV)) {
984     Out << "zeroinitializer";
985     return;
986   }
987   
988   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
989     // As a special case, print the array as a string if it is an array of
990     // i8 with ConstantInt values.
991     //
992     const Type *ETy = CA->getType()->getElementType();
993     if (CA->isString()) {
994       Out << "c\"";
995       PrintEscapedString(CA->getAsString(), Out);
996       Out << '"';
997     } else {                // Cannot output in string format...
998       Out << '[';
999       if (CA->getNumOperands()) {
1000         TypePrinter.print(ETy, Out);
1001         Out << ' ';
1002         WriteAsOperandInternal(Out, CA->getOperand(0),
1003                                TypePrinter, Machine);
1004         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1005           Out << ", ";
1006           TypePrinter.print(ETy, Out);
1007           Out << ' ';
1008           WriteAsOperandInternal(Out, CA->getOperand(i), TypePrinter, Machine);
1009         }
1010       }
1011       Out << ']';
1012     }
1013     return;
1014   }
1015   
1016   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1017     if (CS->getType()->isPacked())
1018       Out << '<';
1019     Out << '{';
1020     unsigned N = CS->getNumOperands();
1021     if (N) {
1022       Out << ' ';
1023       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1024       Out << ' ';
1025
1026       WriteAsOperandInternal(Out, CS->getOperand(0), TypePrinter, Machine);
1027
1028       for (unsigned i = 1; i < N; i++) {
1029         Out << ", ";
1030         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1031         Out << ' ';
1032
1033         WriteAsOperandInternal(Out, CS->getOperand(i), TypePrinter, Machine);
1034       }
1035       Out << ' ';
1036     }
1037  
1038     Out << '}';
1039     if (CS->getType()->isPacked())
1040       Out << '>';
1041     return;
1042   }
1043   
1044   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1045     const Type *ETy = CP->getType()->getElementType();
1046     assert(CP->getNumOperands() > 0 &&
1047            "Number of operands for a PackedConst must be > 0");
1048     Out << '<';
1049     TypePrinter.print(ETy, Out);
1050     Out << ' ';
1051     WriteAsOperandInternal(Out, CP->getOperand(0), TypePrinter, Machine);
1052     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1053       Out << ", ";
1054       TypePrinter.print(ETy, Out);
1055       Out << ' ';
1056       WriteAsOperandInternal(Out, CP->getOperand(i), TypePrinter, Machine);
1057     }
1058     Out << '>';
1059     return;
1060   }
1061   
1062   if (isa<ConstantPointerNull>(CV)) {
1063     Out << "null";
1064     return;
1065   }
1066   
1067   if (isa<UndefValue>(CV)) {
1068     Out << "undef";
1069     return;
1070   }
1071   
1072   if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1073     Out << "!" << Machine->getMetadataSlot(Node);
1074     return;
1075   }
1076
1077   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1078     Out << CE->getOpcodeName();
1079     WriteOptimizationInfo(Out, CE);
1080     if (CE->isCompare())
1081       Out << ' ' << getPredicateText(CE->getPredicate());
1082     Out << " (";
1083
1084     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1085       TypePrinter.print((*OI)->getType(), Out);
1086       Out << ' ';
1087       WriteAsOperandInternal(Out, *OI, TypePrinter, Machine);
1088       if (OI+1 != CE->op_end())
1089         Out << ", ";
1090     }
1091
1092     if (CE->hasIndices()) {
1093       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1094       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1095         Out << ", " << Indices[i];
1096     }
1097
1098     if (CE->isCast()) {
1099       Out << " to ";
1100       TypePrinter.print(CE->getType(), Out);
1101     }
1102
1103     Out << ')';
1104     return;
1105   }
1106   
1107   Out << "<placeholder or erroneous Constant>";
1108 }
1109
1110
1111 /// WriteAsOperand - Write the name of the specified value out to the specified
1112 /// ostream.  This can be useful when you just want to print int %reg126, not
1113 /// the whole instruction that generated it.
1114 ///
1115 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1116                                    TypePrinting &TypePrinter,
1117                                    SlotTracker *Machine) {
1118   if (V->hasName()) {
1119     PrintLLVMName(Out, V);
1120     return;
1121   }
1122   
1123   const Constant *CV = dyn_cast<Constant>(V);
1124   if (CV && !isa<GlobalValue>(CV)) {
1125     WriteConstantInt(Out, CV, TypePrinter, Machine);
1126     return;
1127   }
1128   
1129   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1130     Out << "asm ";
1131     if (IA->hasSideEffects())
1132       Out << "sideeffect ";
1133     Out << '"';
1134     PrintEscapedString(IA->getAsmString(), Out);
1135     Out << "\", \"";
1136     PrintEscapedString(IA->getConstraintString(), Out);
1137     Out << '"';
1138     return;
1139   }
1140
1141   if (const MDNode *N = dyn_cast<MDNode>(V)) {
1142     Out << '!' << Machine->getMetadataSlot(N);
1143     return;
1144   }
1145
1146   if (const MDString *MDS = dyn_cast<MDString>(V)) {
1147     Out << "!\"";
1148     PrintEscapedString(MDS->getString(), Out);
1149     Out << '"';
1150     return;
1151   }
1152
1153   char Prefix = '%';
1154   int Slot;
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     Machine = createSlotTracker(V);
1164     if (Machine) {
1165       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1166         Slot = Machine->getGlobalSlot(GV);
1167         Prefix = '@';
1168       } else {
1169         Slot = Machine->getLocalSlot(V);
1170       }
1171     } else {
1172       Slot = -1;
1173     }
1174     delete Machine;
1175   }
1176   
1177   if (Slot != -1)
1178     Out << Prefix << Slot;
1179   else
1180     Out << "<badref>";
1181 }
1182
1183 /// WriteAsOperand - Write the name of the specified value out to the specified
1184 /// ostream.  This can be useful when you just want to print int %reg126, not
1185 /// the whole instruction that generated it.
1186 ///
1187 void llvm::WriteAsOperand(std::ostream &Out, const Value *V, bool PrintType,
1188                           const Module *Context) {
1189   raw_os_ostream OS(Out);
1190   WriteAsOperand(OS, V, PrintType, Context);
1191 }
1192
1193 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V, bool PrintType,
1194                           const Module *Context) {
1195   if (Context == 0) Context = getModuleFromVal(V);
1196
1197   TypePrinting TypePrinter;
1198   std::vector<const Type*> NumberedTypes;
1199   AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1200   if (PrintType) {
1201     TypePrinter.print(V->getType(), Out);
1202     Out << ' ';
1203   }
1204
1205   WriteAsOperandInternal(Out, V, TypePrinter, 0);
1206 }
1207
1208
1209 namespace {
1210
1211 class AssemblyWriter {
1212   raw_ostream &Out;
1213   SlotTracker &Machine;
1214   const Module *TheModule;
1215   TypePrinting TypePrinter;
1216   AssemblyAnnotationWriter *AnnotationWriter;
1217   std::vector<const Type*> NumberedTypes;
1218
1219   // Each MDNode is assigned unique MetadataIDNo.
1220   std::map<const MDNode *, unsigned> MDNodes;
1221   unsigned MetadataIDNo;
1222 public:
1223   inline AssemblyWriter(raw_ostream &o, SlotTracker &Mac, const Module *M,
1224                         AssemblyAnnotationWriter *AAW)
1225     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1226     AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1227   }
1228
1229   void write(const Module *M) { printModule(M); }
1230   
1231   void write(const GlobalValue *G) {
1232     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1233       printGlobal(GV);
1234     else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1235       printAlias(GA);
1236     else if (const Function *F = dyn_cast<Function>(G))
1237       printFunction(F);
1238     else
1239       llvm_unreachable("Unknown global");
1240   }
1241   
1242   void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
1243   void write(const Instruction *I)    { printInstruction(*I); }
1244
1245   void writeOperand(const Value *Op, bool PrintType);
1246   void writeParamOperand(const Value *Operand, Attributes Attrs);
1247
1248   const Module* getModule() { return TheModule; }
1249
1250 private:
1251   void printModule(const Module *M);
1252   void printTypeSymbolTable(const TypeSymbolTable &ST);
1253   void printGlobal(const GlobalVariable *GV);
1254   void printAlias(const GlobalAlias *GV);
1255   void printFunction(const Function *F);
1256   void printArgument(const Argument *FA, Attributes Attrs);
1257   void printBasicBlock(const BasicBlock *BB);
1258   void printInstruction(const Instruction &I);
1259
1260   // printInfoComment - Print a little comment after the instruction indicating
1261   // which slot it occupies.
1262   void printInfoComment(const Value &V);
1263 };
1264 }  // end of anonymous namespace
1265
1266
1267 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1268   if (Operand == 0) {
1269     Out << "<null operand!>";
1270   } else {
1271     if (PrintType) {
1272       TypePrinter.print(Operand->getType(), Out);
1273       Out << ' ';
1274     }
1275     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1276   }
1277 }
1278
1279 void AssemblyWriter::writeParamOperand(const Value *Operand, 
1280                                        Attributes Attrs) {
1281   if (Operand == 0) {
1282     Out << "<null operand!>";
1283   } else {
1284     // Print the type
1285     TypePrinter.print(Operand->getType(), Out);
1286     // Print parameter attributes list
1287     if (Attrs != Attribute::None)
1288       Out << ' ' << Attribute::getAsString(Attrs);
1289     Out << ' ';
1290     // Print the operand
1291     WriteAsOperandInternal(Out, Operand, TypePrinter, &Machine);
1292   }
1293 }
1294
1295 void AssemblyWriter::printModule(const Module *M) {
1296   if (!M->getModuleIdentifier().empty() &&
1297       // Don't print the ID if it will start a new line (which would
1298       // require a comment char before it).
1299       M->getModuleIdentifier().find('\n') == std::string::npos)
1300     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1301
1302   if (!M->getDataLayout().empty())
1303     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1304   if (!M->getTargetTriple().empty())
1305     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1306
1307   if (!M->getModuleInlineAsm().empty()) {
1308     // Split the string into lines, to make it easier to read the .ll file.
1309     std::string Asm = M->getModuleInlineAsm();
1310     size_t CurPos = 0;
1311     size_t NewLine = Asm.find_first_of('\n', CurPos);
1312     while (NewLine != std::string::npos) {
1313       // We found a newline, print the portion of the asm string from the
1314       // last newline up to this newline.
1315       Out << "module asm \"";
1316       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1317                          Out);
1318       Out << "\"\n";
1319       CurPos = NewLine+1;
1320       NewLine = Asm.find_first_of('\n', CurPos);
1321     }
1322     Out << "module asm \"";
1323     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1324     Out << "\"\n";
1325   }
1326   
1327   // Loop over the dependent libraries and emit them.
1328   Module::lib_iterator LI = M->lib_begin();
1329   Module::lib_iterator LE = M->lib_end();
1330   if (LI != LE) {
1331     Out << "deplibs = [ ";
1332     while (LI != LE) {
1333       Out << '"' << *LI << '"';
1334       ++LI;
1335       if (LI != LE)
1336         Out << ", ";
1337     }
1338     Out << " ]\n";
1339   }
1340
1341   // Loop over the symbol table, emitting all id'd types.
1342   printTypeSymbolTable(M->getTypeSymbolTable());
1343
1344   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1345        I != E; ++I)
1346     printGlobal(I);
1347   
1348   // Output all aliases.
1349   if (!M->alias_empty()) Out << "\n";
1350   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1351        I != E; ++I)
1352     printAlias(I);
1353
1354   // Output all of the functions.
1355   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1356     printFunction(I);
1357
1358   // Output named metadata.
1359   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1360          E = M->named_metadata_end(); I != E; ++I) {
1361     const NamedMDNode *NMD = I;
1362     Out << "!" << NMD->getName() << " = !{";
1363     for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1364       if (i) Out << ", ";
1365       MDNode *MD = cast<MDNode>(NMD->getElement(i));
1366       Out << '!' << Machine.getMetadataSlot(MD);
1367     }
1368     Out << "}\n";
1369   }
1370
1371   // Output metadata.
1372   WriteMDNodes(Out, TypePrinter, Machine);
1373 }
1374
1375 static void PrintLinkage(GlobalValue::LinkageTypes LT, raw_ostream &Out) {
1376   switch (LT) {
1377   case GlobalValue::ExternalLinkage: break;
1378   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
1379   case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1380   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
1381   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
1382   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
1383   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
1384   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
1385   case GlobalValue::CommonLinkage:        Out << "common ";         break;
1386   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
1387   case GlobalValue::DLLImportLinkage:     Out << "dllimport ";      break;
1388   case GlobalValue::DLLExportLinkage:     Out << "dllexport ";      break;
1389   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
1390   case GlobalValue::AvailableExternallyLinkage:
1391     Out << "available_externally ";
1392     break;
1393   case GlobalValue::GhostLinkage:
1394     llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1395   }
1396 }
1397
1398
1399 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1400                             raw_ostream &Out) {
1401   switch (Vis) {
1402   default: llvm_unreachable("Invalid visibility style!");
1403   case GlobalValue::DefaultVisibility: break;
1404   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1405   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1406   }
1407 }
1408
1409 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1410   if (GV->hasName()) {
1411     PrintLLVMName(Out, GV);
1412     Out << " = ";
1413   }
1414
1415   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1416     Out << "external ";
1417   
1418   PrintLinkage(GV->getLinkage(), Out);
1419   PrintVisibility(GV->getVisibility(), Out);
1420
1421   if (GV->isThreadLocal()) Out << "thread_local ";
1422   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1423     Out << "addrspace(" << AddressSpace << ") ";
1424   Out << (GV->isConstant() ? "constant " : "global ");
1425   TypePrinter.print(GV->getType()->getElementType(), Out);
1426
1427   if (GV->hasInitializer()) {
1428     Out << ' ';
1429     writeOperand(GV->getInitializer(), false);
1430   }
1431     
1432   if (GV->hasSection())
1433     Out << ", section \"" << GV->getSection() << '"';
1434   if (GV->getAlignment())
1435     Out << ", align " << GV->getAlignment();
1436
1437   printInfoComment(*GV);
1438   Out << '\n';
1439 }
1440
1441 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1442   // Don't crash when dumping partially built GA
1443   if (!GA->hasName())
1444     Out << "<<nameless>> = ";
1445   else {
1446     PrintLLVMName(Out, GA);
1447     Out << " = ";
1448   }
1449   PrintVisibility(GA->getVisibility(), Out);
1450
1451   Out << "alias ";
1452
1453   PrintLinkage(GA->getLinkage(), Out);
1454   
1455   const Constant *Aliasee = GA->getAliasee();
1456     
1457   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1458     TypePrinter.print(GV->getType(), Out);
1459     Out << ' ';
1460     PrintLLVMName(Out, GV);
1461   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1462     TypePrinter.print(F->getFunctionType(), Out);
1463     Out << "* ";
1464
1465     WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1466   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1467     TypePrinter.print(GA->getType(), Out);
1468     Out << ' ';
1469     PrintLLVMName(Out, GA);
1470   } else {
1471     const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1472     // The only valid GEP is an all zero GEP.
1473     assert((CE->getOpcode() == Instruction::BitCast ||
1474             CE->getOpcode() == Instruction::GetElementPtr) &&
1475            "Unsupported aliasee");
1476     writeOperand(CE, false);
1477   }
1478   
1479   printInfoComment(*GA);
1480   Out << '\n';
1481 }
1482
1483 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1484   // Emit all numbered types.
1485   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1486     Out << "\ttype ";
1487     
1488     // Make sure we print out at least one level of the type structure, so
1489     // that we do not get %2 = type %2
1490     TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1491     Out << "\t\t; type %" << i << '\n';
1492   }
1493   
1494   // Print the named types.
1495   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1496        TI != TE; ++TI) {
1497     Out << '\t';
1498     PrintLLVMName(Out, TI->first, LocalPrefix);
1499     Out << " = type ";
1500
1501     // Make sure we print out at least one level of the type structure, so
1502     // that we do not get %FILE = type %FILE
1503     TypePrinter.printAtLeastOneLevel(TI->second, Out);
1504     Out << '\n';
1505   }
1506 }
1507
1508 /// printFunction - Print all aspects of a function.
1509 ///
1510 void AssemblyWriter::printFunction(const Function *F) {
1511   // Print out the return type and name.
1512   Out << '\n';
1513
1514   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1515
1516   if (F->isDeclaration())
1517     Out << "declare ";
1518   else
1519     Out << "define ";
1520   
1521   PrintLinkage(F->getLinkage(), Out);
1522   PrintVisibility(F->getVisibility(), Out);
1523
1524   // Print the calling convention.
1525   switch (F->getCallingConv()) {
1526   case CallingConv::C: break;   // default
1527   case CallingConv::Fast:         Out << "fastcc "; break;
1528   case CallingConv::Cold:         Out << "coldcc "; break;
1529   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1530   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1531   case CallingConv::ARM_APCS:     Out << "arm_apcscc "; break;
1532   case CallingConv::ARM_AAPCS:    Out << "arm_aapcscc "; break;
1533   case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1534   default: Out << "cc" << F->getCallingConv() << " "; break;
1535   }
1536
1537   const FunctionType *FT = F->getFunctionType();
1538   const AttrListPtr &Attrs = F->getAttributes();
1539   Attributes RetAttrs = Attrs.getRetAttributes();
1540   if (RetAttrs != Attribute::None)
1541     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1542   TypePrinter.print(F->getReturnType(), Out);
1543   Out << ' ';
1544   WriteAsOperandInternal(Out, F, TypePrinter, &Machine);
1545   Out << '(';
1546   Machine.incorporateFunction(F);
1547
1548   // Loop over the arguments, printing them...
1549
1550   unsigned Idx = 1;
1551   if (!F->isDeclaration()) {
1552     // If this isn't a declaration, print the argument names as well.
1553     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1554          I != E; ++I) {
1555       // Insert commas as we go... the first arg doesn't get a comma
1556       if (I != F->arg_begin()) Out << ", ";
1557       printArgument(I, Attrs.getParamAttributes(Idx));
1558       Idx++;
1559     }
1560   } else {
1561     // Otherwise, print the types from the function type.
1562     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1563       // Insert commas as we go... the first arg doesn't get a comma
1564       if (i) Out << ", ";
1565       
1566       // Output type...
1567       TypePrinter.print(FT->getParamType(i), Out);
1568       
1569       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1570       if (ArgAttrs != Attribute::None)
1571         Out << ' ' << Attribute::getAsString(ArgAttrs);
1572     }
1573   }
1574
1575   // Finish printing arguments...
1576   if (FT->isVarArg()) {
1577     if (FT->getNumParams()) Out << ", ";
1578     Out << "...";  // Output varargs portion of signature!
1579   }
1580   Out << ')';
1581   Attributes FnAttrs = Attrs.getFnAttributes();
1582   if (FnAttrs != Attribute::None)
1583     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1584   if (F->hasSection())
1585     Out << " section \"" << F->getSection() << '"';
1586   if (F->getAlignment())
1587     Out << " align " << F->getAlignment();
1588   if (F->hasGC())
1589     Out << " gc \"" << F->getGC() << '"';
1590   if (F->isDeclaration()) {
1591     Out << "\n";
1592   } else {
1593     Out << " {";
1594
1595     // Output all of its basic blocks... for the function
1596     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1597       printBasicBlock(I);
1598
1599     Out << "}\n";
1600   }
1601
1602   Machine.purgeFunction();
1603 }
1604
1605 /// printArgument - This member is called for every argument that is passed into
1606 /// the function.  Simply print it out
1607 ///
1608 void AssemblyWriter::printArgument(const Argument *Arg, 
1609                                    Attributes Attrs) {
1610   // Output type...
1611   TypePrinter.print(Arg->getType(), Out);
1612
1613   // Output parameter attributes list
1614   if (Attrs != Attribute::None)
1615     Out << ' ' << Attribute::getAsString(Attrs);
1616
1617   // Output name, if available...
1618   if (Arg->hasName()) {
1619     Out << ' ';
1620     PrintLLVMName(Out, Arg);
1621   }
1622 }
1623
1624 /// printBasicBlock - This member is called for each basic block in a method.
1625 ///
1626 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1627   if (BB->hasName()) {              // Print out the label if it exists...
1628     Out << "\n";
1629     PrintLLVMName(Out, BB->getName(), LabelPrefix);
1630     Out << ':';
1631   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1632     Out << "\n; <label>:";
1633     int Slot = Machine.getLocalSlot(BB);
1634     if (Slot != -1)
1635       Out << Slot;
1636     else
1637       Out << "<badref>";
1638   }
1639
1640   if (BB->getParent() == 0)
1641     Out << "\t\t; Error: Block without parent!";
1642   else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1643     // Output predecessors for the block...
1644     Out << "\t\t;";
1645     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1646     
1647     if (PI == PE) {
1648       Out << " No predecessors!";
1649     } else {
1650       Out << " preds = ";
1651       writeOperand(*PI, false);
1652       for (++PI; PI != PE; ++PI) {
1653         Out << ", ";
1654         writeOperand(*PI, false);
1655       }
1656     }
1657   }
1658
1659   Out << "\n";
1660
1661   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1662
1663   // Output all of the instructions in the basic block...
1664   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1665     printInstruction(*I);
1666     Out << '\n';
1667   }
1668
1669   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1670 }
1671
1672
1673 /// printInfoComment - Print a little comment after the instruction indicating
1674 /// which slot it occupies.
1675 ///
1676 void AssemblyWriter::printInfoComment(const Value &V) {
1677   if (V.getType() != Type::VoidTy) {
1678     Out << "\t\t; <";
1679     TypePrinter.print(V.getType(), Out);
1680     Out << '>';
1681
1682     if (!V.hasName() && !isa<Instruction>(V)) {
1683       int SlotNum;
1684       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1685         SlotNum = Machine.getGlobalSlot(GV);
1686       else
1687         SlotNum = Machine.getLocalSlot(&V);
1688       if (SlotNum == -1)
1689         Out << ":<badref>";
1690       else
1691         Out << ':' << SlotNum; // Print out the def slot taken.
1692     }
1693     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1694   }
1695 }
1696
1697 // This member is called for each Instruction in a function..
1698 void AssemblyWriter::printInstruction(const Instruction &I) {
1699   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1700
1701   Out << '\t';
1702
1703   // Print out name if it exists...
1704   if (I.hasName()) {
1705     PrintLLVMName(Out, &I);
1706     Out << " = ";
1707   } else if (I.getType() != Type::VoidTy) {
1708     // Print out the def slot taken.
1709     int SlotNum = Machine.getLocalSlot(&I);
1710     if (SlotNum == -1)
1711       Out << "<badref> = ";
1712     else
1713       Out << '%' << SlotNum << " = ";
1714   }
1715
1716   // If this is a volatile load or store, print out the volatile marker.
1717   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1718       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1719       Out << "volatile ";
1720   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1721     // If this is a call, check if it's a tail call.
1722     Out << "tail ";
1723   }
1724
1725   // Print out the opcode...
1726   Out << I.getOpcodeName();
1727
1728   // Print out optimization information.
1729   WriteOptimizationInfo(Out, &I);
1730
1731   // Print out the compare instruction predicates
1732   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1733     Out << ' ' << getPredicateText(CI->getPredicate());
1734
1735   // Print out the type of the operands...
1736   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1737
1738   // Special case conditional branches to swizzle the condition out to the front
1739   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1740     BranchInst &BI(cast<BranchInst>(I));
1741     Out << ' ';
1742     writeOperand(BI.getCondition(), true);
1743     Out << ", ";
1744     writeOperand(BI.getSuccessor(0), true);
1745     Out << ", ";
1746     writeOperand(BI.getSuccessor(1), true);
1747
1748   } else if (isa<SwitchInst>(I)) {
1749     // Special case switch statement to get formatting nice and correct...
1750     Out << ' ';
1751     writeOperand(Operand        , true);
1752     Out << ", ";
1753     writeOperand(I.getOperand(1), true);
1754     Out << " [";
1755
1756     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1757       Out << "\n\t\t";
1758       writeOperand(I.getOperand(op  ), true);
1759       Out << ", ";
1760       writeOperand(I.getOperand(op+1), true);
1761     }
1762     Out << "\n\t]";
1763   } else if (isa<PHINode>(I)) {
1764     Out << ' ';
1765     TypePrinter.print(I.getType(), Out);
1766     Out << ' ';
1767
1768     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1769       if (op) Out << ", ";
1770       Out << "[ ";
1771       writeOperand(I.getOperand(op  ), false); Out << ", ";
1772       writeOperand(I.getOperand(op+1), false); Out << " ]";
1773     }
1774   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1775     Out << ' ';
1776     writeOperand(I.getOperand(0), true);
1777     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1778       Out << ", " << *i;
1779   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1780     Out << ' ';
1781     writeOperand(I.getOperand(0), true); Out << ", ";
1782     writeOperand(I.getOperand(1), true);
1783     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1784       Out << ", " << *i;
1785   } else if (isa<ReturnInst>(I) && !Operand) {
1786     Out << " void";
1787   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1788     // Print the calling convention being used.
1789     switch (CI->getCallingConv()) {
1790     case CallingConv::C: break;   // default
1791     case CallingConv::Fast:  Out << " fastcc"; break;
1792     case CallingConv::Cold:  Out << " coldcc"; break;
1793     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1794     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1795     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1796     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1797     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1798     default: Out << " cc" << CI->getCallingConv(); break;
1799     }
1800
1801     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1802     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1803     const Type         *RetTy = FTy->getReturnType();
1804     const AttrListPtr &PAL = CI->getAttributes();
1805
1806     if (PAL.getRetAttributes() != Attribute::None)
1807       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1808
1809     // If possible, print out the short form of the call instruction.  We can
1810     // only do this if the first argument is a pointer to a nonvararg function,
1811     // and if the return type is not a pointer to a function.
1812     //
1813     Out << ' ';
1814     if (!FTy->isVarArg() &&
1815         (!isa<PointerType>(RetTy) ||
1816          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1817       TypePrinter.print(RetTy, Out);
1818       Out << ' ';
1819       writeOperand(Operand, false);
1820     } else {
1821       writeOperand(Operand, true);
1822     }
1823     Out << '(';
1824     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1825       if (op > 1)
1826         Out << ", ";
1827       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1828     }
1829     Out << ')';
1830     if (PAL.getFnAttributes() != Attribute::None)
1831       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1832   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1833     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1834     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1835     const Type         *RetTy = FTy->getReturnType();
1836     const AttrListPtr &PAL = II->getAttributes();
1837
1838     // Print the calling convention being used.
1839     switch (II->getCallingConv()) {
1840     case CallingConv::C: break;   // default
1841     case CallingConv::Fast:  Out << " fastcc"; break;
1842     case CallingConv::Cold:  Out << " coldcc"; break;
1843     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1844     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1845     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1846     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1847     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1848     default: Out << " cc" << II->getCallingConv(); break;
1849     }
1850
1851     if (PAL.getRetAttributes() != Attribute::None)
1852       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1853
1854     // If possible, print out the short form of the invoke instruction. We can
1855     // only do this if the first argument is a pointer to a nonvararg function,
1856     // and if the return type is not a pointer to a function.
1857     //
1858     Out << ' ';
1859     if (!FTy->isVarArg() &&
1860         (!isa<PointerType>(RetTy) ||
1861          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1862       TypePrinter.print(RetTy, Out);
1863       Out << ' ';
1864       writeOperand(Operand, false);
1865     } else {
1866       writeOperand(Operand, true);
1867     }
1868     Out << '(';
1869     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1870       if (op > 3)
1871         Out << ", ";
1872       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1873     }
1874
1875     Out << ')';
1876     if (PAL.getFnAttributes() != Attribute::None)
1877       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1878
1879     Out << "\n\t\t\tto ";
1880     writeOperand(II->getNormalDest(), true);
1881     Out << " unwind ";
1882     writeOperand(II->getUnwindDest(), true);
1883
1884   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1885     Out << ' ';
1886     TypePrinter.print(AI->getType()->getElementType(), Out);
1887     if (AI->isArrayAllocation()) {
1888       Out << ", ";
1889       writeOperand(AI->getArraySize(), true);
1890     }
1891     if (AI->getAlignment()) {
1892       Out << ", align " << AI->getAlignment();
1893     }
1894   } else if (isa<CastInst>(I)) {
1895     if (Operand) {
1896       Out << ' ';
1897       writeOperand(Operand, true);   // Work with broken code
1898     }
1899     Out << " to ";
1900     TypePrinter.print(I.getType(), Out);
1901   } else if (isa<VAArgInst>(I)) {
1902     if (Operand) {
1903       Out << ' ';
1904       writeOperand(Operand, true);   // Work with broken code
1905     }
1906     Out << ", ";
1907     TypePrinter.print(I.getType(), Out);
1908   } else if (Operand) {   // Print the normal way.
1909
1910     // PrintAllTypes - Instructions who have operands of all the same type
1911     // omit the type from all but the first operand.  If the instruction has
1912     // different type operands (for example br), then they are all printed.
1913     bool PrintAllTypes = false;
1914     const Type *TheType = Operand->getType();
1915
1916     // Select, Store and ShuffleVector always print all types.
1917     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1918         || isa<ReturnInst>(I)) {
1919       PrintAllTypes = true;
1920     } else {
1921       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1922         Operand = I.getOperand(i);
1923         // note that Operand shouldn't be null, but the test helps make dump()
1924         // more tolerant of malformed IR
1925         if (Operand && Operand->getType() != TheType) {
1926           PrintAllTypes = true;    // We have differing types!  Print them all!
1927           break;
1928         }
1929       }
1930     }
1931
1932     if (!PrintAllTypes) {
1933       Out << ' ';
1934       TypePrinter.print(TheType, Out);
1935     }
1936
1937     Out << ' ';
1938     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1939       if (i) Out << ", ";
1940       writeOperand(I.getOperand(i), PrintAllTypes);
1941     }
1942   }
1943   
1944   // Print post operand alignment for load/store
1945   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1946     Out << ", align " << cast<LoadInst>(I).getAlignment();
1947   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1948     Out << ", align " << cast<StoreInst>(I).getAlignment();
1949   }
1950
1951   printInfoComment(I);
1952 }
1953
1954
1955 //===----------------------------------------------------------------------===//
1956 //                       External Interface declarations
1957 //===----------------------------------------------------------------------===//
1958
1959 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1960   raw_os_ostream OS(o);
1961   print(OS, AAW);
1962 }
1963 void Module::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1964   SlotTracker SlotTable(this);
1965   AssemblyWriter W(OS, SlotTable, this, AAW);
1966   W.write(this);
1967 }
1968
1969 void Type::print(std::ostream &o) const {
1970   raw_os_ostream OS(o);
1971   print(OS);
1972 }
1973
1974 void Type::print(raw_ostream &OS) const {
1975   if (this == 0) {
1976     OS << "<null Type>";
1977     return;
1978   }
1979   TypePrinting().print(this, OS);
1980 }
1981
1982 void Value::print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const {
1983   if (this == 0) {
1984     OS << "printing a <null> value\n";
1985     return;
1986   }
1987   if (const Instruction *I = dyn_cast<Instruction>(this)) {
1988     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
1989     SlotTracker SlotTable(F);
1990     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
1991     W.write(I);
1992   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
1993     SlotTracker SlotTable(BB->getParent());
1994     AssemblyWriter W(OS, SlotTable,
1995                      BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
1996     W.write(BB);
1997   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
1998     SlotTracker SlotTable(GV->getParent());
1999     AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2000     W.write(GV);
2001   } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
2002     TypePrinting TypePrinter;
2003     TypePrinter.print(MDS->getType(), OS);
2004     OS << ' ';
2005     OS << "!\"";
2006     PrintEscapedString(MDS->getString(), OS);
2007     OS << '"';
2008   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2009     SlotTracker SlotTable(N);
2010     TypePrinting TypePrinter;
2011     SlotTable.initialize();
2012     WriteMDNodes(OS, TypePrinter, SlotTable);
2013   } else if (const Constant *C = dyn_cast<Constant>(this)) {
2014     TypePrinting TypePrinter;
2015     TypePrinter.print(C->getType(), OS);
2016     OS << ' ';
2017     WriteConstantInt(OS, C, TypePrinter, 0);
2018   } else if (const Argument *A = dyn_cast<Argument>(this)) {
2019     WriteAsOperand(OS, this, true,
2020                    A->getParent() ? A->getParent()->getParent() : 0);
2021   } else if (isa<InlineAsm>(this)) {
2022     WriteAsOperand(OS, this, true, 0);
2023   } else {
2024     llvm_unreachable("Unknown value to print out!");
2025   }
2026 }
2027
2028 void Value::print(std::ostream &O, AssemblyAnnotationWriter *AAW) const {
2029   raw_os_ostream OS(O);
2030   print(OS, AAW);
2031 }
2032
2033 // Value::dump - allow easy printing of Values from the debugger.
2034 void Value::dump() const { print(errs()); errs() << '\n'; }
2035
2036 // Type::dump - allow easy printing of Types from the debugger.
2037 // This one uses type names from the given context module
2038 void Type::dump(const Module *Context) const {
2039   WriteTypeSymbolic(errs(), this, Context);
2040   errs() << '\n';
2041 }
2042
2043 // Type::dump - allow easy printing of Types from the debugger.
2044 void Type::dump() const { dump(0); }
2045
2046 // Module::dump() - Allow printing of Modules from the debugger.
2047 void Module::dump() const { print(errs(), 0); }