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