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