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