Kill off <TARGET>MachineModule variables, and <TARGETASMPRINTER>ForceLink
[oota-llvm.git] / lib / Target / CppBackend / CPPBackend.cpp
1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
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 file implements the writing of the LLVM IR as a set of C++ calls to the
11 // LLVM IR interface. The input module is assumed to be verified.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CPPTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instruction.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/PassManager.h"
25 #include "llvm/TypeSymbolTable.h"
26 #include "llvm/Target/TargetMachineRegistry.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Streams.h"
34 #include "llvm/Config/config.h"
35 #include <algorithm>
36 #include <set>
37
38 using namespace llvm;
39
40 static cl::opt<std::string>
41 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
42          cl::value_desc("function name"));
43
44 enum WhatToGenerate {
45   GenProgram,
46   GenModule,
47   GenContents,
48   GenFunction,
49   GenFunctions,
50   GenInline,
51   GenVariable,
52   GenType
53 };
54
55 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
56   cl::desc("Choose what kind of output to generate"),
57   cl::init(GenProgram),
58   cl::values(
59     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
60     clEnumValN(GenModule,   "module",    "Generate a module definition"),
61     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
62     clEnumValN(GenFunction, "function",  "Generate a function definition"),
63     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
64     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
65     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
66     clEnumValN(GenType,     "type",      "Generate a type definition"),
67     clEnumValEnd
68   )
69 );
70
71 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
72   cl::desc("Specify the name of the thing to generate"),
73   cl::init("!bad!"));
74
75 // Register the target.
76 extern Target TheCppBackendTarget;
77 static RegisterTarget<CPPTargetMachine> X(TheCppBackendTarget, "cpp", "C++ backend");
78
79 // Force static initialization.
80 extern "C" void LLVMInitializeCppBackendTarget() { }
81
82 namespace {
83   typedef std::vector<const Type*> TypeList;
84   typedef std::map<const Type*,std::string> TypeMap;
85   typedef std::map<const Value*,std::string> ValueMap;
86   typedef std::set<std::string> NameSet;
87   typedef std::set<const Type*> TypeSet;
88   typedef std::set<const Value*> ValueSet;
89   typedef std::map<const Value*,std::string> ForwardRefMap;
90
91   /// CppWriter - This class is the main chunk of code that converts an LLVM
92   /// module to a C++ translation unit.
93   class CppWriter : public ModulePass {
94     formatted_raw_ostream &Out;
95     const Module *TheModule;
96     uint64_t uniqueNum;
97     TypeMap TypeNames;
98     ValueMap ValueNames;
99     TypeMap UnresolvedTypes;
100     TypeList TypeStack;
101     NameSet UsedNames;
102     TypeSet DefinedTypes;
103     ValueSet DefinedValues;
104     ForwardRefMap ForwardRefs;
105     bool is_inline;
106
107   public:
108     static char ID;
109     explicit CppWriter(formatted_raw_ostream &o) :
110       ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {}
111
112     virtual const char *getPassName() const { return "C++ backend"; }
113
114     bool runOnModule(Module &M);
115
116     void printProgram(const std::string& fname, const std::string& modName );
117     void printModule(const std::string& fname, const std::string& modName );
118     void printContents(const std::string& fname, const std::string& modName );
119     void printFunction(const std::string& fname, const std::string& funcName );
120     void printFunctions();
121     void printInline(const std::string& fname, const std::string& funcName );
122     void printVariable(const std::string& fname, const std::string& varName );
123     void printType(const std::string& fname, const std::string& typeName );
124
125     void error(const std::string& msg);
126
127   private:
128     void printLinkageType(GlobalValue::LinkageTypes LT);
129     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
130     void printCallingConv(unsigned cc);
131     void printEscapedString(const std::string& str);
132     void printCFP(const ConstantFP* CFP);
133
134     std::string getCppName(const Type* val);
135     inline void printCppName(const Type* val);
136
137     std::string getCppName(const Value* val);
138     inline void printCppName(const Value* val);
139
140     void printAttributes(const AttrListPtr &PAL, const std::string &name);
141     bool printTypeInternal(const Type* Ty);
142     inline void printType(const Type* Ty);
143     void printTypes(const Module* M);
144
145     void printConstant(const Constant *CPV);
146     void printConstants(const Module* M);
147
148     void printVariableUses(const GlobalVariable *GV);
149     void printVariableHead(const GlobalVariable *GV);
150     void printVariableBody(const GlobalVariable *GV);
151
152     void printFunctionUses(const Function *F);
153     void printFunctionHead(const Function *F);
154     void printFunctionBody(const Function *F);
155     void printInstruction(const Instruction *I, const std::string& bbname);
156     std::string getOpName(Value*);
157
158     void printModuleBody();
159   };
160
161   static unsigned indent_level = 0;
162   inline formatted_raw_ostream& nl(formatted_raw_ostream& Out, int delta = 0) {
163     Out << "\n";
164     if (delta >= 0 || indent_level >= unsigned(-delta))
165       indent_level += delta;
166     for (unsigned i = 0; i < indent_level; ++i)
167       Out << "  ";
168     return Out;
169   }
170
171   inline void in() { indent_level++; }
172   inline void out() { if (indent_level >0) indent_level--; }
173
174   inline void
175   sanitize(std::string& str) {
176     for (size_t i = 0; i < str.length(); ++i)
177       if (!isalnum(str[i]) && str[i] != '_')
178         str[i] = '_';
179   }
180
181   inline std::string
182   getTypePrefix(const Type* Ty ) {
183     switch (Ty->getTypeID()) {
184     case Type::VoidTyID:     return "void_";
185     case Type::IntegerTyID:
186       return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) +
187         "_";
188     case Type::FloatTyID:    return "float_";
189     case Type::DoubleTyID:   return "double_";
190     case Type::LabelTyID:    return "label_";
191     case Type::FunctionTyID: return "func_";
192     case Type::StructTyID:   return "struct_";
193     case Type::ArrayTyID:    return "array_";
194     case Type::PointerTyID:  return "ptr_";
195     case Type::VectorTyID:   return "packed_";
196     case Type::OpaqueTyID:   return "opaque_";
197     default:                 return "other_";
198     }
199     return "unknown_";
200   }
201
202   // Looks up the type in the symbol table and returns a pointer to its name or
203   // a null pointer if it wasn't found. Note that this isn't the same as the
204   // Mode::getTypeName function which will return an empty string, not a null
205   // pointer if the name is not found.
206   inline const std::string*
207   findTypeName(const TypeSymbolTable& ST, const Type* Ty) {
208     TypeSymbolTable::const_iterator TI = ST.begin();
209     TypeSymbolTable::const_iterator TE = ST.end();
210     for (;TI != TE; ++TI)
211       if (TI->second == Ty)
212         return &(TI->first);
213     return 0;
214   }
215
216   void CppWriter::error(const std::string& msg) {
217     llvm_report_error(msg);
218   }
219
220   // printCFP - Print a floating point constant .. very carefully :)
221   // This makes sure that conversion to/from floating yields the same binary
222   // result so that we don't lose precision.
223   void CppWriter::printCFP(const ConstantFP *CFP) {
224     bool ignored;
225     APFloat APF = APFloat(CFP->getValueAPF());  // copy
226     if (CFP->getType() == Type::FloatTy)
227       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
228     Out << "ConstantFP::get(";
229     Out << "APFloat(";
230 #if HAVE_PRINTF_A
231     char Buffer[100];
232     sprintf(Buffer, "%A", APF.convertToDouble());
233     if ((!strncmp(Buffer, "0x", 2) ||
234          !strncmp(Buffer, "-0x", 3) ||
235          !strncmp(Buffer, "+0x", 3)) &&
236         APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
237       if (CFP->getType() == Type::DoubleTy)
238         Out << "BitsToDouble(" << Buffer << ")";
239       else
240         Out << "BitsToFloat((float)" << Buffer << ")";
241       Out << ")";
242     } else {
243 #endif
244       std::string StrVal = ftostr(CFP->getValueAPF());
245
246       while (StrVal[0] == ' ')
247         StrVal.erase(StrVal.begin());
248
249       // Check to make sure that the stringized number is not some string like
250       // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
251       if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
252            ((StrVal[0] == '-' || StrVal[0] == '+') &&
253             (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
254           (CFP->isExactlyValue(atof(StrVal.c_str())))) {
255         if (CFP->getType() == Type::DoubleTy)
256           Out <<  StrVal;
257         else
258           Out << StrVal << "f";
259       } else if (CFP->getType() == Type::DoubleTy)
260         Out << "BitsToDouble(0x"
261             << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
262             << "ULL) /* " << StrVal << " */";
263       else
264         Out << "BitsToFloat(0x"
265             << utohexstr((uint32_t)CFP->getValueAPF().
266                                         bitcastToAPInt().getZExtValue())
267             << "U) /* " << StrVal << " */";
268       Out << ")";
269 #if HAVE_PRINTF_A
270     }
271 #endif
272     Out << ")";
273   }
274
275   void CppWriter::printCallingConv(unsigned cc){
276     // Print the calling convention.
277     switch (cc) {
278     case CallingConv::C:     Out << "CallingConv::C"; break;
279     case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
280     case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
281     case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
282     default:                 Out << cc; break;
283     }
284   }
285
286   void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
287     switch (LT) {
288     case GlobalValue::InternalLinkage:
289       Out << "GlobalValue::InternalLinkage"; break;
290     case GlobalValue::PrivateLinkage:
291       Out << "GlobalValue::PrivateLinkage"; break;
292     case GlobalValue::AvailableExternallyLinkage:
293       Out << "GlobalValue::AvailableExternallyLinkage "; break;
294     case GlobalValue::LinkOnceAnyLinkage:
295       Out << "GlobalValue::LinkOnceAnyLinkage "; break;
296     case GlobalValue::LinkOnceODRLinkage:
297       Out << "GlobalValue::LinkOnceODRLinkage "; break;
298     case GlobalValue::WeakAnyLinkage:
299       Out << "GlobalValue::WeakAnyLinkage"; break;
300     case GlobalValue::WeakODRLinkage:
301       Out << "GlobalValue::WeakODRLinkage"; break;
302     case GlobalValue::AppendingLinkage:
303       Out << "GlobalValue::AppendingLinkage"; break;
304     case GlobalValue::ExternalLinkage:
305       Out << "GlobalValue::ExternalLinkage"; break;
306     case GlobalValue::DLLImportLinkage:
307       Out << "GlobalValue::DLLImportLinkage"; break;
308     case GlobalValue::DLLExportLinkage:
309       Out << "GlobalValue::DLLExportLinkage"; break;
310     case GlobalValue::ExternalWeakLinkage:
311       Out << "GlobalValue::ExternalWeakLinkage"; break;
312     case GlobalValue::GhostLinkage:
313       Out << "GlobalValue::GhostLinkage"; break;
314     case GlobalValue::CommonLinkage:
315       Out << "GlobalValue::CommonLinkage"; break;
316     }
317   }
318
319   void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
320     switch (VisType) {
321     default: llvm_unreachable("Unknown GVar visibility");
322     case GlobalValue::DefaultVisibility:
323       Out << "GlobalValue::DefaultVisibility";
324       break;
325     case GlobalValue::HiddenVisibility:
326       Out << "GlobalValue::HiddenVisibility";
327       break;
328     case GlobalValue::ProtectedVisibility:
329       Out << "GlobalValue::ProtectedVisibility";
330       break;
331     }
332   }
333
334   // printEscapedString - Print each character of the specified string, escaping
335   // it if it is not printable or if it is an escape char.
336   void CppWriter::printEscapedString(const std::string &Str) {
337     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
338       unsigned char C = Str[i];
339       if (isprint(C) && C != '"' && C != '\\') {
340         Out << C;
341       } else {
342         Out << "\\x"
343             << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
344             << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
345       }
346     }
347   }
348
349   std::string CppWriter::getCppName(const Type* Ty) {
350     // First, handle the primitive types .. easy
351     if (Ty->isPrimitiveType() || Ty->isInteger()) {
352       switch (Ty->getTypeID()) {
353       case Type::VoidTyID:   return "Type::VoidTy";
354       case Type::IntegerTyID: {
355         unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
356         return "IntegerType::get(" + utostr(BitWidth) + ")";
357       }
358       case Type::X86_FP80TyID: return "Type::X86_FP80Ty";
359       case Type::FloatTyID:    return "Type::FloatTy";
360       case Type::DoubleTyID:   return "Type::DoubleTy";
361       case Type::LabelTyID:    return "Type::LabelTy";
362       default:
363         error("Invalid primitive type");
364         break;
365       }
366       return "Type::VoidTy"; // shouldn't be returned, but make it sensible
367     }
368
369     // Now, see if we've seen the type before and return that
370     TypeMap::iterator I = TypeNames.find(Ty);
371     if (I != TypeNames.end())
372       return I->second;
373
374     // Okay, let's build a new name for this type. Start with a prefix
375     const char* prefix = 0;
376     switch (Ty->getTypeID()) {
377     case Type::FunctionTyID:    prefix = "FuncTy_"; break;
378     case Type::StructTyID:      prefix = "StructTy_"; break;
379     case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
380     case Type::PointerTyID:     prefix = "PointerTy_"; break;
381     case Type::OpaqueTyID:      prefix = "OpaqueTy_"; break;
382     case Type::VectorTyID:      prefix = "VectorTy_"; break;
383     default:                    prefix = "OtherTy_"; break; // prevent breakage
384     }
385
386     // See if the type has a name in the symboltable and build accordingly
387     const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty);
388     std::string name;
389     if (tName)
390       name = std::string(prefix) + *tName;
391     else
392       name = std::string(prefix) + utostr(uniqueNum++);
393     sanitize(name);
394
395     // Save the name
396     return TypeNames[Ty] = name;
397   }
398
399   void CppWriter::printCppName(const Type* Ty) {
400     printEscapedString(getCppName(Ty));
401   }
402
403   std::string CppWriter::getCppName(const Value* val) {
404     std::string name;
405     ValueMap::iterator I = ValueNames.find(val);
406     if (I != ValueNames.end() && I->first == val)
407       return  I->second;
408
409     if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
410       name = std::string("gvar_") +
411         getTypePrefix(GV->getType()->getElementType());
412     } else if (isa<Function>(val)) {
413       name = std::string("func_");
414     } else if (const Constant* C = dyn_cast<Constant>(val)) {
415       name = std::string("const_") + getTypePrefix(C->getType());
416     } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
417       if (is_inline) {
418         unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
419                                         Function::const_arg_iterator(Arg)) + 1;
420         name = std::string("arg_") + utostr(argNum);
421         NameSet::iterator NI = UsedNames.find(name);
422         if (NI != UsedNames.end())
423           name += std::string("_") + utostr(uniqueNum++);
424         UsedNames.insert(name);
425         return ValueNames[val] = name;
426       } else {
427         name = getTypePrefix(val->getType());
428       }
429     } else {
430       name = getTypePrefix(val->getType());
431     }
432     name += (val->hasName() ? val->getName() : utostr(uniqueNum++));
433     sanitize(name);
434     NameSet::iterator NI = UsedNames.find(name);
435     if (NI != UsedNames.end())
436       name += std::string("_") + utostr(uniqueNum++);
437     UsedNames.insert(name);
438     return ValueNames[val] = name;
439   }
440
441   void CppWriter::printCppName(const Value* val) {
442     printEscapedString(getCppName(val));
443   }
444
445   void CppWriter::printAttributes(const AttrListPtr &PAL,
446                                   const std::string &name) {
447     Out << "AttrListPtr " << name << "_PAL;";
448     nl(Out);
449     if (!PAL.isEmpty()) {
450       Out << '{'; in(); nl(Out);
451       Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out);
452       Out << "AttributeWithIndex PAWI;"; nl(Out);
453       for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
454         unsigned index = PAL.getSlot(i).Index;
455         Attributes attrs = PAL.getSlot(i).Attrs;
456         Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 ";
457 #define HANDLE_ATTR(X)                 \
458         if (attrs & Attribute::X)      \
459           Out << " | Attribute::" #X;  \
460         attrs &= ~Attribute::X;
461         
462         HANDLE_ATTR(SExt);
463         HANDLE_ATTR(ZExt);
464         HANDLE_ATTR(NoReturn);
465         HANDLE_ATTR(InReg);
466         HANDLE_ATTR(StructRet);
467         HANDLE_ATTR(NoUnwind);
468         HANDLE_ATTR(NoAlias);
469         HANDLE_ATTR(ByVal);
470         HANDLE_ATTR(Nest);
471         HANDLE_ATTR(ReadNone);
472         HANDLE_ATTR(ReadOnly);
473         HANDLE_ATTR(NoInline);
474         HANDLE_ATTR(AlwaysInline);
475         HANDLE_ATTR(OptimizeForSize);
476         HANDLE_ATTR(StackProtect);
477         HANDLE_ATTR(StackProtectReq);
478         HANDLE_ATTR(NoCapture);
479 #undef HANDLE_ATTR
480         assert(attrs == 0 && "Unhandled attribute!");
481         Out << ";";
482         nl(Out);
483         Out << "Attrs.push_back(PAWI);";
484         nl(Out);
485       }
486       Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());";
487       nl(Out);
488       out(); nl(Out);
489       Out << '}'; nl(Out);
490     }
491   }
492
493   bool CppWriter::printTypeInternal(const Type* Ty) {
494     // We don't print definitions for primitive types
495     if (Ty->isPrimitiveType() || Ty->isInteger())
496       return false;
497
498     // If we already defined this type, we don't need to define it again.
499     if (DefinedTypes.find(Ty) != DefinedTypes.end())
500       return false;
501
502     // Everything below needs the name for the type so get it now.
503     std::string typeName(getCppName(Ty));
504
505     // Search the type stack for recursion. If we find it, then generate this
506     // as an OpaqueType, but make sure not to do this multiple times because
507     // the type could appear in multiple places on the stack. Once the opaque
508     // definition is issued, it must not be re-issued. Consequently we have to
509     // check the UnresolvedTypes list as well.
510     TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(),
511                                             Ty);
512     if (TI != TypeStack.end()) {
513       TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
514       if (I == UnresolvedTypes.end()) {
515         Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();";
516         nl(Out);
517         UnresolvedTypes[Ty] = typeName;
518       }
519       return true;
520     }
521
522     // We're going to print a derived type which, by definition, contains other
523     // types. So, push this one we're printing onto the type stack to assist with
524     // recursive definitions.
525     TypeStack.push_back(Ty);
526
527     // Print the type definition
528     switch (Ty->getTypeID()) {
529     case Type::FunctionTyID:  {
530       const FunctionType* FT = cast<FunctionType>(Ty);
531       Out << "std::vector<const Type*>" << typeName << "_args;";
532       nl(Out);
533       FunctionType::param_iterator PI = FT->param_begin();
534       FunctionType::param_iterator PE = FT->param_end();
535       for (; PI != PE; ++PI) {
536         const Type* argTy = static_cast<const Type*>(*PI);
537         bool isForward = printTypeInternal(argTy);
538         std::string argName(getCppName(argTy));
539         Out << typeName << "_args.push_back(" << argName;
540         if (isForward)
541           Out << "_fwd";
542         Out << ");";
543         nl(Out);
544       }
545       bool isForward = printTypeInternal(FT->getReturnType());
546       std::string retTypeName(getCppName(FT->getReturnType()));
547       Out << "FunctionType* " << typeName << " = FunctionType::get(";
548       in(); nl(Out) << "/*Result=*/" << retTypeName;
549       if (isForward)
550         Out << "_fwd";
551       Out << ",";
552       nl(Out) << "/*Params=*/" << typeName << "_args,";
553       nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
554       out();
555       nl(Out);
556       break;
557     }
558     case Type::StructTyID: {
559       const StructType* ST = cast<StructType>(Ty);
560       Out << "std::vector<const Type*>" << typeName << "_fields;";
561       nl(Out);
562       StructType::element_iterator EI = ST->element_begin();
563       StructType::element_iterator EE = ST->element_end();
564       for (; EI != EE; ++EI) {
565         const Type* fieldTy = static_cast<const Type*>(*EI);
566         bool isForward = printTypeInternal(fieldTy);
567         std::string fieldName(getCppName(fieldTy));
568         Out << typeName << "_fields.push_back(" << fieldName;
569         if (isForward)
570           Out << "_fwd";
571         Out << ");";
572         nl(Out);
573       }
574       Out << "StructType* " << typeName << " = StructType::get("
575           << typeName << "_fields, /*isPacked=*/"
576           << (ST->isPacked() ? "true" : "false") << ");";
577       nl(Out);
578       break;
579     }
580     case Type::ArrayTyID: {
581       const ArrayType* AT = cast<ArrayType>(Ty);
582       const Type* ET = AT->getElementType();
583       bool isForward = printTypeInternal(ET);
584       std::string elemName(getCppName(ET));
585       Out << "ArrayType* " << typeName << " = ArrayType::get("
586           << elemName << (isForward ? "_fwd" : "")
587           << ", " << utostr(AT->getNumElements()) << ");";
588       nl(Out);
589       break;
590     }
591     case Type::PointerTyID: {
592       const PointerType* PT = cast<PointerType>(Ty);
593       const Type* ET = PT->getElementType();
594       bool isForward = printTypeInternal(ET);
595       std::string elemName(getCppName(ET));
596       Out << "PointerType* " << typeName << " = PointerType::get("
597           << elemName << (isForward ? "_fwd" : "")
598           << ", " << utostr(PT->getAddressSpace()) << ");";
599       nl(Out);
600       break;
601     }
602     case Type::VectorTyID: {
603       const VectorType* PT = cast<VectorType>(Ty);
604       const Type* ET = PT->getElementType();
605       bool isForward = printTypeInternal(ET);
606       std::string elemName(getCppName(ET));
607       Out << "VectorType* " << typeName << " = VectorType::get("
608           << elemName << (isForward ? "_fwd" : "")
609           << ", " << utostr(PT->getNumElements()) << ");";
610       nl(Out);
611       break;
612     }
613     case Type::OpaqueTyID: {
614       Out << "OpaqueType* " << typeName << " = OpaqueType::get();";
615       nl(Out);
616       break;
617     }
618     default:
619       error("Invalid TypeID");
620     }
621
622     // If the type had a name, make sure we recreate it.
623     const std::string* progTypeName =
624       findTypeName(TheModule->getTypeSymbolTable(),Ty);
625     if (progTypeName) {
626       Out << "mod->addTypeName(\"" << *progTypeName << "\", "
627           << typeName << ");";
628       nl(Out);
629     }
630
631     // Pop us off the type stack
632     TypeStack.pop_back();
633
634     // Indicate that this type is now defined.
635     DefinedTypes.insert(Ty);
636
637     // Early resolve as many unresolved types as possible. Search the unresolved
638     // types map for the type we just printed. Now that its definition is complete
639     // we can resolve any previous references to it. This prevents a cascade of
640     // unresolved types.
641     TypeMap::iterator I = UnresolvedTypes.find(Ty);
642     if (I != UnresolvedTypes.end()) {
643       Out << "cast<OpaqueType>(" << I->second
644           << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");";
645       nl(Out);
646       Out << I->second << " = cast<";
647       switch (Ty->getTypeID()) {
648       case Type::FunctionTyID: Out << "FunctionType"; break;
649       case Type::ArrayTyID:    Out << "ArrayType"; break;
650       case Type::StructTyID:   Out << "StructType"; break;
651       case Type::VectorTyID:   Out << "VectorType"; break;
652       case Type::PointerTyID:  Out << "PointerType"; break;
653       case Type::OpaqueTyID:   Out << "OpaqueType"; break;
654       default:                 Out << "NoSuchDerivedType"; break;
655       }
656       Out << ">(" << I->second << "_fwd.get());";
657       nl(Out); nl(Out);
658       UnresolvedTypes.erase(I);
659     }
660
661     // Finally, separate the type definition from other with a newline.
662     nl(Out);
663
664     // We weren't a recursive type
665     return false;
666   }
667
668   // Prints a type definition. Returns true if it could not resolve all the
669   // types in the definition but had to use a forward reference.
670   void CppWriter::printType(const Type* Ty) {
671     assert(TypeStack.empty());
672     TypeStack.clear();
673     printTypeInternal(Ty);
674     assert(TypeStack.empty());
675   }
676
677   void CppWriter::printTypes(const Module* M) {
678     // Walk the symbol table and print out all its types
679     const TypeSymbolTable& symtab = M->getTypeSymbolTable();
680     for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end();
681          TI != TE; ++TI) {
682
683       // For primitive types and types already defined, just add a name
684       TypeMap::const_iterator TNI = TypeNames.find(TI->second);
685       if (TI->second->isInteger() || TI->second->isPrimitiveType() ||
686           TNI != TypeNames.end()) {
687         Out << "mod->addTypeName(\"";
688         printEscapedString(TI->first);
689         Out << "\", " << getCppName(TI->second) << ");";
690         nl(Out);
691         // For everything else, define the type
692       } else {
693         printType(TI->second);
694       }
695     }
696
697     // Add all of the global variables to the value table...
698     for (Module::const_global_iterator I = TheModule->global_begin(),
699            E = TheModule->global_end(); I != E; ++I) {
700       if (I->hasInitializer())
701         printType(I->getInitializer()->getType());
702       printType(I->getType());
703     }
704
705     // Add all the functions to the table
706     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
707          FI != FE; ++FI) {
708       printType(FI->getReturnType());
709       printType(FI->getFunctionType());
710       // Add all the function arguments
711       for (Function::const_arg_iterator AI = FI->arg_begin(),
712              AE = FI->arg_end(); AI != AE; ++AI) {
713         printType(AI->getType());
714       }
715
716       // Add all of the basic blocks and instructions
717       for (Function::const_iterator BB = FI->begin(),
718              E = FI->end(); BB != E; ++BB) {
719         printType(BB->getType());
720         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
721              ++I) {
722           printType(I->getType());
723           for (unsigned i = 0; i < I->getNumOperands(); ++i)
724             printType(I->getOperand(i)->getType());
725         }
726       }
727     }
728   }
729
730
731   // printConstant - Print out a constant pool entry...
732   void CppWriter::printConstant(const Constant *CV) {
733     // First, if the constant is actually a GlobalValue (variable or function)
734     // or its already in the constant list then we've printed it already and we
735     // can just return.
736     if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
737       return;
738
739     std::string constName(getCppName(CV));
740     std::string typeName(getCppName(CV->getType()));
741
742     if (isa<GlobalValue>(CV)) {
743       // Skip variables and functions, we emit them elsewhere
744       return;
745     }
746
747     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
748       std::string constValue = CI->getValue().toString(10, true);
749       Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt("
750           << cast<IntegerType>(CI->getType())->getBitWidth() << ",  \""
751           <<  constValue << "\", " << constValue.length() << ", 10));";
752     } else if (isa<ConstantAggregateZero>(CV)) {
753       Out << "ConstantAggregateZero* " << constName
754           << " = ConstantAggregateZero::get(" << typeName << ");";
755     } else if (isa<ConstantPointerNull>(CV)) {
756       Out << "ConstantPointerNull* " << constName
757           << " = ConstantPointerNull::get(" << typeName << ");";
758     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
759       Out << "ConstantFP* " << constName << " = ";
760       printCFP(CFP);
761       Out << ";";
762     } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
763       if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) {
764         Out << "Constant* " << constName << " = ConstantArray::get(\"";
765         std::string tmp = CA->getAsString();
766         bool nullTerminate = false;
767         if (tmp[tmp.length()-1] == 0) {
768           tmp.erase(tmp.length()-1);
769           nullTerminate = true;
770         }
771         printEscapedString(tmp);
772         // Determine if we want null termination or not.
773         if (nullTerminate)
774           Out << "\", true"; // Indicate that the null terminator should be
775                              // added.
776         else
777           Out << "\", false";// No null terminator
778         Out << ");";
779       } else {
780         Out << "std::vector<Constant*> " << constName << "_elems;";
781         nl(Out);
782         unsigned N = CA->getNumOperands();
783         for (unsigned i = 0; i < N; ++i) {
784           printConstant(CA->getOperand(i)); // recurse to print operands
785           Out << constName << "_elems.push_back("
786               << getCppName(CA->getOperand(i)) << ");";
787           nl(Out);
788         }
789         Out << "Constant* " << constName << " = ConstantArray::get("
790             << typeName << ", " << constName << "_elems);";
791       }
792     } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
793       Out << "std::vector<Constant*> " << constName << "_fields;";
794       nl(Out);
795       unsigned N = CS->getNumOperands();
796       for (unsigned i = 0; i < N; i++) {
797         printConstant(CS->getOperand(i));
798         Out << constName << "_fields.push_back("
799             << getCppName(CS->getOperand(i)) << ");";
800         nl(Out);
801       }
802       Out << "Constant* " << constName << " = ConstantStruct::get("
803           << typeName << ", " << constName << "_fields);";
804     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
805       Out << "std::vector<Constant*> " << constName << "_elems;";
806       nl(Out);
807       unsigned N = CP->getNumOperands();
808       for (unsigned i = 0; i < N; ++i) {
809         printConstant(CP->getOperand(i));
810         Out << constName << "_elems.push_back("
811             << getCppName(CP->getOperand(i)) << ");";
812         nl(Out);
813       }
814       Out << "Constant* " << constName << " = ConstantVector::get("
815           << typeName << ", " << constName << "_elems);";
816     } else if (isa<UndefValue>(CV)) {
817       Out << "UndefValue* " << constName << " = UndefValue::get("
818           << typeName << ");";
819     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
820       if (CE->getOpcode() == Instruction::GetElementPtr) {
821         Out << "std::vector<Constant*> " << constName << "_indices;";
822         nl(Out);
823         printConstant(CE->getOperand(0));
824         for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
825           printConstant(CE->getOperand(i));
826           Out << constName << "_indices.push_back("
827               << getCppName(CE->getOperand(i)) << ");";
828           nl(Out);
829         }
830         Out << "Constant* " << constName
831             << " = ConstantExpr::getGetElementPtr("
832             << getCppName(CE->getOperand(0)) << ", "
833             << "&" << constName << "_indices[0], "
834             << constName << "_indices.size()"
835             << " );";
836       } else if (CE->isCast()) {
837         printConstant(CE->getOperand(0));
838         Out << "Constant* " << constName << " = ConstantExpr::getCast(";
839         switch (CE->getOpcode()) {
840         default: llvm_unreachable("Invalid cast opcode");
841         case Instruction::Trunc: Out << "Instruction::Trunc"; break;
842         case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
843         case Instruction::SExt:  Out << "Instruction::SExt"; break;
844         case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
845         case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
846         case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
847         case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
848         case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
849         case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
850         case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
851         case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
852         case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
853         }
854         Out << ", " << getCppName(CE->getOperand(0)) << ", "
855             << getCppName(CE->getType()) << ");";
856       } else {
857         unsigned N = CE->getNumOperands();
858         for (unsigned i = 0; i < N; ++i ) {
859           printConstant(CE->getOperand(i));
860         }
861         Out << "Constant* " << constName << " = ConstantExpr::";
862         switch (CE->getOpcode()) {
863         case Instruction::Add:    Out << "getAdd(";  break;
864         case Instruction::FAdd:   Out << "getFAdd(";  break;
865         case Instruction::Sub:    Out << "getSub("; break;
866         case Instruction::FSub:   Out << "getFSub("; break;
867         case Instruction::Mul:    Out << "getMul("; break;
868         case Instruction::FMul:   Out << "getFMul("; break;
869         case Instruction::UDiv:   Out << "getUDiv("; break;
870         case Instruction::SDiv:   Out << "getSDiv("; break;
871         case Instruction::FDiv:   Out << "getFDiv("; break;
872         case Instruction::URem:   Out << "getURem("; break;
873         case Instruction::SRem:   Out << "getSRem("; break;
874         case Instruction::FRem:   Out << "getFRem("; break;
875         case Instruction::And:    Out << "getAnd("; break;
876         case Instruction::Or:     Out << "getOr("; break;
877         case Instruction::Xor:    Out << "getXor("; break;
878         case Instruction::ICmp:
879           Out << "getICmp(ICmpInst::ICMP_";
880           switch (CE->getPredicate()) {
881           case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
882           case ICmpInst::ICMP_NE:  Out << "NE"; break;
883           case ICmpInst::ICMP_SLT: Out << "SLT"; break;
884           case ICmpInst::ICMP_ULT: Out << "ULT"; break;
885           case ICmpInst::ICMP_SGT: Out << "SGT"; break;
886           case ICmpInst::ICMP_UGT: Out << "UGT"; break;
887           case ICmpInst::ICMP_SLE: Out << "SLE"; break;
888           case ICmpInst::ICMP_ULE: Out << "ULE"; break;
889           case ICmpInst::ICMP_SGE: Out << "SGE"; break;
890           case ICmpInst::ICMP_UGE: Out << "UGE"; break;
891           default: error("Invalid ICmp Predicate");
892           }
893           break;
894         case Instruction::FCmp:
895           Out << "getFCmp(FCmpInst::FCMP_";
896           switch (CE->getPredicate()) {
897           case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
898           case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
899           case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
900           case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
901           case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
902           case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
903           case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
904           case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
905           case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
906           case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
907           case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
908           case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
909           case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
910           case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
911           case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
912           case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
913           default: error("Invalid FCmp Predicate");
914           }
915           break;
916         case Instruction::Shl:     Out << "getShl("; break;
917         case Instruction::LShr:    Out << "getLShr("; break;
918         case Instruction::AShr:    Out << "getAShr("; break;
919         case Instruction::Select:  Out << "getSelect("; break;
920         case Instruction::ExtractElement: Out << "getExtractElement("; break;
921         case Instruction::InsertElement:  Out << "getInsertElement("; break;
922         case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
923         default:
924           error("Invalid constant expression");
925           break;
926         }
927         Out << getCppName(CE->getOperand(0));
928         for (unsigned i = 1; i < CE->getNumOperands(); ++i)
929           Out << ", " << getCppName(CE->getOperand(i));
930         Out << ");";
931       }
932     } else {
933       error("Bad Constant");
934       Out << "Constant* " << constName << " = 0; ";
935     }
936     nl(Out);
937   }
938
939   void CppWriter::printConstants(const Module* M) {
940     // Traverse all the global variables looking for constant initializers
941     for (Module::const_global_iterator I = TheModule->global_begin(),
942            E = TheModule->global_end(); I != E; ++I)
943       if (I->hasInitializer())
944         printConstant(I->getInitializer());
945
946     // Traverse the LLVM functions looking for constants
947     for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
948          FI != FE; ++FI) {
949       // Add all of the basic blocks and instructions
950       for (Function::const_iterator BB = FI->begin(),
951              E = FI->end(); BB != E; ++BB) {
952         for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
953              ++I) {
954           for (unsigned i = 0; i < I->getNumOperands(); ++i) {
955             if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
956               printConstant(C);
957             }
958           }
959         }
960       }
961     }
962   }
963
964   void CppWriter::printVariableUses(const GlobalVariable *GV) {
965     nl(Out) << "// Type Definitions";
966     nl(Out);
967     printType(GV->getType());
968     if (GV->hasInitializer()) {
969       Constant* Init = GV->getInitializer();
970       printType(Init->getType());
971       if (Function* F = dyn_cast<Function>(Init)) {
972         nl(Out)<< "/ Function Declarations"; nl(Out);
973         printFunctionHead(F);
974       } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
975         nl(Out) << "// Global Variable Declarations"; nl(Out);
976         printVariableHead(gv);
977       } else  {
978         nl(Out) << "// Constant Definitions"; nl(Out);
979         printConstant(gv);
980       }
981       if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
982         nl(Out) << "// Global Variable Definitions"; nl(Out);
983         printVariableBody(gv);
984       }
985     }
986   }
987
988   void CppWriter::printVariableHead(const GlobalVariable *GV) {
989     nl(Out) << "GlobalVariable* " << getCppName(GV);
990     if (is_inline) {
991       Out << " = mod->getGlobalVariable(";
992       printEscapedString(GV->getName());
993       Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
994       nl(Out) << "if (!" << getCppName(GV) << ") {";
995       in(); nl(Out) << getCppName(GV);
996     }
997     Out << " = new GlobalVariable(/*Module=*/*mod";
998     nl(Out) << "/*Type=*/";
999     printCppName(GV->getType()->getElementType());
1000     Out << ",";
1001     nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
1002     Out << ",";
1003     nl(Out) << "/*Linkage=*/";
1004     printLinkageType(GV->getLinkage());
1005     Out << ",";
1006     nl(Out) << "/*Initializer=*/0, ";
1007     if (GV->hasInitializer()) {
1008       Out << "// has initializer, specified below";
1009     }
1010     nl(Out) << "/*Name=*/\"";
1011     printEscapedString(GV->getName());
1012     Out << "\");";
1013     nl(Out);
1014
1015     if (GV->hasSection()) {
1016       printCppName(GV);
1017       Out << "->setSection(\"";
1018       printEscapedString(GV->getSection());
1019       Out << "\");";
1020       nl(Out);
1021     }
1022     if (GV->getAlignment()) {
1023       printCppName(GV);
1024       Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
1025       nl(Out);
1026     }
1027     if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
1028       printCppName(GV);
1029       Out << "->setVisibility(";
1030       printVisibilityType(GV->getVisibility());
1031       Out << ");";
1032       nl(Out);
1033     }
1034     if (is_inline) {
1035       out(); Out << "}"; nl(Out);
1036     }
1037   }
1038
1039   void CppWriter::printVariableBody(const GlobalVariable *GV) {
1040     if (GV->hasInitializer()) {
1041       printCppName(GV);
1042       Out << "->setInitializer(";
1043       Out << getCppName(GV->getInitializer()) << ");";
1044       nl(Out);
1045     }
1046   }
1047
1048   std::string CppWriter::getOpName(Value* V) {
1049     if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
1050       return getCppName(V);
1051
1052     // See if its alread in the map of forward references, if so just return the
1053     // name we already set up for it
1054     ForwardRefMap::const_iterator I = ForwardRefs.find(V);
1055     if (I != ForwardRefs.end())
1056       return I->second;
1057
1058     // This is a new forward reference. Generate a unique name for it
1059     std::string result(std::string("fwdref_") + utostr(uniqueNum++));
1060
1061     // Yes, this is a hack. An Argument is the smallest instantiable value that
1062     // we can make as a placeholder for the real value. We'll replace these
1063     // Argument instances later.
1064     Out << "Argument* " << result << " = new Argument("
1065         << getCppName(V->getType()) << ");";
1066     nl(Out);
1067     ForwardRefs[V] = result;
1068     return result;
1069   }
1070
1071   // printInstruction - This member is called for each Instruction in a function.
1072   void CppWriter::printInstruction(const Instruction *I,
1073                                    const std::string& bbname) {
1074     std::string iName(getCppName(I));
1075
1076     // Before we emit this instruction, we need to take care of generating any
1077     // forward references. So, we get the names of all the operands in advance
1078     std::string* opNames = new std::string[I->getNumOperands()];
1079     for (unsigned i = 0; i < I->getNumOperands(); i++) {
1080       opNames[i] = getOpName(I->getOperand(i));
1081     }
1082
1083     switch (I->getOpcode()) {
1084     default:
1085       error("Invalid instruction");
1086       break;
1087
1088     case Instruction::Ret: {
1089       const ReturnInst* ret =  cast<ReturnInst>(I);
1090       Out << "ReturnInst::Create("
1091           << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
1092       break;
1093     }
1094     case Instruction::Br: {
1095       const BranchInst* br = cast<BranchInst>(I);
1096       Out << "BranchInst::Create(" ;
1097       if (br->getNumOperands() == 3 ) {
1098         Out << opNames[2] << ", "
1099             << opNames[1] << ", "
1100             << opNames[0] << ", ";
1101
1102       } else if (br->getNumOperands() == 1) {
1103         Out << opNames[0] << ", ";
1104       } else {
1105         error("Branch with 2 operands?");
1106       }
1107       Out << bbname << ");";
1108       break;
1109     }
1110     case Instruction::Switch: {
1111       const SwitchInst* sw = cast<SwitchInst>(I);
1112       Out << "SwitchInst* " << iName << " = SwitchInst::Create("
1113           << opNames[0] << ", "
1114           << opNames[1] << ", "
1115           << sw->getNumCases() << ", " << bbname << ");";
1116       nl(Out);
1117       for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) {
1118         Out << iName << "->addCase("
1119             << opNames[i] << ", "
1120             << opNames[i+1] << ");";
1121         nl(Out);
1122       }
1123       break;
1124     }
1125     case Instruction::Invoke: {
1126       const InvokeInst* inv = cast<InvokeInst>(I);
1127       Out << "std::vector<Value*> " << iName << "_params;";
1128       nl(Out);
1129       for (unsigned i = 3; i < inv->getNumOperands(); ++i) {
1130         Out << iName << "_params.push_back("
1131             << opNames[i] << ");";
1132         nl(Out);
1133       }
1134       Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1135           << opNames[0] << ", "
1136           << opNames[1] << ", "
1137           << opNames[2] << ", "
1138           << iName << "_params.begin(), " << iName << "_params.end(), \"";
1139       printEscapedString(inv->getName());
1140       Out << "\", " << bbname << ");";
1141       nl(Out) << iName << "->setCallingConv(";
1142       printCallingConv(inv->getCallingConv());
1143       Out << ");";
1144       printAttributes(inv->getAttributes(), iName);
1145       Out << iName << "->setAttributes(" << iName << "_PAL);";
1146       nl(Out);
1147       break;
1148     }
1149     case Instruction::Unwind: {
1150       Out << "new UnwindInst("
1151           << bbname << ");";
1152       break;
1153     }
1154     case Instruction::Unreachable:{
1155       Out << "new UnreachableInst("
1156           << bbname << ");";
1157       break;
1158     }
1159     case Instruction::Add:
1160     case Instruction::FAdd:
1161     case Instruction::Sub:
1162     case Instruction::FSub:
1163     case Instruction::Mul:
1164     case Instruction::FMul:
1165     case Instruction::UDiv:
1166     case Instruction::SDiv:
1167     case Instruction::FDiv:
1168     case Instruction::URem:
1169     case Instruction::SRem:
1170     case Instruction::FRem:
1171     case Instruction::And:
1172     case Instruction::Or:
1173     case Instruction::Xor:
1174     case Instruction::Shl:
1175     case Instruction::LShr:
1176     case Instruction::AShr:{
1177       Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1178       switch (I->getOpcode()) {
1179       case Instruction::Add: Out << "Instruction::Add"; break;
1180       case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1181       case Instruction::Sub: Out << "Instruction::Sub"; break;
1182       case Instruction::FSub: Out << "Instruction::FSub"; break;
1183       case Instruction::Mul: Out << "Instruction::Mul"; break;
1184       case Instruction::FMul: Out << "Instruction::FMul"; break;
1185       case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1186       case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1187       case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1188       case Instruction::URem:Out << "Instruction::URem"; break;
1189       case Instruction::SRem:Out << "Instruction::SRem"; break;
1190       case Instruction::FRem:Out << "Instruction::FRem"; break;
1191       case Instruction::And: Out << "Instruction::And"; break;
1192       case Instruction::Or:  Out << "Instruction::Or";  break;
1193       case Instruction::Xor: Out << "Instruction::Xor"; break;
1194       case Instruction::Shl: Out << "Instruction::Shl"; break;
1195       case Instruction::LShr:Out << "Instruction::LShr"; break;
1196       case Instruction::AShr:Out << "Instruction::AShr"; break;
1197       default: Out << "Instruction::BadOpCode"; break;
1198       }
1199       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1200       printEscapedString(I->getName());
1201       Out << "\", " << bbname << ");";
1202       break;
1203     }
1204     case Instruction::FCmp: {
1205       Out << "FCmpInst* " << iName << " = new FCmpInst(";
1206       switch (cast<FCmpInst>(I)->getPredicate()) {
1207       case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1208       case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
1209       case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
1210       case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
1211       case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
1212       case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
1213       case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
1214       case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
1215       case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
1216       case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
1217       case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
1218       case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
1219       case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
1220       case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
1221       case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
1222       case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1223       default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1224       }
1225       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1226       printEscapedString(I->getName());
1227       Out << "\", " << bbname << ");";
1228       break;
1229     }
1230     case Instruction::ICmp: {
1231       Out << "ICmpInst* " << iName << " = new ICmpInst(";
1232       switch (cast<ICmpInst>(I)->getPredicate()) {
1233       case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
1234       case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
1235       case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1236       case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1237       case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1238       case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1239       case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1240       case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1241       case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1242       case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1243       default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1244       }
1245       Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1246       printEscapedString(I->getName());
1247       Out << "\", " << bbname << ");";
1248       break;
1249     }
1250     case Instruction::Malloc: {
1251       const MallocInst* mallocI = cast<MallocInst>(I);
1252       Out << "MallocInst* " << iName << " = new MallocInst("
1253           << getCppName(mallocI->getAllocatedType()) << ", ";
1254       if (mallocI->isArrayAllocation())
1255         Out << opNames[0] << ", " ;
1256       Out << "\"";
1257       printEscapedString(mallocI->getName());
1258       Out << "\", " << bbname << ");";
1259       if (mallocI->getAlignment())
1260         nl(Out) << iName << "->setAlignment("
1261             << mallocI->getAlignment() << ");";
1262       break;
1263     }
1264     case Instruction::Free: {
1265       Out << "FreeInst* " << iName << " = new FreeInst("
1266           << getCppName(I->getOperand(0)) << ", " << bbname << ");";
1267       break;
1268     }
1269     case Instruction::Alloca: {
1270       const AllocaInst* allocaI = cast<AllocaInst>(I);
1271       Out << "AllocaInst* " << iName << " = new AllocaInst("
1272           << getCppName(allocaI->getAllocatedType()) << ", ";
1273       if (allocaI->isArrayAllocation())
1274         Out << opNames[0] << ", ";
1275       Out << "\"";
1276       printEscapedString(allocaI->getName());
1277       Out << "\", " << bbname << ");";
1278       if (allocaI->getAlignment())
1279         nl(Out) << iName << "->setAlignment("
1280             << allocaI->getAlignment() << ");";
1281       break;
1282     }
1283     case Instruction::Load:{
1284       const LoadInst* load = cast<LoadInst>(I);
1285       Out << "LoadInst* " << iName << " = new LoadInst("
1286           << opNames[0] << ", \"";
1287       printEscapedString(load->getName());
1288       Out << "\", " << (load->isVolatile() ? "true" : "false" )
1289           << ", " << bbname << ");";
1290       break;
1291     }
1292     case Instruction::Store: {
1293       const StoreInst* store = cast<StoreInst>(I);
1294       Out << " new StoreInst("
1295           << opNames[0] << ", "
1296           << opNames[1] << ", "
1297           << (store->isVolatile() ? "true" : "false")
1298           << ", " << bbname << ");";
1299       break;
1300     }
1301     case Instruction::GetElementPtr: {
1302       const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1303       if (gep->getNumOperands() <= 2) {
1304         Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1305             << opNames[0];
1306         if (gep->getNumOperands() == 2)
1307           Out << ", " << opNames[1];
1308       } else {
1309         Out << "std::vector<Value*> " << iName << "_indices;";
1310         nl(Out);
1311         for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1312           Out << iName << "_indices.push_back("
1313               << opNames[i] << ");";
1314           nl(Out);
1315         }
1316         Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1317             << opNames[0] << ", " << iName << "_indices.begin(), "
1318             << iName << "_indices.end()";
1319       }
1320       Out << ", \"";
1321       printEscapedString(gep->getName());
1322       Out << "\", " << bbname << ");";
1323       break;
1324     }
1325     case Instruction::PHI: {
1326       const PHINode* phi = cast<PHINode>(I);
1327
1328       Out << "PHINode* " << iName << " = PHINode::Create("
1329           << getCppName(phi->getType()) << ", \"";
1330       printEscapedString(phi->getName());
1331       Out << "\", " << bbname << ");";
1332       nl(Out) << iName << "->reserveOperandSpace("
1333         << phi->getNumIncomingValues()
1334           << ");";
1335       nl(Out);
1336       for (unsigned i = 0; i < phi->getNumOperands(); i+=2) {
1337         Out << iName << "->addIncoming("
1338             << opNames[i] << ", " << opNames[i+1] << ");";
1339         nl(Out);
1340       }
1341       break;
1342     }
1343     case Instruction::Trunc:
1344     case Instruction::ZExt:
1345     case Instruction::SExt:
1346     case Instruction::FPTrunc:
1347     case Instruction::FPExt:
1348     case Instruction::FPToUI:
1349     case Instruction::FPToSI:
1350     case Instruction::UIToFP:
1351     case Instruction::SIToFP:
1352     case Instruction::PtrToInt:
1353     case Instruction::IntToPtr:
1354     case Instruction::BitCast: {
1355       const CastInst* cst = cast<CastInst>(I);
1356       Out << "CastInst* " << iName << " = new ";
1357       switch (I->getOpcode()) {
1358       case Instruction::Trunc:    Out << "TruncInst"; break;
1359       case Instruction::ZExt:     Out << "ZExtInst"; break;
1360       case Instruction::SExt:     Out << "SExtInst"; break;
1361       case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
1362       case Instruction::FPExt:    Out << "FPExtInst"; break;
1363       case Instruction::FPToUI:   Out << "FPToUIInst"; break;
1364       case Instruction::FPToSI:   Out << "FPToSIInst"; break;
1365       case Instruction::UIToFP:   Out << "UIToFPInst"; break;
1366       case Instruction::SIToFP:   Out << "SIToFPInst"; break;
1367       case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1368       case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1369       case Instruction::BitCast:  Out << "BitCastInst"; break;
1370       default: assert(!"Unreachable"); break;
1371       }
1372       Out << "(" << opNames[0] << ", "
1373           << getCppName(cst->getType()) << ", \"";
1374       printEscapedString(cst->getName());
1375       Out << "\", " << bbname << ");";
1376       break;
1377     }
1378     case Instruction::Call:{
1379       const CallInst* call = cast<CallInst>(I);
1380       if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1381         Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1382             << getCppName(ila->getFunctionType()) << ", \""
1383             << ila->getAsmString() << "\", \""
1384             << ila->getConstraintString() << "\","
1385             << (ila->hasSideEffects() ? "true" : "false") << ");";
1386         nl(Out);
1387       }
1388       if (call->getNumOperands() > 2) {
1389         Out << "std::vector<Value*> " << iName << "_params;";
1390         nl(Out);
1391         for (unsigned i = 1; i < call->getNumOperands(); ++i) {
1392           Out << iName << "_params.push_back(" << opNames[i] << ");";
1393           nl(Out);
1394         }
1395         Out << "CallInst* " << iName << " = CallInst::Create("
1396             << opNames[0] << ", " << iName << "_params.begin(), "
1397             << iName << "_params.end(), \"";
1398       } else if (call->getNumOperands() == 2) {
1399         Out << "CallInst* " << iName << " = CallInst::Create("
1400             << opNames[0] << ", " << opNames[1] << ", \"";
1401       } else {
1402         Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0]
1403             << ", \"";
1404       }
1405       printEscapedString(call->getName());
1406       Out << "\", " << bbname << ");";
1407       nl(Out) << iName << "->setCallingConv(";
1408       printCallingConv(call->getCallingConv());
1409       Out << ");";
1410       nl(Out) << iName << "->setTailCall("
1411           << (call->isTailCall() ? "true":"false");
1412       Out << ");";
1413       printAttributes(call->getAttributes(), iName);
1414       Out << iName << "->setAttributes(" << iName << "_PAL);";
1415       nl(Out);
1416       break;
1417     }
1418     case Instruction::Select: {
1419       const SelectInst* sel = cast<SelectInst>(I);
1420       Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1421       Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1422       printEscapedString(sel->getName());
1423       Out << "\", " << bbname << ");";
1424       break;
1425     }
1426     case Instruction::UserOp1:
1427       /// FALL THROUGH
1428     case Instruction::UserOp2: {
1429       /// FIXME: What should be done here?
1430       break;
1431     }
1432     case Instruction::VAArg: {
1433       const VAArgInst* va = cast<VAArgInst>(I);
1434       Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1435           << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1436       printEscapedString(va->getName());
1437       Out << "\", " << bbname << ");";
1438       break;
1439     }
1440     case Instruction::ExtractElement: {
1441       const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1442       Out << "ExtractElementInst* " << getCppName(eei)
1443           << " = new ExtractElementInst(" << opNames[0]
1444           << ", " << opNames[1] << ", \"";
1445       printEscapedString(eei->getName());
1446       Out << "\", " << bbname << ");";
1447       break;
1448     }
1449     case Instruction::InsertElement: {
1450       const InsertElementInst* iei = cast<InsertElementInst>(I);
1451       Out << "InsertElementInst* " << getCppName(iei)
1452           << " = InsertElementInst::Create(" << opNames[0]
1453           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1454       printEscapedString(iei->getName());
1455       Out << "\", " << bbname << ");";
1456       break;
1457     }
1458     case Instruction::ShuffleVector: {
1459       const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1460       Out << "ShuffleVectorInst* " << getCppName(svi)
1461           << " = new ShuffleVectorInst(" << opNames[0]
1462           << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1463       printEscapedString(svi->getName());
1464       Out << "\", " << bbname << ");";
1465       break;
1466     }
1467     case Instruction::ExtractValue: {
1468       const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1469       Out << "std::vector<unsigned> " << iName << "_indices;";
1470       nl(Out);
1471       for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1472         Out << iName << "_indices.push_back("
1473             << evi->idx_begin()[i] << ");";
1474         nl(Out);
1475       }
1476       Out << "ExtractValueInst* " << getCppName(evi)
1477           << " = ExtractValueInst::Create(" << opNames[0]
1478           << ", "
1479           << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1480       printEscapedString(evi->getName());
1481       Out << "\", " << bbname << ");";
1482       break;
1483     }
1484     case Instruction::InsertValue: {
1485       const InsertValueInst *ivi = cast<InsertValueInst>(I);
1486       Out << "std::vector<unsigned> " << iName << "_indices;";
1487       nl(Out);
1488       for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1489         Out << iName << "_indices.push_back("
1490             << ivi->idx_begin()[i] << ");";
1491         nl(Out);
1492       }
1493       Out << "InsertValueInst* " << getCppName(ivi)
1494           << " = InsertValueInst::Create(" << opNames[0]
1495           << ", " << opNames[1] << ", "
1496           << iName << "_indices.begin(), " << iName << "_indices.end(), \"";
1497       printEscapedString(ivi->getName());
1498       Out << "\", " << bbname << ");";
1499       break;
1500     }
1501   }
1502   DefinedValues.insert(I);
1503   nl(Out);
1504   delete [] opNames;
1505 }
1506
1507   // Print out the types, constants and declarations needed by one function
1508   void CppWriter::printFunctionUses(const Function* F) {
1509     nl(Out) << "// Type Definitions"; nl(Out);
1510     if (!is_inline) {
1511       // Print the function's return type
1512       printType(F->getReturnType());
1513
1514       // Print the function's function type
1515       printType(F->getFunctionType());
1516
1517       // Print the types of each of the function's arguments
1518       for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1519            AI != AE; ++AI) {
1520         printType(AI->getType());
1521       }
1522     }
1523
1524     // Print type definitions for every type referenced by an instruction and
1525     // make a note of any global values or constants that are referenced
1526     SmallPtrSet<GlobalValue*,64> gvs;
1527     SmallPtrSet<Constant*,64> consts;
1528     for (Function::const_iterator BB = F->begin(), BE = F->end();
1529          BB != BE; ++BB){
1530       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1531            I != E; ++I) {
1532         // Print the type of the instruction itself
1533         printType(I->getType());
1534
1535         // Print the type of each of the instruction's operands
1536         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1537           Value* operand = I->getOperand(i);
1538           printType(operand->getType());
1539
1540           // If the operand references a GVal or Constant, make a note of it
1541           if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1542             gvs.insert(GV);
1543             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1544               if (GVar->hasInitializer())
1545                 consts.insert(GVar->getInitializer());
1546           } else if (Constant* C = dyn_cast<Constant>(operand))
1547             consts.insert(C);
1548         }
1549       }
1550     }
1551
1552     // Print the function declarations for any functions encountered
1553     nl(Out) << "// Function Declarations"; nl(Out);
1554     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1555          I != E; ++I) {
1556       if (Function* Fun = dyn_cast<Function>(*I)) {
1557         if (!is_inline || Fun != F)
1558           printFunctionHead(Fun);
1559       }
1560     }
1561
1562     // Print the global variable declarations for any variables encountered
1563     nl(Out) << "// Global Variable Declarations"; nl(Out);
1564     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1565          I != E; ++I) {
1566       if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1567         printVariableHead(F);
1568     }
1569
1570   // Print the constants found
1571     nl(Out) << "// Constant Definitions"; nl(Out);
1572     for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1573            E = consts.end(); I != E; ++I) {
1574       printConstant(*I);
1575     }
1576
1577     // Process the global variables definitions now that all the constants have
1578     // been emitted. These definitions just couple the gvars with their constant
1579     // initializers.
1580     nl(Out) << "// Global Variable Definitions"; nl(Out);
1581     for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1582          I != E; ++I) {
1583       if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1584         printVariableBody(GV);
1585     }
1586   }
1587
1588   void CppWriter::printFunctionHead(const Function* F) {
1589     nl(Out) << "Function* " << getCppName(F);
1590     if (is_inline) {
1591       Out << " = mod->getFunction(\"";
1592       printEscapedString(F->getName());
1593       Out << "\", " << getCppName(F->getFunctionType()) << ");";
1594       nl(Out) << "if (!" << getCppName(F) << ") {";
1595       nl(Out) << getCppName(F);
1596     }
1597     Out<< " = Function::Create(";
1598     nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1599     nl(Out) << "/*Linkage=*/";
1600     printLinkageType(F->getLinkage());
1601     Out << ",";
1602     nl(Out) << "/*Name=*/\"";
1603     printEscapedString(F->getName());
1604     Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1605     nl(Out,-1);
1606     printCppName(F);
1607     Out << "->setCallingConv(";
1608     printCallingConv(F->getCallingConv());
1609     Out << ");";
1610     nl(Out);
1611     if (F->hasSection()) {
1612       printCppName(F);
1613       Out << "->setSection(\"" << F->getSection() << "\");";
1614       nl(Out);
1615     }
1616     if (F->getAlignment()) {
1617       printCppName(F);
1618       Out << "->setAlignment(" << F->getAlignment() << ");";
1619       nl(Out);
1620     }
1621     if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1622       printCppName(F);
1623       Out << "->setVisibility(";
1624       printVisibilityType(F->getVisibility());
1625       Out << ");";
1626       nl(Out);
1627     }
1628     if (F->hasGC()) {
1629       printCppName(F);
1630       Out << "->setGC(\"" << F->getGC() << "\");";
1631       nl(Out);
1632     }
1633     if (is_inline) {
1634       Out << "}";
1635       nl(Out);
1636     }
1637     printAttributes(F->getAttributes(), getCppName(F));
1638     printCppName(F);
1639     Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1640     nl(Out);
1641   }
1642
1643   void CppWriter::printFunctionBody(const Function *F) {
1644     if (F->isDeclaration())
1645       return; // external functions have no bodies.
1646
1647     // Clear the DefinedValues and ForwardRefs maps because we can't have
1648     // cross-function forward refs
1649     ForwardRefs.clear();
1650     DefinedValues.clear();
1651
1652     // Create all the argument values
1653     if (!is_inline) {
1654       if (!F->arg_empty()) {
1655         Out << "Function::arg_iterator args = " << getCppName(F)
1656             << "->arg_begin();";
1657         nl(Out);
1658       }
1659       for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1660            AI != AE; ++AI) {
1661         Out << "Value* " << getCppName(AI) << " = args++;";
1662         nl(Out);
1663         if (AI->hasName()) {
1664           Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");";
1665           nl(Out);
1666         }
1667       }
1668     }
1669
1670     // Create all the basic blocks
1671     nl(Out);
1672     for (Function::const_iterator BI = F->begin(), BE = F->end();
1673          BI != BE; ++BI) {
1674       std::string bbname(getCppName(BI));
1675       Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\"";
1676       if (BI->hasName())
1677         printEscapedString(BI->getName());
1678       Out << "\"," << getCppName(BI->getParent()) << ",0);";
1679       nl(Out);
1680     }
1681
1682     // Output all of its basic blocks... for the function
1683     for (Function::const_iterator BI = F->begin(), BE = F->end();
1684          BI != BE; ++BI) {
1685       std::string bbname(getCppName(BI));
1686       nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1687       nl(Out);
1688
1689       // Output all of the instructions in the basic block...
1690       for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1691            I != E; ++I) {
1692         printInstruction(I,bbname);
1693       }
1694     }
1695
1696     // Loop over the ForwardRefs and resolve them now that all instructions
1697     // are generated.
1698     if (!ForwardRefs.empty()) {
1699       nl(Out) << "// Resolve Forward References";
1700       nl(Out);
1701     }
1702
1703     while (!ForwardRefs.empty()) {
1704       ForwardRefMap::iterator I = ForwardRefs.begin();
1705       Out << I->second << "->replaceAllUsesWith("
1706           << getCppName(I->first) << "); delete " << I->second << ";";
1707       nl(Out);
1708       ForwardRefs.erase(I);
1709     }
1710   }
1711
1712   void CppWriter::printInline(const std::string& fname,
1713                               const std::string& func) {
1714     const Function* F = TheModule->getFunction(func);
1715     if (!F) {
1716       error(std::string("Function '") + func + "' not found in input module");
1717       return;
1718     }
1719     if (F->isDeclaration()) {
1720       error(std::string("Function '") + func + "' is external!");
1721       return;
1722     }
1723     nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1724             << getCppName(F);
1725     unsigned arg_count = 1;
1726     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1727          AI != AE; ++AI) {
1728       Out << ", Value* arg_" << arg_count;
1729     }
1730     Out << ") {";
1731     nl(Out);
1732     is_inline = true;
1733     printFunctionUses(F);
1734     printFunctionBody(F);
1735     is_inline = false;
1736     Out << "return " << getCppName(F->begin()) << ";";
1737     nl(Out) << "}";
1738     nl(Out);
1739   }
1740
1741   void CppWriter::printModuleBody() {
1742     // Print out all the type definitions
1743     nl(Out) << "// Type Definitions"; nl(Out);
1744     printTypes(TheModule);
1745
1746     // Functions can call each other and global variables can reference them so
1747     // define all the functions first before emitting their function bodies.
1748     nl(Out) << "// Function Declarations"; nl(Out);
1749     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1750          I != E; ++I)
1751       printFunctionHead(I);
1752
1753     // Process the global variables declarations. We can't initialze them until
1754     // after the constants are printed so just print a header for each global
1755     nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1756     for (Module::const_global_iterator I = TheModule->global_begin(),
1757            E = TheModule->global_end(); I != E; ++I) {
1758       printVariableHead(I);
1759     }
1760
1761     // Print out all the constants definitions. Constants don't recurse except
1762     // through GlobalValues. All GlobalValues have been declared at this point
1763     // so we can proceed to generate the constants.
1764     nl(Out) << "// Constant Definitions"; nl(Out);
1765     printConstants(TheModule);
1766
1767     // Process the global variables definitions now that all the constants have
1768     // been emitted. These definitions just couple the gvars with their constant
1769     // initializers.
1770     nl(Out) << "// Global Variable Definitions"; nl(Out);
1771     for (Module::const_global_iterator I = TheModule->global_begin(),
1772            E = TheModule->global_end(); I != E; ++I) {
1773       printVariableBody(I);
1774     }
1775
1776     // Finally, we can safely put out all of the function bodies.
1777     nl(Out) << "// Function Definitions"; nl(Out);
1778     for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1779          I != E; ++I) {
1780       if (!I->isDeclaration()) {
1781         nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1782                 << ")";
1783         nl(Out) << "{";
1784         nl(Out,1);
1785         printFunctionBody(I);
1786         nl(Out,-1) << "}";
1787         nl(Out);
1788       }
1789     }
1790   }
1791
1792   void CppWriter::printProgram(const std::string& fname,
1793                                const std::string& mName) {
1794     Out << "#include <llvm/Module.h>\n";
1795     Out << "#include <llvm/DerivedTypes.h>\n";
1796     Out << "#include <llvm/Constants.h>\n";
1797     Out << "#include <llvm/GlobalVariable.h>\n";
1798     Out << "#include <llvm/Function.h>\n";
1799     Out << "#include <llvm/CallingConv.h>\n";
1800     Out << "#include <llvm/BasicBlock.h>\n";
1801     Out << "#include <llvm/Instructions.h>\n";
1802     Out << "#include <llvm/InlineAsm.h>\n";
1803     Out << "#include <llvm/Support/FormattedStream.h>\n";
1804     Out << "#include <llvm/Support/MathExtras.h>\n";
1805     Out << "#include <llvm/Pass.h>\n";
1806     Out << "#include <llvm/PassManager.h>\n";
1807     Out << "#include <llvm/ADT/SmallVector.h>\n";
1808     Out << "#include <llvm/Analysis/Verifier.h>\n";
1809     Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1810     Out << "#include <algorithm>\n";
1811     Out << "using namespace llvm;\n\n";
1812     Out << "Module* " << fname << "();\n\n";
1813     Out << "int main(int argc, char**argv) {\n";
1814     Out << "  Module* Mod = " << fname << "();\n";
1815     Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1816     Out << "  outs().flush();\n";
1817     Out << "  PassManager PM;\n";
1818     Out << "  PM.add(createPrintModulePass(&outs()));\n";
1819     Out << "  PM.run(*Mod);\n";
1820     Out << "  return 0;\n";
1821     Out << "}\n\n";
1822     printModule(fname,mName);
1823   }
1824
1825   void CppWriter::printModule(const std::string& fname,
1826                               const std::string& mName) {
1827     nl(Out) << "Module* " << fname << "() {";
1828     nl(Out,1) << "// Module Construction";
1829     nl(Out) << "Module* mod = new Module(\"";
1830     printEscapedString(mName);
1831     Out << "\");";
1832     if (!TheModule->getTargetTriple().empty()) {
1833       nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1834     }
1835     if (!TheModule->getTargetTriple().empty()) {
1836       nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1837               << "\");";
1838     }
1839
1840     if (!TheModule->getModuleInlineAsm().empty()) {
1841       nl(Out) << "mod->setModuleInlineAsm(\"";
1842       printEscapedString(TheModule->getModuleInlineAsm());
1843       Out << "\");";
1844     }
1845     nl(Out);
1846
1847     // Loop over the dependent libraries and emit them.
1848     Module::lib_iterator LI = TheModule->lib_begin();
1849     Module::lib_iterator LE = TheModule->lib_end();
1850     while (LI != LE) {
1851       Out << "mod->addLibrary(\"" << *LI << "\");";
1852       nl(Out);
1853       ++LI;
1854     }
1855     printModuleBody();
1856     nl(Out) << "return mod;";
1857     nl(Out,-1) << "}";
1858     nl(Out);
1859   }
1860
1861   void CppWriter::printContents(const std::string& fname,
1862                                 const std::string& mName) {
1863     Out << "\nModule* " << fname << "(Module *mod) {\n";
1864     Out << "\nmod->setModuleIdentifier(\"";
1865     printEscapedString(mName);
1866     Out << "\");\n";
1867     printModuleBody();
1868     Out << "\nreturn mod;\n";
1869     Out << "\n}\n";
1870   }
1871
1872   void CppWriter::printFunction(const std::string& fname,
1873                                 const std::string& funcName) {
1874     const Function* F = TheModule->getFunction(funcName);
1875     if (!F) {
1876       error(std::string("Function '") + funcName + "' not found in input module");
1877       return;
1878     }
1879     Out << "\nFunction* " << fname << "(Module *mod) {\n";
1880     printFunctionUses(F);
1881     printFunctionHead(F);
1882     printFunctionBody(F);
1883     Out << "return " << getCppName(F) << ";\n";
1884     Out << "}\n";
1885   }
1886
1887   void CppWriter::printFunctions() {
1888     const Module::FunctionListType &funcs = TheModule->getFunctionList();
1889     Module::const_iterator I  = funcs.begin();
1890     Module::const_iterator IE = funcs.end();
1891
1892     for (; I != IE; ++I) {
1893       const Function &func = *I;
1894       if (!func.isDeclaration()) {
1895         std::string name("define_");
1896         name += func.getName();
1897         printFunction(name, func.getName());
1898       }
1899     }
1900   }
1901
1902   void CppWriter::printVariable(const std::string& fname,
1903                                 const std::string& varName) {
1904     const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
1905
1906     if (!GV) {
1907       error(std::string("Variable '") + varName + "' not found in input module");
1908       return;
1909     }
1910     Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
1911     printVariableUses(GV);
1912     printVariableHead(GV);
1913     printVariableBody(GV);
1914     Out << "return " << getCppName(GV) << ";\n";
1915     Out << "}\n";
1916   }
1917
1918   void CppWriter::printType(const std::string& fname,
1919                             const std::string& typeName) {
1920     const Type* Ty = TheModule->getTypeByName(typeName);
1921     if (!Ty) {
1922       error(std::string("Type '") + typeName + "' not found in input module");
1923       return;
1924     }
1925     Out << "\nType* " << fname << "(Module *mod) {\n";
1926     printType(Ty);
1927     Out << "return " << getCppName(Ty) << ";\n";
1928     Out << "}\n";
1929   }
1930
1931   bool CppWriter::runOnModule(Module &M) {
1932     TheModule = &M;
1933
1934     // Emit a header
1935     Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
1936
1937     // Get the name of the function we're supposed to generate
1938     std::string fname = FuncName.getValue();
1939
1940     // Get the name of the thing we are to generate
1941     std::string tgtname = NameToGenerate.getValue();
1942     if (GenerationType == GenModule ||
1943         GenerationType == GenContents ||
1944         GenerationType == GenProgram ||
1945         GenerationType == GenFunctions) {
1946       if (tgtname == "!bad!") {
1947         if (M.getModuleIdentifier() == "-")
1948           tgtname = "<stdin>";
1949         else
1950           tgtname = M.getModuleIdentifier();
1951       }
1952     } else if (tgtname == "!bad!")
1953       error("You must use the -for option with -gen-{function,variable,type}");
1954
1955     switch (WhatToGenerate(GenerationType)) {
1956      case GenProgram:
1957       if (fname.empty())
1958         fname = "makeLLVMModule";
1959       printProgram(fname,tgtname);
1960       break;
1961      case GenModule:
1962       if (fname.empty())
1963         fname = "makeLLVMModule";
1964       printModule(fname,tgtname);
1965       break;
1966      case GenContents:
1967       if (fname.empty())
1968         fname = "makeLLVMModuleContents";
1969       printContents(fname,tgtname);
1970       break;
1971      case GenFunction:
1972       if (fname.empty())
1973         fname = "makeLLVMFunction";
1974       printFunction(fname,tgtname);
1975       break;
1976      case GenFunctions:
1977       printFunctions();
1978       break;
1979      case GenInline:
1980       if (fname.empty())
1981         fname = "makeLLVMInline";
1982       printInline(fname,tgtname);
1983       break;
1984      case GenVariable:
1985       if (fname.empty())
1986         fname = "makeLLVMVariable";
1987       printVariable(fname,tgtname);
1988       break;
1989      case GenType:
1990       if (fname.empty())
1991         fname = "makeLLVMType";
1992       printType(fname,tgtname);
1993       break;
1994      default:
1995       error("Invalid generation option");
1996     }
1997
1998     return false;
1999   }
2000 }
2001
2002 char CppWriter::ID = 0;
2003
2004 //===----------------------------------------------------------------------===//
2005 //                       External Interface declaration
2006 //===----------------------------------------------------------------------===//
2007
2008 bool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2009                                                 formatted_raw_ostream &o,
2010                                                 CodeGenFileType FileType,
2011                                                 CodeGenOpt::Level OptLevel) {
2012   if (FileType != TargetMachine::AssemblyFile) return true;
2013   PM.add(new CppWriter(o));
2014   return false;
2015 }