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