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