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