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