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