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