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