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