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