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