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