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