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