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