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