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