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