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