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