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