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