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