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