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