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