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