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