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