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