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