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