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