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