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