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