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