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