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