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