Implement a simple optimization for the termination condition of the loop.
[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/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/SymbolTable.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/Support/CFG.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 namespace llvm {
36
37 // Make virtual table appear in this compilation unit.
38 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
39
40 /// This class provides computation of slot numbers for LLVM Assembly writing.
41 /// @brief LLVM Assembly Writing Slot Computation.
42 class SlotMachine {
43
44 /// @name Types
45 /// @{
46 public:
47
48   /// @brief A mapping of Values to slot numbers
49   typedef std::map<const Value*, unsigned> ValueMap;
50   typedef std::map<const Type*, unsigned> TypeMap;
51
52   /// @brief A plane with next slot number and ValueMap
53   struct ValuePlane {
54     unsigned next_slot;        ///< The next slot number to use
55     ValueMap map;              ///< The map of Value* -> unsigned
56     ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
57   };
58
59   struct TypePlane {
60     unsigned next_slot;
61     TypeMap map;
62     TypePlane() { next_slot = 0; }
63     void clear() { map.clear(); next_slot = 0; }
64   };
65
66   /// @brief The map of planes by Type
67   typedef std::map<const Type*, ValuePlane> TypedPlanes;
68
69 /// @}
70 /// @name Constructors
71 /// @{
72 public:
73   /// @brief Construct from a module
74   SlotMachine(const Module *M );
75
76   /// @brief Construct from a function, starting out in incorp state.
77   SlotMachine(const Function *F );
78
79 /// @}
80 /// @name Accessors
81 /// @{
82 public:
83   /// Return the slot number of the specified value in it's type
84   /// plane.  Its an error to ask for something not in the SlotMachine.
85   /// Its an error to ask for a Type*
86   int getSlot(const Value *V);
87   int getSlot(const Type*Ty);
88
89   /// Determine if a Value has a slot or not
90   bool hasSlot(const Value* V);
91   bool hasSlot(const Type* Ty);
92
93 /// @}
94 /// @name Mutators
95 /// @{
96 public:
97   /// If you'd like to deal with a function instead of just a module, use
98   /// this method to get its data into the SlotMachine.
99   void incorporateFunction(const Function *F) {
100     TheFunction = F;
101     FunctionProcessed = false;
102   }
103
104   /// After calling incorporateFunction, use this method to remove the
105   /// most recently incorporated function from the SlotMachine. This
106   /// will reset the state of the machine back to just the module contents.
107   void purgeFunction();
108
109 /// @}
110 /// @name Implementation Details
111 /// @{
112 private:
113   /// This function does the actual initialization.
114   inline void initialize();
115
116   /// Values can be crammed into here at will. If they haven't
117   /// been inserted already, they get inserted, otherwise they are ignored.
118   /// Either way, the slot number for the Value* is returned.
119   unsigned createSlot(const Value *V);
120   unsigned createSlot(const Type* Ty);
121
122   /// Insert a value into the value table. Return the slot number
123   /// that it now occupies.  BadThings(TM) will happen if you insert a
124   /// Value that's already been inserted.
125   unsigned insertValue( const Value *V );
126   unsigned insertValue( const Type* Ty);
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",PassInfo::Analysis|PassInfo::Optimization);
166 static RegisterPass<PrintFunctionPass>
167 Y("print","Print function to stderr",PassInfo::Analysis|PassInfo::Optimization);
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 /// @brief Internal constant writer.
401 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
402                              bool PrintName,
403                              std::map<const Type *, std::string> &TypeTable,
404                              SlotMachine *Machine) {
405   if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
406     Out << (CB == ConstantBool::True ? "true" : "false");
407   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
408     Out << CI->getValue();
409   } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
410     Out << CI->getValue();
411   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
412     // We would like to output the FP constant value in exponential notation,
413     // but we cannot do this if doing so will lose precision.  Check here to
414     // make sure that we only output it in exponential format if we can parse
415     // the value back and get the same value.
416     //
417     std::string StrVal = ftostr(CFP->getValue());
418
419     // Check to make sure that the stringized number is not some string like
420     // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
421     // the string matches the "[-+]?[0-9]" regex.
422     //
423     if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
424         ((StrVal[0] == '-' || StrVal[0] == '+') &&
425          (StrVal[1] >= '0' && StrVal[1] <= '9')))
426       // Reparse stringized version!
427       if (atof(StrVal.c_str()) == CFP->getValue()) {
428         Out << StrVal;
429         return;
430       }
431
432     // Otherwise we could not reparse it to exactly the same value, so we must
433     // output the string in hexadecimal format!
434     //
435     // Behave nicely in the face of C TBAA rules... see:
436     // http://www.nullstone.com/htmls/category/aliastyp.htm
437     //
438     union {
439       double D;
440       uint64_t U;
441     } V;
442     V.D = CFP->getValue();
443     assert(sizeof(double) == sizeof(uint64_t) &&
444            "assuming that double is 64 bits!");
445     Out << "0x" << utohexstr(V.U);
446
447   } else if (isa<ConstantAggregateZero>(CV)) {
448     Out << "zeroinitializer";
449   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
450     // As a special case, print the array as a string if it is an array of
451     // ubytes or an array of sbytes with positive values.
452     //
453     const Type *ETy = CA->getType()->getElementType();
454     bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
455
456     if (ETy == Type::SByteTy)
457       for (unsigned i = 0; i < CA->getNumOperands(); ++i)
458         if (cast<ConstantSInt>(CA->getOperand(i))->getValue() < 0) {
459           isString = false;
460           break;
461         }
462
463     if (isString) {
464       Out << "c\"";
465       for (unsigned i = 0; i < CA->getNumOperands(); ++i) {
466         unsigned char C =
467           (unsigned char)cast<ConstantInt>(CA->getOperand(i))->getRawValue();
468
469         if (isprint(C) && C != '"' && C != '\\') {
470           Out << C;
471         } else {
472           Out << '\\'
473               << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
474               << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
475         }
476       }
477       Out << "\"";
478
479     } else {                // Cannot output in string format...
480       Out << '[';
481       if (CA->getNumOperands()) {
482         Out << ' ';
483         printTypeInt(Out, ETy, TypeTable);
484         WriteAsOperandInternal(Out, CA->getOperand(0),
485                                PrintName, TypeTable, Machine);
486         for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
487           Out << ", ";
488           printTypeInt(Out, ETy, TypeTable);
489           WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
490                                  TypeTable, Machine);
491         }
492       }
493       Out << " ]";
494     }
495   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
496     Out << '{';
497     if (CS->getNumOperands()) {
498       Out << ' ';
499       printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
500
501       WriteAsOperandInternal(Out, CS->getOperand(0),
502                              PrintName, TypeTable, Machine);
503
504       for (unsigned i = 1; i < CS->getNumOperands(); i++) {
505         Out << ", ";
506         printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
507
508         WriteAsOperandInternal(Out, CS->getOperand(i),
509                                PrintName, TypeTable, Machine);
510       }
511     }
512
513     Out << " }";
514   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
515       const Type *ETy = CP->getType()->getElementType();
516       assert(CP->getNumOperands() > 0 &&
517              "Number of operands for a PackedConst must be > 0");
518       Out << '<';
519       Out << ' ';
520       printTypeInt(Out, ETy, TypeTable);
521       WriteAsOperandInternal(Out, CP->getOperand(0),
522                              PrintName, TypeTable, Machine);
523       for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
524           Out << ", ";
525           printTypeInt(Out, ETy, TypeTable);
526           WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
527                                  TypeTable, Machine);
528       }
529       Out << " >";
530   } else if (isa<ConstantPointerNull>(CV)) {
531     Out << "null";
532
533   } else if (isa<UndefValue>(CV)) {
534     Out << "undef";
535
536   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
537     Out << CE->getOpcodeName() << " (";
538
539     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
540       printTypeInt(Out, (*OI)->getType(), TypeTable);
541       WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
542       if (OI+1 != CE->op_end())
543         Out << ", ";
544     }
545
546     if (CE->getOpcode() == Instruction::Cast) {
547       Out << " to ";
548       printTypeInt(Out, CE->getType(), TypeTable);
549     }
550     Out << ')';
551
552   } else {
553     Out << "<placeholder or erroneous Constant>";
554   }
555 }
556
557
558 /// WriteAsOperand - Write the name of the specified value out to the specified
559 /// ostream.  This can be useful when you just want to print int %reg126, not
560 /// the whole instruction that generated it.
561 ///
562 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
563                                    bool PrintName,
564                                   std::map<const Type*, std::string> &TypeTable,
565                                    SlotMachine *Machine) {
566   Out << ' ';
567   if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
568     Out << getLLVMName(V->getName());
569   else {
570     const Constant *CV = dyn_cast<Constant>(V);
571     if (CV && !isa<GlobalValue>(CV))
572       WriteConstantInt(Out, CV, PrintName, TypeTable, Machine);
573     else {
574       int Slot;
575       if (Machine) {
576         Slot = Machine->getSlot(V);
577       } else {
578         Machine = createSlotMachine(V);
579         if (Machine == 0)
580           Slot = Machine->getSlot(V);
581         else
582           Slot = -1;
583         delete Machine;
584       }
585       if (Slot != -1)
586         Out << '%' << Slot;
587       else
588         Out << "<badref>";
589     }
590   }
591 }
592
593 /// WriteAsOperand - Write the name of the specified value out to the specified
594 /// ostream.  This can be useful when you just want to print int %reg126, not
595 /// the whole instruction that generated it.
596 ///
597 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
598                                    bool PrintType, bool PrintName,
599                                    const Module *Context) {
600   std::map<const Type *, std::string> TypeNames;
601   if (Context == 0) Context = getModuleFromVal(V);
602
603   if (Context)
604     fillTypeNameTable(Context, TypeNames);
605
606   if (PrintType)
607     printTypeInt(Out, V->getType(), TypeNames);
608
609   WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
610   return Out;
611 }
612
613 /// WriteAsOperandInternal - Write the name of the specified value out to
614 /// the specified ostream.  This can be useful when you just want to print
615 /// int %reg126, not the whole instruction that generated it.
616 ///
617 static void WriteAsOperandInternal(std::ostream &Out, const Type *T,
618                                    bool PrintName,
619                                   std::map<const Type*, std::string> &TypeTable,
620                                    SlotMachine *Machine) {
621   Out << ' ';
622   int Slot;
623   if (Machine) {
624     Slot = Machine->getSlot(T);
625     if (Slot != -1)
626       Out << '%' << Slot;
627     else
628       Out << "<badref>";
629   } else {
630     Out << T->getDescription();
631   }
632 }
633
634 /// WriteAsOperand - Write the name of the specified value out to the specified
635 /// ostream.  This can be useful when you just want to print int %reg126, not
636 /// the whole instruction that generated it.
637 ///
638 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Type *Ty,
639                                    bool PrintType, bool PrintName,
640                                    const Module *Context) {
641   std::map<const Type *, std::string> TypeNames;
642   assert(Context != 0 && "Can't write types as operand without module context");
643
644   fillTypeNameTable(Context, TypeNames);
645
646   // if (PrintType)
647     // printTypeInt(Out, V->getType(), TypeNames);
648
649   printTypeInt(Out, Ty, TypeNames);
650
651   WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
652   return Out;
653 }
654
655 namespace llvm {
656
657 class AssemblyWriter {
658   std::ostream &Out;
659   SlotMachine &Machine;
660   const Module *TheModule;
661   std::map<const Type *, std::string> TypeNames;
662   AssemblyAnnotationWriter *AnnotationWriter;
663 public:
664   inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
665                         AssemblyAnnotationWriter *AAW)
666     : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
667
668     // If the module has a symbol table, take all global types and stuff their
669     // names into the TypeNames map.
670     //
671     fillTypeNameTable(M, TypeNames);
672   }
673
674   inline void write(const Module *M)         { printModule(M);      }
675   inline void write(const GlobalVariable *G) { printGlobal(G);      }
676   inline void write(const Function *F)       { printFunction(F);    }
677   inline void write(const BasicBlock *BB)    { printBasicBlock(BB); }
678   inline void write(const Instruction *I)    { printInstruction(*I); }
679   inline void write(const Constant *CPV)     { printConstant(CPV);  }
680   inline void write(const Type *Ty)          { printType(Ty);       }
681
682   void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
683
684   const Module* getModule() { return TheModule; }
685
686 private:
687   void printModule(const Module *M);
688   void printSymbolTable(const SymbolTable &ST);
689   void printConstant(const Constant *CPV);
690   void printGlobal(const GlobalVariable *GV);
691   void printFunction(const Function *F);
692   void printArgument(const Argument *FA);
693   void printBasicBlock(const BasicBlock *BB);
694   void printInstruction(const Instruction &I);
695
696   // printType - Go to extreme measures to attempt to print out a short,
697   // symbolic version of a type name.
698   //
699   std::ostream &printType(const Type *Ty) {
700     return printTypeInt(Out, Ty, TypeNames);
701   }
702
703   // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
704   // without considering any symbolic types that we may have equal to it.
705   //
706   std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
707
708   // printInfoComment - Print a little comment after the instruction indicating
709   // which slot it occupies.
710   void printInfoComment(const Value &V);
711 };
712 }  // end of llvm namespace
713
714 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
715 /// without considering any symbolic types that we may have equal to it.
716 ///
717 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
718   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
719     printType(FTy->getReturnType()) << " (";
720     for (FunctionType::param_iterator I = FTy->param_begin(),
721            E = FTy->param_end(); I != E; ++I) {
722       if (I != FTy->param_begin())
723         Out << ", ";
724       printType(*I);
725     }
726     if (FTy->isVarArg()) {
727       if (FTy->getNumParams()) Out << ", ";
728       Out << "...";
729     }
730     Out << ')';
731   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
732     Out << "{ ";
733     for (StructType::element_iterator I = STy->element_begin(),
734            E = STy->element_end(); I != E; ++I) {
735       if (I != STy->element_begin())
736         Out << ", ";
737       printType(*I);
738     }
739     Out << " }";
740   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
741     printType(PTy->getElementType()) << '*';
742   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
743     Out << '[' << ATy->getNumElements() << " x ";
744     printType(ATy->getElementType()) << ']';
745   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
746     Out << '<' << PTy->getNumElements() << " x ";
747     printType(PTy->getElementType()) << '>';
748   }
749   else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
750     Out << "opaque";
751   } else {
752     if (!Ty->isPrimitiveType())
753       Out << "<unknown derived type>";
754     printType(Ty);
755   }
756   return Out;
757 }
758
759
760 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
761                                   bool PrintName) {
762   if (Operand != 0) {
763     if (PrintType) { Out << ' '; printType(Operand->getType()); }
764     WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
765   } else {
766     Out << "<null operand!>";
767   }
768 }
769
770
771 void AssemblyWriter::printModule(const Module *M) {
772   if (!M->getModuleIdentifier().empty() &&
773       // Don't print the ID if it will start a new line (which would
774       // require a comment char before it).
775       M->getModuleIdentifier().find('\n') == std::string::npos)
776     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
777
778   switch (M->getEndianness()) {
779   case Module::LittleEndian: Out << "target endian = little\n"; break;
780   case Module::BigEndian:    Out << "target endian = big\n";    break;
781   case Module::AnyEndianness: break;
782   }
783   switch (M->getPointerSize()) {
784   case Module::Pointer32:    Out << "target pointersize = 32\n"; break;
785   case Module::Pointer64:    Out << "target pointersize = 64\n"; break;
786   case Module::AnyPointerSize: break;
787   }
788   if (!M->getTargetTriple().empty())
789     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
790
791   // Loop over the dependent libraries and emit them.
792   Module::lib_iterator LI = M->lib_begin();
793   Module::lib_iterator LE = M->lib_end();
794   if (LI != LE) {
795     Out << "deplibs = [ ";
796     while (LI != LE) {
797       Out << '"' << *LI << '"';
798       ++LI;
799       if (LI != LE)
800         Out << ", ";
801     }
802     Out << " ]\n";
803   }
804
805   // Loop over the symbol table, emitting all named constants.
806   printSymbolTable(M->getSymbolTable());
807
808   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
809     printGlobal(I);
810
811   Out << "\nimplementation   ; Functions:\n";
812
813   // Output all of the functions.
814   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
815     printFunction(I);
816 }
817
818 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
819   if (GV->hasName()) Out << getLLVMName(GV->getName()) << " = ";
820
821   if (!GV->hasInitializer())
822     Out << "external ";
823   else
824     switch (GV->getLinkage()) {
825     case GlobalValue::InternalLinkage:  Out << "internal "; break;
826     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
827     case GlobalValue::WeakLinkage:      Out << "weak "; break;
828     case GlobalValue::AppendingLinkage: Out << "appending "; break;
829     case GlobalValue::ExternalLinkage: break;
830     case GlobalValue::GhostLinkage:
831       std::cerr << "GhostLinkage not allowed in AsmWriter!\n";
832       abort();
833     }
834
835   Out << (GV->isConstant() ? "constant " : "global ");
836   printType(GV->getType()->getElementType());
837
838   if (GV->hasInitializer()) {
839     Constant* C = cast<Constant>(GV->getInitializer());
840     assert(C &&  "GlobalVar initializer isn't constant?");
841     writeOperand(GV->getInitializer(), false, isa<GlobalValue>(C));
842   }
843
844   printInfoComment(*GV);
845   Out << "\n";
846 }
847
848
849 // printSymbolTable - Run through symbol table looking for constants
850 // and types. Emit their declarations.
851 void AssemblyWriter::printSymbolTable(const SymbolTable &ST) {
852
853   // Print the types.
854   for (SymbolTable::type_const_iterator TI = ST.type_begin();
855        TI != ST.type_end(); ++TI ) {
856     Out << "\t" << getLLVMName(TI->first) << " = type ";
857
858     // Make sure we print out at least one level of the type structure, so
859     // that we do not get %FILE = type %FILE
860     //
861     printTypeAtLeastOneLevel(TI->second) << "\n";
862   }
863
864   // Print the constants, in type plane order.
865   for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
866        PI != ST.plane_end(); ++PI ) {
867     SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
868     SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
869
870     for (; VI != VE; ++VI) {
871       const Value* V = VI->second;
872       const Constant *CPV = dyn_cast<Constant>(V) ;
873       if (CPV && !isa<GlobalValue>(V)) {
874         printConstant(CPV);
875       }
876     }
877   }
878 }
879
880
881 /// printConstant - Print out a constant pool entry...
882 ///
883 void AssemblyWriter::printConstant(const Constant *CPV) {
884   // Don't print out unnamed constants, they will be inlined
885   if (!CPV->hasName()) return;
886
887   // Print out name...
888   Out << "\t" << getLLVMName(CPV->getName()) << " =";
889
890   // Write the value out now...
891   writeOperand(CPV, true, false);
892
893   printInfoComment(*CPV);
894   Out << "\n";
895 }
896
897 /// printFunction - Print all aspects of a function.
898 ///
899 void AssemblyWriter::printFunction(const Function *F) {
900   // Print out the return type and name...
901   Out << "\n";
902
903   // Ensure that no local symbols conflict with global symbols.
904   const_cast<Function*>(F)->renameLocalSymbols();
905
906   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
907
908   if (F->isExternal())
909     Out << "declare ";
910   else
911     switch (F->getLinkage()) {
912     case GlobalValue::InternalLinkage:  Out << "internal "; break;
913     case GlobalValue::LinkOnceLinkage:  Out << "linkonce "; break;
914     case GlobalValue::WeakLinkage:      Out << "weak "; break;
915     case GlobalValue::AppendingLinkage: Out << "appending "; break;
916     case GlobalValue::ExternalLinkage: break;
917     case GlobalValue::GhostLinkage:
918       std::cerr << "GhostLinkage not allowed in AsmWriter!\n";
919       abort();
920     }
921
922   // Print the calling convention.
923   switch (F->getCallingConv()) {
924   case CallingConv::C: break;   // default
925   case CallingConv::Fast: Out << "fastcc "; break;
926   case CallingConv::Cold: Out << "coldcc "; break;
927   default: Out << "cc" << F->getCallingConv() << " "; break;
928   }
929
930   printType(F->getReturnType()) << ' ';
931   if (!F->getName().empty())
932     Out << getLLVMName(F->getName());
933   else
934     Out << "\"\"";
935   Out << '(';
936   Machine.incorporateFunction(F);
937
938   // Loop over the arguments, printing them...
939   const FunctionType *FT = F->getFunctionType();
940
941   for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
942     printArgument(I);
943
944   // Finish printing arguments...
945   if (FT->isVarArg()) {
946     if (FT->getNumParams()) Out << ", ";
947     Out << "...";  // Output varargs portion of signature!
948   }
949   Out << ')';
950
951   if (F->isExternal()) {
952     Out << "\n";
953   } else {
954     Out << " {";
955
956     // Output all of its basic blocks... for the function
957     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
958       printBasicBlock(I);
959
960     Out << "}\n";
961   }
962
963   Machine.purgeFunction();
964 }
965
966 /// printArgument - This member is called for every argument that is passed into
967 /// the function.  Simply print it out
968 ///
969 void AssemblyWriter::printArgument(const Argument *Arg) {
970   // Insert commas as we go... the first arg doesn't get a comma
971   if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
972
973   // Output type...
974   printType(Arg->getType());
975
976   // Output name, if available...
977   if (Arg->hasName())
978     Out << ' ' << getLLVMName(Arg->getName());
979 }
980
981 /// printBasicBlock - This member is called for each basic block in a method.
982 ///
983 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
984   if (BB->hasName()) {              // Print out the label if it exists...
985     Out << "\n" << getLLVMName(BB->getName(), false) << ':';
986   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
987     Out << "\n; <label>:";
988     int Slot = Machine.getSlot(BB);
989     if (Slot != -1)
990       Out << Slot;
991     else
992       Out << "<badref>";
993   }
994
995   if (BB->getParent() == 0)
996     Out << "\t\t; Error: Block without parent!";
997   else {
998     if (BB != &BB->getParent()->front()) {  // Not the entry block?
999       // Output predecessors for the block...
1000       Out << "\t\t;";
1001       pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1002
1003       if (PI == PE) {
1004         Out << " No predecessors!";
1005       } else {
1006         Out << " preds =";
1007         writeOperand(*PI, false, true);
1008         for (++PI; PI != PE; ++PI) {
1009           Out << ',';
1010           writeOperand(*PI, false, true);
1011         }
1012       }
1013     }
1014   }
1015
1016   Out << "\n";
1017
1018   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1019
1020   // Output all of the instructions in the basic block...
1021   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1022     printInstruction(*I);
1023
1024   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1025 }
1026
1027
1028 /// printInfoComment - Print a little comment after the instruction indicating
1029 /// which slot it occupies.
1030 ///
1031 void AssemblyWriter::printInfoComment(const Value &V) {
1032   if (V.getType() != Type::VoidTy) {
1033     Out << "\t\t; <";
1034     printType(V.getType()) << '>';
1035
1036     if (!V.hasName()) {
1037       int SlotNum = Machine.getSlot(&V);
1038       if (SlotNum == -1)
1039         Out << ":<badref>";
1040       else
1041         Out << ':' << SlotNum; // Print out the def slot taken.
1042     }
1043     Out << " [#uses=" << V.getNumUses() << ']';  // Output # uses
1044   }
1045 }
1046
1047 /// printInstruction - This member is called for each Instruction in a function..
1048 ///
1049 void AssemblyWriter::printInstruction(const Instruction &I) {
1050   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1051
1052   Out << "\t";
1053
1054   // Print out name if it exists...
1055   if (I.hasName())
1056     Out << getLLVMName(I.getName()) << " = ";
1057
1058   // If this is a volatile load or store, print out the volatile marker.
1059   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
1060       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1061       Out << "volatile ";
1062   } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1063     // If this is a call, check if it's a tail call.
1064     Out << "tail ";
1065   }
1066
1067   // Print out the opcode...
1068   Out << I.getOpcodeName();
1069
1070   // Print out the type of the operands...
1071   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1072
1073   // Special case conditional branches to swizzle the condition out to the front
1074   if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1075     writeOperand(I.getOperand(2), true);
1076     Out << ',';
1077     writeOperand(Operand, true);
1078     Out << ',';
1079     writeOperand(I.getOperand(1), true);
1080
1081   } else if (isa<SwitchInst>(I)) {
1082     // Special case switch statement to get formatting nice and correct...
1083     writeOperand(Operand        , true); Out << ',';
1084     writeOperand(I.getOperand(1), true); Out << " [";
1085
1086     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1087       Out << "\n\t\t";
1088       writeOperand(I.getOperand(op  ), true); Out << ',';
1089       writeOperand(I.getOperand(op+1), true);
1090     }
1091     Out << "\n\t]";
1092   } else if (isa<PHINode>(I)) {
1093     Out << ' ';
1094     printType(I.getType());
1095     Out << ' ';
1096
1097     for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1098       if (op) Out << ", ";
1099       Out << '[';
1100       writeOperand(I.getOperand(op  ), false); Out << ',';
1101       writeOperand(I.getOperand(op+1), false); Out << " ]";
1102     }
1103   } else if (isa<ReturnInst>(I) && !Operand) {
1104     Out << " void";
1105   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1106     // Print the calling convention being used.
1107     switch (CI->getCallingConv()) {
1108     case CallingConv::C: break;   // default
1109     case CallingConv::Fast: Out << " fastcc"; break;
1110     case CallingConv::Cold: Out << " coldcc"; break;
1111     default: Out << " cc" << CI->getCallingConv(); break;
1112     }
1113
1114     const PointerType  *PTy = cast<PointerType>(Operand->getType());
1115     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1116     const Type       *RetTy = FTy->getReturnType();
1117
1118     // If possible, print out the short form of the call instruction.  We can
1119     // only do this if the first argument is a pointer to a nonvararg function,
1120     // and if the return type is not a pointer to a function.
1121     //
1122     if (!FTy->isVarArg() &&
1123         (!isa<PointerType>(RetTy) ||
1124          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1125       Out << ' '; printType(RetTy);
1126       writeOperand(Operand, false);
1127     } else {
1128       writeOperand(Operand, true);
1129     }
1130     Out << '(';
1131     if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1132     for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1133       Out << ',';
1134       writeOperand(I.getOperand(op), true);
1135     }
1136
1137     Out << " )";
1138   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1139     const PointerType  *PTy = cast<PointerType>(Operand->getType());
1140     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1141     const Type       *RetTy = FTy->getReturnType();
1142
1143     // Print the calling convention being used.
1144     switch (II->getCallingConv()) {
1145     case CallingConv::C: break;   // default
1146     case CallingConv::Fast: Out << " fastcc"; break;
1147     case CallingConv::Cold: Out << " coldcc"; break;
1148     default: Out << " cc" << II->getCallingConv(); break;
1149     }
1150
1151     // If possible, print out the short form of the invoke instruction. We can
1152     // only do this if the first argument is a pointer to a nonvararg function,
1153     // and if the return type is not a pointer to a function.
1154     //
1155     if (!FTy->isVarArg() &&
1156         (!isa<PointerType>(RetTy) ||
1157          !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1158       Out << ' '; printType(RetTy);
1159       writeOperand(Operand, false);
1160     } else {
1161       writeOperand(Operand, true);
1162     }
1163
1164     Out << '(';
1165     if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1166     for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1167       Out << ',';
1168       writeOperand(I.getOperand(op), true);
1169     }
1170
1171     Out << " )\n\t\t\tto";
1172     writeOperand(II->getNormalDest(), true);
1173     Out << " unwind";
1174     writeOperand(II->getUnwindDest(), true);
1175
1176   } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1177     Out << ' ';
1178     printType(AI->getType()->getElementType());
1179     if (AI->isArrayAllocation()) {
1180       Out << ',';
1181       writeOperand(AI->getArraySize(), true);
1182     }
1183   } else if (isa<CastInst>(I)) {
1184     if (Operand) writeOperand(Operand, true);   // Work with broken code
1185     Out << " to ";
1186     printType(I.getType());
1187   } else if (isa<VAArgInst>(I)) {
1188     if (Operand) writeOperand(Operand, true);   // Work with broken code
1189     Out << ", ";
1190     printType(I.getType());
1191   } else if (Operand) {   // Print the normal way...
1192
1193     // PrintAllTypes - Instructions who have operands of all the same type
1194     // omit the type from all but the first operand.  If the instruction has
1195     // different type operands (for example br), then they are all printed.
1196     bool PrintAllTypes = false;
1197     const Type *TheType = Operand->getType();
1198
1199     // Shift Left & Right print both types even for Ubyte LHS, and select prints
1200     // types even if all operands are bools.
1201     if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I)) {
1202       PrintAllTypes = true;
1203     } else {
1204       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1205         Operand = I.getOperand(i);
1206         if (Operand->getType() != TheType) {
1207           PrintAllTypes = true;    // We have differing types!  Print them all!
1208           break;
1209         }
1210       }
1211     }
1212
1213     if (!PrintAllTypes) {
1214       Out << ' ';
1215       printType(TheType);
1216     }
1217
1218     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1219       if (i) Out << ',';
1220       writeOperand(I.getOperand(i), PrintAllTypes);
1221     }
1222   }
1223
1224   printInfoComment(I);
1225   Out << "\n";
1226 }
1227
1228
1229 //===----------------------------------------------------------------------===//
1230 //                       External Interface declarations
1231 //===----------------------------------------------------------------------===//
1232
1233 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1234   SlotMachine SlotTable(this);
1235   AssemblyWriter W(o, SlotTable, this, AAW);
1236   W.write(this);
1237 }
1238
1239 void GlobalVariable::print(std::ostream &o) const {
1240   SlotMachine SlotTable(getParent());
1241   AssemblyWriter W(o, SlotTable, getParent(), 0);
1242   W.write(this);
1243 }
1244
1245 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1246   SlotMachine SlotTable(getParent());
1247   AssemblyWriter W(o, SlotTable, getParent(), AAW);
1248
1249   W.write(this);
1250 }
1251
1252 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1253   SlotMachine SlotTable(getParent());
1254   AssemblyWriter W(o, SlotTable,
1255                    getParent() ? getParent()->getParent() : 0, AAW);
1256   W.write(this);
1257 }
1258
1259 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1260   const Function *F = getParent() ? getParent()->getParent() : 0;
1261   SlotMachine SlotTable(F);
1262   AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1263
1264   W.write(this);
1265 }
1266
1267 void Constant::print(std::ostream &o) const {
1268   if (this == 0) { o << "<null> constant value\n"; return; }
1269
1270   o << ' ' << getType()->getDescription() << ' ';
1271
1272   std::map<const Type *, std::string> TypeTable;
1273   WriteConstantInt(o, this, false, TypeTable, 0);
1274 }
1275
1276 void Type::print(std::ostream &o) const {
1277   if (this == 0)
1278     o << "<null Type>";
1279   else
1280     o << getDescription();
1281 }
1282
1283 void Argument::print(std::ostream &o) const {
1284   WriteAsOperand(o, this, true, true,
1285                  getParent() ? getParent()->getParent() : 0);
1286 }
1287
1288 // Value::dump - allow easy printing of  Values from the debugger.
1289 // Located here because so much of the needed functionality is here.
1290 void Value::dump() const { print(std::cerr); }
1291
1292 // Type::dump - allow easy printing of  Values from the debugger.
1293 // Located here because so much of the needed functionality is here.
1294 void Type::dump() const { print(std::cerr); }
1295
1296 //===----------------------------------------------------------------------===//
1297 //  CachedWriter Class Implementation
1298 //===----------------------------------------------------------------------===//
1299
1300 void CachedWriter::setModule(const Module *M) {
1301   delete SC; delete AW;
1302   if (M) {
1303     SC = new SlotMachine(M );
1304     AW = new AssemblyWriter(Out, *SC, M, 0);
1305   } else {
1306     SC = 0; AW = 0;
1307   }
1308 }
1309
1310 CachedWriter::~CachedWriter() {
1311   delete AW;
1312   delete SC;
1313 }
1314
1315 CachedWriter &CachedWriter::operator<<(const Value &V) {
1316   assert(AW && SC && "CachedWriter does not have a current module!");
1317   if (const Instruction *I = dyn_cast<Instruction>(&V))
1318     AW->write(I);
1319   else if (const BasicBlock *BB = dyn_cast<BasicBlock>(&V))
1320     AW->write(BB);
1321   else if (const Function *F = dyn_cast<Function>(&V))
1322     AW->write(F);
1323   else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(&V))
1324     AW->write(GV);
1325   else
1326     AW->writeOperand(&V, true, true);
1327   return *this;
1328 }
1329
1330 CachedWriter& CachedWriter::operator<<(const Type &Ty) {
1331   if (SymbolicTypes) {
1332     const Module *M = AW->getModule();
1333     if (M) WriteTypeSymbolic(Out, &Ty, M);
1334   } else {
1335     AW->write(&Ty);
1336   }
1337   return *this;
1338 }
1339
1340 //===----------------------------------------------------------------------===//
1341 //===--                    SlotMachine Implementation
1342 //===----------------------------------------------------------------------===//
1343
1344 #if 0
1345 #define SC_DEBUG(X) std::cerr << X
1346 #else
1347 #define SC_DEBUG(X)
1348 #endif
1349
1350 // Module level constructor. Causes the contents of the Module (sans functions)
1351 // to be added to the slot table.
1352 SlotMachine::SlotMachine(const Module *M)
1353   : TheModule(M)    ///< Saved for lazy initialization.
1354   , TheFunction(0)
1355   , FunctionProcessed(false)
1356   , mMap()
1357   , mTypes()
1358   , fMap()
1359   , fTypes()
1360 {
1361 }
1362
1363 // Function level constructor. Causes the contents of the Module and the one
1364 // function provided to be added to the slot table.
1365 SlotMachine::SlotMachine(const Function *F )
1366   : TheModule( F ? F->getParent() : 0 ) ///< Saved for lazy initialization
1367   , TheFunction(F) ///< Saved for lazy initialization
1368   , FunctionProcessed(false)
1369   , mMap()
1370   , mTypes()
1371   , fMap()
1372   , fTypes()
1373 {
1374 }
1375
1376 inline void SlotMachine::initialize(void) {
1377   if ( TheModule) {
1378     processModule();
1379     TheModule = 0; ///< Prevent re-processing next time we're called.
1380   }
1381   if ( TheFunction && ! FunctionProcessed) {
1382     processFunction();
1383   }
1384 }
1385
1386 // Iterate through all the global variables, functions, and global
1387 // variable initializers and create slots for them.
1388 void SlotMachine::processModule() {
1389   SC_DEBUG("begin processModule!\n");
1390
1391   // Add all of the global variables to the value table...
1392   for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end();
1393        I != E; ++I)
1394     createSlot(I);
1395
1396   // Add all the functions to the table
1397   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1398        I != E; ++I)
1399     createSlot(I);
1400
1401   SC_DEBUG("end processModule!\n");
1402 }
1403
1404
1405 // Process the arguments, basic blocks, and instructions  of a function.
1406 void SlotMachine::processFunction() {
1407   SC_DEBUG("begin processFunction!\n");
1408
1409   // Add all the function arguments
1410   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1411       AE = TheFunction->arg_end(); AI != AE; ++AI)
1412     createSlot(AI);
1413
1414   SC_DEBUG("Inserting Instructions:\n");
1415
1416   // Add all of the basic blocks and instructions
1417   for (Function::const_iterator BB = TheFunction->begin(),
1418        E = TheFunction->end(); BB != E; ++BB) {
1419     createSlot(BB);
1420     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
1421       createSlot(I);
1422     }
1423   }
1424
1425   FunctionProcessed = true;
1426
1427   SC_DEBUG("end processFunction!\n");
1428 }
1429
1430 // Clean up after incorporating a function. This is the only way
1431 // to get out of the function incorporation state that affects the
1432 // getSlot/createSlot lock. Function incorporation state is indicated
1433 // by TheFunction != 0.
1434 void SlotMachine::purgeFunction() {
1435   SC_DEBUG("begin purgeFunction!\n");
1436   fMap.clear(); // Simply discard the function level map
1437   fTypes.clear();
1438   TheFunction = 0;
1439   FunctionProcessed = false;
1440   SC_DEBUG("end purgeFunction!\n");
1441 }
1442
1443 /// Get the slot number for a value. This function will assert if you
1444 /// ask for a Value that hasn't previously been inserted with createSlot.
1445 /// Types are forbidden because Type does not inherit from Value (any more).
1446 int SlotMachine::getSlot(const Value *V) {
1447   assert( V && "Can't get slot for null Value" );
1448   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1449     "Can't insert a non-GlobalValue Constant into SlotMachine");
1450
1451   // Check for uninitialized state and do lazy initialization
1452   this->initialize();
1453
1454   // Get the type of the value
1455   const Type* VTy = V->getType();
1456
1457   // Find the type plane in the module map
1458   TypedPlanes::const_iterator MI = mMap.find(VTy);
1459
1460   if ( TheFunction ) {
1461     // Lookup the type in the function map too
1462     TypedPlanes::const_iterator FI = fMap.find(VTy);
1463     // If there is a corresponding type plane in the function map
1464     if ( FI != fMap.end() ) {
1465       // Lookup the Value in the function map
1466       ValueMap::const_iterator FVI = FI->second.map.find(V);
1467       // If the value doesn't exist in the function map
1468       if ( FVI == FI->second.map.end() ) {
1469         // Look up the value in the module map.
1470         if (MI == mMap.end()) return -1;
1471         ValueMap::const_iterator MVI = MI->second.map.find(V);
1472         // If we didn't find it, it wasn't inserted
1473         if (MVI == MI->second.map.end()) return -1;
1474         assert( MVI != MI->second.map.end() && "Value not found");
1475         // We found it only at the module level
1476         return MVI->second;
1477
1478       // else the value exists in the function map
1479       } else {
1480         // Return the slot number as the module's contribution to
1481         // the type plane plus the index in the function's contribution
1482         // to the type plane.
1483         if (MI != mMap.end())
1484           return MI->second.next_slot + FVI->second;
1485         else
1486           return FVI->second;
1487       }
1488     }
1489   }
1490
1491   // N.B. Can get here only if either !TheFunction or the function doesn't
1492   // have a corresponding type plane for the Value
1493
1494   // Make sure the type plane exists
1495   if (MI == mMap.end()) return -1;
1496   // Lookup the value in the module's map
1497   ValueMap::const_iterator MVI = MI->second.map.find(V);
1498   // Make sure we found it.
1499   if (MVI == MI->second.map.end()) return -1;
1500   // Return it.
1501   return MVI->second;
1502 }
1503
1504 /// Get the slot number for a value. This function will assert if you
1505 /// ask for a Value that hasn't previously been inserted with createSlot.
1506 /// Types are forbidden because Type does not inherit from Value (any more).
1507 int SlotMachine::getSlot(const Type *Ty) {
1508   assert( Ty && "Can't get slot for null Type" );
1509
1510   // Check for uninitialized state and do lazy initialization
1511   this->initialize();
1512
1513   if ( TheFunction ) {
1514     // Lookup the Type in the function map
1515     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1516     // If the Type doesn't exist in the function map
1517     if ( FTI == fTypes.map.end() ) {
1518       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1519       // If we didn't find it, it wasn't inserted
1520       if (MTI == mTypes.map.end())
1521         return -1;
1522       // We found it only at the module level
1523       return MTI->second;
1524
1525     // else the value exists in the function map
1526     } else {
1527       // Return the slot number as the module's contribution to
1528       // the type plane plus the index in the function's contribution
1529       // to the type plane.
1530       return mTypes.next_slot + FTI->second;
1531     }
1532   }
1533
1534   // N.B. Can get here only if either !TheFunction
1535
1536   // Lookup the value in the module's map
1537   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1538   // Make sure we found it.
1539   if (MTI == mTypes.map.end()) return -1;
1540   // Return it.
1541   return MTI->second;
1542 }
1543
1544 // Create a new slot, or return the existing slot if it is already
1545 // inserted. Note that the logic here parallels getSlot but instead
1546 // of asserting when the Value* isn't found, it inserts the value.
1547 unsigned SlotMachine::createSlot(const Value *V) {
1548   assert( V && "Can't insert a null Value to SlotMachine");
1549   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1550     "Can't insert a non-GlobalValue Constant into SlotMachine");
1551
1552   const Type* VTy = V->getType();
1553
1554   // Just ignore void typed things
1555   if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1556
1557   // Look up the type plane for the Value's type from the module map
1558   TypedPlanes::const_iterator MI = mMap.find(VTy);
1559
1560   if ( TheFunction ) {
1561     // Get the type plane for the Value's type from the function map
1562     TypedPlanes::const_iterator FI = fMap.find(VTy);
1563     // If there is a corresponding type plane in the function map
1564     if ( FI != fMap.end() ) {
1565       // Lookup the Value in the function map
1566       ValueMap::const_iterator FVI = FI->second.map.find(V);
1567       // If the value doesn't exist in the function map
1568       if ( FVI == FI->second.map.end() ) {
1569         // If there is no corresponding type plane in the module map
1570         if ( MI == mMap.end() )
1571           return insertValue(V);
1572         // Look up the value in the module map
1573         ValueMap::const_iterator MVI = MI->second.map.find(V);
1574         // If we didn't find it, it wasn't inserted
1575         if ( MVI == MI->second.map.end() )
1576           return insertValue(V);
1577         else
1578           // We found it only at the module level
1579           return MVI->second;
1580
1581       // else the value exists in the function map
1582       } else {
1583         if ( MI == mMap.end() )
1584           return FVI->second;
1585         else
1586           // Return the slot number as the module's contribution to
1587           // the type plane plus the index in the function's contribution
1588           // to the type plane.
1589           return MI->second.next_slot + FVI->second;
1590       }
1591
1592     // else there is not a corresponding type plane in the function map
1593     } else {
1594       // If the type plane doesn't exists at the module level
1595       if ( MI == mMap.end() ) {
1596         return insertValue(V);
1597       // else type plane exists at the module level, examine it
1598       } else {
1599         // Look up the value in the module's map
1600         ValueMap::const_iterator MVI = MI->second.map.find(V);
1601         // If we didn't find it there either
1602         if ( MVI == MI->second.map.end() )
1603           // Return the slot number as the module's contribution to
1604           // the type plane plus the index of the function map insertion.
1605           return MI->second.next_slot + insertValue(V);
1606         else
1607           return MVI->second;
1608       }
1609     }
1610   }
1611
1612   // N.B. Can only get here if !TheFunction
1613
1614   // If the module map's type plane is not for the Value's type
1615   if ( MI != mMap.end() ) {
1616     // Lookup the value in the module's map
1617     ValueMap::const_iterator MVI = MI->second.map.find(V);
1618     if ( MVI != MI->second.map.end() )
1619       return MVI->second;
1620   }
1621
1622   return insertValue(V);
1623 }
1624
1625 // Create a new slot, or return the existing slot if it is already
1626 // inserted. Note that the logic here parallels getSlot but instead
1627 // of asserting when the Value* isn't found, it inserts the value.
1628 unsigned SlotMachine::createSlot(const Type *Ty) {
1629   assert( Ty && "Can't insert a null Type to SlotMachine");
1630
1631   if ( TheFunction ) {
1632     // Lookup the Type in the function map
1633     TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1634     // If the type doesn't exist in the function map
1635     if ( FTI == fTypes.map.end() ) {
1636       // Look up the type in the module map
1637       TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1638       // If we didn't find it, it wasn't inserted
1639       if ( MTI == mTypes.map.end() )
1640         return insertValue(Ty);
1641       else
1642         // We found it only at the module level
1643         return MTI->second;
1644
1645     // else the value exists in the function map
1646     } else {
1647       // Return the slot number as the module's contribution to
1648       // the type plane plus the index in the function's contribution
1649       // to the type plane.
1650       return mTypes.next_slot + FTI->second;
1651     }
1652   }
1653
1654   // N.B. Can only get here if !TheFunction
1655
1656   // Lookup the type in the module's map
1657   TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1658   if ( MTI != mTypes.map.end() )
1659     return MTI->second;
1660
1661   return insertValue(Ty);
1662 }
1663
1664 // Low level insert function. Minimal checking is done. This
1665 // function is just for the convenience of createSlot (above).
1666 unsigned SlotMachine::insertValue(const Value *V ) {
1667   assert(V && "Can't insert a null Value into SlotMachine!");
1668   assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1669     "Can't insert a non-GlobalValue Constant into SlotMachine");
1670
1671   // If this value does not contribute to a plane (is void)
1672   // or if the value already has a name then ignore it.
1673   if (V->getType() == Type::VoidTy || V->hasName() ) {
1674       SC_DEBUG("ignored value " << *V << "\n");
1675       return 0;   // FIXME: Wrong return value
1676   }
1677
1678   const Type *VTy = V->getType();
1679   unsigned DestSlot = 0;
1680
1681   if ( TheFunction ) {
1682     TypedPlanes::iterator I = fMap.find( VTy );
1683     if ( I == fMap.end() )
1684       I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1685     DestSlot = I->second.map[V] = I->second.next_slot++;
1686   } else {
1687     TypedPlanes::iterator I = mMap.find( VTy );
1688     if ( I == mMap.end() )
1689       I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1690     DestSlot = I->second.map[V] = I->second.next_slot++;
1691   }
1692
1693   SC_DEBUG("  Inserting value [" << VTy << "] = " << V << " slot=" <<
1694            DestSlot << " [");
1695   // G = Global, C = Constant, T = Type, F = Function, o = other
1696   SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1697            (isa<Constant>(V) ? 'C' : 'o'))));
1698   SC_DEBUG("]\n");
1699   return DestSlot;
1700 }
1701
1702 // Low level insert function. Minimal checking is done. This
1703 // function is just for the convenience of createSlot (above).
1704 unsigned SlotMachine::insertValue(const Type *Ty ) {
1705   assert(Ty && "Can't insert a null Type into SlotMachine!");
1706
1707   unsigned DestSlot = 0;
1708
1709   if ( TheFunction ) {
1710     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1711   } else {
1712     DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1713   }
1714   SC_DEBUG("  Inserting type [" << DestSlot << "] = " << Ty << "\n");
1715   return DestSlot;
1716 }
1717
1718 // vim: sw=2