remove dead code left over from when this functionality was shared with the
[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 getOrCreateSlot(const Value *V);
122
123   /// Insert a value into the value table. Return the slot number
124   /// that it now occupies.  BadThings(TM) will happen if you insert a
125   /// Value that's already been inserted.
126   unsigned insertValue(const Value *V);
127
128   /// Add all of the module level global variables (and their initializers)
129   /// and function declarations, but not the contents of those functions.
130   void processModule();
131
132   /// Add all of the functions arguments, basic blocks, and instructions
133   void processFunction();
134
135   SlotMachine(const SlotMachine &);  // DO NOT IMPLEMENT
136   void operator=(const SlotMachine &);  // DO NOT IMPLEMENT
137
138 /// @}
139 /// @name Data
140 /// @{
141 public:
142
143   /// @brief The module for which we are holding slot numbers
144   const Module* TheModule;
145
146   /// @brief The function for which we are holding slot numbers
147   const Function* TheFunction;
148   bool FunctionProcessed;
149
150   /// @brief The TypePlanes map for the module level data
151   TypedPlanes mMap;
152   TypePlane mTypes;
153
154   /// @brief The TypePlanes map for the function level data
155   TypedPlanes fMap;
156   TypePlane fTypes;
157
158 /// @}
159
160 };
161
162 }  // end namespace llvm
163
164 static RegisterPass<PrintModulePass>
165 X("printm", "Print module to stderr");
166 static RegisterPass<PrintFunctionPass>
167 Y("print","Print function to stderr");
168
169 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
170                                    bool PrintName,
171                                  std::map<const Type *, std::string> &TypeTable,
172                                    SlotMachine *Machine);
173
174 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
175                                    bool PrintName,
176                                  std::map<const Type *, std::string> &TypeTable,
177                                    SlotMachine *Machine);
178
179 static const Module *getModuleFromVal(const Value *V) {
180   if (const Argument *MA = dyn_cast<Argument>(V))
181     return MA->getParent() ? MA->getParent()->getParent() : 0;
182   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
183     return BB->getParent() ? BB->getParent()->getParent() : 0;
184   else if (const Instruction *I = dyn_cast<Instruction>(V)) {
185     const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
186     return M ? M->getParent() : 0;
187   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
188     return GV->getParent();
189   return 0;
190 }
191
192 static SlotMachine *createSlotMachine(const Value *V) {
193   if (const Argument *FA = dyn_cast<Argument>(V)) {
194     return new SlotMachine(FA->getParent());
195   } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
196     return new SlotMachine(I->getParent()->getParent());
197   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
198     return new SlotMachine(BB->getParent());
199   } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
200     return new SlotMachine(GV->getParent());
201   } else if (const Function *Func = dyn_cast<Function>(V)) {
202     return new SlotMachine(Func);
203   }
204   return 0;
205 }
206
207 // getLLVMName - Turn the specified string into an 'LLVM name', which is either
208 // prefixed with % (if the string only contains simple characters) or is
209 // surrounded with ""'s (if it has special chars in it).
210 static std::string getLLVMName(const std::string &Name,
211                                bool prefixName = true) {
212   assert(!Name.empty() && "Cannot get empty name!");
213
214   // First character cannot start with a number...
215   if (Name[0] >= '0' && Name[0] <= '9')
216     return "\"" + Name + "\"";
217
218   // Scan to see if we have any characters that are not on the "white list"
219   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
220     char C = Name[i];
221     assert(C != '"' && "Illegal character in LLVM value name!");
222     if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
223         C != '-' && C != '.' && C != '_')
224       return "\"" + Name + "\"";
225   }
226
227   // If we get here, then the identifier is legal to use as a "VarID".
228   if (prefixName)
229     return "%"+Name;
230   else
231     return Name;
232 }
233
234
235 /// fillTypeNameTable - If the module has a symbol table, take all global types
236 /// and stuff their names into the TypeNames map.
237 ///
238 static void fillTypeNameTable(const Module *M,
239                               std::map<const Type *, std::string> &TypeNames) {
240   if (!M) return;
241   const SymbolTable &ST = M->getSymbolTable();
242   SymbolTable::type_const_iterator TI = ST.type_begin();
243   for (; TI != ST.type_end(); ++TI) {
244     // As a heuristic, don't insert pointer to primitive types, because
245     // they are used too often to have a single useful name.
246     //
247     const Type *Ty = cast<Type>(TI->second);
248     if (!isa<PointerType>(Ty) ||
249         !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
250         isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
251       TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
252   }
253 }
254
255
256
257 static void calcTypeName(const Type *Ty,
258                          std::vector<const Type *> &TypeStack,
259                          std::map<const Type *, std::string> &TypeNames,
260                          std::string & Result){
261   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
262     Result += Ty->getDescription();  // Base case
263     return;
264   }
265
266   // Check to see if the type is named.
267   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
268   if (I != TypeNames.end()) {
269     Result += I->second;
270     return;
271   }
272
273   if (isa<OpaqueType>(Ty)) {
274     Result += "opaque";
275     return;
276   }
277
278   // Check to see if the Type is already on the stack...
279   unsigned Slot = 0, CurSize = TypeStack.size();
280   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
281
282   // This is another base case for the recursion.  In this case, we know
283   // that we have looped back to a type that we have previously visited.
284   // Generate the appropriate upreference to handle this.
285   if (Slot < CurSize) {
286     Result += "\\" + utostr(CurSize-Slot);     // Here's the upreference
287     return;
288   }
289
290   TypeStack.push_back(Ty);    // Recursive case: Add us to the stack..
291
292   switch (Ty->getTypeID()) {
293   case Type::FunctionTyID: {
294     const FunctionType *FTy = cast<FunctionType>(Ty);
295     calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
296     Result += " (";
297     for (FunctionType::param_iterator I = FTy->param_begin(),
298            E = FTy->param_end(); I != E; ++I) {
299       if (I != FTy->param_begin())
300         Result += ", ";
301       calcTypeName(*I, TypeStack, TypeNames, Result);
302     }
303     if (FTy->isVarArg()) {
304       if (FTy->getNumParams()) Result += ", ";
305       Result += "...";
306     }
307     Result += ")";
308     break;
309   }
310   case Type::StructTyID: {
311     const StructType *STy = cast<StructType>(Ty);
312     Result += "{ ";
313     for (StructType::element_iterator I = STy->element_begin(),
314            E = STy->element_end(); I != E; ++I) {
315       if (I != STy->element_begin())
316         Result += ", ";
317       calcTypeName(*I, TypeStack, TypeNames, Result);
318     }
319     Result += " }";
320     break;
321   }
322   case Type::PointerTyID:
323     calcTypeName(cast<PointerType>(Ty)->getElementType(),
324                           TypeStack, TypeNames, Result);
325     Result += "*";
326     break;
327   case Type::ArrayTyID: {
328     const ArrayType *ATy = cast<ArrayType>(Ty);
329     Result += "[" + utostr(ATy->getNumElements()) + " x ";
330     calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
331     Result += "]";
332     break;
333   }
334   case Type::PackedTyID: {
335     const PackedType *PTy = cast<PackedType>(Ty);
336     Result += "<" + utostr(PTy->getNumElements()) + " x ";
337     calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
338     Result += ">";
339     break;
340   }
341   case Type::OpaqueTyID:
342     Result += "opaque";
343     break;
344   default:
345     Result += "<unrecognized-type>";
346   }
347
348   TypeStack.pop_back();       // Remove self from stack...
349   return;
350 }
351
352
353 /// printTypeInt - The internal guts of printing out a type that has a
354 /// potentially named portion.
355 ///
356 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
357                               std::map<const Type *, std::string> &TypeNames) {
358   // Primitive types always print out their description, regardless of whether
359   // they have been named or not.
360   //
361   if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
362     return Out << Ty->getDescription();
363
364   // Check to see if the type is named.
365   std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
366   if (I != TypeNames.end()) return Out << I->second;
367
368   // Otherwise we have a type that has not been named but is a derived type.
369   // Carefully recurse the type hierarchy to print out any contained symbolic
370   // names.
371   //
372   std::vector<const Type *> TypeStack;
373   std::string TypeName;
374   calcTypeName(Ty, TypeStack, TypeNames, TypeName);
375   TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
376   return (Out << TypeName);
377 }
378
379
380 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
381 /// type, iff there is an entry in the modules symbol table for the specified
382 /// type or one of it's component types. This is slower than a simple x << Type
383 ///
384 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
385                                       const Module *M) {
386   Out << ' ';
387
388   // If they want us to print out a type, attempt to make it symbolic if there
389   // is a symbol table in the module...
390   if (M) {
391     std::map<const Type *, std::string> TypeNames;
392     fillTypeNameTable(M, TypeNames);
393
394     return printTypeInt(Out, Ty, TypeNames);
395   } else {
396     return Out << Ty->getDescription();
397   }
398 }
399
400 // PrintEscapedString - Print each character of the specified string, escaping
401 // it if it is not printable or if it is an escape char.
402 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
403   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
404     unsigned char C = Str[i];
405     if (isprint(C) && C != '"' && C != '\\') {
406       Out << C;
407     } else {
408       Out << '\\'
409           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
410           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
411     }
412   }
413 }
414
415 static const char * getPredicateText(unsigned predicate) {
416   const char * pred = "unknown";
417   switch (predicate) {
418     case FCmpInst::FCMP_FALSE: pred = "false"; break;
419     case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
420     case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
421     case FCmpInst::FCMP_OGE:   pred = "oge"; break;
422     case FCmpInst::FCMP_OLT:   pred = "olt"; break;
423     case FCmpInst::FCMP_OLE:   pred = "ole"; break;
424     case FCmpInst::FCMP_ONE:   pred = "one"; break;
425     case FCmpInst::FCMP_ORD:   pred = "ord"; break;
426     case FCmpInst::FCMP_UNO:   pred = "uno"; break;
427     case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
428     case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
429     case FCmpInst::FCMP_UGE:   pred = "uge"; break;
430     case FCmpInst::FCMP_ULT:   pred = "ult"; break;
431     case FCmpInst::FCMP_ULE:   pred = "ule"; break;
432     case FCmpInst::FCMP_UNE:   pred = "une"; break;
433     case FCmpInst::FCMP_TRUE:  pred = "true"; break;
434     case ICmpInst::ICMP_EQ:    pred = "eq"; break;
435     case ICmpInst::ICMP_NE:    pred = "ne"; break;
436     case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
437     case ICmpInst::ICMP_SGE:   pred = "sge"; break;
438     case ICmpInst::ICMP_SLT:   pred = "slt"; break;
439     case ICmpInst::ICMP_SLE:   pred = "sle"; break;
440     case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
441     case ICmpInst::ICMP_UGE:   pred = "uge"; break;
442     case ICmpInst::ICMP_ULT:   pred = "ult"; break;
443     case ICmpInst::ICMP_ULE:   pred = "ule"; break;
444   }
445   return pred;
446 }
447
448 /// @brief Internal constant writer.
449 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
450                              bool PrintName,
451                              std::map<const Type *, std::string> &TypeTable,
452                              SlotMachine *Machine) {
453   const int IndentSize = 4;
454   static std::string Indent = "\n";
455   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
456     Out << (CB->getValue() ? "true" : "false");
457   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
458     if (CI->getType()->isSigned())
459       Out << CI->getSExtValue();
460     else
461       Out << CI->getZExtValue();
462   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
463     // We would like to output the FP constant value in exponential notation,
464     // but we cannot do this if doing so will lose precision.  Check here to
465     // make sure that we only output it in exponential format if we can parse
466     // the value back and get the same value.
467     //
468     std::string StrVal = ftostr(CFP->getValue());
469
470     // Check to make sure that the stringized number is not some string like
471     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
472     // the string matches the "[-+]?[0-9]" regex.
473     //
474     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
475         ((StrVal[0] == '-' || StrVal[0] == '+') &&
476          (StrVal[1] >= '0' && StrVal[1] <= '9')))
477       // Reparse stringized version!
478       if (atof(StrVal.c_str()) == CFP->getValue()) {
479         Out << StrVal;
480         return;
481       }
482
483     // Otherwise we could not reparse it to exactly the same value, so we must
484     // output the string in hexadecimal format!
485     assert(sizeof(double) == sizeof(uint64_t) &&
486            "assuming that double is 64 bits!");
487     Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
488
489   } else if (isa<ConstantAggregateZero>(CV)) {
490     Out << "zeroinitializer";
491   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
492     // As a special case, print the array as a string if it is an array of
493     // ubytes or an array of sbytes with positive values.
494     //
495     const Type *ETy = CA->getType()->getElementType();
496     if (CA->isString()) {
497       Out << "c\"";
498       PrintEscapedString(CA->getAsString(), Out);
499       Out << "\"";
500
501     } else {                // Cannot output in string format...
502       Out << '[';
503       if (CA->getNumOperands()) {
504         Out << ' ';
505         printTypeInt(Out, ETy, TypeTable);
506         WriteAsOperandInternal(Out, CA->getOperand(0),
507                                PrintName, TypeTable, Machine);
508         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
509           Out << ", ";
510           printTypeInt(Out, ETy, TypeTable);
511           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
512                                  TypeTable, Machine);
513         }
514       }
515       Out << " ]";
516     }
517   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
518     Out << '{';
519     unsigned N = CS->getNumOperands();
520     if (N) {
521       if (N > 2) {
522         Indent += std::string(IndentSize, ' ');
523         Out << Indent;
524       } else {
525         Out << ' ';
526       }
527       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
528
529       WriteAsOperandInternal(Out, CS->getOperand(0),
530                              PrintName, TypeTable, Machine);
531
532       for (unsigned i = 1; i < N; i++) {
533         Out << ", ";
534         if (N > 2) Out << Indent;
535         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
536
537         WriteAsOperandInternal(Out, CS->getOperand(i),
538                                PrintName, TypeTable, Machine);
539       }
540       if (N > 2) Indent.resize(Indent.size() - IndentSize);
541     }
542  
543     Out << " }";
544   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
545       const Type *ETy = CP->getType()->getElementType();
546       assert(CP->getNumOperands() > 0 &&
547              "Number of operands for a PackedConst must be > 0");
548       Out << '<';
549       Out << ' ';
550       printTypeInt(Out, ETy, TypeTable);
551       WriteAsOperandInternal(Out, CP->getOperand(0),
552                              PrintName, TypeTable, Machine);
553       for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
554           Out << ", ";
555           printTypeInt(Out, ETy, TypeTable);
556           WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
557                                  TypeTable, Machine);
558       }
559       Out << " >";
560   } else if (isa<ConstantPointerNull>(CV)) {
561     Out << "null";
562
563   } else if (isa<UndefValue>(CV)) {
564     Out << "undef";
565
566   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
567     Out << CE->getOpcodeName();
568     if (CE->isCompare())
569       Out << " " << getPredicateText(CE->getPredicate());
570     Out << " (";
571
572     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
573       printTypeInt(Out, (*OI)->getType(), TypeTable);
574       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
575       if (OI+1 != CE->op_end())
576         Out << ", ";
577     }
578
579     if (CE->isCast()) {
580       Out << " to ";
581       printTypeInt(Out, CE->getType(), TypeTable);
582     }
583
584     Out << ')';
585
586   } else {
587     Out << "<placeholder or erroneous Constant>";
588   }
589 }
590
591
592 /// WriteAsOperand - Write the name of the specified value out to the specified
593 /// ostream.  This can be useful when you just want to print int %reg126, not
594 /// the whole instruction that generated it.
595 ///
596 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
597                                    bool PrintName,
598                                   std::map<const Type*, std::string> &TypeTable,
599                                    SlotMachine *Machine) {
600   Out << ' ';
601   if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
602     Out << getLLVMName(V->getName());
603   else {
604     const Constant *CV = dyn_cast<Constant>(V);
605     if (CV && !isa<GlobalValue>(CV)) {
606       WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
607     } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
608       Out << "asm ";
609       if (IA->hasSideEffects())
610         Out << "sideeffect ";
611       Out << '"';
612       PrintEscapedString(IA->getAsmString(), Out);
613       Out << "\", \"";
614       PrintEscapedString(IA->getConstraintString(), Out);
615       Out << '"';
616     } else {
617       int Slot;
618       if (Machine) {
619         Slot = Machine->getSlot(V);
620       } else {
621         Machine = createSlotMachine(V);
622         if (Machine)
623           Slot = Machine->getSlot(V);
624         else
625           Slot = -1;
626         delete Machine;
627       }
628       if (Slot != -1)
629         Out << '%' << Slot;
630       else
631         Out << "<badref>";
632     }
633   }
634 }
635
636 /// WriteAsOperand - Write the name of the specified value out to the specified
637 /// ostream.  This can be useful when you just want to print int %reg126, not
638 /// the whole instruction that generated it.
639 ///
640 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
641                                    bool PrintType, bool PrintName,
642                                    const Module *Context) {
643   std::map<const Type *, std::string> TypeNames;
644   if (Context == 0) Context = getModuleFromVal(V);
645
646   if (Context)
647     fillTypeNameTable(Context, TypeNames);
648
649   if (PrintType)
650     printTypeInt(Out, V->getType(), TypeNames);
651
652   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
653   return Out;
654 }
655
656 /// WriteAsOperandInternal - Write the name of the specified value out to
657 /// the specified ostream.  This can be useful when you just want to print
658 /// int %reg126, not the whole instruction that generated it.
659 ///
660 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
661                                    bool PrintName,
662                                   std::map<const Type*, std::string> &TypeTable,
663                                    SlotMachine *Machine) {
664   Out << ' ';
665   int Slot;
666   if (Machine) {
667     Slot = Machine->getSlot(T);
668     if (Slot != -1)
669       Out << '%' << Slot;
670     else
671       Out << "<badref>";
672   } else {
673     Out << T->getDescription();
674   }
675 }
676
677 /// WriteAsOperand - Write the name of the specified value out to the specified
678 /// ostream.  This can be useful when you just want to print int %reg126, not
679 /// the whole instruction that generated it.
680 ///
681 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
682                                    bool PrintType, bool PrintName,
683                                    const Module *Context) {
684   std::map<const Type *, std::string> TypeNames;
685   assert(Context != 0 && "Can't write types as operand without module context");
686
687   fillTypeNameTable(Context, TypeNames);
688
689   // if (PrintType)
690     // printTypeInt(Out, V->getType(), TypeNames);
691
692   printTypeInt(Out, Ty, TypeNames);
693
694   WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
695   return Out;
696 }
697
698 namespace llvm {
699
700 class AssemblyWriter {
701   std::ostream &Out;
702   SlotMachine &Machine;
703   const Module *TheModule;
704   std::map<const Type *, std::string> TypeNames;
705   AssemblyAnnotationWriter *AnnotationWriter;
706 public:
707   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
708                         AssemblyAnnotationWriter *AAW)
709     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
710
711     // If the module has a symbol table, take all global types and stuff their
712     // names into the TypeNames map.
713     //
714     fillTypeNameTable(M, TypeNames);
715   }
716
717   inline void write(const Module *M)         { printModule(M);      }
718   inline void write(const GlobalVariable *G) { printGlobal(G);      }
719   inline void write(const Function *F)       { printFunction(F);    }
720   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
721   inline void write(const Instruction *I)    { printInstruction(*I); }
722   inline void write(const Constant *CPV)     { printConstant(CPV);  }
723   inline void write(const Type *Ty)          { printType(Ty);       }
724
725   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
726
727   const Module* getModule() { return TheModule; }
728
729 private:
730   void printModule(const Module *M);
731   void printSymbolTable(const SymbolTable &ST);
732   void printConstant(const Constant *CPV);
733   void printGlobal(const GlobalVariable *GV);
734   void printFunction(const Function *F);
735   void printArgument(const Argument *FA);
736   void printBasicBlock(const BasicBlock *BB);
737   void printInstruction(const Instruction &I);
738
739   // printType - Go to extreme measures to attempt to print out a short,
740   // symbolic version of a type name.
741   //
742   std::ostream &printType(const Type *Ty) {
743     return printTypeInt(Out, Ty, TypeNames);
744   }
745
746   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
747   // without considering any symbolic types that we may have equal to it.
748   //
749   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
750
751   // printInfoComment - Print a little comment after the instruction indicating
752   // which slot it occupies.
753   void printInfoComment(const Value &V);
754 };
755 }  // end of llvm namespace
756
757 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
758 /// without considering any symbolic types that we may have equal to it.
759 ///
760 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
761   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
762     printType(FTy->getReturnType()) << " (";
763     for (FunctionType::param_iterator I = FTy->param_begin(),
764            E = FTy->param_end(); I != E; ++I) {
765       if (I != FTy->param_begin())
766         Out << ", ";
767       printType(*I);
768     }
769     if (FTy->isVarArg()) {
770       if (FTy->getNumParams()) Out << ", ";
771       Out << "...";
772     }
773     Out << ')';
774   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
775     Out << "{ ";
776     for (StructType::element_iterator I = STy->element_begin(),
777            E = STy->element_end(); I != E; ++I) {
778       if (I != STy->element_begin())
779         Out << ", ";
780       printType(*I);
781     }
782     Out << " }";
783   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
784     printType(PTy->getElementType()) << '*';
785   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
786     Out << '[' << ATy->getNumElements() << " x ";
787     printType(ATy->getElementType()) << ']';
788   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
789     Out << '<' << PTy->getNumElements() << " x ";
790     printType(PTy->getElementType()) << '>';
791   }
792   else if (isa<OpaqueType>(Ty)) {
793     Out << "opaque";
794   } else {
795     if (!Ty->isPrimitiveType())
796       Out << "<unknown derived type>";
797     printType(Ty);
798   }
799   return Out;
800 }
801
802
803 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
804                                   bool PrintName) {
805   if (Operand != 0) {
806     if (PrintType) { Out << ' '; printType(Operand->getType()); }
807     WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
808   } else {
809     Out << "<null operand!>";
810   }
811 }
812
813
814 void AssemblyWriter::printModule(const Module *M) {
815   if (!M->getModuleIdentifier().empty() &&
816       // Don't print the ID if it will start a new line (which would
817       // require a comment char before it).
818       M->getModuleIdentifier().find('\n') == std::string::npos)
819     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
820
821   if (!M->getDataLayout().empty())
822     Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
823
824   switch (M->getEndianness()) {
825   case Module::LittleEndian: Out << "target endian = little\n"; break;
826   case Module::BigEndian:    Out << "target endian = big\n";    break;
827   case Module::AnyEndianness: break;
828   }
829   switch (M->getPointerSize()) {
830   case Module::Pointer32:    Out << "target pointersize = 32\n"; break;
831   case Module::Pointer64:    Out << "target pointersize = 64\n"; break;
832   case Module::AnyPointerSize: break;
833   }
834   if (!M->getTargetTriple().empty())
835     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
836
837   if (!M->getModuleInlineAsm().empty()) {
838     // Split the string into lines, to make it easier to read the .ll file.
839     std::string Asm = M->getModuleInlineAsm();
840     size_t CurPos = 0;
841     size_t NewLine = Asm.find_first_of('\n', CurPos);
842     while (NewLine != std::string::npos) {
843       // We found a newline, print the portion of the asm string from the
844       // last newline up to this newline.
845       Out << "module asm \"";
846       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
847                          Out);
848       Out << "\"\n";
849       CurPos = NewLine+1;
850       NewLine = Asm.find_first_of('\n', CurPos);
851     }
852     Out << "module asm \"";
853     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
854     Out << "\"\n";
855   }
856   
857   // Loop over the dependent libraries and emit them.
858   Module::lib_iterator LI = M->lib_begin();
859   Module::lib_iterator LE = M->lib_end();
860   if (LI != LE) {
861     Out << "deplibs = [ ";
862     while (LI != LE) {
863       Out << '"' << *LI << '"';
864       ++LI;
865       if (LI != LE)
866         Out << ", ";
867     }
868     Out << " ]\n";
869   }
870
871   // Loop over the symbol table, emitting all named constants.
872   printSymbolTable(M->getSymbolTable());
873
874   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
875        I != E; ++I)
876     printGlobal(I);
877
878   Out << "\nimplementation   ; Functions:\n";
879
880   // Output all of the functions.
881   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
882     printFunction(I);
883 }
884
885 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
886   if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
887
888   if (!GV->hasInitializer())
889     switch (GV->getLinkage()) {
890      case GlobalValue::DLLImportLinkage:   Out << "dllimport "; break;
891      case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
892      default: Out << "external "; break;
893     }
894   else
895     switch (GV->getLinkage()) {
896     case GlobalValue::InternalLinkage:     Out << "internal "; break;
897     case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
898     case GlobalValue::WeakLinkage:         Out << "weak "; break;
899     case GlobalValue::AppendingLinkage:    Out << "appending "; break;
900     case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
901     case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;     
902     case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
903     case GlobalValue::ExternalLinkage:     break;
904     case GlobalValue::GhostLinkage:
905       llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
906       abort();
907     }
908
909   Out << (GV->isConstant() ? "constant " : "global ");
910   printType(GV->getType()->getElementType());
911
912   if (GV->hasInitializer()) {
913     Constant* C = cast<Constant>(GV->getInitializer());
914     assert(C &&  "GlobalVar initializer isn't constant?");
915     writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
916   }
917   
918   if (GV->hasSection())
919     Out << ", section \"" << GV->getSection() << '"';
920   if (GV->getAlignment())
921     Out << ", align " << GV->getAlignment();
922   
923   printInfoComment(*GV);
924   Out << "\n";
925 }
926
927
928 // printSymbolTable - Run through symbol table looking for constants
929 // and types. Emit their declarations.
930 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
931
932   // Print the types.
933   for (SymbolTable::type_const_iterator TI = ST.type_begin();
934        TI != ST.type_end(); ++TI) {
935     Out << "\t" << getLLVMName(TI->first) << " = type ";
936
937     // Make sure we print out at least one level of the type structure, so
938     // that we do not get %FILE = type %FILE
939     //
940     printTypeAtLeastOneLevel(TI->second) << "\n";
941   }
942
943   // Print the constants, in type plane order.
944   for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
945        PI != ST.plane_end(); ++PI) {
946     SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
947     SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
948
949     for (; VI != VE; ++VI) {
950       const Value* V = VI->second;
951       const Constant *CPV = dyn_cast<Constant>(V) ;
952       if (CPV && !isa<GlobalValue>(V)) {
953         printConstant(CPV);
954       }
955     }
956   }
957 }
958
959
960 /// printConstant - Print out a constant pool entry...
961 ///
962 void AssemblyWriter::printConstant(const Constant *CPV) {
963   // Don't print out unnamed constants, they will be inlined
964   if (!CPV->hasName()) return;
965
966   // Print out name...
967   Out << "\t" << getLLVMName(CPV->getName()) << " =";
968
969   // Write the value out now...
970   writeOperand(CPV, true, false);
971
972   printInfoComment(*CPV);
973   Out << "\n";
974 }
975
976 /// printFunction - Print all aspects of a function.
977 ///
978 void AssemblyWriter::printFunction(const Function *F) {
979   // Print out the return type and name...
980   Out << "\n";
981
982   // Ensure that no local symbols conflict with global symbols.
983   const_cast<Function*>(F)->renameLocalSymbols();
984
985   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
986
987   if (F->isExternal())
988     switch (F->getLinkage()) {
989     case GlobalValue::DLLImportLinkage:    Out << "declare dllimport "; break;
990     case GlobalValue::ExternalWeakLinkage: Out << "declare extern_weak "; break;
991     default: Out << "declare ";
992     }
993   else
994     switch (F->getLinkage()) {
995     case GlobalValue::InternalLinkage:     Out << "internal "; break;
996     case GlobalValue::LinkOnceLinkage:     Out << "linkonce "; break;
997     case GlobalValue::WeakLinkage:         Out << "weak "; break;
998     case GlobalValue::AppendingLinkage:    Out << "appending "; break;
999     case GlobalValue::DLLImportLinkage:    Out << "dllimport "; break;
1000     case GlobalValue::DLLExportLinkage:    Out << "dllexport "; break;
1001     case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;      
1002     case GlobalValue::ExternalLinkage: break;
1003     case GlobalValue::GhostLinkage:
1004       llvm_cerr << "GhostLinkage not allowed in AsmWriter!\n";
1005       abort();
1006     }
1007
1008   // Print the calling convention.
1009   switch (F->getCallingConv()) {
1010   case CallingConv::C: break;   // default
1011   case CallingConv::CSRet:        Out << "csretcc "; break;
1012   case CallingConv::Fast:         Out << "fastcc "; break;
1013   case CallingConv::Cold:         Out << "coldcc "; break;
1014   case CallingConv::X86_StdCall:  Out << "x86_stdcallcc "; break;
1015   case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break; 
1016   default: Out << "cc" << F->getCallingConv() << " "; break;
1017   }
1018
1019   printType(F->getReturnType()) << ' ';
1020   if (!F->getName().empty())
1021     Out << getLLVMName(F->getName());
1022   else
1023     Out << "\"\"";
1024   Out << '(';
1025   Machine.incorporateFunction(F);
1026
1027   // Loop over the arguments, printing them...
1028   const FunctionType *FT = F->getFunctionType();
1029
1030   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1031        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 // Iterate through all the global variables, functions, and global
1501 // variable initializers and create slots for them.
1502 void SlotMachine::processModule() {
1503   SC_DEBUG("begin processModule!\n");
1504
1505   // Add all of the global variables to the value table...
1506   for (Module::const_global_iterator I = TheModule->global_begin(),
1507        E = TheModule->global_end(); I != E; ++I)
1508     getOrCreateSlot(I);
1509
1510   // Add all the functions to the table
1511   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1512        I != E; ++I)
1513     getOrCreateSlot(I);
1514
1515   SC_DEBUG("end processModule!\n");
1516 }
1517
1518
1519 // Process the arguments, basic blocks, and instructions  of a function.
1520 void SlotMachine::processFunction() {
1521   SC_DEBUG("begin processFunction!\n");
1522
1523   // Add all the function arguments
1524   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1525       AE = TheFunction->arg_end(); AI != AE; ++AI)
1526     getOrCreateSlot(AI);
1527
1528   SC_DEBUG("Inserting Instructions:\n");
1529
1530   // Add all of the basic blocks and instructions
1531   for (Function::const_iterator BB = TheFunction->begin(),
1532        E = TheFunction->end(); BB != E; ++BB) {
1533     getOrCreateSlot(BB);
1534     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
1535       getOrCreateSlot(I);
1536   }
1537
1538   FunctionProcessed = true;
1539
1540   SC_DEBUG("end processFunction!\n");
1541 }
1542
1543 /// Clean up after incorporating a function. This is the only way to get out of
1544 /// the function incorporation state that affects the
1545 /// getSlot/getOrCreateSlot lock. Function incorporation state is indicated
1546 /// by TheFunction != 0.
1547 void SlotMachine::purgeFunction() {
1548   SC_DEBUG("begin purgeFunction!\n");
1549   fMap.clear(); // Simply discard the function level map
1550   fTypes.clear();
1551   TheFunction = 0;
1552   FunctionProcessed = false;
1553   SC_DEBUG("end purgeFunction!\n");
1554 }
1555
1556 /// Get the slot number for a value. This function will assert if you
1557 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1558 /// Types are forbidden because Type does not inherit from Value (any more).
1559 int SlotMachine::getSlot(const Value *V) {
1560   assert(V && "Can't get slot for null Value");
1561   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1562     "Can't insert a non-GlobalValue Constant into SlotMachine");
1563
1564   // Check for uninitialized state and do lazy initialization
1565   this->initialize();
1566
1567   // Get the type of the value
1568   const Type* VTy = V->getType();
1569
1570   // Find the type plane in the module map
1571   TypedPlanes::const_iterator MI = mMap.find(VTy);
1572
1573   if (TheFunction) {
1574     // Lookup the type in the function map too
1575     TypedPlanes::const_iterator FI = fMap.find(VTy);
1576     // If there is a corresponding type plane in the function map
1577     if (FI != fMap.end()) {
1578       // Lookup the Value in the function map
1579       ValueMap::const_iterator FVI = FI->second.map.find(V);
1580       // If the value doesn't exist in the function map
1581       if (FVI == FI->second.map.end()) {
1582         // Look up the value in the module map.
1583         if (MI == mMap.end()) return -1;
1584         ValueMap::const_iterator MVI = MI->second.map.find(V);
1585         // If we didn't find it, it wasn't inserted
1586         if (MVI == MI->second.map.end()) return -1;
1587         assert(MVI != MI->second.map.end() && "Value not found");
1588         // We found it only at the module level
1589         return MVI->second;
1590
1591       // else the value exists in the function map
1592       } else {
1593         // Return the slot number as the module's contribution to
1594         // the type plane plus the index in the function's contribution
1595         // to the type plane.
1596         if (MI != mMap.end())
1597           return MI->second.next_slot + FVI->second;
1598         else
1599           return FVI->second;
1600       }
1601     }
1602   }
1603
1604   // N.B. Can get here only if either !TheFunction or the function doesn't
1605   // have a corresponding type plane for the Value
1606
1607   // Make sure the type plane exists
1608   if (MI == mMap.end()) return -1;
1609   // Lookup the value in the module's map
1610   ValueMap::const_iterator MVI = MI->second.map.find(V);
1611   // Make sure we found it.
1612   if (MVI == MI->second.map.end()) return -1;
1613   // Return it.
1614   return MVI->second;
1615 }
1616
1617 /// Get the slot number for a value. This function will assert if you
1618 /// ask for a Value that hasn't previously been inserted with getOrCreateSlot.
1619 /// Types are forbidden because Type does not inherit from Value (any more).
1620 int SlotMachine::getSlot(const Type *Ty) {
1621   assert(Ty && "Can't get slot for null Type");
1622
1623   // Check for uninitialized state and do lazy initialization
1624   this->initialize();
1625
1626   if (TheFunction) {
1627     // Lookup the Type in the function map
1628     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1629     // If the Type doesn't exist in the function map
1630     if (FTI == fTypes.map.end()) {
1631       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1632       // If we didn't find it, it wasn't inserted
1633       if (MTI == mTypes.map.end())
1634         return -1;
1635       // We found it only at the module level
1636       return MTI->second;
1637
1638     // else the value exists in the function map
1639     } else {
1640       // Return the slot number as the module's contribution to
1641       // the type plane plus the index in the function's contribution
1642       // to the type plane.
1643       return mTypes.next_slot + FTI->second;
1644     }
1645   }
1646
1647   // N.B. Can get here only if either !TheFunction
1648
1649   // Lookup the value in the module's map
1650   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1651   // Make sure we found it.
1652   if (MTI == mTypes.map.end()) return -1;
1653   // Return it.
1654   return MTI->second;
1655 }
1656
1657 // Create a new slot, or return the existing slot if it is already
1658 // inserted. Note that the logic here parallels getSlot but instead
1659 // of asserting when the Value* isn't found, it inserts the value.
1660 unsigned SlotMachine::getOrCreateSlot(const Value *V) {
1661   assert(V && "Can't insert a null Value to SlotMachine");
1662   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1663     "Can't insert a non-GlobalValue Constant into SlotMachine");
1664
1665   const Type* VTy = V->getType();
1666
1667   // Just ignore void typed things or things with names.
1668   if (VTy == Type::VoidTy || V->hasName())
1669     return 0; // FIXME: Wrong return value!
1670
1671   // Look up the type plane for the Value's type from the module map
1672   TypedPlanes::const_iterator MI = mMap.find(VTy);
1673
1674   if (TheFunction) {
1675     // Get the type plane for the Value's type from the function map
1676     TypedPlanes::const_iterator FI = fMap.find(VTy);
1677     // If there is a corresponding type plane in the function map
1678     if (FI != fMap.end()) {
1679       // Lookup the Value in the function map
1680       ValueMap::const_iterator FVI = FI->second.map.find(V);
1681       // If the value doesn't exist in the function map
1682       if (FVI == FI->second.map.end()) {
1683         // If there is no corresponding type plane in the module map
1684         if (MI == mMap.end())
1685           return insertValue(V);
1686         // Look up the value in the module map
1687         ValueMap::const_iterator MVI = MI->second.map.find(V);
1688         // If we didn't find it, it wasn't inserted
1689         if (MVI == MI->second.map.end())
1690           return insertValue(V);
1691         else
1692           // We found it only at the module level
1693           return MVI->second;
1694
1695       // else the value exists in the function map
1696       } else {
1697         if (MI == mMap.end())
1698           return FVI->second;
1699         else
1700           // Return the slot number as the module's contribution to
1701           // the type plane plus the index in the function's contribution
1702           // to the type plane.
1703           return MI->second.next_slot + FVI->second;
1704       }
1705
1706     // else there is not a corresponding type plane in the function map
1707     } else {
1708       // If the type plane doesn't exists at the module level
1709       if (MI == mMap.end()) {
1710         return insertValue(V);
1711       // else type plane exists at the module level, examine it
1712       } else {
1713         // Look up the value in the module's map
1714         ValueMap::const_iterator MVI = MI->second.map.find(V);
1715         // If we didn't find it there either
1716         if (MVI == MI->second.map.end())
1717           // Return the slot number as the module's contribution to
1718           // the type plane plus the index of the function map insertion.
1719           return MI->second.next_slot + insertValue(V);
1720         else
1721           return MVI->second;
1722       }
1723     }
1724   }
1725
1726   // N.B. Can only get here if !TheFunction
1727
1728   // If the module map's type plane is not for the Value's type
1729   if (MI != mMap.end()) {
1730     // Lookup the value in the module's map
1731     ValueMap::const_iterator MVI = MI->second.map.find(V);
1732     if (MVI != MI->second.map.end())
1733       return MVI->second;
1734   }
1735
1736   return insertValue(V);
1737 }
1738
1739
1740 // Low level insert function. Minimal checking is done. This
1741 // function is just for the convenience of getOrCreateSlot (above).
1742 unsigned SlotMachine::insertValue(const Value *V) {
1743   assert(V && "Can't insert a null Value into SlotMachine!");
1744   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1745          "Can't insert a non-GlobalValue Constant into SlotMachine");
1746   assert(V->getType() != Type::VoidTy && !V->hasName());
1747
1748   const Type *VTy = V->getType();
1749   unsigned DestSlot = 0;
1750
1751   if (TheFunction) {
1752     TypedPlanes::iterator I = fMap.find(VTy);
1753     if (I == fMap.end())
1754       I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1755     DestSlot = I->second.map[V] = I->second.next_slot++;
1756   } else {
1757     TypedPlanes::iterator I = mMap.find(VTy);
1758     if (I == mMap.end())
1759       I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1760     DestSlot = I->second.map[V] = I->second.next_slot++;
1761   }
1762
1763   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" <<
1764            DestSlot << " [");
1765   // G = Global, C = Constant, T = Type, F = Function, o = other
1766   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1767            (isa<Constant>(V) ? 'C' : 'o'))));
1768   SC_DEBUG("]\n");
1769   return DestSlot;
1770 }