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