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