random cleanups.
[oota-llvm.git] / lib / VMCore / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cctype>
37 using namespace llvm;
38
39 namespace llvm {
40
41 // Make virtual table appear in this compilation unit.
42 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
43
44 /// This class provides computation of slot numbers for LLVM Assembly writing.
45 ///
46 class SlotMachine {
47 public:
48   /// ValueMap - A mapping of Values to slot numbers
49   typedef std::map<const Value*, unsigned> ValueMap;
50   
51 private:  
52   /// TheModule - The module for which we are holding slot numbers
53   const Module* TheModule;
54   
55   /// TheFunction - The function for which we are holding slot numbers
56   const Function* TheFunction;
57   bool FunctionProcessed;
58   
59   /// mMap - The TypePlanes map for the module level data
60   ValueMap mMap;
61   unsigned mNext;
62   
63   /// fMap - The TypePlanes map for the function level data
64   ValueMap fMap;
65   unsigned fNext;
66   
67 public:
68   /// Construct from a module
69   explicit SlotMachine(const Module *M);
70   /// Construct from a function, starting out in incorp state.
71   explicit SlotMachine(const Function *F);
72
73   /// Return the slot number of the specified value in it's type
74   /// plane.  If something is not in the SlotMachine, return -1.
75   int getLocalSlot(const Value *V);
76   int getGlobalSlot(const GlobalValue *V);
77
78   /// If you'd like to deal with a function instead of just a module, use
79   /// this method to get its data into the SlotMachine.
80   void incorporateFunction(const Function *F) {
81     TheFunction = F;
82     FunctionProcessed = false;
83   }
84
85   /// After calling incorporateFunction, use this method to remove the
86   /// most recently incorporated function from the SlotMachine. This
87   /// will reset the state of the machine back to just the module contents.
88   void purgeFunction();
89
90   // Implementation Details
91 private:
92   /// This function does the actual initialization.
93   inline void initialize();
94
95   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
96   void CreateModuleSlot(const GlobalValue *V);
97   
98   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
99   void CreateFunctionSlot(const Value *V);
100
101   /// Add all of the module level global variables (and their initializers)
102   /// and function declarations, but not the contents of those functions.
103   void processModule();
104
105   /// Add all of the functions arguments, basic blocks, and instructions
106   void processFunction();
107
108   SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
109   void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
110 };
111
112 }  // end namespace llvm
113
114 char PrintModulePass::ID = 0;
115 static RegisterPass<PrintModulePass>
116 X("printm", "Print module to stderr");
117 char PrintFunctionPass::ID = 0;
118 static RegisterPass<PrintFunctionPass>
119 Y("print","Print function to stderr");
120
121 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
122                                std::map<const Type *, std::string> &TypeTable,
123                                    SlotMachine *Machine);
124
125 static const Module *getModuleFromVal(const Value *V) {
126   if (const Argument *MA = dyn_cast<Argument>(V))
127     return MA->getParent() ? MA->getParent()->getParent() : 0;
128   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
129     return BB->getParent() ? BB->getParent()->getParent() : 0;
130   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
131     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
132     return M ? M->getParent() : 0;
133   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
134     return GV->getParent();
135   return 0;
136 }
137
138 static SlotMachine *createSlotMachine(const Value *V) {
139   if (const Argument *FA = dyn_cast<Argument>(V)) {
140     return new SlotMachine(FA->getParent());
141   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
142     return new SlotMachine(I->getParent()->getParent());
143   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
144     return new SlotMachine(BB->getParent());
145   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
146     return new SlotMachine(GV->getParent());
147   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
148     return new SlotMachine(GA->getParent());    
149   } else if (const Function *Func = dyn_cast<Function>(V)) {
150     return new SlotMachine(Func);
151   }
152   return 0;
153 }
154
155 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
156 /// with ""'s.
157 static std::string QuoteNameIfNeeded(const std::string &Name) {
158   std::string result;
159   bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
160   // Scan the name to see if it needs quotes and to replace funky chars with
161   // their octal equivalent.
162   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
163     char C = Name[i];
164     assert(C != '"' && "Illegal character in LLVM value name!");
165     if (isalnum(C) || C == '-' || C == '.' || C == '_')
166       result += C;
167     else if (C == '\\')  {
168       needsQuotes = true;
169       result += "\\\\";
170     } else if (isprint(C)) {
171       needsQuotes = true;
172       result += C;
173     } else {
174       needsQuotes = true;
175       result += "\\";
176       char hex1 = (C >> 4) & 0x0F;
177       if (hex1 < 10)
178         result += hex1 + '0';
179       else 
180         result += hex1 - 10 + 'A';
181       char hex2 = C & 0x0F;
182       if (hex2 < 10)
183         result += hex2 + '0';
184       else 
185         result += hex2 - 10 + 'A';
186     }
187   }
188   if (needsQuotes) {
189     result.insert(0,"\"");
190     result += '"';
191   }
192   return result;
193 }
194
195 enum PrefixType {
196   GlobalPrefix,
197   LabelPrefix,
198   LocalPrefix
199 };
200
201 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
202 /// prefixed with % (if the string only contains simple characters) or is
203 /// surrounded with ""'s (if it has special chars in it).
204 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
205   assert(!Name.empty() && "Cannot get empty name!");
206   switch (Prefix) {
207   default: assert(0 && "Bad prefix!");
208   case GlobalPrefix: return '@' + QuoteNameIfNeeded(Name);
209   case LabelPrefix:  return QuoteNameIfNeeded(Name);
210   case LocalPrefix:  return '%' + QuoteNameIfNeeded(Name);
211   }      
212 }
213
214
215 /// fillTypeNameTable - If the module has a symbol table, take all global types
216 /// and stuff their names into the TypeNames map.
217 ///
218 static void fillTypeNameTable(const Module *M,
219                               std::map<const Type *, std::string> &TypeNames) {
220   if (!M) return;
221   const TypeSymbolTable &ST = M->getTypeSymbolTable();
222   TypeSymbolTable::const_iterator TI = ST.begin();
223   for (; TI != ST.end(); ++TI) {
224     // As a heuristic, don't insert pointer to primitive types, because
225     // they are used too often to have a single useful name.
226     //
227     const Type *Ty = cast<Type>(TI->second);
228     if (!isa<PointerType>(Ty) ||
229         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
230         !cast<PointerType>(Ty)->getElementType()->isInteger() ||
231         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
232       TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
233   }
234 }
235
236
237
238 static void calcTypeName(const Type *Ty,
239                          std::vector<const Type *> &TypeStack,
240                          std::map<const Type *, std::string> &TypeNames,
241                          std::string & Result){
242   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
243     Result += Ty->getDescription();  // Base case
244     return;
245   }
246
247   // Check to see if the type is named.
248   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
249   if (I != TypeNames.end()) {
250     Result += I->second;
251     return;
252   }
253
254   if (isa<OpaqueType>(Ty)) {
255     Result += "opaque";
256     return;
257   }
258
259   // Check to see if the Type is already on the stack...
260   unsigned Slot = 0, CurSize = TypeStack.size();
261   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
262
263   // This is another base case for the recursion.  In this case, we know
264   // that we have looped back to a type that we have previously visited.
265   // Generate the appropriate upreference to handle this.
266   if (Slot < CurSize) {
267     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
268     return;
269   }
270
271   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
272
273   switch (Ty->getTypeID()) {
274   case Type::IntegerTyID: {
275     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
276     Result += "i" + utostr(BitWidth);
277     break;
278   }
279   case Type::FunctionTyID: {
280     const FunctionType *FTy = cast<FunctionType>(Ty);
281     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
282     Result += " (";
283     for (FunctionType::param_iterator I = FTy->param_begin(),
284          E = FTy->param_end(); I != E; ++I) {
285       if (I != FTy->param_begin())
286         Result += ", ";
287       calcTypeName(*I, TypeStack, TypeNames, Result);
288     }
289     if (FTy->isVarArg()) {
290       if (FTy->getNumParams()) Result += ", ";
291       Result += "...";
292     }
293     Result += ")";
294     break;
295   }
296   case Type::StructTyID: {
297     const StructType *STy = cast<StructType>(Ty);
298     if (STy->isPacked())
299       Result += '<';
300     Result += "{ ";
301     for (StructType::element_iterator I = STy->element_begin(),
302            E = STy->element_end(); I != E; ++I) {
303       if (I != STy->element_begin())
304         Result += ", ";
305       calcTypeName(*I, TypeStack, TypeNames, Result);
306     }
307     Result += " }";
308     if (STy->isPacked())
309       Result += '>';
310     break;
311   }
312   case Type::PointerTyID: {
313     const PointerType *PTy = cast<PointerType>(Ty);
314     calcTypeName(PTy->getElementType(),
315                           TypeStack, TypeNames, Result);
316     if (unsigned AddressSpace = PTy->getAddressSpace())
317       Result += " addrspace(" + utostr(AddressSpace) + ")";
318     Result += "*";
319     break;
320   }
321   case Type::ArrayTyID: {
322     const ArrayType *ATy = cast<ArrayType>(Ty);
323     Result += "[" + utostr(ATy->getNumElements()) + " x ";
324     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
325     Result += "]";
326     break;
327   }
328   case Type::VectorTyID: {
329     const VectorType *PTy = cast<VectorType>(Ty);
330     Result += "<" + utostr(PTy->getNumElements()) + " x ";
331     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
332     Result += ">";
333     break;
334   }
335   case Type::OpaqueTyID:
336     Result += "opaque";
337     break;
338   default:
339     Result += "<unrecognized-type>";
340     break;
341   }
342
343   TypeStack.pop_back();       // Remove self from stack...
344 }
345
346
347 /// printTypeInt - The internal guts of printing out a type that has a
348 /// potentially named portion.
349 ///
350 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
351                               std::map<const Type *, std::string> &TypeNames) {
352   // Primitive types always print out their description, regardless of whether
353   // they have been named or not.
354   //
355   if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
356     return Out << Ty->getDescription();
357
358   // Check to see if the type is named.
359   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
360   if (I != TypeNames.end()) return Out << I->second;
361
362   // Otherwise we have a type that has not been named but is a derived type.
363   // Carefully recurse the type hierarchy to print out any contained symbolic
364   // names.
365   //
366   std::vector<const Type *> TypeStack;
367   std::string TypeName;
368   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
369   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
370   return (Out << TypeName);
371 }
372
373
374 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
375 /// type, iff there is an entry in the modules symbol table for the specified
376 /// type or one of it's component types. This is slower than a simple x << Type
377 ///
378 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
379                                       const Module *M) {
380   Out << ' ';
381
382   // If they want us to print out a type, but there is no context, we can't
383   // print it symbolically.
384   if (!M)
385     return Out << Ty->getDescription();
386     
387   std::map<const Type *, std::string> TypeNames;
388   fillTypeNameTable(M, TypeNames);
389   return printTypeInt(Out, Ty, TypeNames);
390 }
391
392 // PrintEscapedString - Print each character of the specified string, escaping
393 // it if it is not printable or if it is an escape char.
394 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
395   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
396     unsigned char C = Str[i];
397     if (isprint(C) && C != '"' && C != '\\') {
398       Out << C;
399     } else {
400       Out << '\\'
401           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
402           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
403     }
404   }
405 }
406
407 static const char *getPredicateText(unsigned predicate) {
408   const char * pred = "unknown";
409   switch (predicate) {
410     case FCmpInst::FCMP_FALSE: pred = "false"; break;
411     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
412     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
413     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
414     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
415     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
416     case FCmpInst::FCMP_ONE:   pred = "one"; break;
417     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
418     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
419     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
420     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
421     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
422     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
423     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
424     case FCmpInst::FCMP_UNE:   pred = "une"; break;
425     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
426     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
427     case ICmpInst::ICMP_NE:    pred = "ne"; break;
428     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
429     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
430     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
431     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
432     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
433     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
434     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
435     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
436   }
437   return pred;
438 }
439
440 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
441                              std::map<const Type *, std::string> &TypeTable,
442                              SlotMachine *Machine) {
443   const int IndentSize = 4;
444   static std::string Indent = "\n";
445   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
446     if (CI->getType() == Type::Int1Ty) 
447       Out << (CI->getZExtValue() ? "true" : "false");
448     else 
449       Out << CI->getValue().toStringSigned(10);
450   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
451     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
452         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
453       // We would like to output the FP constant value in exponential notation,
454       // but we cannot do this if doing so will lose precision.  Check here to
455       // make sure that we only output it in exponential format if we can parse
456       // the value back and get the same value.
457       //
458       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
459       double Val = (isDouble) ? CFP->getValueAPF().convertToDouble() :
460                                 CFP->getValueAPF().convertToFloat();
461       std::string StrVal = ftostr(CFP->getValueAPF());
462
463       // Check to make sure that the stringized number is not some string like
464       // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
465       // that the string matches the "[-+]?[0-9]" regex.
466       //
467       if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
468           ((StrVal[0] == '-' || StrVal[0] == '+') &&
469            (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
470         // Reparse stringized version!
471         if (atof(StrVal.c_str()) == Val) {
472           Out << StrVal;
473           return;
474         }
475       }
476       // Otherwise we could not reparse it to exactly the same value, so we must
477       // output the string in hexadecimal format!
478       assert(sizeof(double) == sizeof(uint64_t) &&
479              "assuming that double is 64 bits!");
480       Out << "0x" << utohexstr(DoubleToBits(Val));
481     } else {
482       // Some form of long double.  These appear as a magic letter identifying
483       // the type, then a fixed number of hex digits.
484       Out << "0x";
485       if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
486         Out << 'K';
487       else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
488         Out << 'L';
489       else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
490         Out << 'M';
491       else
492         assert(0 && "Unsupported floating point type");
493       // api needed to prevent premature destruction
494       APInt api = CFP->getValueAPF().convertToAPInt();
495       const uint64_t* p = api.getRawData();
496       uint64_t word = *p;
497       int shiftcount=60;
498       int width = api.getBitWidth();
499       for (int j=0; j<width; j+=4, shiftcount-=4) {
500         unsigned int nibble = (word>>shiftcount) & 15;
501         if (nibble < 10)
502           Out << (unsigned char)(nibble + '0');
503         else
504           Out << (unsigned char)(nibble - 10 + 'A');
505         if (shiftcount == 0 && j+4 < width) {
506           word = *(++p);
507           shiftcount = 64;
508           if (width-j-4 < 64)
509             shiftcount = width-j-4;
510         }
511       }
512     }
513   } else if (isa<ConstantAggregateZero>(CV)) {
514     Out << "zeroinitializer";
515   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
516     // As a special case, print the array as a string if it is an array of
517     // i8 with ConstantInt values.
518     //
519     const Type *ETy = CA->getType()->getElementType();
520     if (CA->isString()) {
521       Out << "c\"";
522       PrintEscapedString(CA->getAsString(), Out);
523       Out << "\"";
524
525     } else {                // Cannot output in string format...
526       Out << '[';
527       if (CA->getNumOperands()) {
528         Out << ' ';
529         printTypeInt(Out, ETy, TypeTable);
530         WriteAsOperandInternal(Out, CA->getOperand(0),
531                                TypeTable, Machine);
532         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
533           Out << ", ";
534           printTypeInt(Out, ETy, TypeTable);
535           WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
536         }
537       }
538       Out << " ]";
539     }
540   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
541     if (CS->getType()->isPacked())
542       Out << '<';
543     Out << '{';
544     unsigned N = CS->getNumOperands();
545     if (N) {
546       if (N > 2) {
547         Indent += std::string(IndentSize, ' ');
548         Out << Indent;
549       } else {
550         Out << ' ';
551       }
552       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
553
554       WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
555
556       for (unsigned i = 1; i < N; i++) {
557         Out << ", ";
558         if (N > 2) Out << Indent;
559         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
560
561         WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
562       }
563       if (N > 2) Indent.resize(Indent.size() - IndentSize);
564     }
565  
566     Out << " }";
567     if (CS->getType()->isPacked())
568       Out << '>';
569   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
570       const Type *ETy = CP->getType()->getElementType();
571       assert(CP->getNumOperands() > 0 &&
572              "Number of operands for a PackedConst must be > 0");
573       Out << '<';
574       Out << ' ';
575       printTypeInt(Out, ETy, TypeTable);
576       WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
577       for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
578           Out << ", ";
579           printTypeInt(Out, ETy, TypeTable);
580           WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
581       }
582       Out << " >";
583   } else if (isa<ConstantPointerNull>(CV)) {
584     Out << "null";
585
586   } else if (isa<UndefValue>(CV)) {
587     Out << "undef";
588
589   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
590     Out << CE->getOpcodeName();
591     if (CE->isCompare())
592       Out << " " << getPredicateText(CE->getPredicate());
593     Out << " (";
594
595     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
596       printTypeInt(Out, (*OI)->getType(), TypeTable);
597       WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
598       if (OI+1 != CE->op_end())
599         Out << ", ";
600     }
601
602     if (CE->hasIndices()) {
603       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
604       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
605         Out << ", " << Indices[i];
606     }
607
608     if (CE->isCast()) {
609       Out << " to ";
610       printTypeInt(Out, CE->getType(), TypeTable);
611     }
612
613     Out << ')';
614
615   } else {
616     Out << "<placeholder or erroneous Constant>";
617   }
618 }
619
620
621 /// WriteAsOperand - Write the name of the specified value out to the specified
622 /// ostream.  This can be useful when you just want to print int %reg126, not
623 /// the whole instruction that generated it.
624 ///
625 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
626                                   std::map<const Type*, std::string> &TypeTable,
627                                    SlotMachine *Machine) {
628   Out << ' ';
629   if (V->hasName())
630     Out << getLLVMName(V->getName(),
631                        isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
632   else {
633     const Constant *CV = dyn_cast<Constant>(V);
634     if (CV && !isa<GlobalValue>(CV)) {
635       WriteConstantInt(Out, CV, TypeTable, Machine);
636     } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
637       Out << "asm ";
638       if (IA->hasSideEffects())
639         Out << "sideeffect ";
640       Out << '"';
641       PrintEscapedString(IA->getAsmString(), Out);
642       Out << "\", \"";
643       PrintEscapedString(IA->getConstraintString(), Out);
644       Out << '"';
645     } else {
646       char Prefix = '%';
647       int Slot;
648       if (Machine) {
649         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
650           Slot = Machine->getGlobalSlot(GV);
651           Prefix = '@';
652         } else {
653           Slot = Machine->getLocalSlot(V);
654         }
655       } else {
656         Machine = createSlotMachine(V);
657         if (Machine) {
658           if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
659             Slot = Machine->getGlobalSlot(GV);
660             Prefix = '@';
661           } else {
662             Slot = Machine->getLocalSlot(V);
663           }
664         } else {
665           Slot = -1;
666         }
667         delete Machine;
668       }
669       if (Slot != -1)
670         Out << Prefix << Slot;
671       else
672         Out << "<badref>";
673     }
674   }
675 }
676
677 /// WriteAsOperand - Write the name of the specified value out to the specified
678 /// ostream.  This can be useful when you just want to print int %reg126, not
679 /// the whole instruction that generated it.
680 ///
681 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
682                                    bool PrintType, const Module *Context) {
683   std::map<const Type *, std::string> TypeNames;
684   if (Context == 0) Context = getModuleFromVal(V);
685
686   if (Context)
687     fillTypeNameTable(Context, TypeNames);
688
689   if (PrintType)
690     printTypeInt(Out, V->getType(), TypeNames);
691
692   WriteAsOperandInternal(Out, V, TypeNames, 0);
693   return Out;
694 }
695
696
697 namespace llvm {
698
699 class AssemblyWriter {
700   std::ostream &Out;
701   SlotMachine &Machine;
702   const Module *TheModule;
703   std::map<const Type *, std::string> TypeNames;
704   AssemblyAnnotationWriter *AnnotationWriter;
705 public:
706   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
707                         AssemblyAnnotationWriter *AAW)
708     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
709
710     // If the module has a symbol table, take all global types and stuff their
711     // names into the TypeNames map.
712     //
713     fillTypeNameTable(M, TypeNames);
714   }
715
716   inline void write(const Module *M)         { printModule(M);       }
717   inline void write(const GlobalVariable *G) { printGlobal(G);       }
718   inline void write(const GlobalAlias *G)    { printAlias(G);        }
719   inline void write(const Function *F)       { printFunction(F);     }
720   inline void write(const BasicBlock *BB)    { printBasicBlock(BB);  }
721   inline void write(const Instruction *I)    { printInstruction(*I); }
722   inline void write(const Type *Ty)          { printType(Ty);        }
723
724   void writeOperand(const Value *Op, bool PrintType);
725   void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
726
727   const Module* getModule() { return TheModule; }
728
729 private:
730   void printModule(const Module *M);
731   void printTypeSymbolTable(const TypeSymbolTable &ST);
732   void printGlobal(const GlobalVariable *GV);
733   void printAlias(const GlobalAlias *GV);
734   void printFunction(const Function *F);
735   void printArgument(const Argument *FA, ParameterAttributes Attrs);
736   void printBasicBlock(const BasicBlock *BB);
737   void printInstruction(const Instruction &I);
738
739   // printType - Go to extreme measures to attempt to print out a short,
740   // symbolic version of a type name.
741   //
742   std::ostream &printType(const Type *Ty) {
743     return printTypeInt(Out, Ty, TypeNames);
744   }
745
746   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
747   // without considering any symbolic types that we may have equal to it.
748   //
749   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
750
751   // printInfoComment - Print a little comment after the instruction indicating
752   // which slot it occupies.
753   void printInfoComment(const Value &V);
754 };
755 }  // end of llvm namespace
756
757 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
758 /// without considering any symbolic types that we may have equal to it.
759 ///
760 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
761   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
762     Out << "i" << utostr(ITy->getBitWidth());
763   else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
764     printType(FTy->getReturnType());
765     Out << " (";
766     for (FunctionType::param_iterator I = FTy->param_begin(),
767            E = FTy->param_end(); I != E; ++I) {
768       if (I != FTy->param_begin())
769         Out << ", ";
770       printType(*I);
771     }
772     if (FTy->isVarArg()) {
773       if (FTy->getNumParams()) Out << ", ";
774       Out << "...";
775     }
776     Out << ')';
777   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
778     if (STy->isPacked())
779       Out << '<';
780     Out << "{ ";
781     for (StructType::element_iterator I = STy->element_begin(),
782            E = STy->element_end(); I != E; ++I) {
783       if (I != STy->element_begin())
784         Out << ", ";
785       printType(*I);
786     }
787     Out << " }";
788     if (STy->isPacked())
789       Out << '>';
790   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
791     printType(PTy->getElementType());
792     if (unsigned AddressSpace = PTy->getAddressSpace())
793       Out << " addrspace(" << AddressSpace << ")";
794     Out << '*';
795   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
796     Out << '[' << ATy->getNumElements() << " x ";
797     printType(ATy->getElementType()) << ']';
798   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
799     Out << '<' << PTy->getNumElements() << " x ";
800     printType(PTy->getElementType()) << '>';
801   }
802   else if (isa<OpaqueType>(Ty)) {
803     Out << "opaque";
804   } else {
805     if (!Ty->isPrimitiveType())
806       Out << "<unknown derived type>";
807     printType(Ty);
808   }
809   return Out;
810 }
811
812
813 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
814   if (Operand == 0) {
815     Out << "<null operand!>";
816   } else {
817     if (PrintType) { Out << ' '; printType(Operand->getType()); }
818     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
819   }
820 }
821
822 void AssemblyWriter::writeParamOperand(const Value *Operand, 
823                                        ParameterAttributes Attrs) {
824   if (Operand == 0) {
825     Out << "<null operand!>";
826   } else {
827     Out << ' ';
828     // Print the type
829     printType(Operand->getType());
830     // Print parameter attributes list
831     if (Attrs != ParamAttr::None)
832       Out << ' ' << ParamAttr::getAsString(Attrs);
833     // Print the operand
834     WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
835   }
836 }
837
838 void AssemblyWriter::printModule(const Module *M) {
839   if (!M->getModuleIdentifier().empty() &&
840       // Don't print the ID if it will start a new line (which would
841       // require a comment char before it).
842       M->getModuleIdentifier().find('\n') == std::string::npos)
843     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
844
845   if (!M->getDataLayout().empty())
846     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
847   if (!M->getTargetTriple().empty())
848     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
849
850   if (!M->getModuleInlineAsm().empty()) {
851     // Split the string into lines, to make it easier to read the .ll file.
852     std::string Asm = M->getModuleInlineAsm();
853     size_t CurPos = 0;
854     size_t NewLine = Asm.find_first_of('\n', CurPos);
855     while (NewLine != std::string::npos) {
856       // We found a newline, print the portion of the asm string from the
857       // last newline up to this newline.
858       Out << "module asm \"";
859       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
860                          Out);
861       Out << "\"\n";
862       CurPos = NewLine+1;
863       NewLine = Asm.find_first_of('\n', CurPos);
864     }
865     Out << "module asm \"";
866     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
867     Out << "\"\n";
868   }
869   
870   // Loop over the dependent libraries and emit them.
871   Module::lib_iterator LI = M->lib_begin();
872   Module::lib_iterator LE = M->lib_end();
873   if (LI != LE) {
874     Out << "deplibs = [ ";
875     while (LI != LE) {
876       Out << '"' << *LI << '"';
877       ++LI;
878       if (LI != LE)
879         Out << ", ";
880     }
881     Out << " ]\n";
882   }
883
884   // Loop over the symbol table, emitting all named constants.
885   printTypeSymbolTable(M->getTypeSymbolTable());
886
887   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
888        I != E; ++I)
889     printGlobal(I);
890   
891   // Output all aliases.
892   if (!M->alias_empty()) Out << "\n";
893   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
894        I != E; ++I)
895     printAlias(I);
896
897   // Output all of the functions.
898   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
899     printFunction(I);
900 }
901
902 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
903   if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
904
905   if (!GV->hasInitializer()) {
906     switch (GV->getLinkage()) {
907      case GlobalValue::DLLImportLinkage:   Out << "dllimport "; break;
908      case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
909      default: Out << "external "; break;
910     }
911   } else {
912     switch (GV->getLinkage()) {
913     case GlobalValue::InternalLinkage:     Out << "internal "; break;
914     case GlobalValue::CommonLinkage:       Out << "common "; break;
915     case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
916     case GlobalValue::WeakLinkage:         Out << "weak "; break;
917     case GlobalValue::AppendingLinkage:    Out << "appending "; break;
918     case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
919     case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;     
920     case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
921     case GlobalValue::ExternalLinkage:     break;
922     case GlobalValue::GhostLinkage:
923       cerr << "GhostLinkage not allowed in AsmWriter!\n";
924       abort();
925     }
926     switch (GV->getVisibility()) {
927     default: assert(0 && "Invalid visibility style!");
928     case GlobalValue::DefaultVisibility: break;
929     case GlobalValue::HiddenVisibility: Out << "hidden "; break;
930     case GlobalValue::ProtectedVisibility: Out << "protected "; break;
931     }
932   }
933
934   if (GV->isThreadLocal()) Out << "thread_local ";
935   Out << (GV->isConstant() ? "constant " : "global ");
936   printType(GV->getType()->getElementType());
937
938   if (GV->hasInitializer()) {
939     Constant* C = cast<Constant>(GV->getInitializer());
940     assert(C &&  "GlobalVar initializer isn't constant?");
941     writeOperand(GV->getInitializer(), false);
942   }
943
944   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
945     Out << " addrspace(" << AddressSpace << ") ";
946     
947   if (GV->hasSection())
948     Out << ", section \"" << GV->getSection() << '"';
949   if (GV->getAlignment())
950     Out << ", align " << GV->getAlignment();
951
952   printInfoComment(*GV);
953   Out << "\n";
954 }
955
956 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
957   // Don't crash when dumping partially built GA
958   if (!GA->hasName())
959     Out << "<<nameless>> = ";
960   else
961     Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
962   switch (GA->getVisibility()) {
963   default: assert(0 && "Invalid visibility style!");
964   case GlobalValue::DefaultVisibility: break;
965   case GlobalValue::HiddenVisibility: Out << "hidden "; break;
966   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
967   }
968
969   Out << "alias ";
970
971   switch (GA->getLinkage()) {
972   case GlobalValue::WeakLinkage: Out << "weak "; break;
973   case GlobalValue::InternalLinkage: Out << "internal "; break;
974   case GlobalValue::ExternalLinkage: break;
975   default:
976    assert(0 && "Invalid alias linkage");
977   }
978   
979   const Constant *Aliasee = GA->getAliasee();
980     
981   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
982     printType(GV->getType());
983     Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
984   } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
985     printType(F->getFunctionType());
986     Out << "* ";
987
988     if (!F->getName().empty())
989       Out << getLLVMName(F->getName(), GlobalPrefix);
990     else
991       Out << "@\"\"";
992   } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
993     printType(GA->getType());
994     Out << " " << getLLVMName(GA->getName(), GlobalPrefix);
995   } else {
996     const ConstantExpr *CE = 0;
997     if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
998         (CE->getOpcode() == Instruction::BitCast)) {
999       writeOperand(CE, false);    
1000     } else
1001       assert(0 && "Unsupported aliasee");
1002   }
1003   
1004   printInfoComment(*GA);
1005   Out << "\n";
1006 }
1007
1008 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1009   // Print the types.
1010   for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1011        TI != TE; ++TI) {
1012     Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
1013
1014     // Make sure we print out at least one level of the type structure, so
1015     // that we do not get %FILE = type %FILE
1016     //
1017     printTypeAtLeastOneLevel(TI->second) << "\n";
1018   }
1019 }
1020
1021 /// printFunction - Print all aspects of a function.
1022 ///
1023 void AssemblyWriter::printFunction(const Function *F) {
1024   // Print out the return type and name...
1025   Out << "\n";
1026
1027   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1028
1029   if (F->isDeclaration())
1030     Out << "declare ";
1031   else
1032     Out << "define ";
1033     
1034   switch (F->getLinkage()) {
1035   case GlobalValue::InternalLinkage:     Out << "internal "; break;
1036   case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
1037   case GlobalValue::WeakLinkage:         Out << "weak "; break;
1038   case GlobalValue::CommonLinkage:       Out << "common "; break;
1039   case GlobalValue::AppendingLinkage:    Out << "appending "; break;
1040   case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
1041   case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;
1042   case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;      
1043   case GlobalValue::ExternalLinkage: break;
1044   case GlobalValue::GhostLinkage:
1045     cerr << "GhostLinkage not allowed in AsmWriter!\n";
1046     abort();
1047   }
1048   switch (F->getVisibility()) {
1049   default: assert(0 && "Invalid visibility style!");
1050   case GlobalValue::DefaultVisibility: break;
1051   case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1052   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1053   }
1054
1055   // Print the calling convention.
1056   switch (F->getCallingConv()) {
1057   case CallingConv::C: break;   // default
1058   case CallingConv::Fast:         Out << "fastcc "; break;
1059   case CallingConv::Cold:         Out << "coldcc "; break;
1060   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1061   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1062   case CallingConv::X86_SSECall:  Out << "x86_ssecallcc "; break;
1063   default: Out << "cc" << F->getCallingConv() << " "; break;
1064   }
1065
1066   const FunctionType *FT = F->getFunctionType();
1067   const PAListPtr &Attrs = F->getParamAttrs();
1068   printType(F->getReturnType()) << ' ';
1069   if (!F->getName().empty())
1070     Out << getLLVMName(F->getName(), GlobalPrefix);
1071   else
1072     Out << "@\"\"";
1073   Out << '(';
1074   Machine.incorporateFunction(F);
1075
1076   // Loop over the arguments, printing them...
1077
1078   unsigned Idx = 1;
1079   if (!F->isDeclaration()) {
1080     // If this isn't a declaration, print the argument names as well.
1081     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1082          I != E; ++I) {
1083       // Insert commas as we go... the first arg doesn't get a comma
1084       if (I != F->arg_begin()) Out << ", ";
1085       printArgument(I, Attrs.getParamAttrs(Idx));
1086       Idx++;
1087     }
1088   } else {
1089     // Otherwise, print the types from the function type.
1090     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1091       // Insert commas as we go... the first arg doesn't get a comma
1092       if (i) Out << ", ";
1093       
1094       // Output type...
1095       printType(FT->getParamType(i));
1096       
1097       ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1098       if (ArgAttrs != ParamAttr::None)
1099         Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1100     }
1101   }
1102
1103   // Finish printing arguments...
1104   if (FT->isVarArg()) {
1105     if (FT->getNumParams()) Out << ", ";
1106     Out << "...";  // Output varargs portion of signature!
1107   }
1108   Out << ')';
1109   ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1110   if (RetAttrs != ParamAttr::None)
1111     Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1112   if (F->hasSection())
1113     Out << " section \"" << F->getSection() << '"';
1114   if (F->getAlignment())
1115     Out << " align " << F->getAlignment();
1116   if (F->hasCollector())
1117     Out << " gc \"" << F->getCollector() << '"';
1118
1119   if (F->isDeclaration()) {
1120     Out << "\n";
1121   } else {
1122     Out << " {";
1123
1124     // Output all of its basic blocks... for the function
1125     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1126       printBasicBlock(I);
1127
1128     Out << "}\n";
1129   }
1130
1131   Machine.purgeFunction();
1132 }
1133
1134 /// printArgument - This member is called for every argument that is passed into
1135 /// the function.  Simply print it out
1136 ///
1137 void AssemblyWriter::printArgument(const Argument *Arg, 
1138                                    ParameterAttributes Attrs) {
1139   // Output type...
1140   printType(Arg->getType());
1141
1142   // Output parameter attributes list
1143   if (Attrs != ParamAttr::None)
1144     Out << ' ' << ParamAttr::getAsString(Attrs);
1145
1146   // Output name, if available...
1147   if (Arg->hasName())
1148     Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1149 }
1150
1151 /// printBasicBlock - This member is called for each basic block in a method.
1152 ///
1153 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1154   if (BB->hasName()) {              // Print out the label if it exists...
1155     Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1156   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
1157     Out << "\n; <label>:";
1158     int Slot = Machine.getLocalSlot(BB);
1159     if (Slot != -1)
1160       Out << Slot;
1161     else
1162       Out << "<badref>";
1163   }
1164
1165   if (BB->getParent() == 0)
1166     Out << "\t\t; Error: Block without parent!";
1167   else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
1168     // Output predecessors for the block...
1169     Out << "\t\t;";
1170     pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1171     
1172     if (PI == PE) {
1173       Out << " No predecessors!";
1174     } else {
1175       Out << " preds =";
1176       writeOperand(*PI, false);
1177       for (++PI; PI != PE; ++PI) {
1178         Out << ',';
1179         writeOperand(*PI, false);
1180       }
1181     }
1182   }
1183
1184   Out << "\n";
1185
1186   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1187
1188   // Output all of the instructions in the basic block...
1189   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1190     printInstruction(*I);
1191
1192   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1193 }
1194
1195
1196 /// printInfoComment - Print a little comment after the instruction indicating
1197 /// which slot it occupies.
1198 ///
1199 void AssemblyWriter::printInfoComment(const Value &V) {
1200   if (V.getType() != Type::VoidTy) {
1201     Out << "\t\t; <";
1202     printType(V.getType()) << '>';
1203
1204     if (!V.hasName()) {
1205       int SlotNum;
1206       if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1207         SlotNum = Machine.getGlobalSlot(GV);
1208       else
1209         SlotNum = Machine.getLocalSlot(&V);
1210       if (SlotNum == -1)
1211         Out << ":<badref>";
1212       else
1213         Out << ':' << SlotNum; // Print out the def slot taken.
1214     }
1215     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1216   }
1217 }
1218
1219 // This member is called for each Instruction in a function..
1220 void AssemblyWriter::printInstruction(const Instruction &I) {
1221   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1222
1223   Out << "\t";
1224
1225   // Print out name if it exists...
1226   if (I.hasName())
1227     Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1228
1229   // If this is a volatile load or store, print out the volatile marker.
1230   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1231       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1232       Out << "volatile ";
1233   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1234     // If this is a call, check if it's a tail call.
1235     Out << "tail ";
1236   }
1237
1238   // Print out the opcode...
1239   Out << I.getOpcodeName();
1240
1241   // Print out the compare instruction predicates
1242   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1243     Out << " " << getPredicateText(CI->getPredicate());
1244
1245   // Print out the type of the operands...
1246   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1247
1248   // Special case conditional branches to swizzle the condition out to the front
1249   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1250     writeOperand(I.getOperand(2), true);
1251     Out << ',';
1252     writeOperand(Operand, true);
1253     Out << ',';
1254     writeOperand(I.getOperand(1), true);
1255
1256   } else if (isa<SwitchInst>(I)) {
1257     // Special case switch statement to get formatting nice and correct...
1258     writeOperand(Operand        , true); Out << ',';
1259     writeOperand(I.getOperand(1), true); Out << " [";
1260
1261     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1262       Out << "\n\t\t";
1263       writeOperand(I.getOperand(op  ), true); Out << ',';
1264       writeOperand(I.getOperand(op+1), true);
1265     }
1266     Out << "\n\t]";
1267   } else if (isa<PHINode>(I)) {
1268     Out << ' ';
1269     printType(I.getType());
1270     Out << ' ';
1271
1272     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1273       if (op) Out << ", ";
1274       Out << '[';
1275       writeOperand(I.getOperand(op  ), false); Out << ',';
1276       writeOperand(I.getOperand(op+1), false); Out << " ]";
1277     }
1278   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1279     writeOperand(I.getOperand(0), true);
1280     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1281       Out << ", " << *i;
1282   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1283     writeOperand(I.getOperand(0), true); Out << ',';
1284     writeOperand(I.getOperand(1), true);
1285     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1286       Out << ", " << *i;
1287   } else if (isa<ReturnInst>(I) && !Operand) {
1288     Out << " void";
1289   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1290     // Print the calling convention being used.
1291     switch (CI->getCallingConv()) {
1292     case CallingConv::C: break;   // default
1293     case CallingConv::Fast:  Out << " fastcc"; break;
1294     case CallingConv::Cold:  Out << " coldcc"; break;
1295     case CallingConv::X86_StdCall:  Out << " x86_stdcallcc"; break;
1296     case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break; 
1297     case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break; 
1298     default: Out << " cc" << CI->getCallingConv(); break;
1299     }
1300
1301     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1302     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1303     const Type         *RetTy = FTy->getReturnType();
1304     const PAListPtr &PAL = CI->getParamAttrs();
1305
1306     // If possible, print out the short form of the call instruction.  We can
1307     // only do this if the first argument is a pointer to a nonvararg function,
1308     // and if the return type is not a pointer to a function.
1309     //
1310     if (!FTy->isVarArg() &&
1311         (!isa<PointerType>(RetTy) ||
1312          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1313       Out << ' '; printType(RetTy);
1314       writeOperand(Operand, false);
1315     } else {
1316       writeOperand(Operand, true);
1317     }
1318     Out << '(';
1319     for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1320       if (op > 1)
1321         Out << ',';
1322       writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1323     }
1324     Out << " )";
1325     if (PAL.getParamAttrs(0) != ParamAttr::None)
1326       Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1327   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1328     const PointerType    *PTy = cast<PointerType>(Operand->getType());
1329     const FunctionType   *FTy = cast<FunctionType>(PTy->getElementType());
1330     const Type         *RetTy = FTy->getReturnType();
1331     const PAListPtr &PAL = II->getParamAttrs();
1332
1333     // Print the calling convention being used.
1334     switch (II->getCallingConv()) {
1335     case CallingConv::C: break;   // default
1336     case CallingConv::Fast:  Out << " fastcc"; break;
1337     case CallingConv::Cold:  Out << " coldcc"; break;
1338     case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1339     case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1340     case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1341     default: Out << " cc" << II->getCallingConv(); break;
1342     }
1343
1344     // If possible, print out the short form of the invoke instruction. We can
1345     // only do this if the first argument is a pointer to a nonvararg function,
1346     // and if the return type is not a pointer to a function.
1347     //
1348     if (!FTy->isVarArg() &&
1349         (!isa<PointerType>(RetTy) ||
1350          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1351       Out << ' '; printType(RetTy);
1352       writeOperand(Operand, false);
1353     } else {
1354       writeOperand(Operand, true);
1355     }
1356
1357     Out << '(';
1358     for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1359       if (op > 3)
1360         Out << ',';
1361       writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1362     }
1363
1364     Out << " )";
1365     if (PAL.getParamAttrs(0) != ParamAttr::None)
1366       Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1367     Out << "\n\t\t\tto";
1368     writeOperand(II->getNormalDest(), true);
1369     Out << " unwind";
1370     writeOperand(II->getUnwindDest(), true);
1371
1372   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1373     Out << ' ';
1374     printType(AI->getType()->getElementType());
1375     if (AI->isArrayAllocation()) {
1376       Out << ',';
1377       writeOperand(AI->getArraySize(), true);
1378     }
1379     if (AI->getAlignment()) {
1380       Out << ", align " << AI->getAlignment();
1381     }
1382   } else if (isa<CastInst>(I)) {
1383     if (Operand) writeOperand(Operand, true);   // Work with broken code
1384     Out << " to ";
1385     printType(I.getType());
1386   } else if (isa<VAArgInst>(I)) {
1387     if (Operand) writeOperand(Operand, true);   // Work with broken code
1388     Out << ", ";
1389     printType(I.getType());
1390   } else if (Operand) {   // Print the normal way...
1391
1392     // PrintAllTypes - Instructions who have operands of all the same type
1393     // omit the type from all but the first operand.  If the instruction has
1394     // different type operands (for example br), then they are all printed.
1395     bool PrintAllTypes = false;
1396     const Type *TheType = Operand->getType();
1397
1398     // Select, Store and ShuffleVector always print all types.
1399     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1400         || isa<ReturnInst>(I)) {
1401       PrintAllTypes = true;
1402     } else {
1403       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1404         Operand = I.getOperand(i);
1405         if (Operand->getType() != TheType) {
1406           PrintAllTypes = true;    // We have differing types!  Print them all!
1407           break;
1408         }
1409       }
1410     }
1411
1412     if (!PrintAllTypes) {
1413       Out << ' ';
1414       printType(TheType);
1415     }
1416
1417     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1418       if (i) Out << ',';
1419       writeOperand(I.getOperand(i), PrintAllTypes);
1420     }
1421   }
1422   
1423   // Print post operand alignment for load/store
1424   if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1425     Out << ", align " << cast<LoadInst>(I).getAlignment();
1426   } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1427     Out << ", align " << cast<StoreInst>(I).getAlignment();
1428   }
1429
1430   printInfoComment(I);
1431   Out << "\n";
1432 }
1433
1434
1435 //===----------------------------------------------------------------------===//
1436 //                       External Interface declarations
1437 //===----------------------------------------------------------------------===//
1438
1439 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1440   SlotMachine SlotTable(this);
1441   AssemblyWriter W(o, SlotTable, this, AAW);
1442   W.write(this);
1443 }
1444
1445 void GlobalVariable::print(std::ostream &o) const {
1446   SlotMachine SlotTable(getParent());
1447   AssemblyWriter W(o, SlotTable, getParent(), 0);
1448   W.write(this);
1449 }
1450
1451 void GlobalAlias::print(std::ostream &o) const {
1452   SlotMachine SlotTable(getParent());
1453   AssemblyWriter W(o, SlotTable, getParent(), 0);
1454   W.write(this);
1455 }
1456
1457 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1458   SlotMachine SlotTable(getParent());
1459   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1460
1461   W.write(this);
1462 }
1463
1464 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1465   WriteAsOperand(o, this, true, 0);
1466 }
1467
1468 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1469   SlotMachine SlotTable(getParent());
1470   AssemblyWriter W(o, SlotTable,
1471                    getParent() ? getParent()->getParent() : 0, AAW);
1472   W.write(this);
1473 }
1474
1475 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1476   const Function *F = getParent() ? getParent()->getParent() : 0;
1477   SlotMachine SlotTable(F);
1478   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1479
1480   W.write(this);
1481 }
1482
1483 void Constant::print(std::ostream &o) const {
1484   if (this == 0) { o << "<null> constant value\n"; return; }
1485
1486   o << ' ' << getType()->getDescription() << ' ';
1487
1488   std::map<const Type *, std::string> TypeTable;
1489   WriteConstantInt(o, this, TypeTable, 0);
1490 }
1491
1492 void Type::print(std::ostream &o) const {
1493   if (this == 0)
1494     o << "<null Type>";
1495   else
1496     o << getDescription();
1497 }
1498
1499 void Argument::print(std::ostream &o) const {
1500   WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1501 }
1502
1503 // Value::dump - allow easy printing of  Values from the debugger.
1504 // Located here because so much of the needed functionality is here.
1505 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1506
1507 // Type::dump - allow easy printing of  Values from the debugger.
1508 // Located here because so much of the needed functionality is here.
1509 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1510
1511 //===----------------------------------------------------------------------===//
1512 //                         SlotMachine Implementation
1513 //===----------------------------------------------------------------------===//
1514
1515 #if 0
1516 #define SC_DEBUG(X) cerr << X
1517 #else
1518 #define SC_DEBUG(X)
1519 #endif
1520
1521 // Module level constructor. Causes the contents of the Module (sans functions)
1522 // to be added to the slot table.
1523 SlotMachine::SlotMachine(const Module *M)
1524   : TheModule(M)    ///< Saved for lazy initialization.
1525   , TheFunction(0)
1526   , FunctionProcessed(false)
1527   , mNext(0), fMap(), fNext(0)
1528 {
1529 }
1530
1531 // Function level constructor. Causes the contents of the Module and the one
1532 // function provided to be added to the slot table.
1533 SlotMachine::SlotMachine(const Function *F)
1534   : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1535   , TheFunction(F) ///< Saved for lazy initialization
1536   , FunctionProcessed(false)
1537   , mNext(0), fMap(), fNext(0)
1538 {
1539 }
1540
1541 inline void SlotMachine::initialize() {
1542   if (TheModule) {
1543     processModule();
1544     TheModule = 0; ///< Prevent re-processing next time we're called.
1545   }
1546   if (TheFunction && !FunctionProcessed)
1547     processFunction();
1548 }
1549
1550 // Iterate through all the global variables, functions, and global
1551 // variable initializers and create slots for them.
1552 void SlotMachine::processModule() {
1553   SC_DEBUG("begin processModule!\n");
1554
1555   // Add all of the unnamed global variables to the value table.
1556   for (Module::const_global_iterator I = TheModule->global_begin(),
1557        E = TheModule->global_end(); I != E; ++I)
1558     if (!I->hasName()) 
1559       CreateModuleSlot(I);
1560
1561   // Add all the unnamed functions to the table.
1562   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1563        I != E; ++I)
1564     if (!I->hasName())
1565       CreateModuleSlot(I);
1566
1567   SC_DEBUG("end processModule!\n");
1568 }
1569
1570
1571 // Process the arguments, basic blocks, and instructions  of a function.
1572 void SlotMachine::processFunction() {
1573   SC_DEBUG("begin processFunction!\n");
1574   fNext = 0;
1575
1576   // Add all the function arguments with no names.
1577   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1578       AE = TheFunction->arg_end(); AI != AE; ++AI)
1579     if (!AI->hasName())
1580       CreateFunctionSlot(AI);
1581
1582   SC_DEBUG("Inserting Instructions:\n");
1583
1584   // Add all of the basic blocks and instructions with no names.
1585   for (Function::const_iterator BB = TheFunction->begin(),
1586        E = TheFunction->end(); BB != E; ++BB) {
1587     if (!BB->hasName())
1588       CreateFunctionSlot(BB);
1589     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1590       if (I->getType() != Type::VoidTy && !I->hasName())
1591         CreateFunctionSlot(I);
1592   }
1593
1594   FunctionProcessed = true;
1595
1596   SC_DEBUG("end processFunction!\n");
1597 }
1598
1599 /// Clean up after incorporating a function. This is the only way to get out of
1600 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1601 /// incorporation state is indicated by TheFunction != 0.
1602 void SlotMachine::purgeFunction() {
1603   SC_DEBUG("begin purgeFunction!\n");
1604   fMap.clear(); // Simply discard the function level map
1605   TheFunction = 0;
1606   FunctionProcessed = false;
1607   SC_DEBUG("end purgeFunction!\n");
1608 }
1609
1610 /// getGlobalSlot - Get the slot number of a global value.
1611 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1612   // Check for uninitialized state and do lazy initialization.
1613   initialize();
1614   
1615   // Find the type plane in the module map
1616   ValueMap::const_iterator MI = mMap.find(V);
1617   if (MI == mMap.end()) return -1;
1618
1619   return MI->second;
1620 }
1621
1622
1623 /// getLocalSlot - Get the slot number for a value that is local to a function.
1624 int SlotMachine::getLocalSlot(const Value *V) {
1625   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1626
1627   // Check for uninitialized state and do lazy initialization.
1628   initialize();
1629
1630   ValueMap::const_iterator FI = fMap.find(V);
1631   if (FI == fMap.end()) return -1;
1632   
1633   return FI->second;
1634 }
1635
1636
1637 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1638 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1639   assert(V && "Can't insert a null Value into SlotMachine!");
1640   assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1641   assert(!V->hasName() && "Doesn't need a slot!");
1642   
1643   unsigned DestSlot = mNext++;
1644   mMap[V] = DestSlot;
1645   
1646   SC_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1647            DestSlot << " [");
1648   // G = Global, F = Function, A = Alias, o = other
1649   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1650             (isa<Function>(V) ? 'F' :
1651              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
1652 }
1653
1654
1655 /// CreateSlot - Create a new slot for the specified value if it has no name.
1656 void SlotMachine::CreateFunctionSlot(const Value *V) {
1657   const Type *VTy = V->getType();
1658   assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1659   
1660   unsigned DestSlot = fNext++;
1661   fMap[V] = DestSlot;
1662   
1663   // G = Global, F = Function, o = other
1664   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" <<
1665            DestSlot << " [o]\n");
1666 }