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