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