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