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