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