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