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