eliminate the std::ostream form of WriteAsOperand and update clients.
[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::getVoidTy(TheFunction->getContext()) &&
689           !I->hasName())
690         CreateFunctionSlot(I);
691       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 
692         if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
693           CreateMetadataSlot(N);
694     }
695   }
696   
697   FunctionProcessed = true;
698   
699   ST_DEBUG("end processFunction!\n");
700 }
701
702 /// processMDNode - Process TheMDNode.
703 void SlotTracker::processMDNode() {
704   ST_DEBUG("begin processMDNode!\n");
705   mdnNext = 0;
706   CreateMetadataSlot(TheMDNode);
707   TheMDNode = 0;
708   ST_DEBUG("end processMDNode!\n");
709 }
710
711 /// processNamedMDNode - Process TheNamedMDNode.
712 void SlotTracker::processNamedMDNode() {
713   ST_DEBUG("begin processNamedMDNode!\n");
714   mdnNext = 0;
715   for (unsigned i = 0, e = TheNamedMDNode->getNumElements(); i != e; ++i) {
716     MDNode *MD = dyn_cast_or_null<MDNode>(TheNamedMDNode->getElement(i));
717     if (MD)
718       CreateMetadataSlot(MD);
719   }
720   TheNamedMDNode = 0;
721   ST_DEBUG("end processNamedMDNode!\n");
722 }
723
724 /// Clean up after incorporating a function. This is the only way to get out of
725 /// the function incorporation state that affects get*Slot/Create*Slot. Function
726 /// incorporation state is indicated by TheFunction != 0.
727 void SlotTracker::purgeFunction() {
728   ST_DEBUG("begin purgeFunction!\n");
729   fMap.clear(); // Simply discard the function level map
730   TheFunction = 0;
731   FunctionProcessed = false;
732   ST_DEBUG("end purgeFunction!\n");
733 }
734
735 /// getGlobalSlot - Get the slot number of a global value.
736 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
737   // Check for uninitialized state and do lazy initialization.
738   initialize();
739   
740   // Find the type plane in the module map
741   ValueMap::iterator MI = mMap.find(V);
742   return MI == mMap.end() ? -1 : (int)MI->second;
743 }
744
745 /// getGlobalSlot - Get the slot number of a MDNode.
746 int SlotTracker::getMetadataSlot(const MDNode *N) {
747   // Check for uninitialized state and do lazy initialization.
748   initialize();
749   
750   // Find the type plane in the module map
751   ValueMap::iterator MI = mdnMap.find(N);
752   return MI == mdnMap.end() ? -1 : (int)MI->second;
753 }
754
755
756 /// getLocalSlot - Get the slot number for a value that is local to a function.
757 int SlotTracker::getLocalSlot(const Value *V) {
758   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
759   
760   // Check for uninitialized state and do lazy initialization.
761   initialize();
762   
763   ValueMap::iterator FI = fMap.find(V);
764   return FI == fMap.end() ? -1 : (int)FI->second;
765 }
766
767
768 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
769 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
770   assert(V && "Can't insert a null Value into SlotTracker!");
771   assert(V->getType() != Type::getVoidTy(V->getContext()) && 
772          "Doesn't need a slot!");
773   assert(!V->hasName() && "Doesn't need a slot!");
774   
775   unsigned DestSlot = mNext++;
776   mMap[V] = DestSlot;
777   
778   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
779            DestSlot << " [");
780   // G = Global, F = Function, A = Alias, o = other
781   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
782             (isa<Function>(V) ? 'F' :
783              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
784 }
785
786 /// CreateSlot - Create a new slot for the specified value if it has no name.
787 void SlotTracker::CreateFunctionSlot(const Value *V) {
788   assert(V->getType() != Type::getVoidTy(TheFunction->getContext()) && 
789          !V->hasName() && "Doesn't need a slot!");
790   
791   unsigned DestSlot = fNext++;
792   fMap[V] = DestSlot;
793   
794   // G = Global, F = Function, o = other
795   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
796            DestSlot << " [o]\n");
797 }  
798
799 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
800 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
801   assert(N && "Can't insert a null Value into SlotTracker!");
802   
803   ValueMap::iterator I = mdnMap.find(N);
804   if (I != mdnMap.end())
805     return;
806
807   unsigned DestSlot = mdnNext++;
808   mdnMap[N] = DestSlot;
809
810   for (MDNode::const_elem_iterator MDI = N->elem_begin(), 
811          MDE = N->elem_end(); MDI != MDE; ++MDI) {
812     const Value *TV = *MDI;
813     if (TV)
814       if (const MDNode *N2 = dyn_cast<MDNode>(TV)) 
815         CreateMetadataSlot(N2);
816   }
817 }
818
819 //===----------------------------------------------------------------------===//
820 // AsmWriter Implementation
821 //===----------------------------------------------------------------------===//
822
823 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
824                                    TypePrinting *TypePrinter,
825                                    SlotTracker *Machine);
826
827
828
829 static const char *getPredicateText(unsigned predicate) {
830   const char * pred = "unknown";
831   switch (predicate) {
832     case FCmpInst::FCMP_FALSE: pred = "false"; break;
833     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
834     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
835     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
836     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
837     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
838     case FCmpInst::FCMP_ONE:   pred = "one"; break;
839     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
840     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
841     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
842     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
843     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
844     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
845     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
846     case FCmpInst::FCMP_UNE:   pred = "une"; break;
847     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
848     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
849     case ICmpInst::ICMP_NE:    pred = "ne"; break;
850     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
851     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
852     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
853     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
854     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
855     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
856     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
857     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
858   }
859   return pred;
860 }
861
862 static void WriteMDNodes(formatted_raw_ostream &Out, TypePrinting &TypePrinter,
863                          SlotTracker &Machine) {
864   SmallVector<const MDNode *, 16> Nodes;
865   Nodes.resize(Machine.mdnSize());
866   for (SlotTracker::ValueMap::iterator I = 
867          Machine.mdnBegin(), E = Machine.mdnEnd(); I != E; ++I) 
868     Nodes[I->second] = cast<MDNode>(I->first);
869
870   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
871     Out << '!' << i << " = metadata ";
872     const MDNode *Node = Nodes[i];
873     Out << "!{";
874     for (MDNode::const_elem_iterator NI = Node->elem_begin(), 
875            NE = Node->elem_end(); NI != NE;) {
876       const Value *V = *NI;
877       if (!V)
878         Out << "null";
879       else if (const MDNode *N = dyn_cast<MDNode>(V)) {
880         Out << "metadata ";
881         Out << '!' << Machine.getMetadataSlot(N);
882       }
883       else {
884         TypePrinter.print((*NI)->getType(), Out);
885         Out << ' ';
886         WriteAsOperandInternal(Out, *NI, &TypePrinter, &Machine);
887       }
888       if (++NI != NE)
889         Out << ", ";
890     }
891     Out << "}\n";
892   }
893 }
894
895 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
896   if (const OverflowingBinaryOperator *OBO =
897         dyn_cast<OverflowingBinaryOperator>(U)) {
898     if (OBO->hasNoUnsignedWrap())
899       Out << " nuw";
900     if (OBO->hasNoSignedWrap())
901       Out << " nsw";
902   } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
903     if (Div->isExact())
904       Out << " exact";
905   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
906     if (GEP->isInBounds())
907       Out << " inbounds";
908   }
909 }
910
911 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
912                              TypePrinting &TypePrinter, SlotTracker *Machine) {
913   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
914     if (CI->getType() == Type::getInt1Ty(CV->getContext())) {
915       Out << (CI->getZExtValue() ? "true" : "false");
916       return;
917     }
918     Out << CI->getValue();
919     return;
920   }
921   
922   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
923     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
924         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
925       // We would like to output the FP constant value in exponential notation,
926       // but we cannot do this if doing so will lose precision.  Check here to
927       // make sure that we only output it in exponential format if we can parse
928       // the value back and get the same value.
929       //
930       bool ignored;
931       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
932       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
933                               CFP->getValueAPF().convertToFloat();
934       std::string StrVal = ftostr(CFP->getValueAPF());
935
936       // Check to make sure that the stringized number is not some string like
937       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
938       // that the string matches the "[-+]?[0-9]" regex.
939       //
940       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
941           ((StrVal[0] == '-' || StrVal[0] == '+') &&
942            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
943         // Reparse stringized version!
944         if (atof(StrVal.c_str()) == Val) {
945           Out << StrVal;
946           return;
947         }
948       }
949       // Otherwise we could not reparse it to exactly the same value, so we must
950       // output the string in hexadecimal format!  Note that loading and storing
951       // floating point types changes the bits of NaNs on some hosts, notably
952       // x86, so we must not use these types.
953       assert(sizeof(double) == sizeof(uint64_t) &&
954              "assuming that double is 64 bits!");
955       char Buffer[40];
956       APFloat apf = CFP->getValueAPF();
957       // Floats are represented in ASCII IR as double, convert.
958       if (!isDouble)
959         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 
960                           &ignored);
961       Out << "0x" << 
962               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()), 
963                             Buffer+40);
964       return;
965     }
966     
967     // Some form of long double.  These appear as a magic letter identifying
968     // the type, then a fixed number of hex digits.
969     Out << "0x";
970     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
971       Out << 'K';
972       // api needed to prevent premature destruction
973       APInt api = CFP->getValueAPF().bitcastToAPInt();
974       const uint64_t* p = api.getRawData();
975       uint64_t word = p[1];
976       int shiftcount=12;
977       int width = api.getBitWidth();
978       for (int j=0; j<width; j+=4, shiftcount-=4) {
979         unsigned int nibble = (word>>shiftcount) & 15;
980         if (nibble < 10)
981           Out << (unsigned char)(nibble + '0');
982         else
983           Out << (unsigned char)(nibble - 10 + 'A');
984         if (shiftcount == 0 && j+4 < width) {
985           word = *p;
986           shiftcount = 64;
987           if (width-j-4 < 64)
988             shiftcount = width-j-4;
989         }
990       }
991       return;
992     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
993       Out << 'L';
994     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
995       Out << 'M';
996     else
997       llvm_unreachable("Unsupported floating point type");
998     // api needed to prevent premature destruction
999     APInt api = CFP->getValueAPF().bitcastToAPInt();
1000     const uint64_t* p = api.getRawData();
1001     uint64_t word = *p;
1002     int shiftcount=60;
1003     int width = api.getBitWidth();
1004     for (int j=0; j<width; j+=4, shiftcount-=4) {
1005       unsigned int nibble = (word>>shiftcount) & 15;
1006       if (nibble < 10)
1007         Out << (unsigned char)(nibble + '0');
1008       else
1009         Out << (unsigned char)(nibble - 10 + 'A');
1010       if (shiftcount == 0 && j+4 < width) {
1011         word = *(++p);
1012         shiftcount = 64;
1013         if (width-j-4 < 64)
1014           shiftcount = width-j-4;
1015       }
1016     }
1017     return;
1018   }
1019   
1020   if (isa<ConstantAggregateZero>(CV)) {
1021     Out << "zeroinitializer";
1022     return;
1023   }
1024   
1025   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1026     // As a special case, print the array as a string if it is an array of
1027     // i8 with ConstantInt values.
1028     //
1029     const Type *ETy = CA->getType()->getElementType();
1030     if (CA->isString()) {
1031       Out << "c\"";
1032       PrintEscapedString(CA->getAsString(), Out);
1033       Out << '"';
1034     } else {                // Cannot output in string format...
1035       Out << '[';
1036       if (CA->getNumOperands()) {
1037         TypePrinter.print(ETy, Out);
1038         Out << ' ';
1039         WriteAsOperandInternal(Out, CA->getOperand(0),
1040                                &TypePrinter, Machine);
1041         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1042           Out << ", ";
1043           TypePrinter.print(ETy, Out);
1044           Out << ' ';
1045           WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
1046         }
1047       }
1048       Out << ']';
1049     }
1050     return;
1051   }
1052   
1053   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1054     if (CS->getType()->isPacked())
1055       Out << '<';
1056     Out << '{';
1057     unsigned N = CS->getNumOperands();
1058     if (N) {
1059       Out << ' ';
1060       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1061       Out << ' ';
1062
1063       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1064
1065       for (unsigned i = 1; i < N; i++) {
1066         Out << ", ";
1067         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1068         Out << ' ';
1069
1070         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1071       }
1072       Out << ' ';
1073     }
1074  
1075     Out << '}';
1076     if (CS->getType()->isPacked())
1077       Out << '>';
1078     return;
1079   }
1080   
1081   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1082     const Type *ETy = CP->getType()->getElementType();
1083     assert(CP->getNumOperands() > 0 &&
1084            "Number of operands for a PackedConst must be > 0");
1085     Out << '<';
1086     TypePrinter.print(ETy, Out);
1087     Out << ' ';
1088     WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1089     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1090       Out << ", ";
1091       TypePrinter.print(ETy, Out);
1092       Out << ' ';
1093       WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1094     }
1095     Out << '>';
1096     return;
1097   }
1098   
1099   if (isa<ConstantPointerNull>(CV)) {
1100     Out << "null";
1101     return;
1102   }
1103   
1104   if (isa<UndefValue>(CV)) {
1105     Out << "undef";
1106     return;
1107   }
1108   
1109   if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1110     Out << "!" << Machine->getMetadataSlot(Node);
1111     return;
1112   }
1113
1114   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1115     Out << CE->getOpcodeName();
1116     WriteOptimizationInfo(Out, CE);
1117     if (CE->isCompare())
1118       Out << ' ' << getPredicateText(CE->getPredicate());
1119     Out << " (";
1120
1121     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1122       TypePrinter.print((*OI)->getType(), Out);
1123       Out << ' ';
1124       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1125       if (OI+1 != CE->op_end())
1126         Out << ", ";
1127     }
1128
1129     if (CE->hasIndices()) {
1130       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1131       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1132         Out << ", " << Indices[i];
1133     }
1134
1135     if (CE->isCast()) {
1136       Out << " to ";
1137       TypePrinter.print(CE->getType(), Out);
1138     }
1139
1140     Out << ')';
1141     return;
1142   }
1143   
1144   Out << "<placeholder or erroneous Constant>";
1145 }
1146
1147
1148 /// WriteAsOperand - Write the name of the specified value out to the specified
1149 /// ostream.  This can be useful when you just want to print int %reg126, not
1150 /// the whole instruction that generated it.
1151 ///
1152 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1153                                    TypePrinting *TypePrinter,
1154                                    SlotTracker *Machine) {
1155   if (V->hasName()) {
1156     PrintLLVMName(Out, V);
1157     return;
1158   }
1159   
1160   const Constant *CV = dyn_cast<Constant>(V);
1161   if (CV && !isa<GlobalValue>(CV)) {
1162     assert(TypePrinter && "Constants require TypePrinting!");
1163     WriteConstantInt(Out, CV, *TypePrinter, Machine);
1164     return;
1165   }
1166   
1167   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1168     Out << "asm ";
1169     if (IA->hasSideEffects())
1170       Out << "sideeffect ";
1171     Out << '"';
1172     PrintEscapedString(IA->getAsmString(), Out);
1173     Out << "\", \"";
1174     PrintEscapedString(IA->getConstraintString(), Out);
1175     Out << '"';
1176     return;
1177   }
1178
1179   if (const MDNode *N = dyn_cast<MDNode>(V)) {
1180     Out << '!' << Machine->getMetadataSlot(N);
1181     return;
1182   }
1183
1184   if (const MDString *MDS = dyn_cast<MDString>(V)) {
1185     Out << "!\"";
1186     PrintEscapedString(MDS->getString(), Out);
1187     Out << '"';
1188     return;
1189   }
1190
1191   char Prefix = '%';
1192   int Slot;
1193   if (Machine) {
1194     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1195       Slot = Machine->getGlobalSlot(GV);
1196       Prefix = '@';
1197     } else {
1198       Slot = Machine->getLocalSlot(V);
1199     }
1200   } else {
1201     Machine = createSlotTracker(V);
1202     if (Machine) {
1203       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1204         Slot = Machine->getGlobalSlot(GV);
1205         Prefix = '@';
1206       } else {
1207         Slot = Machine->getLocalSlot(V);
1208       }
1209       delete Machine;
1210     } else {
1211       Slot = -1;
1212     }
1213   }
1214   
1215   if (Slot != -1)
1216     Out << Prefix << Slot;
1217   else
1218     Out << "<badref>";
1219 }
1220
1221 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1222                           bool PrintType, const Module *Context) {
1223
1224   // Fast path: Don't construct and populate a TypePrinting object if we
1225   // won't be needing any types printed.
1226   if (!PrintType &&
1227       (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1228     WriteAsOperandInternal(Out, V, 0, 0);
1229     return;
1230   }
1231
1232   if (Context == 0) Context = getModuleFromVal(V);
1233
1234   TypePrinting TypePrinter;
1235   std::vector<const Type*> NumberedTypes;
1236   AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1237   if (PrintType) {
1238     TypePrinter.print(V->getType(), Out);
1239     Out << ' ';
1240   }
1241
1242   WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1243 }
1244
1245 namespace {
1246
1247 class AssemblyWriter {
1248   formatted_raw_ostream &Out;
1249   SlotTracker &Machine;
1250   const Module *TheModule;
1251   TypePrinting TypePrinter;
1252   AssemblyAnnotationWriter *AnnotationWriter;
1253   std::vector<const Type*> NumberedTypes;
1254
1255   // Each MDNode is assigned unique MetadataIDNo.
1256   std::map<const MDNode *, unsigned> MDNodes;
1257   unsigned MetadataIDNo;
1258 public:
1259   inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1260                         const Module *M,
1261                         AssemblyAnnotationWriter *AAW)
1262     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW), MetadataIDNo(0) {
1263     AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1264   }
1265
1266   void write(const Module *M) { printModule(M); }
1267   
1268   void write(const GlobalValue *G) {
1269     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G))
1270       printGlobal(GV);
1271     else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(G))
1272       printAlias(GA);
1273     else if (const Function *F = dyn_cast<Function>(G))
1274       printFunction(F);
1275     else
1276       llvm_unreachable("Unknown global");
1277   }
1278   
1279   void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
1280   void write(const Instruction *I)    { printInstruction(*I); }
1281
1282   void writeOperand(const Value *Op, bool PrintType);
1283   void writeParamOperand(const Value *Operand, Attributes Attrs);
1284
1285   const Module* getModule() { return TheModule; }
1286
1287 private:
1288   void printModule(const Module *M);
1289   void printTypeSymbolTable(const TypeSymbolTable &ST);
1290   void printGlobal(const GlobalVariable *GV);
1291   void printAlias(const GlobalAlias *GV);
1292   void printFunction(const Function *F);
1293   void printArgument(const Argument *FA, Attributes Attrs);
1294   void printBasicBlock(const BasicBlock *BB);
1295   void printInstruction(const Instruction &I);
1296
1297   // printInfoComment - Print a little comment after the instruction indicating
1298   // which slot it occupies.
1299   void printInfoComment(const Value &V);
1300 };
1301 }  // end of anonymous namespace
1302
1303
1304 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1305   if (Operand == 0) {
1306     Out << "<null operand!>";
1307   } else {
1308     if (PrintType) {
1309       TypePrinter.print(Operand->getType(), Out);
1310       Out << ' ';
1311     }
1312     WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1313   }
1314 }
1315
1316 void AssemblyWriter::writeParamOperand(const Value *Operand, 
1317                                        Attributes Attrs) {
1318   if (Operand == 0) {
1319     Out << "<null operand!>";
1320   } else {
1321     // Print the type
1322     TypePrinter.print(Operand->getType(), Out);
1323     // Print parameter attributes list
1324     if (Attrs != Attribute::None)
1325       Out << ' ' << Attribute::getAsString(Attrs);
1326     Out << ' ';
1327     // Print the operand
1328     WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1329   }
1330 }
1331
1332 void AssemblyWriter::printModule(const Module *M) {
1333   if (!M->getModuleIdentifier().empty() &&
1334       // Don't print the ID if it will start a new line (which would
1335       // require a comment char before it).
1336       M->getModuleIdentifier().find('\n') == std::string::npos)
1337     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1338
1339   if (!M->getDataLayout().empty())
1340     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1341   if (!M->getTargetTriple().empty())
1342     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1343
1344   if (!M->getModuleInlineAsm().empty()) {
1345     // Split the string into lines, to make it easier to read the .ll file.
1346     std::string Asm = M->getModuleInlineAsm();
1347     size_t CurPos = 0;
1348     size_t NewLine = Asm.find_first_of('\n', CurPos);
1349     Out << '\n';
1350     while (NewLine != std::string::npos) {
1351       // We found a newline, print the portion of the asm string from the
1352       // last newline up to this newline.
1353       Out << "module asm \"";
1354       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1355                          Out);
1356       Out << "\"\n";
1357       CurPos = NewLine+1;
1358       NewLine = Asm.find_first_of('\n', CurPos);
1359     }
1360     Out << "module asm \"";
1361     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1362     Out << "\"\n";
1363   }
1364   
1365   // Loop over the dependent libraries and emit them.
1366   Module::lib_iterator LI = M->lib_begin();
1367   Module::lib_iterator LE = M->lib_end();
1368   if (LI != LE) {
1369     Out << '\n';
1370     Out << "deplibs = [ ";
1371     while (LI != LE) {
1372       Out << '"' << *LI << '"';
1373       ++LI;
1374       if (LI != LE)
1375         Out << ", ";
1376     }
1377     Out << " ]";
1378   }
1379
1380   // Loop over the symbol table, emitting all id'd types.
1381   if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1382   printTypeSymbolTable(M->getTypeSymbolTable());
1383
1384   // Output all globals.
1385   if (!M->global_empty()) Out << '\n';
1386   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1387        I != E; ++I)
1388     printGlobal(I);
1389   
1390   // Output all aliases.
1391   if (!M->alias_empty()) Out << "\n";
1392   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1393        I != E; ++I)
1394     printAlias(I);
1395
1396   // Output all of the functions.
1397   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1398     printFunction(I);
1399
1400   // Output named metadata.
1401   if (!M->named_metadata_empty()) Out << '\n';
1402   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1403          E = M->named_metadata_end(); I != E; ++I) {
1404     const NamedMDNode *NMD = I;
1405     Out << "!" << NMD->getName() << " = !{";
1406     for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1407       if (i) Out << ", ";
1408       MDNode *MD = dyn_cast_or_null<MDNode>(NMD->getElement(i));
1409       Out << '!' << Machine.getMetadataSlot(MD);
1410     }
1411     Out << "}\n";
1412   }
1413
1414   // Output metadata.
1415   if (!Machine.mdnEmpty()) Out << '\n';
1416   WriteMDNodes(Out, TypePrinter, Machine);
1417 }
1418
1419 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1420                          formatted_raw_ostream &Out) {
1421   switch (LT) {
1422   case GlobalValue::ExternalLinkage: break;
1423   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
1424   case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1425   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
1426   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
1427   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
1428   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
1429   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
1430   case GlobalValue::CommonLinkage:        Out << "common ";         break;
1431   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
1432   case GlobalValue::DLLImportLinkage:     Out << "dllimport ";      break;
1433   case GlobalValue::DLLExportLinkage:     Out << "dllexport ";      break;
1434   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
1435   case GlobalValue::AvailableExternallyLinkage:
1436     Out << "available_externally ";
1437     break;
1438   case GlobalValue::GhostLinkage:
1439     llvm_unreachable("GhostLinkage not allowed in AsmWriter!");
1440   }
1441 }
1442
1443
1444 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1445                             formatted_raw_ostream &Out) {
1446   switch (Vis) {
1447   default: llvm_unreachable("Invalid visibility style!");
1448   case GlobalValue::DefaultVisibility: break;
1449   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1450   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1451   }
1452 }
1453
1454 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1455   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1456   Out << " = ";
1457
1458   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1459     Out << "external ";
1460   
1461   PrintLinkage(GV->getLinkage(), Out);
1462   PrintVisibility(GV->getVisibility(), Out);
1463
1464   if (GV->isThreadLocal()) Out << "thread_local ";
1465   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1466     Out << "addrspace(" << AddressSpace << ") ";
1467   Out << (GV->isConstant() ? "constant " : "global ");
1468   TypePrinter.print(GV->getType()->getElementType(), Out);
1469
1470   if (GV->hasInitializer()) {
1471     Out << ' ';
1472     writeOperand(GV->getInitializer(), false);
1473   }
1474     
1475   if (GV->hasSection())
1476     Out << ", section \"" << GV->getSection() << '"';
1477   if (GV->getAlignment())
1478     Out << ", align " << GV->getAlignment();
1479
1480   printInfoComment(*GV);
1481   Out << '\n';
1482 }
1483
1484 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1485   // Don't crash when dumping partially built GA
1486   if (!GA->hasName())
1487     Out << "<<nameless>> = ";
1488   else {
1489     PrintLLVMName(Out, GA);
1490     Out << " = ";
1491   }
1492   PrintVisibility(GA->getVisibility(), Out);
1493
1494   Out << "alias ";
1495
1496   PrintLinkage(GA->getLinkage(), Out);
1497   
1498   const Constant *Aliasee = GA->getAliasee();
1499     
1500   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1501     TypePrinter.print(GV->getType(), Out);
1502     Out << ' ';
1503     PrintLLVMName(Out, GV);
1504   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1505     TypePrinter.print(F->getFunctionType(), Out);
1506     Out << "* ";
1507
1508     WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1509   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1510     TypePrinter.print(GA->getType(), Out);
1511     Out << ' ';
1512     PrintLLVMName(Out, GA);
1513   } else {
1514     const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1515     // The only valid GEP is an all zero GEP.
1516     assert((CE->getOpcode() == Instruction::BitCast ||
1517             CE->getOpcode() == Instruction::GetElementPtr) &&
1518            "Unsupported aliasee");
1519     writeOperand(CE, false);
1520   }
1521   
1522   printInfoComment(*GA);
1523   Out << '\n';
1524 }
1525
1526 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1527   // Emit all numbered types.
1528   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1529     Out << '%' << i << " = type ";
1530     
1531     // Make sure we print out at least one level of the type structure, so
1532     // that we do not get %2 = type %2
1533     TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1534     Out << '\n';
1535   }
1536   
1537   // Print the named types.
1538   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1539        TI != TE; ++TI) {
1540     PrintLLVMName(Out, TI->first, LocalPrefix);
1541     Out << " = type ";
1542
1543     // Make sure we print out at least one level of the type structure, so
1544     // that we do not get %FILE = type %FILE
1545     TypePrinter.printAtLeastOneLevel(TI->second, Out);
1546     Out << '\n';
1547   }
1548 }
1549
1550 /// printFunction - Print all aspects of a function.
1551 ///
1552 void AssemblyWriter::printFunction(const Function *F) {
1553   // Print out the return type and name.
1554   Out << '\n';
1555
1556   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1557
1558   if (F->isDeclaration())
1559     Out << "declare ";
1560   else
1561     Out << "define ";
1562   
1563   PrintLinkage(F->getLinkage(), Out);
1564   PrintVisibility(F->getVisibility(), Out);
1565
1566   // Print the calling convention.
1567   switch (F->getCallingConv()) {
1568   case CallingConv::C: break;   // default
1569   case CallingConv::Fast:         Out << "fastcc "; break;
1570   case CallingConv::Cold:         Out << "coldcc "; break;
1571   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1572   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1573   case CallingConv::ARM_APCS:     Out << "arm_apcscc "; break;
1574   case CallingConv::ARM_AAPCS:    Out << "arm_aapcscc "; break;
1575   case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1576   default: Out << "cc" << F->getCallingConv() << " "; break;
1577   }
1578
1579   const FunctionType *FT = F->getFunctionType();
1580   const AttrListPtr &Attrs = F->getAttributes();
1581   Attributes RetAttrs = Attrs.getRetAttributes();
1582   if (RetAttrs != Attribute::None)
1583     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1584   TypePrinter.print(F->getReturnType(), Out);
1585   Out << ' ';
1586   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1587   Out << '(';
1588   Machine.incorporateFunction(F);
1589
1590   // Loop over the arguments, printing them...
1591
1592   unsigned Idx = 1;
1593   if (!F->isDeclaration()) {
1594     // If this isn't a declaration, print the argument names as well.
1595     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1596          I != E; ++I) {
1597       // Insert commas as we go... the first arg doesn't get a comma
1598       if (I != F->arg_begin()) Out << ", ";
1599       printArgument(I, Attrs.getParamAttributes(Idx));
1600       Idx++;
1601     }
1602   } else {
1603     // Otherwise, print the types from the function type.
1604     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1605       // Insert commas as we go... the first arg doesn't get a comma
1606       if (i) Out << ", ";
1607       
1608       // Output type...
1609       TypePrinter.print(FT->getParamType(i), Out);
1610       
1611       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1612       if (ArgAttrs != Attribute::None)
1613         Out << ' ' << Attribute::getAsString(ArgAttrs);
1614     }
1615   }
1616
1617   // Finish printing arguments...
1618   if (FT->isVarArg()) {
1619     if (FT->getNumParams()) Out << ", ";
1620     Out << "...";  // Output varargs portion of signature!
1621   }
1622   Out << ')';
1623   Attributes FnAttrs = Attrs.getFnAttributes();
1624   if (FnAttrs != Attribute::None)
1625     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1626   if (F->hasSection())
1627     Out << " section \"" << F->getSection() << '"';
1628   if (F->getAlignment())
1629     Out << " align " << F->getAlignment();
1630   if (F->hasGC())
1631     Out << " gc \"" << F->getGC() << '"';
1632   if (F->isDeclaration()) {
1633     Out << "\n";
1634   } else {
1635     Out << " {";
1636
1637     // Output all of its basic blocks... for the function
1638     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1639       printBasicBlock(I);
1640
1641     Out << "}\n";
1642   }
1643
1644   Machine.purgeFunction();
1645 }
1646
1647 /// printArgument - This member is called for every argument that is passed into
1648 /// the function.  Simply print it out
1649 ///
1650 void AssemblyWriter::printArgument(const Argument *Arg, 
1651                                    Attributes Attrs) {
1652   // Output type...
1653   TypePrinter.print(Arg->getType(), Out);
1654
1655   // Output parameter attributes list
1656   if (Attrs != Attribute::None)
1657     Out << ' ' << Attribute::getAsString(Attrs);
1658
1659   // Output name, if available...
1660   if (Arg->hasName()) {
1661     Out << ' ';
1662     PrintLLVMName(Out, Arg);
1663   }
1664 }
1665
1666 /// printBasicBlock - This member is called for each basic block in a method.
1667 ///
1668 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1669   if (BB->hasName()) {              // Print out the label if it exists...
1670     Out << "\n";
1671     PrintLLVMName(Out, BB->getName(), LabelPrefix);
1672     Out << ':';
1673   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1674     Out << "\n; <label>:";
1675     int Slot = Machine.getLocalSlot(BB);
1676     if (Slot != -1)
1677       Out << Slot;
1678     else
1679       Out << "<badref>";
1680   }
1681
1682   if (BB->getParent() == 0) {
1683     Out.PadToColumn(50);
1684     Out << "; Error: Block without parent!";
1685   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1686     // Output predecessors for the block...
1687     Out.PadToColumn(50);
1688     Out << ";";
1689     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1690     
1691     if (PI == PE) {
1692       Out << " No predecessors!";
1693     } else {
1694       Out << " preds = ";
1695       writeOperand(*PI, false);
1696       for (++PI; PI != PE; ++PI) {
1697         Out << ", ";
1698         writeOperand(*PI, false);
1699       }
1700     }
1701   }
1702
1703   Out << "\n";
1704
1705   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1706
1707   // Output all of the instructions in the basic block...
1708   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1709     printInstruction(*I);
1710     Out << '\n';
1711   }
1712
1713   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1714 }
1715
1716
1717 /// printInfoComment - Print a little comment after the instruction indicating
1718 /// which slot it occupies.
1719 ///
1720 void AssemblyWriter::printInfoComment(const Value &V) {
1721   if (V.getType() != Type::getVoidTy(V.getContext())) {
1722     Out.PadToColumn(50);
1723     Out << "; <";
1724     TypePrinter.print(V.getType(), Out);
1725     Out << "> [#uses=" << V.getNumUses() << ']';  // Output # uses
1726   }
1727 }
1728
1729 // This member is called for each Instruction in a function..
1730 void AssemblyWriter::printInstruction(const Instruction &I) {
1731   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1732
1733   // Print out indentation for an instruction.
1734   Out << "  ";
1735
1736   // Print out name if it exists...
1737   if (I.hasName()) {
1738     PrintLLVMName(Out, &I);
1739     Out << " = ";
1740   } else if (I.getType() != Type::getVoidTy(I.getContext())) {
1741     // Print out the def slot taken.
1742     int SlotNum = Machine.getLocalSlot(&I);
1743     if (SlotNum == -1)
1744       Out << "<badref> = ";
1745     else
1746       Out << '%' << SlotNum << " = ";
1747   }
1748
1749   // If this is a volatile load or store, print out the volatile marker.
1750   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1751       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1752       Out << "volatile ";
1753   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1754     // If this is a call, check if it's a tail call.
1755     Out << "tail ";
1756   }
1757
1758   // Print out the opcode...
1759   Out << I.getOpcodeName();
1760
1761   // Print out optimization information.
1762   WriteOptimizationInfo(Out, &I);
1763
1764   // Print out the compare instruction predicates
1765   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1766     Out << ' ' << getPredicateText(CI->getPredicate());
1767
1768   // Print out the type of the operands...
1769   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1770
1771   // Special case conditional branches to swizzle the condition out to the front
1772   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1773     BranchInst &BI(cast<BranchInst>(I));
1774     Out << ' ';
1775     writeOperand(BI.getCondition(), true);
1776     Out << ", ";
1777     writeOperand(BI.getSuccessor(0), true);
1778     Out << ", ";
1779     writeOperand(BI.getSuccessor(1), true);
1780
1781   } else if (isa<SwitchInst>(I)) {
1782     // Special case switch statement to get formatting nice and correct...
1783     Out << ' ';
1784     writeOperand(Operand        , true);
1785     Out << ", ";
1786     writeOperand(I.getOperand(1), true);
1787     Out << " [";
1788
1789     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1790       Out << "\n    ";
1791       writeOperand(I.getOperand(op  ), true);
1792       Out << ", ";
1793       writeOperand(I.getOperand(op+1), true);
1794     }
1795     Out << "\n  ]";
1796   } else if (isa<PHINode>(I)) {
1797     Out << ' ';
1798     TypePrinter.print(I.getType(), Out);
1799     Out << ' ';
1800
1801     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1802       if (op) Out << ", ";
1803       Out << "[ ";
1804       writeOperand(I.getOperand(op  ), false); Out << ", ";
1805       writeOperand(I.getOperand(op+1), false); Out << " ]";
1806     }
1807   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1808     Out << ' ';
1809     writeOperand(I.getOperand(0), true);
1810     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1811       Out << ", " << *i;
1812   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1813     Out << ' ';
1814     writeOperand(I.getOperand(0), true); Out << ", ";
1815     writeOperand(I.getOperand(1), true);
1816     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1817       Out << ", " << *i;
1818   } else if (isa<ReturnInst>(I) && !Operand) {
1819     Out << " void";
1820   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1821     // Print the calling convention being used.
1822     switch (CI->getCallingConv()) {
1823     case CallingConv::C: break;   // default
1824     case CallingConv::Fast:  Out << " fastcc"; break;
1825     case CallingConv::Cold:  Out << " coldcc"; break;
1826     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1827     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1828     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1829     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1830     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1831     default: Out << " cc" << CI->getCallingConv(); break;
1832     }
1833
1834     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1835     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1836     const Type         *RetTy = FTy->getReturnType();
1837     const AttrListPtr &PAL = CI->getAttributes();
1838
1839     if (PAL.getRetAttributes() != Attribute::None)
1840       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1841
1842     // If possible, print out the short form of the call instruction.  We can
1843     // only do this if the first argument is a pointer to a nonvararg function,
1844     // and if the return type is not a pointer to a function.
1845     //
1846     Out << ' ';
1847     if (!FTy->isVarArg() &&
1848         (!isa<PointerType>(RetTy) ||
1849          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1850       TypePrinter.print(RetTy, Out);
1851       Out << ' ';
1852       writeOperand(Operand, false);
1853     } else {
1854       writeOperand(Operand, true);
1855     }
1856     Out << '(';
1857     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1858       if (op > 1)
1859         Out << ", ";
1860       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1861     }
1862     Out << ')';
1863     if (PAL.getFnAttributes() != Attribute::None)
1864       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1865   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1866     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1867     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1868     const Type         *RetTy = FTy->getReturnType();
1869     const AttrListPtr &PAL = II->getAttributes();
1870
1871     // Print the calling convention being used.
1872     switch (II->getCallingConv()) {
1873     case CallingConv::C: break;   // default
1874     case CallingConv::Fast:  Out << " fastcc"; break;
1875     case CallingConv::Cold:  Out << " coldcc"; break;
1876     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1877     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1878     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1879     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1880     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1881     default: Out << " cc" << II->getCallingConv(); break;
1882     }
1883
1884     if (PAL.getRetAttributes() != Attribute::None)
1885       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1886
1887     // If possible, print out the short form of the invoke instruction. We can
1888     // only do this if the first argument is a pointer to a nonvararg function,
1889     // and if the return type is not a pointer to a function.
1890     //
1891     Out << ' ';
1892     if (!FTy->isVarArg() &&
1893         (!isa<PointerType>(RetTy) ||
1894          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1895       TypePrinter.print(RetTy, Out);
1896       Out << ' ';
1897       writeOperand(Operand, false);
1898     } else {
1899       writeOperand(Operand, true);
1900     }
1901     Out << '(';
1902     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1903       if (op > 3)
1904         Out << ", ";
1905       writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1906     }
1907
1908     Out << ')';
1909     if (PAL.getFnAttributes() != Attribute::None)
1910       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1911
1912     Out << "\n          to ";
1913     writeOperand(II->getNormalDest(), true);
1914     Out << " unwind ";
1915     writeOperand(II->getUnwindDest(), true);
1916
1917   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1918     Out << ' ';
1919     TypePrinter.print(AI->getType()->getElementType(), Out);
1920     if (!AI->getArraySize() || AI->isArrayAllocation()) {
1921       Out << ", ";
1922       writeOperand(AI->getArraySize(), true);
1923     }
1924     if (AI->getAlignment()) {
1925       Out << ", align " << AI->getAlignment();
1926     }
1927   } else if (isa<CastInst>(I)) {
1928     if (Operand) {
1929       Out << ' ';
1930       writeOperand(Operand, true);   // Work with broken code
1931     }
1932     Out << " to ";
1933     TypePrinter.print(I.getType(), Out);
1934   } else if (isa<VAArgInst>(I)) {
1935     if (Operand) {
1936       Out << ' ';
1937       writeOperand(Operand, true);   // Work with broken code
1938     }
1939     Out << ", ";
1940     TypePrinter.print(I.getType(), Out);
1941   } else if (Operand) {   // Print the normal way.
1942
1943     // PrintAllTypes - Instructions who have operands of all the same type
1944     // omit the type from all but the first operand.  If the instruction has
1945     // different type operands (for example br), then they are all printed.
1946     bool PrintAllTypes = false;
1947     const Type *TheType = Operand->getType();
1948
1949     // Select, Store and ShuffleVector always print all types.
1950     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1951         || isa<ReturnInst>(I)) {
1952       PrintAllTypes = true;
1953     } else {
1954       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1955         Operand = I.getOperand(i);
1956         // note that Operand shouldn't be null, but the test helps make dump()
1957         // more tolerant of malformed IR
1958         if (Operand && Operand->getType() != TheType) {
1959           PrintAllTypes = true;    // We have differing types!  Print them all!
1960           break;
1961         }
1962       }
1963     }
1964
1965     if (!PrintAllTypes) {
1966       Out << ' ';
1967       TypePrinter.print(TheType, Out);
1968     }
1969
1970     Out << ' ';
1971     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1972       if (i) Out << ", ";
1973       writeOperand(I.getOperand(i), PrintAllTypes);
1974     }
1975   }
1976   
1977   // Print post operand alignment for load/store
1978   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1979     Out << ", align " << cast<LoadInst>(I).getAlignment();
1980   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1981     Out << ", align " << cast<StoreInst>(I).getAlignment();
1982   }
1983
1984   printInfoComment(I);
1985 }
1986
1987
1988 //===----------------------------------------------------------------------===//
1989 //                       External Interface declarations
1990 //===----------------------------------------------------------------------===//
1991
1992 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
1993   SlotTracker SlotTable(this);
1994   formatted_raw_ostream OS(ROS);
1995   AssemblyWriter W(OS, SlotTable, this, AAW);
1996   W.write(this);
1997 }
1998
1999 void Type::print(raw_ostream &OS) const {
2000   if (this == 0) {
2001     OS << "<null Type>";
2002     return;
2003   }
2004   TypePrinting().print(this, OS);
2005 }
2006
2007 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2008   if (this == 0) {
2009     ROS << "printing a <null> value\n";
2010     return;
2011   }
2012   formatted_raw_ostream OS(ROS);
2013   if (const Instruction *I = dyn_cast<Instruction>(this)) {
2014     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2015     SlotTracker SlotTable(F);
2016     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2017     W.write(I);
2018   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2019     SlotTracker SlotTable(BB->getParent());
2020     AssemblyWriter W(OS, SlotTable,
2021                      BB->getParent() ? BB->getParent()->getParent() : 0, AAW);
2022     W.write(BB);
2023   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2024     SlotTracker SlotTable(GV->getParent());
2025     AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2026     W.write(GV);
2027   } else if (const MDString *MDS = dyn_cast<MDString>(this)) {
2028     TypePrinting TypePrinter;
2029     TypePrinter.print(MDS->getType(), OS);
2030     OS << ' ';
2031     OS << "!\"";
2032     PrintEscapedString(MDS->getString(), OS);
2033     OS << '"';
2034   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2035     SlotTracker SlotTable(N);
2036     TypePrinting TypePrinter;
2037     SlotTable.initialize();
2038     WriteMDNodes(OS, TypePrinter, SlotTable);
2039   } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2040     SlotTracker SlotTable(N);
2041     TypePrinting TypePrinter;
2042     SlotTable.initialize();
2043     OS << "!" << N->getName() << " = !{";
2044     for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
2045       if (i) OS << ", ";
2046       MDNode *MD = dyn_cast_or_null<MDNode>(N->getElement(i));
2047       if (MD)
2048         OS << '!' << SlotTable.getMetadataSlot(MD);
2049       else 
2050         OS << "null";
2051     }
2052     OS << "}\n";
2053     WriteMDNodes(OS, TypePrinter, SlotTable);
2054   } else if (const Constant *C = dyn_cast<Constant>(this)) {
2055     TypePrinting TypePrinter;
2056     TypePrinter.print(C->getType(), OS);
2057     OS << ' ';
2058     WriteConstantInt(OS, C, TypePrinter, 0);
2059   } else if (const Argument *A = dyn_cast<Argument>(this)) {
2060     WriteAsOperand(OS, this, true,
2061                    A->getParent() ? A->getParent()->getParent() : 0);
2062   } else if (isa<InlineAsm>(this)) {
2063     WriteAsOperand(OS, this, true, 0);
2064   } else {
2065     llvm_unreachable("Unknown value to print out!");
2066   }
2067 }
2068
2069 // Value::dump - allow easy printing of Values from the debugger.
2070 void Value::dump() const { print(errs()); errs() << '\n'; }
2071
2072 // Type::dump - allow easy printing of Types from the debugger.
2073 // This one uses type names from the given context module
2074 void Type::dump(const Module *Context) const {
2075   WriteTypeSymbolic(errs(), this, Context);
2076   errs() << '\n';
2077 }
2078
2079 // Type::dump - allow easy printing of Types from the debugger.
2080 void Type::dump() const { dump(0); }
2081
2082 // Module::dump() - Allow printing of Modules from the debugger.
2083 void Module::dump() const { print(errs(), 0); }