f9597cd44922bde3e9cf6a0134f982554444e038
[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 #include <map>
43 using namespace llvm;
44
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47
48 //===----------------------------------------------------------------------===//
49 // Helper Functions
50 //===----------------------------------------------------------------------===//
51
52 static const Module *getModuleFromVal(const Value *V) {
53   if (const Argument *MA = dyn_cast<Argument>(V))
54     return MA->getParent() ? MA->getParent()->getParent() : 0;
55
56   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57     return BB->getParent() ? BB->getParent()->getParent() : 0;
58
59   if (const Instruction *I = dyn_cast<Instruction>(V)) {
60     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61     return M ? M->getParent() : 0;
62   }
63   
64   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65     return GV->getParent();
66   return 0;
67 }
68
69 // PrintEscapedString - Print each character of the specified string, escaping
70 // it if it is not printable or if it is an escape char.
71 static void PrintEscapedString(StringRef Name, 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, StringRef Name, PrefixType Prefix) {
92   assert(Name.data() && "Cannot get empty name!");
93   switch (Prefix) {
94   default: llvm_unreachable("Bad prefix!");
95   case NoPrefix: break;
96   case GlobalPrefix: OS << '@'; break;
97   case LabelPrefix:  break;
98   case LocalPrefix:  OS << '%'; break;
99   }
100
101   // Scan the name to see if it needs quotes first.
102   bool NeedsQuotes = isdigit(Name[0]);
103   if (!NeedsQuotes) {
104     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
105       char C = Name[i];
106       if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
107         NeedsQuotes = true;
108         break;
109       }
110     }
111   }
112
113   // If we didn't need any quotes, just write out the name in one blast.
114   if (!NeedsQuotes) {
115     OS << Name;
116     return;
117   }
118
119   // Okay, we need quotes.  Output the quotes and escape any scary characters as
120   // needed.
121   OS << '"';
122   PrintEscapedString(Name, OS);
123   OS << '"';
124 }
125
126 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
127 /// prefixed with % (if the string only contains simple characters) or is
128 /// surrounded with ""'s (if it has special chars in it).  Print it out.
129 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
130   PrintLLVMName(OS, V->getName(),
131                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
132 }
133
134 //===----------------------------------------------------------------------===//
135 // TypePrinting Class: Type printing machinery
136 //===----------------------------------------------------------------------===//
137
138 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
139   return *static_cast<DenseMap<const Type *, std::string>*>(M);
140 }
141
142 void TypePrinting::clear() {
143   getTypeNamesMap(TypeNames).clear();
144 }
145
146 bool TypePrinting::hasTypeName(const Type *Ty) const {
147   return getTypeNamesMap(TypeNames).count(Ty);
148 }
149
150 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
151   getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
152 }
153
154
155 TypePrinting::TypePrinting() {
156   TypeNames = new DenseMap<const Type *, std::string>();
157 }
158
159 TypePrinting::~TypePrinting() {
160   delete &getTypeNamesMap(TypeNames);
161 }
162
163 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
164 /// use of type names or up references to shorten the type name where possible.
165 void TypePrinting::CalcTypeName(const Type *Ty,
166                                 SmallVectorImpl<const Type *> &TypeStack,
167                                 raw_ostream &OS, bool IgnoreTopLevelName) {
168   // Check to see if the type is named.
169   if (!IgnoreTopLevelName) {
170     DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
171     DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
172     if (I != TM.end()) {
173       OS << I->second;
174       return;
175     }
176   }
177
178   // Check to see if the Type is already on the stack...
179   unsigned Slot = 0, CurSize = TypeStack.size();
180   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
181
182   // This is another base case for the recursion.  In this case, we know
183   // that we have looped back to a type that we have previously visited.
184   // Generate the appropriate upreference to handle this.
185   if (Slot < CurSize) {
186     OS << '\\' << unsigned(CurSize-Slot);     // Here's the upreference
187     return;
188   }
189
190   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
191
192   switch (Ty->getTypeID()) {
193   case Type::VoidTyID:      OS << "void"; break;
194   case Type::FloatTyID:     OS << "float"; break;
195   case Type::DoubleTyID:    OS << "double"; break;
196   case Type::X86_FP80TyID:  OS << "x86_fp80"; break;
197   case Type::FP128TyID:     OS << "fp128"; break;
198   case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
199   case Type::LabelTyID:     OS << "label"; break;
200   case Type::MetadataTyID:  OS << "metadata"; break;
201   case Type::IntegerTyID:
202     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
203     break;
204
205   case Type::FunctionTyID: {
206     const FunctionType *FTy = cast<FunctionType>(Ty);
207     CalcTypeName(FTy->getReturnType(), TypeStack, OS);
208     OS << " (";
209     for (FunctionType::param_iterator I = FTy->param_begin(),
210          E = FTy->param_end(); I != E; ++I) {
211       if (I != FTy->param_begin())
212         OS << ", ";
213       CalcTypeName(*I, TypeStack, OS);
214     }
215     if (FTy->isVarArg()) {
216       if (FTy->getNumParams()) OS << ", ";
217       OS << "...";
218     }
219     OS << ')';
220     break;
221   }
222   case Type::StructTyID: {
223     const StructType *STy = cast<StructType>(Ty);
224     if (STy->isPacked())
225       OS << '<';
226     OS << '{';
227     for (StructType::element_iterator I = STy->element_begin(),
228          E = STy->element_end(); I != E; ++I) {
229       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 SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
834     if (Div->isExact())
835       Out << " exact";
836   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
837     if (GEP->isInBounds())
838       Out << " inbounds";
839   }
840 }
841
842 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
843                                   TypePrinting &TypePrinter,
844                                   SlotTracker *Machine,
845                                   const Module *Context) {
846   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
847     if (CI->getType()->isIntegerTy(1)) {
848       Out << (CI->getZExtValue() ? "true" : "false");
849       return;
850     }
851     Out << CI->getValue();
852     return;
853   }
854
855   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
856     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
857         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
858       // We would like to output the FP constant value in exponential notation,
859       // but we cannot do this if doing so will lose precision.  Check here to
860       // make sure that we only output it in exponential format if we can parse
861       // the value back and get the same value.
862       //
863       bool ignored;
864       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
865       double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
866                               CFP->getValueAPF().convertToFloat();
867       SmallString<128> StrVal;
868       raw_svector_ostream(StrVal) << Val;
869
870       // Check to make sure that the stringized number is not some string like
871       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
872       // that the string matches the "[-+]?[0-9]" regex.
873       //
874       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
875           ((StrVal[0] == '-' || StrVal[0] == '+') &&
876            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
877         // Reparse stringized version!
878         if (atof(StrVal.c_str()) == Val) {
879           Out << StrVal.str();
880           return;
881         }
882       }
883       // Otherwise we could not reparse it to exactly the same value, so we must
884       // output the string in hexadecimal format!  Note that loading and storing
885       // floating point types changes the bits of NaNs on some hosts, notably
886       // x86, so we must not use these types.
887       assert(sizeof(double) == sizeof(uint64_t) &&
888              "assuming that double is 64 bits!");
889       char Buffer[40];
890       APFloat apf = CFP->getValueAPF();
891       // Floats are represented in ASCII IR as double, convert.
892       if (!isDouble)
893         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
894                           &ignored);
895       Out << "0x" <<
896               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
897                             Buffer+40);
898       return;
899     }
900
901     // Some form of long double.  These appear as a magic letter identifying
902     // the type, then a fixed number of hex digits.
903     Out << "0x";
904     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
905       Out << 'K';
906       // api needed to prevent premature destruction
907       APInt api = CFP->getValueAPF().bitcastToAPInt();
908       const uint64_t* p = api.getRawData();
909       uint64_t word = p[1];
910       int shiftcount=12;
911       int width = api.getBitWidth();
912       for (int j=0; j<width; j+=4, shiftcount-=4) {
913         unsigned int nibble = (word>>shiftcount) & 15;
914         if (nibble < 10)
915           Out << (unsigned char)(nibble + '0');
916         else
917           Out << (unsigned char)(nibble - 10 + 'A');
918         if (shiftcount == 0 && j+4 < width) {
919           word = *p;
920           shiftcount = 64;
921           if (width-j-4 < 64)
922             shiftcount = width-j-4;
923         }
924       }
925       return;
926     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
927       Out << 'L';
928     else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
929       Out << 'M';
930     else
931       llvm_unreachable("Unsupported floating point type");
932     // api needed to prevent premature destruction
933     APInt api = CFP->getValueAPF().bitcastToAPInt();
934     const uint64_t* p = api.getRawData();
935     uint64_t word = *p;
936     int shiftcount=60;
937     int width = api.getBitWidth();
938     for (int j=0; j<width; j+=4, shiftcount-=4) {
939       unsigned int nibble = (word>>shiftcount) & 15;
940       if (nibble < 10)
941         Out << (unsigned char)(nibble + '0');
942       else
943         Out << (unsigned char)(nibble - 10 + 'A');
944       if (shiftcount == 0 && j+4 < width) {
945         word = *(++p);
946         shiftcount = 64;
947         if (width-j-4 < 64)
948           shiftcount = width-j-4;
949       }
950     }
951     return;
952   }
953
954   if (isa<ConstantAggregateZero>(CV)) {
955     Out << "zeroinitializer";
956     return;
957   }
958   
959   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
960     Out << "blockaddress(";
961     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
962                            Context);
963     Out << ", ";
964     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
965                            Context);
966     Out << ")";
967     return;
968   }
969
970   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
971     // As a special case, print the array as a string if it is an array of
972     // i8 with ConstantInt values.
973     //
974     const Type *ETy = CA->getType()->getElementType();
975     if (CA->isString()) {
976       Out << "c\"";
977       PrintEscapedString(CA->getAsString(), Out);
978       Out << '"';
979     } else {                // Cannot output in string format...
980       Out << '[';
981       if (CA->getNumOperands()) {
982         TypePrinter.print(ETy, Out);
983         Out << ' ';
984         WriteAsOperandInternal(Out, CA->getOperand(0),
985                                &TypePrinter, Machine,
986                                Context);
987         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
988           Out << ", ";
989           TypePrinter.print(ETy, Out);
990           Out << ' ';
991           WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
992                                  Context);
993         }
994       }
995       Out << ']';
996     }
997     return;
998   }
999
1000   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1001     if (CS->getType()->isPacked())
1002       Out << '<';
1003     Out << '{';
1004     unsigned N = CS->getNumOperands();
1005     if (N) {
1006       Out << ' ';
1007       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1008       Out << ' ';
1009
1010       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1011                              Context);
1012
1013       for (unsigned i = 1; i < N; i++) {
1014         Out << ", ";
1015         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1016         Out << ' ';
1017
1018         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1019                                Context);
1020       }
1021       Out << ' ';
1022     }
1023
1024     Out << '}';
1025     if (CS->getType()->isPacked())
1026       Out << '>';
1027     return;
1028   }
1029
1030   if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1031     const Type *ETy = CP->getType()->getElementType();
1032     assert(CP->getNumOperands() > 0 &&
1033            "Number of operands for a PackedConst must be > 0");
1034     Out << '<';
1035     TypePrinter.print(ETy, Out);
1036     Out << ' ';
1037     WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
1038                            Context);
1039     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1040       Out << ", ";
1041       TypePrinter.print(ETy, Out);
1042       Out << ' ';
1043       WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
1044                              Context);
1045     }
1046     Out << '>';
1047     return;
1048   }
1049
1050   if (isa<ConstantPointerNull>(CV)) {
1051     Out << "null";
1052     return;
1053   }
1054
1055   if (isa<UndefValue>(CV)) {
1056     Out << "undef";
1057     return;
1058   }
1059
1060   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1061     Out << CE->getOpcodeName();
1062     WriteOptimizationInfo(Out, CE);
1063     if (CE->isCompare())
1064       Out << ' ' << getPredicateText(CE->getPredicate());
1065     Out << " (";
1066
1067     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1068       TypePrinter.print((*OI)->getType(), Out);
1069       Out << ' ';
1070       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1071       if (OI+1 != CE->op_end())
1072         Out << ", ";
1073     }
1074
1075     if (CE->hasIndices()) {
1076       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1077       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1078         Out << ", " << Indices[i];
1079     }
1080
1081     if (CE->isCast()) {
1082       Out << " to ";
1083       TypePrinter.print(CE->getType(), Out);
1084     }
1085
1086     Out << ')';
1087     return;
1088   }
1089
1090   Out << "<placeholder or erroneous Constant>";
1091 }
1092
1093 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1094                                     TypePrinting *TypePrinter,
1095                                     SlotTracker *Machine,
1096                                     const Module *Context) {
1097   Out << "!{";
1098   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1099     const Value *V = Node->getOperand(mi);
1100     if (V == 0)
1101       Out << "null";
1102     else {
1103       TypePrinter->print(V->getType(), Out);
1104       Out << ' ';
1105       WriteAsOperandInternal(Out, Node->getOperand(mi), 
1106                              TypePrinter, Machine, Context);
1107     }
1108     if (mi + 1 != me)
1109       Out << ", ";
1110   }
1111   
1112   Out << "}";
1113 }
1114
1115
1116 /// WriteAsOperand - Write the name of the specified value out to the specified
1117 /// ostream.  This can be useful when you just want to print int %reg126, not
1118 /// the whole instruction that generated it.
1119 ///
1120 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1121                                    TypePrinting *TypePrinter,
1122                                    SlotTracker *Machine,
1123                                    const Module *Context) {
1124   if (V->hasName()) {
1125     PrintLLVMName(Out, V);
1126     return;
1127   }
1128
1129   const Constant *CV = dyn_cast<Constant>(V);
1130   if (CV && !isa<GlobalValue>(CV)) {
1131     assert(TypePrinter && "Constants require TypePrinting!");
1132     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1133     return;
1134   }
1135
1136   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1137     Out << "asm ";
1138     if (IA->hasSideEffects())
1139       Out << "sideeffect ";
1140     if (IA->isAlignStack())
1141       Out << "alignstack ";
1142     Out << '"';
1143     PrintEscapedString(IA->getAsmString(), Out);
1144     Out << "\", \"";
1145     PrintEscapedString(IA->getConstraintString(), Out);
1146     Out << '"';
1147     return;
1148   }
1149
1150   if (const MDNode *N = dyn_cast<MDNode>(V)) {
1151     if (N->isFunctionLocal()) {
1152       // Print metadata inline, not via slot reference number.
1153       WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1154       return;
1155     }
1156   
1157     if (!Machine) {
1158       if (N->isFunctionLocal())
1159         Machine = new SlotTracker(N->getFunction());
1160       else
1161         Machine = new SlotTracker(Context);
1162     }
1163     int Slot = Machine->getMetadataSlot(N);
1164     if (Slot == -1)
1165       Out << "<badref>";
1166     else
1167       Out << '!' << Slot;
1168     return;
1169   }
1170
1171   if (const MDString *MDS = dyn_cast<MDString>(V)) {
1172     Out << "!\"";
1173     PrintEscapedString(MDS->getString(), Out);
1174     Out << '"';
1175     return;
1176   }
1177
1178   if (V->getValueID() == Value::PseudoSourceValueVal ||
1179       V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1180     V->print(Out);
1181     return;
1182   }
1183
1184   char Prefix = '%';
1185   int Slot;
1186   if (Machine) {
1187     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1188       Slot = Machine->getGlobalSlot(GV);
1189       Prefix = '@';
1190     } else {
1191       Slot = Machine->getLocalSlot(V);
1192     }
1193   } else {
1194     Machine = createSlotTracker(V);
1195     if (Machine) {
1196       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1197         Slot = Machine->getGlobalSlot(GV);
1198         Prefix = '@';
1199       } else {
1200         Slot = Machine->getLocalSlot(V);
1201       }
1202       delete Machine;
1203     } else {
1204       Slot = -1;
1205     }
1206   }
1207
1208   if (Slot != -1)
1209     Out << Prefix << Slot;
1210   else
1211     Out << "<badref>";
1212 }
1213
1214 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1215                           bool PrintType, const Module *Context) {
1216
1217   // Fast path: Don't construct and populate a TypePrinting object if we
1218   // won't be needing any types printed.
1219   if (!PrintType &&
1220       ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1221        V->hasName() || isa<GlobalValue>(V))) {
1222     WriteAsOperandInternal(Out, V, 0, 0, Context);
1223     return;
1224   }
1225
1226   if (Context == 0) Context = getModuleFromVal(V);
1227
1228   TypePrinting TypePrinter;
1229   std::vector<const Type*> NumberedTypes;
1230   AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1231   if (PrintType) {
1232     TypePrinter.print(V->getType(), Out);
1233     Out << ' ';
1234   }
1235
1236   WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1237 }
1238
1239 namespace {
1240
1241 class AssemblyWriter {
1242   formatted_raw_ostream &Out;
1243   SlotTracker &Machine;
1244   const Module *TheModule;
1245   TypePrinting TypePrinter;
1246   AssemblyAnnotationWriter *AnnotationWriter;
1247   std::vector<const Type*> NumberedTypes;
1248   
1249 public:
1250   inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1251                         const Module *M,
1252                         AssemblyAnnotationWriter *AAW)
1253     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1254     AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1255   }
1256
1257   void printMDNodeBody(const MDNode *MD);
1258   void printNamedMDNode(const NamedMDNode *NMD);
1259   
1260   void printModule(const Module *M);
1261
1262   void writeOperand(const Value *Op, bool PrintType);
1263   void writeParamOperand(const Value *Operand, Attributes Attrs);
1264
1265   void writeAllMDNodes();
1266
1267   void printTypeSymbolTable(const TypeSymbolTable &ST);
1268   void printGlobal(const GlobalVariable *GV);
1269   void printAlias(const GlobalAlias *GV);
1270   void printFunction(const Function *F);
1271   void printArgument(const Argument *FA, Attributes Attrs);
1272   void printBasicBlock(const BasicBlock *BB);
1273   void printInstruction(const Instruction &I);
1274
1275 private:
1276   // printInfoComment - Print a little comment after the instruction indicating
1277   // which slot it occupies.
1278   void printInfoComment(const Value &V);
1279 };
1280 }  // end of anonymous namespace
1281
1282 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1283   if (Operand == 0) {
1284     Out << "<null operand!>";
1285     return;
1286   }
1287   if (PrintType) {
1288     TypePrinter.print(Operand->getType(), Out);
1289     Out << ' ';
1290   }
1291   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1292 }
1293
1294 void AssemblyWriter::writeParamOperand(const Value *Operand,
1295                                        Attributes Attrs) {
1296   if (Operand == 0) {
1297     Out << "<null operand!>";
1298     return;
1299   }
1300
1301   // Print the type
1302   TypePrinter.print(Operand->getType(), Out);
1303   // Print parameter attributes list
1304   if (Attrs != Attribute::None)
1305     Out << ' ' << Attribute::getAsString(Attrs);
1306   Out << ' ';
1307   // Print the operand
1308   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1309 }
1310
1311 void AssemblyWriter::printModule(const Module *M) {
1312   if (!M->getModuleIdentifier().empty() &&
1313       // Don't print the ID if it will start a new line (which would
1314       // require a comment char before it).
1315       M->getModuleIdentifier().find('\n') == std::string::npos)
1316     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1317
1318   if (!M->getDataLayout().empty())
1319     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1320   if (!M->getTargetTriple().empty())
1321     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1322
1323   if (!M->getModuleInlineAsm().empty()) {
1324     // Split the string into lines, to make it easier to read the .ll file.
1325     std::string Asm = M->getModuleInlineAsm();
1326     size_t CurPos = 0;
1327     size_t NewLine = Asm.find_first_of('\n', CurPos);
1328     Out << '\n';
1329     while (NewLine != std::string::npos) {
1330       // We found a newline, print the portion of the asm string from the
1331       // last newline up to this newline.
1332       Out << "module asm \"";
1333       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1334                          Out);
1335       Out << "\"\n";
1336       CurPos = NewLine+1;
1337       NewLine = Asm.find_first_of('\n', CurPos);
1338     }
1339     Out << "module asm \"";
1340     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1341     Out << "\"\n";
1342   }
1343
1344   // Loop over the dependent libraries and emit them.
1345   Module::lib_iterator LI = M->lib_begin();
1346   Module::lib_iterator LE = M->lib_end();
1347   if (LI != LE) {
1348     Out << '\n';
1349     Out << "deplibs = [ ";
1350     while (LI != LE) {
1351       Out << '"' << *LI << '"';
1352       ++LI;
1353       if (LI != LE)
1354         Out << ", ";
1355     }
1356     Out << " ]";
1357   }
1358
1359   // Loop over the symbol table, emitting all id'd types.
1360   if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1361   printTypeSymbolTable(M->getTypeSymbolTable());
1362
1363   // Output all globals.
1364   if (!M->global_empty()) Out << '\n';
1365   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1366        I != E; ++I)
1367     printGlobal(I);
1368
1369   // Output all aliases.
1370   if (!M->alias_empty()) Out << "\n";
1371   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1372        I != E; ++I)
1373     printAlias(I);
1374
1375   // Output all of the functions.
1376   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1377     printFunction(I);
1378
1379   // Output named metadata.
1380   if (!M->named_metadata_empty()) Out << '\n';
1381   
1382   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1383        E = M->named_metadata_end(); I != E; ++I)
1384     printNamedMDNode(I);
1385
1386   // Output metadata.
1387   if (!Machine.mdn_empty()) {
1388     Out << '\n';
1389     writeAllMDNodes();
1390   }
1391 }
1392
1393 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1394   Out << "!" << NMD->getName() << " = !{";
1395   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1396     if (i) Out << ", ";
1397     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1398     if (Slot == -1)
1399       Out << "<badref>";
1400     else
1401       Out << '!' << Slot;
1402   }
1403   Out << "}\n";
1404 }
1405
1406
1407 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1408                          formatted_raw_ostream &Out) {
1409   switch (LT) {
1410   case GlobalValue::ExternalLinkage: break;
1411   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
1412   case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1413   case GlobalValue::LinkerPrivateWeakLinkage:
1414     Out << "linker_private_weak ";
1415     break;
1416   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1417     Out << "linker_private_weak_def_auto ";
1418     break;
1419   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
1420   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
1421   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
1422   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
1423   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
1424   case GlobalValue::CommonLinkage:        Out << "common ";         break;
1425   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
1426   case GlobalValue::DLLImportLinkage:     Out << "dllimport ";      break;
1427   case GlobalValue::DLLExportLinkage:     Out << "dllexport ";      break;
1428   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
1429   case GlobalValue::AvailableExternallyLinkage:
1430     Out << "available_externally ";
1431     break;
1432   }
1433 }
1434
1435
1436 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1437                             formatted_raw_ostream &Out) {
1438   switch (Vis) {
1439   case GlobalValue::DefaultVisibility: break;
1440   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
1441   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1442   }
1443 }
1444
1445 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1446   if (GV->isMaterializable())
1447     Out << "; Materializable\n";
1448
1449   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1450   Out << " = ";
1451
1452   if (!GV->hasInitializer() && GV->hasExternalLinkage())
1453     Out << "external ";
1454
1455   PrintLinkage(GV->getLinkage(), Out);
1456   PrintVisibility(GV->getVisibility(), Out);
1457
1458   if (GV->isThreadLocal()) Out << "thread_local ";
1459   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1460     Out << "addrspace(" << AddressSpace << ") ";
1461   Out << (GV->isConstant() ? "constant " : "global ");
1462   TypePrinter.print(GV->getType()->getElementType(), Out);
1463
1464   if (GV->hasInitializer()) {
1465     Out << ' ';
1466     writeOperand(GV->getInitializer(), false);
1467   }
1468
1469   if (GV->hasSection()) {
1470     Out << ", section \"";
1471     PrintEscapedString(GV->getSection(), Out);
1472     Out << '"';
1473   }
1474   if (GV->getAlignment())
1475     Out << ", align " << GV->getAlignment();
1476
1477   printInfoComment(*GV);
1478   Out << '\n';
1479 }
1480
1481 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1482   if (GA->isMaterializable())
1483     Out << "; Materializable\n";
1484
1485   // Don't crash when dumping partially built GA
1486   if (!GA->hasName())
1487     Out << "<<nameless>> = ";
1488   else {
1489     PrintLLVMName(Out, GA);
1490     Out << " = ";
1491   }
1492   PrintVisibility(GA->getVisibility(), Out);
1493
1494   Out << "alias ";
1495
1496   PrintLinkage(GA->getLinkage(), Out);
1497
1498   const Constant *Aliasee = GA->getAliasee();
1499
1500   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1501     TypePrinter.print(GV->getType(), Out);
1502     Out << ' ';
1503     PrintLLVMName(Out, GV);
1504   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1505     TypePrinter.print(F->getFunctionType(), Out);
1506     Out << "* ";
1507
1508     WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1509   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1510     TypePrinter.print(GA->getType(), Out);
1511     Out << ' ';
1512     PrintLLVMName(Out, GA);
1513   } else {
1514     const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1515     // The only valid GEP is an all zero GEP.
1516     assert((CE->getOpcode() == Instruction::BitCast ||
1517             CE->getOpcode() == Instruction::GetElementPtr) &&
1518            "Unsupported aliasee");
1519     writeOperand(CE, false);
1520   }
1521
1522   printInfoComment(*GA);
1523   Out << '\n';
1524 }
1525
1526 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1527   // Emit all numbered types.
1528   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1529     Out << '%' << i << " = type ";
1530
1531     // Make sure we print out at least one level of the type structure, so
1532     // that we do not get %2 = type %2
1533     TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1534     Out << '\n';
1535   }
1536
1537   // Print the named types.
1538   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1539        TI != TE; ++TI) {
1540     PrintLLVMName(Out, TI->first, LocalPrefix);
1541     Out << " = type ";
1542
1543     // Make sure we print out at least one level of the type structure, so
1544     // that we do not get %FILE = type %FILE
1545     TypePrinter.printAtLeastOneLevel(TI->second, Out);
1546     Out << '\n';
1547   }
1548 }
1549
1550 /// printFunction - Print all aspects of a function.
1551 ///
1552 void AssemblyWriter::printFunction(const Function *F) {
1553   // Print out the return type and name.
1554   Out << '\n';
1555
1556   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1557
1558   if (F->isMaterializable())
1559     Out << "; Materializable\n";
1560
1561   if (F->isDeclaration())
1562     Out << "declare ";
1563   else
1564     Out << "define ";
1565
1566   PrintLinkage(F->getLinkage(), Out);
1567   PrintVisibility(F->getVisibility(), Out);
1568
1569   // Print the calling convention.
1570   switch (F->getCallingConv()) {
1571   case CallingConv::C: break;   // default
1572   case CallingConv::Fast:         Out << "fastcc "; break;
1573   case CallingConv::Cold:         Out << "coldcc "; break;
1574   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1575   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1576   case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1577   case CallingConv::ARM_APCS:     Out << "arm_apcscc "; break;
1578   case CallingConv::ARM_AAPCS:    Out << "arm_aapcscc "; break;
1579   case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1580   case CallingConv::MSP430_INTR:  Out << "msp430_intrcc "; break;
1581   default: Out << "cc" << F->getCallingConv() << " "; break;
1582   }
1583
1584   const FunctionType *FT = F->getFunctionType();
1585   const AttrListPtr &Attrs = F->getAttributes();
1586   Attributes RetAttrs = Attrs.getRetAttributes();
1587   if (RetAttrs != Attribute::None)
1588     Out <<  Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1589   TypePrinter.print(F->getReturnType(), Out);
1590   Out << ' ';
1591   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1592   Out << '(';
1593   Machine.incorporateFunction(F);
1594
1595   // Loop over the arguments, printing them...
1596
1597   unsigned Idx = 1;
1598   if (!F->isDeclaration()) {
1599     // If this isn't a declaration, print the argument names as well.
1600     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1601          I != E; ++I) {
1602       // Insert commas as we go... the first arg doesn't get a comma
1603       if (I != F->arg_begin()) Out << ", ";
1604       printArgument(I, Attrs.getParamAttributes(Idx));
1605       Idx++;
1606     }
1607   } else {
1608     // Otherwise, print the types from the function type.
1609     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1610       // Insert commas as we go... the first arg doesn't get a comma
1611       if (i) Out << ", ";
1612
1613       // Output type...
1614       TypePrinter.print(FT->getParamType(i), Out);
1615
1616       Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1617       if (ArgAttrs != Attribute::None)
1618         Out << ' ' << Attribute::getAsString(ArgAttrs);
1619     }
1620   }
1621
1622   // Finish printing arguments...
1623   if (FT->isVarArg()) {
1624     if (FT->getNumParams()) Out << ", ";
1625     Out << "...";  // Output varargs portion of signature!
1626   }
1627   Out << ')';
1628   Attributes FnAttrs = Attrs.getFnAttributes();
1629   if (FnAttrs != Attribute::None)
1630     Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1631   if (F->hasSection()) {
1632     Out << " section \"";
1633     PrintEscapedString(F->getSection(), Out);
1634     Out << '"';
1635   }
1636   if (F->getAlignment())
1637     Out << " align " << F->getAlignment();
1638   if (F->hasGC())
1639     Out << " gc \"" << F->getGC() << '"';
1640   if (F->isDeclaration()) {
1641     Out << '\n';
1642   } else {
1643     Out << " {";
1644     // Output all of the function's basic blocks.
1645     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1646       printBasicBlock(I);
1647
1648     Out << "}\n";
1649   }
1650
1651   Machine.purgeFunction();
1652 }
1653
1654 /// printArgument - This member is called for every argument that is passed into
1655 /// the function.  Simply print it out
1656 ///
1657 void AssemblyWriter::printArgument(const Argument *Arg,
1658                                    Attributes Attrs) {
1659   // Output type...
1660   TypePrinter.print(Arg->getType(), Out);
1661
1662   // Output parameter attributes list
1663   if (Attrs != Attribute::None)
1664     Out << ' ' << Attribute::getAsString(Attrs);
1665
1666   // Output name, if available...
1667   if (Arg->hasName()) {
1668     Out << ' ';
1669     PrintLLVMName(Out, Arg);
1670   }
1671 }
1672
1673 /// printBasicBlock - This member is called for each basic block in a method.
1674 ///
1675 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1676   if (BB->hasName()) {              // Print out the label if it exists...
1677     Out << "\n";
1678     PrintLLVMName(Out, BB->getName(), LabelPrefix);
1679     Out << ':';
1680   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1681     Out << "\n; <label>:";
1682     int Slot = Machine.getLocalSlot(BB);
1683     if (Slot != -1)
1684       Out << Slot;
1685     else
1686       Out << "<badref>";
1687   }
1688
1689   if (BB->getParent() == 0) {
1690     Out.PadToColumn(50);
1691     Out << "; Error: Block without parent!";
1692   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1693     // Output predecessors for the block.
1694     Out.PadToColumn(50);
1695     Out << ";";
1696     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1697
1698     if (PI == PE) {
1699       Out << " No predecessors!";
1700     } else {
1701       Out << " preds = ";
1702       writeOperand(*PI, false);
1703       for (++PI; PI != PE; ++PI) {
1704         Out << ", ";
1705         writeOperand(*PI, false);
1706       }
1707     }
1708   }
1709
1710   Out << "\n";
1711
1712   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1713
1714   // Output all of the instructions in the basic block...
1715   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1716     printInstruction(*I);
1717     Out << '\n';
1718   }
1719
1720   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1721 }
1722
1723 /// printInfoComment - Print a little comment after the instruction indicating
1724 /// which slot it occupies.
1725 ///
1726 void AssemblyWriter::printInfoComment(const Value &V) {
1727   if (AnnotationWriter) {
1728     AnnotationWriter->printInfoComment(V, Out);
1729     return;
1730   }
1731 }
1732
1733 // This member is called for each Instruction in a function..
1734 void AssemblyWriter::printInstruction(const Instruction &I) {
1735   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1736
1737   // Print out indentation for an instruction.
1738   Out << "  ";
1739
1740   // Print out name if it exists...
1741   if (I.hasName()) {
1742     PrintLLVMName(Out, &I);
1743     Out << " = ";
1744   } else if (!I.getType()->isVoidTy()) {
1745     // Print out the def slot taken.
1746     int SlotNum = Machine.getLocalSlot(&I);
1747     if (SlotNum == -1)
1748       Out << "<badref> = ";
1749     else
1750       Out << '%' << SlotNum << " = ";
1751   }
1752
1753   // If this is a volatile load or store, print out the volatile marker.
1754   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1755       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1756       Out << "volatile ";
1757   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1758     // If this is a call, check if it's a tail call.
1759     Out << "tail ";
1760   }
1761
1762   // Print out the opcode...
1763   Out << I.getOpcodeName();
1764
1765   // Print out optimization information.
1766   WriteOptimizationInfo(Out, &I);
1767
1768   // Print out the compare instruction predicates
1769   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1770     Out << ' ' << getPredicateText(CI->getPredicate());
1771
1772   // Print out the type of the operands...
1773   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1774
1775   // Special case conditional branches to swizzle the condition out to the front
1776   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1777     BranchInst &BI(cast<BranchInst>(I));
1778     Out << ' ';
1779     writeOperand(BI.getCondition(), true);
1780     Out << ", ";
1781     writeOperand(BI.getSuccessor(0), true);
1782     Out << ", ";
1783     writeOperand(BI.getSuccessor(1), true);
1784
1785   } else if (isa<SwitchInst>(I)) {
1786     // Special case switch instruction to get formatting nice and correct.
1787     Out << ' ';
1788     writeOperand(Operand        , true);
1789     Out << ", ";
1790     writeOperand(I.getOperand(1), true);
1791     Out << " [";
1792
1793     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1794       Out << "\n    ";
1795       writeOperand(I.getOperand(op  ), true);
1796       Out << ", ";
1797       writeOperand(I.getOperand(op+1), true);
1798     }
1799     Out << "\n  ]";
1800   } else if (isa<IndirectBrInst>(I)) {
1801     // Special case indirectbr instruction to get formatting nice and correct.
1802     Out << ' ';
1803     writeOperand(Operand, true);
1804     Out << ", [";
1805     
1806     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1807       if (i != 1)
1808         Out << ", ";
1809       writeOperand(I.getOperand(i), true);
1810     }
1811     Out << ']';
1812   } else if (isa<PHINode>(I)) {
1813     Out << ' ';
1814     TypePrinter.print(I.getType(), Out);
1815     Out << ' ';
1816
1817     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1818       if (op) Out << ", ";
1819       Out << "[ ";
1820       writeOperand(I.getOperand(op  ), false); Out << ", ";
1821       writeOperand(I.getOperand(op+1), false); Out << " ]";
1822     }
1823   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1824     Out << ' ';
1825     writeOperand(I.getOperand(0), true);
1826     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1827       Out << ", " << *i;
1828   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1829     Out << ' ';
1830     writeOperand(I.getOperand(0), true); Out << ", ";
1831     writeOperand(I.getOperand(1), true);
1832     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1833       Out << ", " << *i;
1834   } else if (isa<ReturnInst>(I) && !Operand) {
1835     Out << " void";
1836   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1837     // Print the calling convention being used.
1838     switch (CI->getCallingConv()) {
1839     case CallingConv::C: break;   // default
1840     case CallingConv::Fast:  Out << " fastcc"; break;
1841     case CallingConv::Cold:  Out << " coldcc"; break;
1842     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1843     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1844     case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1845     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1846     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1847     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1848     case CallingConv::MSP430_INTR:  Out << " msp430_intrcc "; break;
1849     default: Out << " cc" << CI->getCallingConv(); break;
1850     }
1851
1852     Operand = CI->getCalledValue();
1853     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1854     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1855     const Type         *RetTy = FTy->getReturnType();
1856     const AttrListPtr &PAL = CI->getAttributes();
1857
1858     if (PAL.getRetAttributes() != Attribute::None)
1859       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1860
1861     // If possible, print out the short form of the call instruction.  We can
1862     // only do this if the first argument is a pointer to a nonvararg function,
1863     // and if the return type is not a pointer to a function.
1864     //
1865     Out << ' ';
1866     if (!FTy->isVarArg() &&
1867         (!RetTy->isPointerTy() ||
1868          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1869       TypePrinter.print(RetTy, Out);
1870       Out << ' ';
1871       writeOperand(Operand, false);
1872     } else {
1873       writeOperand(Operand, true);
1874     }
1875     Out << '(';
1876     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1877       if (op > 0)
1878         Out << ", ";
1879       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1880     }
1881     Out << ')';
1882     if (PAL.getFnAttributes() != Attribute::None)
1883       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1884   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1885     Operand = II->getCalledValue();
1886     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1887     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1888     const Type         *RetTy = FTy->getReturnType();
1889     const AttrListPtr &PAL = II->getAttributes();
1890
1891     // Print the calling convention being used.
1892     switch (II->getCallingConv()) {
1893     case CallingConv::C: break;   // default
1894     case CallingConv::Fast:  Out << " fastcc"; break;
1895     case CallingConv::Cold:  Out << " coldcc"; break;
1896     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1897     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1898     case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1899     case CallingConv::ARM_APCS:     Out << " arm_apcscc "; break;
1900     case CallingConv::ARM_AAPCS:    Out << " arm_aapcscc "; break;
1901     case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1902     case CallingConv::MSP430_INTR:  Out << " msp430_intrcc "; break;
1903     default: Out << " cc" << II->getCallingConv(); break;
1904     }
1905
1906     if (PAL.getRetAttributes() != Attribute::None)
1907       Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1908
1909     // If possible, print out the short form of the invoke instruction. We can
1910     // only do this if the first argument is a pointer to a nonvararg function,
1911     // and if the return type is not a pointer to a function.
1912     //
1913     Out << ' ';
1914     if (!FTy->isVarArg() &&
1915         (!RetTy->isPointerTy() ||
1916          !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1917       TypePrinter.print(RetTy, Out);
1918       Out << ' ';
1919       writeOperand(Operand, false);
1920     } else {
1921       writeOperand(Operand, true);
1922     }
1923     Out << '(';
1924     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1925       if (op)
1926         Out << ", ";
1927       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1928     }
1929
1930     Out << ')';
1931     if (PAL.getFnAttributes() != Attribute::None)
1932       Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1933
1934     Out << "\n          to ";
1935     writeOperand(II->getNormalDest(), true);
1936     Out << " unwind ";
1937     writeOperand(II->getUnwindDest(), true);
1938
1939   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1940     Out << ' ';
1941     TypePrinter.print(AI->getType()->getElementType(), Out);
1942     if (!AI->getArraySize() || AI->isArrayAllocation()) {
1943       Out << ", ";
1944       writeOperand(AI->getArraySize(), true);
1945     }
1946     if (AI->getAlignment()) {
1947       Out << ", align " << AI->getAlignment();
1948     }
1949   } else if (isa<CastInst>(I)) {
1950     if (Operand) {
1951       Out << ' ';
1952       writeOperand(Operand, true);   // Work with broken code
1953     }
1954     Out << " to ";
1955     TypePrinter.print(I.getType(), Out);
1956   } else if (isa<VAArgInst>(I)) {
1957     if (Operand) {
1958       Out << ' ';
1959       writeOperand(Operand, true);   // Work with broken code
1960     }
1961     Out << ", ";
1962     TypePrinter.print(I.getType(), Out);
1963   } else if (Operand) {   // Print the normal way.
1964
1965     // PrintAllTypes - Instructions who have operands of all the same type
1966     // omit the type from all but the first operand.  If the instruction has
1967     // different type operands (for example br), then they are all printed.
1968     bool PrintAllTypes = false;
1969     const Type *TheType = Operand->getType();
1970
1971     // Select, Store and ShuffleVector always print all types.
1972     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1973         || isa<ReturnInst>(I)) {
1974       PrintAllTypes = true;
1975     } else {
1976       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1977         Operand = I.getOperand(i);
1978         // note that Operand shouldn't be null, but the test helps make dump()
1979         // more tolerant of malformed IR
1980         if (Operand && Operand->getType() != TheType) {
1981           PrintAllTypes = true;    // We have differing types!  Print them all!
1982           break;
1983         }
1984       }
1985     }
1986
1987     if (!PrintAllTypes) {
1988       Out << ' ';
1989       TypePrinter.print(TheType, Out);
1990     }
1991
1992     Out << ' ';
1993     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1994       if (i) Out << ", ";
1995       writeOperand(I.getOperand(i), PrintAllTypes);
1996     }
1997   }
1998
1999   // Print post operand alignment for load/store.
2000   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2001     Out << ", align " << cast<LoadInst>(I).getAlignment();
2002   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2003     Out << ", align " << cast<StoreInst>(I).getAlignment();
2004   }
2005
2006   // Print Metadata info.
2007   SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2008   I.getAllMetadata(InstMD);
2009   if (!InstMD.empty()) {
2010     SmallVector<StringRef, 8> MDNames;
2011     I.getType()->getContext().getMDKindNames(MDNames);
2012     for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2013       unsigned Kind = InstMD[i].first;
2014        if (Kind < MDNames.size()) {
2015          Out << ", !" << MDNames[Kind];
2016       } else {
2017         Out << ", !<unknown kind #" << Kind << ">";
2018       }
2019       Out << ' ';
2020       WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2021                              TheModule);
2022     }
2023   }
2024   printInfoComment(I);
2025 }
2026
2027 static void WriteMDNodeComment(const MDNode *Node,
2028                                formatted_raw_ostream &Out) {
2029   if (Node->getNumOperands() < 1)
2030     return;
2031   ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2032   if (!CI) return;
2033   APInt Val = CI->getValue();
2034   APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2035   if (Val.ult(LLVMDebugVersion))
2036     return;
2037   
2038   Out.PadToColumn(50);
2039   if (Tag == dwarf::DW_TAG_auto_variable)
2040     Out << "; [ DW_TAG_auto_variable ]";
2041   else if (Tag == dwarf::DW_TAG_arg_variable)
2042     Out << "; [ DW_TAG_arg_variable ]";
2043   else if (Tag == dwarf::DW_TAG_return_variable)
2044     Out << "; [ DW_TAG_return_variable ]";
2045   else if (Tag == dwarf::DW_TAG_vector_type)
2046     Out << "; [ DW_TAG_vector_type ]";
2047   else if (Tag == dwarf::DW_TAG_user_base)
2048     Out << "; [ DW_TAG_user_base ]";
2049   else if (Tag.isIntN(32)) {
2050     if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2051       Out << "; [ " << TagName << " ]";
2052   }
2053 }
2054
2055 void AssemblyWriter::writeAllMDNodes() {
2056   SmallVector<const MDNode *, 16> Nodes;
2057   Nodes.resize(Machine.mdn_size());
2058   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2059        I != E; ++I)
2060     Nodes[I->second] = cast<MDNode>(I->first);
2061   
2062   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2063     Out << '!' << i << " = metadata ";
2064     printMDNodeBody(Nodes[i]);
2065   }
2066 }
2067
2068 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2069   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2070   WriteMDNodeComment(Node, Out);
2071   Out << "\n";
2072 }
2073
2074 //===----------------------------------------------------------------------===//
2075 //                       External Interface declarations
2076 //===----------------------------------------------------------------------===//
2077
2078 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2079   SlotTracker SlotTable(this);
2080   formatted_raw_ostream OS(ROS);
2081   AssemblyWriter W(OS, SlotTable, this, AAW);
2082   W.printModule(this);
2083 }
2084
2085 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2086   SlotTracker SlotTable(getParent());
2087   formatted_raw_ostream OS(ROS);
2088   AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2089   W.printNamedMDNode(this);
2090 }
2091
2092 void Type::print(raw_ostream &OS) const {
2093   if (this == 0) {
2094     OS << "<null Type>";
2095     return;
2096   }
2097   TypePrinting().print(this, OS);
2098 }
2099
2100 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2101   if (this == 0) {
2102     ROS << "printing a <null> value\n";
2103     return;
2104   }
2105   formatted_raw_ostream OS(ROS);
2106   if (const Instruction *I = dyn_cast<Instruction>(this)) {
2107     const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2108     SlotTracker SlotTable(F);
2109     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2110     W.printInstruction(*I);
2111   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2112     SlotTracker SlotTable(BB->getParent());
2113     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2114     W.printBasicBlock(BB);
2115   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2116     SlotTracker SlotTable(GV->getParent());
2117     AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2118     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2119       W.printGlobal(V);
2120     else if (const Function *F = dyn_cast<Function>(GV))
2121       W.printFunction(F);
2122     else
2123       W.printAlias(cast<GlobalAlias>(GV));
2124   } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2125     const Function *F = N->getFunction();
2126     SlotTracker SlotTable(F);
2127     AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2128     W.printMDNodeBody(N);
2129   } else if (const Constant *C = dyn_cast<Constant>(this)) {
2130     TypePrinting TypePrinter;
2131     TypePrinter.print(C->getType(), OS);
2132     OS << ' ';
2133     WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2134   } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2135              isa<Argument>(this)) {
2136     WriteAsOperand(OS, this, true, 0);
2137   } else {
2138     // Otherwise we don't know what it is. Call the virtual function to
2139     // allow a subclass to print itself.
2140     printCustom(OS);
2141   }
2142 }
2143
2144 // Value::printCustom - subclasses should override this to implement printing.
2145 void Value::printCustom(raw_ostream &OS) const {
2146   llvm_unreachable("Unknown value to print out!");
2147 }
2148
2149 // Value::dump - allow easy printing of Values from the debugger.
2150 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2151
2152 // Type::dump - allow easy printing of Types from the debugger.
2153 // This one uses type names from the given context module
2154 void Type::dump(const Module *Context) const {
2155   WriteTypeSymbolic(dbgs(), this, Context);
2156   dbgs() << '\n';
2157 }
2158
2159 // Type::dump - allow easy printing of Types from the debugger.
2160 void Type::dump() const { dump(0); }
2161
2162 // Module::dump() - Allow printing of Modules from the debugger.
2163 void Module::dump() const { print(dbgs(), 0); }