CPPBackend.cpp revision 263508
1//===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the writing of the LLVM IR as a set of C++ calls to the
11// LLVM IR interface. The input module is assumed to be verified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CPPTargetMachine.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Config/config.h"
19#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DerivedTypes.h"
22#include "llvm/IR/InlineAsm.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Module.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCInstrInfo.h"
28#include "llvm/MC/MCSubtargetInfo.h"
29#include "llvm/Pass.h"
30#include "llvm/PassManager.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/FormattedStream.h"
34#include "llvm/Support/TargetRegistry.h"
35#include <algorithm>
36#include <cctype>
37#include <cstdio>
38#include <map>
39#include <set>
40using namespace llvm;
41
42static cl::opt<std::string>
43FuncName("cppfname", cl::desc("Specify the name of the generated function"),
44         cl::value_desc("function name"));
45
46enum WhatToGenerate {
47  GenProgram,
48  GenModule,
49  GenContents,
50  GenFunction,
51  GenFunctions,
52  GenInline,
53  GenVariable,
54  GenType
55};
56
57static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
58  cl::desc("Choose what kind of output to generate"),
59  cl::init(GenProgram),
60  cl::values(
61    clEnumValN(GenProgram,  "program",   "Generate a complete program"),
62    clEnumValN(GenModule,   "module",    "Generate a module definition"),
63    clEnumValN(GenContents, "contents",  "Generate contents of a module"),
64    clEnumValN(GenFunction, "function",  "Generate a function definition"),
65    clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
66    clEnumValN(GenInline,   "inline",    "Generate an inline function"),
67    clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
68    clEnumValN(GenType,     "type",      "Generate a type definition"),
69    clEnumValEnd
70  )
71);
72
73static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
74  cl::desc("Specify the name of the thing to generate"),
75  cl::init("!bad!"));
76
77extern "C" void LLVMInitializeCppBackendTarget() {
78  // Register the target.
79  RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
80}
81
82namespace {
83  typedef std::vector<Type*> TypeList;
84  typedef std::map<Type*,std::string> TypeMap;
85  typedef std::map<const Value*,std::string> ValueMap;
86  typedef std::set<std::string> NameSet;
87  typedef std::set<Type*> TypeSet;
88  typedef std::set<const Value*> ValueSet;
89  typedef std::map<const Value*,std::string> ForwardRefMap;
90
91  /// CppWriter - This class is the main chunk of code that converts an LLVM
92  /// module to a C++ translation unit.
93  class CppWriter : public ModulePass {
94    formatted_raw_ostream &Out;
95    const Module *TheModule;
96    uint64_t uniqueNum;
97    TypeMap TypeNames;
98    ValueMap ValueNames;
99    NameSet UsedNames;
100    TypeSet DefinedTypes;
101    ValueSet DefinedValues;
102    ForwardRefMap ForwardRefs;
103    bool is_inline;
104    unsigned indent_level;
105
106  public:
107    static char ID;
108    explicit CppWriter(formatted_raw_ostream &o) :
109      ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){}
110
111    virtual const char *getPassName() const { return "C++ backend"; }
112
113    bool runOnModule(Module &M);
114
115    void printProgram(const std::string& fname, const std::string& modName );
116    void printModule(const std::string& fname, const std::string& modName );
117    void printContents(const std::string& fname, const std::string& modName );
118    void printFunction(const std::string& fname, const std::string& funcName );
119    void printFunctions();
120    void printInline(const std::string& fname, const std::string& funcName );
121    void printVariable(const std::string& fname, const std::string& varName );
122    void printType(const std::string& fname, const std::string& typeName );
123
124    void error(const std::string& msg);
125
126
127    formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
128    inline void in() { indent_level++; }
129    inline void out() { if (indent_level >0) indent_level--; }
130
131  private:
132    void printLinkageType(GlobalValue::LinkageTypes LT);
133    void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
134    void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
135    void printCallingConv(CallingConv::ID cc);
136    void printEscapedString(const std::string& str);
137    void printCFP(const ConstantFP* CFP);
138
139    std::string getCppName(Type* val);
140    inline void printCppName(Type* val);
141
142    std::string getCppName(const Value* val);
143    inline void printCppName(const Value* val);
144
145    void printAttributes(const AttributeSet &PAL, const std::string &name);
146    void printType(Type* Ty);
147    void printTypes(const Module* M);
148
149    void printConstant(const Constant *CPV);
150    void printConstants(const Module* M);
151
152    void printVariableUses(const GlobalVariable *GV);
153    void printVariableHead(const GlobalVariable *GV);
154    void printVariableBody(const GlobalVariable *GV);
155
156    void printFunctionUses(const Function *F);
157    void printFunctionHead(const Function *F);
158    void printFunctionBody(const Function *F);
159    void printInstruction(const Instruction *I, const std::string& bbname);
160    std::string getOpName(const Value*);
161
162    void printModuleBody();
163  };
164} // end anonymous namespace.
165
166formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
167  Out << '\n';
168  if (delta >= 0 || indent_level >= unsigned(-delta))
169    indent_level += delta;
170  Out.indent(indent_level);
171  return Out;
172}
173
174static inline void sanitize(std::string &str) {
175  for (size_t i = 0; i < str.length(); ++i)
176    if (!isalnum(str[i]) && str[i] != '_')
177      str[i] = '_';
178}
179
180static std::string getTypePrefix(Type *Ty) {
181  switch (Ty->getTypeID()) {
182  case Type::VoidTyID:     return "void_";
183  case Type::IntegerTyID:
184    return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
185  case Type::FloatTyID:    return "float_";
186  case Type::DoubleTyID:   return "double_";
187  case Type::LabelTyID:    return "label_";
188  case Type::FunctionTyID: return "func_";
189  case Type::StructTyID:   return "struct_";
190  case Type::ArrayTyID:    return "array_";
191  case Type::PointerTyID:  return "ptr_";
192  case Type::VectorTyID:   return "packed_";
193  default:                 return "other_";
194  }
195}
196
197void CppWriter::error(const std::string& msg) {
198  report_fatal_error(msg);
199}
200
201static inline std::string ftostr(const APFloat& V) {
202  std::string Buf;
203  if (&V.getSemantics() == &APFloat::IEEEdouble) {
204    raw_string_ostream(Buf) << V.convertToDouble();
205    return Buf;
206  } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
207    raw_string_ostream(Buf) << (double)V.convertToFloat();
208    return Buf;
209  }
210  return "<unknown format in ftostr>"; // error
211}
212
213// printCFP - Print a floating point constant .. very carefully :)
214// This makes sure that conversion to/from floating yields the same binary
215// result so that we don't lose precision.
216void CppWriter::printCFP(const ConstantFP *CFP) {
217  bool ignored;
218  APFloat APF = APFloat(CFP->getValueAPF());  // copy
219  if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
220    APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
221  Out << "ConstantFP::get(mod->getContext(), ";
222  Out << "APFloat(";
223#if HAVE_PRINTF_A
224  char Buffer[100];
225  sprintf(Buffer, "%A", APF.convertToDouble());
226  if ((!strncmp(Buffer, "0x", 2) ||
227       !strncmp(Buffer, "-0x", 3) ||
228       !strncmp(Buffer, "+0x", 3)) &&
229      APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
230    if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
231      Out << "BitsToDouble(" << Buffer << ")";
232    else
233      Out << "BitsToFloat((float)" << Buffer << ")";
234    Out << ")";
235  } else {
236#endif
237    std::string StrVal = ftostr(CFP->getValueAPF());
238
239    while (StrVal[0] == ' ')
240      StrVal.erase(StrVal.begin());
241
242    // Check to make sure that the stringized number is not some string like
243    // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
244    if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
245         ((StrVal[0] == '-' || StrVal[0] == '+') &&
246          (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
247        (CFP->isExactlyValue(atof(StrVal.c_str())))) {
248      if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
249        Out <<  StrVal;
250      else
251        Out << StrVal << "f";
252    } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
253      Out << "BitsToDouble(0x"
254          << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
255          << "ULL) /* " << StrVal << " */";
256    else
257      Out << "BitsToFloat(0x"
258          << utohexstr((uint32_t)CFP->getValueAPF().
259                                      bitcastToAPInt().getZExtValue())
260          << "U) /* " << StrVal << " */";
261    Out << ")";
262#if HAVE_PRINTF_A
263  }
264#endif
265  Out << ")";
266}
267
268void CppWriter::printCallingConv(CallingConv::ID cc){
269  // Print the calling convention.
270  switch (cc) {
271  case CallingConv::C:     Out << "CallingConv::C"; break;
272  case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
273  case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
274  case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
275  default:                 Out << cc; break;
276  }
277}
278
279void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
280  switch (LT) {
281  case GlobalValue::InternalLinkage:
282    Out << "GlobalValue::InternalLinkage"; break;
283  case GlobalValue::PrivateLinkage:
284    Out << "GlobalValue::PrivateLinkage"; break;
285  case GlobalValue::LinkerPrivateLinkage:
286    Out << "GlobalValue::LinkerPrivateLinkage"; break;
287  case GlobalValue::LinkerPrivateWeakLinkage:
288    Out << "GlobalValue::LinkerPrivateWeakLinkage"; 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::DLLImportLinkage:
304    Out << "GlobalValue::DLLImportLinkage"; break;
305  case GlobalValue::DLLExportLinkage:
306    Out << "GlobalValue::DLLExportLinkage"; break;
307  case GlobalValue::ExternalWeakLinkage:
308    Out << "GlobalValue::ExternalWeakLinkage"; break;
309  case GlobalValue::CommonLinkage:
310    Out << "GlobalValue::CommonLinkage"; break;
311  }
312}
313
314void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
315  switch (VisType) {
316  case GlobalValue::DefaultVisibility:
317    Out << "GlobalValue::DefaultVisibility";
318    break;
319  case GlobalValue::HiddenVisibility:
320    Out << "GlobalValue::HiddenVisibility";
321    break;
322  case GlobalValue::ProtectedVisibility:
323    Out << "GlobalValue::ProtectedVisibility";
324    break;
325  }
326}
327
328void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
329  switch (TLM) {
330    case GlobalVariable::NotThreadLocal:
331      Out << "GlobalVariable::NotThreadLocal";
332      break;
333    case GlobalVariable::GeneralDynamicTLSModel:
334      Out << "GlobalVariable::GeneralDynamicTLSModel";
335      break;
336    case GlobalVariable::LocalDynamicTLSModel:
337      Out << "GlobalVariable::LocalDynamicTLSModel";
338      break;
339    case GlobalVariable::InitialExecTLSModel:
340      Out << "GlobalVariable::InitialExecTLSModel";
341      break;
342    case GlobalVariable::LocalExecTLSModel:
343      Out << "GlobalVariable::LocalExecTLSModel";
344      break;
345  }
346}
347
348// printEscapedString - Print each character of the specified string, escaping
349// it if it is not printable or if it is an escape char.
350void CppWriter::printEscapedString(const std::string &Str) {
351  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
352    unsigned char C = Str[i];
353    if (isprint(C) && C != '"' && C != '\\') {
354      Out << C;
355    } else {
356      Out << "\\x"
357          << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
358          << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
359    }
360  }
361}
362
363std::string CppWriter::getCppName(Type* Ty) {
364  // First, handle the primitive types .. easy
365  if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
366    switch (Ty->getTypeID()) {
367    case Type::VoidTyID:   return "Type::getVoidTy(mod->getContext())";
368    case Type::IntegerTyID: {
369      unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
370      return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
371    }
372    case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())";
373    case Type::FloatTyID:    return "Type::getFloatTy(mod->getContext())";
374    case Type::DoubleTyID:   return "Type::getDoubleTy(mod->getContext())";
375    case Type::LabelTyID:    return "Type::getLabelTy(mod->getContext())";
376    case Type::X86_MMXTyID:  return "Type::getX86_MMXTy(mod->getContext())";
377    default:
378      error("Invalid primitive type");
379      break;
380    }
381    // shouldn't be returned, but make it sensible
382    return "Type::getVoidTy(mod->getContext())";
383  }
384
385  // Now, see if we've seen the type before and return that
386  TypeMap::iterator I = TypeNames.find(Ty);
387  if (I != TypeNames.end())
388    return I->second;
389
390  // Okay, let's build a new name for this type. Start with a prefix
391  const char* prefix = 0;
392  switch (Ty->getTypeID()) {
393  case Type::FunctionTyID:    prefix = "FuncTy_"; break;
394  case Type::StructTyID:      prefix = "StructTy_"; break;
395  case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
396  case Type::PointerTyID:     prefix = "PointerTy_"; break;
397  case Type::VectorTyID:      prefix = "VectorTy_"; break;
398  default:                    prefix = "OtherTy_"; break; // prevent breakage
399  }
400
401  // See if the type has a name in the symboltable and build accordingly
402  std::string name;
403  if (StructType *STy = dyn_cast<StructType>(Ty))
404    if (STy->hasName())
405      name = STy->getName();
406
407  if (name.empty())
408    name = utostr(uniqueNum++);
409
410  name = std::string(prefix) + name;
411  sanitize(name);
412
413  // Save the name
414  return TypeNames[Ty] = name;
415}
416
417void CppWriter::printCppName(Type* Ty) {
418  printEscapedString(getCppName(Ty));
419}
420
421std::string CppWriter::getCppName(const Value* val) {
422  std::string name;
423  ValueMap::iterator I = ValueNames.find(val);
424  if (I != ValueNames.end() && I->first == val)
425    return  I->second;
426
427  if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
428    name = std::string("gvar_") +
429      getTypePrefix(GV->getType()->getElementType());
430  } else if (isa<Function>(val)) {
431    name = std::string("func_");
432  } else if (const Constant* C = dyn_cast<Constant>(val)) {
433    name = std::string("const_") + getTypePrefix(C->getType());
434  } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
435    if (is_inline) {
436      unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
437                                      Function::const_arg_iterator(Arg)) + 1;
438      name = std::string("arg_") + utostr(argNum);
439      NameSet::iterator NI = UsedNames.find(name);
440      if (NI != UsedNames.end())
441        name += std::string("_") + utostr(uniqueNum++);
442      UsedNames.insert(name);
443      return ValueNames[val] = name;
444    } else {
445      name = getTypePrefix(val->getType());
446    }
447  } else {
448    name = getTypePrefix(val->getType());
449  }
450  if (val->hasName())
451    name += val->getName();
452  else
453    name += utostr(uniqueNum++);
454  sanitize(name);
455  NameSet::iterator NI = UsedNames.find(name);
456  if (NI != UsedNames.end())
457    name += std::string("_") + utostr(uniqueNum++);
458  UsedNames.insert(name);
459  return ValueNames[val] = name;
460}
461
462void CppWriter::printCppName(const Value* val) {
463  printEscapedString(getCppName(val));
464}
465
466void CppWriter::printAttributes(const AttributeSet &PAL,
467                                const std::string &name) {
468  Out << "AttributeSet " << name << "_PAL;";
469  nl(Out);
470  if (!PAL.isEmpty()) {
471    Out << '{'; in(); nl(Out);
472    Out << "SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
473    Out << "AttributeSet PAS;"; in(); nl(Out);
474    for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
475      unsigned index = PAL.getSlotIndex(i);
476      AttrBuilder attrs(PAL.getSlotAttributes(i), index);
477      Out << "{"; in(); nl(Out);
478      Out << "AttrBuilder B;"; nl(Out);
479
480#define HANDLE_ATTR(X)                                                  \
481      if (attrs.contains(Attribute::X)) {                               \
482        Out << "B.addAttribute(Attribute::" #X ");"; nl(Out);           \
483        attrs.removeAttribute(Attribute::X);                            \
484      }
485
486      HANDLE_ATTR(SExt);
487      HANDLE_ATTR(ZExt);
488      HANDLE_ATTR(NoReturn);
489      HANDLE_ATTR(InReg);
490      HANDLE_ATTR(StructRet);
491      HANDLE_ATTR(NoUnwind);
492      HANDLE_ATTR(NoAlias);
493      HANDLE_ATTR(ByVal);
494      HANDLE_ATTR(Nest);
495      HANDLE_ATTR(ReadNone);
496      HANDLE_ATTR(ReadOnly);
497      HANDLE_ATTR(NoInline);
498      HANDLE_ATTR(AlwaysInline);
499      HANDLE_ATTR(OptimizeNone);
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 ConstantInt* CaseVal = i.getCaseValue();
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(" << opNames[0] << ", " << bbname << ");";
1164    break;
1165  }
1166  case Instruction::Invoke: {
1167    const InvokeInst* inv = cast<InvokeInst>(I);
1168    Out << "std::vector<Value*> " << iName << "_params;";
1169    nl(Out);
1170    for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
1171      Out << iName << "_params.push_back("
1172          << getOpName(inv->getArgOperand(i)) << ");";
1173      nl(Out);
1174    }
1175    // FIXME: This shouldn't use magic numbers -3, -2, and -1.
1176    Out << "InvokeInst *" << iName << " = InvokeInst::Create("
1177        << getOpName(inv->getCalledValue()) << ", "
1178        << getOpName(inv->getNormalDest()) << ", "
1179        << getOpName(inv->getUnwindDest()) << ", "
1180        << iName << "_params, \"";
1181    printEscapedString(inv->getName());
1182    Out << "\", " << bbname << ");";
1183    nl(Out) << iName << "->setCallingConv(";
1184    printCallingConv(inv->getCallingConv());
1185    Out << ");";
1186    printAttributes(inv->getAttributes(), iName);
1187    Out << iName << "->setAttributes(" << iName << "_PAL);";
1188    nl(Out);
1189    break;
1190  }
1191  case Instruction::Unreachable: {
1192    Out << "new UnreachableInst("
1193        << "mod->getContext(), "
1194        << bbname << ");";
1195    break;
1196  }
1197  case Instruction::Add:
1198  case Instruction::FAdd:
1199  case Instruction::Sub:
1200  case Instruction::FSub:
1201  case Instruction::Mul:
1202  case Instruction::FMul:
1203  case Instruction::UDiv:
1204  case Instruction::SDiv:
1205  case Instruction::FDiv:
1206  case Instruction::URem:
1207  case Instruction::SRem:
1208  case Instruction::FRem:
1209  case Instruction::And:
1210  case Instruction::Or:
1211  case Instruction::Xor:
1212  case Instruction::Shl:
1213  case Instruction::LShr:
1214  case Instruction::AShr:{
1215    Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
1216    switch (I->getOpcode()) {
1217    case Instruction::Add: Out << "Instruction::Add"; break;
1218    case Instruction::FAdd: Out << "Instruction::FAdd"; break;
1219    case Instruction::Sub: Out << "Instruction::Sub"; break;
1220    case Instruction::FSub: Out << "Instruction::FSub"; break;
1221    case Instruction::Mul: Out << "Instruction::Mul"; break;
1222    case Instruction::FMul: Out << "Instruction::FMul"; break;
1223    case Instruction::UDiv:Out << "Instruction::UDiv"; break;
1224    case Instruction::SDiv:Out << "Instruction::SDiv"; break;
1225    case Instruction::FDiv:Out << "Instruction::FDiv"; break;
1226    case Instruction::URem:Out << "Instruction::URem"; break;
1227    case Instruction::SRem:Out << "Instruction::SRem"; break;
1228    case Instruction::FRem:Out << "Instruction::FRem"; break;
1229    case Instruction::And: Out << "Instruction::And"; break;
1230    case Instruction::Or:  Out << "Instruction::Or";  break;
1231    case Instruction::Xor: Out << "Instruction::Xor"; break;
1232    case Instruction::Shl: Out << "Instruction::Shl"; break;
1233    case Instruction::LShr:Out << "Instruction::LShr"; break;
1234    case Instruction::AShr:Out << "Instruction::AShr"; break;
1235    default: Out << "Instruction::BadOpCode"; break;
1236    }
1237    Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1238    printEscapedString(I->getName());
1239    Out << "\", " << bbname << ");";
1240    break;
1241  }
1242  case Instruction::FCmp: {
1243    Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
1244    switch (cast<FCmpInst>(I)->getPredicate()) {
1245    case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
1246    case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
1247    case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
1248    case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
1249    case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
1250    case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
1251    case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
1252    case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
1253    case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
1254    case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
1255    case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
1256    case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
1257    case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
1258    case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
1259    case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
1260    case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
1261    default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
1262    }
1263    Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1264    printEscapedString(I->getName());
1265    Out << "\");";
1266    break;
1267  }
1268  case Instruction::ICmp: {
1269    Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
1270    switch (cast<ICmpInst>(I)->getPredicate()) {
1271    case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
1272    case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
1273    case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
1274    case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
1275    case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
1276    case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
1277    case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
1278    case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
1279    case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
1280    case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
1281    default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
1282    }
1283    Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
1284    printEscapedString(I->getName());
1285    Out << "\");";
1286    break;
1287  }
1288  case Instruction::Alloca: {
1289    const AllocaInst* allocaI = cast<AllocaInst>(I);
1290    Out << "AllocaInst* " << iName << " = new AllocaInst("
1291        << getCppName(allocaI->getAllocatedType()) << ", ";
1292    if (allocaI->isArrayAllocation())
1293      Out << opNames[0] << ", ";
1294    Out << "\"";
1295    printEscapedString(allocaI->getName());
1296    Out << "\", " << bbname << ");";
1297    if (allocaI->getAlignment())
1298      nl(Out) << iName << "->setAlignment("
1299          << allocaI->getAlignment() << ");";
1300    break;
1301  }
1302  case Instruction::Load: {
1303    const LoadInst* load = cast<LoadInst>(I);
1304    Out << "LoadInst* " << iName << " = new LoadInst("
1305        << opNames[0] << ", \"";
1306    printEscapedString(load->getName());
1307    Out << "\", " << (load->isVolatile() ? "true" : "false" )
1308        << ", " << bbname << ");";
1309    if (load->getAlignment())
1310      nl(Out) << iName << "->setAlignment("
1311              << load->getAlignment() << ");";
1312    if (load->isAtomic()) {
1313      StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
1314      StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
1315      nl(Out) << iName << "->setAtomic("
1316              << Ordering << ", " << CrossThread << ");";
1317    }
1318    break;
1319  }
1320  case Instruction::Store: {
1321    const StoreInst* store = cast<StoreInst>(I);
1322    Out << "StoreInst* " << iName << " = new StoreInst("
1323        << opNames[0] << ", "
1324        << opNames[1] << ", "
1325        << (store->isVolatile() ? "true" : "false")
1326        << ", " << bbname << ");";
1327    if (store->getAlignment())
1328      nl(Out) << iName << "->setAlignment("
1329              << store->getAlignment() << ");";
1330    if (store->isAtomic()) {
1331      StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
1332      StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
1333      nl(Out) << iName << "->setAtomic("
1334              << Ordering << ", " << CrossThread << ");";
1335    }
1336    break;
1337  }
1338  case Instruction::GetElementPtr: {
1339    const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
1340    if (gep->getNumOperands() <= 2) {
1341      Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
1342          << opNames[0];
1343      if (gep->getNumOperands() == 2)
1344        Out << ", " << opNames[1];
1345    } else {
1346      Out << "std::vector<Value*> " << iName << "_indices;";
1347      nl(Out);
1348      for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
1349        Out << iName << "_indices.push_back("
1350            << opNames[i] << ");";
1351        nl(Out);
1352      }
1353      Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
1354          << opNames[0] << ", " << iName << "_indices";
1355    }
1356    Out << ", \"";
1357    printEscapedString(gep->getName());
1358    Out << "\", " << bbname << ");";
1359    break;
1360  }
1361  case Instruction::PHI: {
1362    const PHINode* phi = cast<PHINode>(I);
1363
1364    Out << "PHINode* " << iName << " = PHINode::Create("
1365        << getCppName(phi->getType()) << ", "
1366        << phi->getNumIncomingValues() << ", \"";
1367    printEscapedString(phi->getName());
1368    Out << "\", " << bbname << ");";
1369    nl(Out);
1370    for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
1371      Out << iName << "->addIncoming("
1372          << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
1373          << getOpName(phi->getIncomingBlock(i)) << ");";
1374      nl(Out);
1375    }
1376    break;
1377  }
1378  case Instruction::Trunc:
1379  case Instruction::ZExt:
1380  case Instruction::SExt:
1381  case Instruction::FPTrunc:
1382  case Instruction::FPExt:
1383  case Instruction::FPToUI:
1384  case Instruction::FPToSI:
1385  case Instruction::UIToFP:
1386  case Instruction::SIToFP:
1387  case Instruction::PtrToInt:
1388  case Instruction::IntToPtr:
1389  case Instruction::BitCast: {
1390    const CastInst* cst = cast<CastInst>(I);
1391    Out << "CastInst* " << iName << " = new ";
1392    switch (I->getOpcode()) {
1393    case Instruction::Trunc:    Out << "TruncInst"; break;
1394    case Instruction::ZExt:     Out << "ZExtInst"; break;
1395    case Instruction::SExt:     Out << "SExtInst"; break;
1396    case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
1397    case Instruction::FPExt:    Out << "FPExtInst"; break;
1398    case Instruction::FPToUI:   Out << "FPToUIInst"; break;
1399    case Instruction::FPToSI:   Out << "FPToSIInst"; break;
1400    case Instruction::UIToFP:   Out << "UIToFPInst"; break;
1401    case Instruction::SIToFP:   Out << "SIToFPInst"; break;
1402    case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
1403    case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
1404    case Instruction::BitCast:  Out << "BitCastInst"; break;
1405    default: llvm_unreachable("Unreachable");
1406    }
1407    Out << "(" << opNames[0] << ", "
1408        << getCppName(cst->getType()) << ", \"";
1409    printEscapedString(cst->getName());
1410    Out << "\", " << bbname << ");";
1411    break;
1412  }
1413  case Instruction::Call: {
1414    const CallInst* call = cast<CallInst>(I);
1415    if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
1416      Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
1417          << getCppName(ila->getFunctionType()) << ", \""
1418          << ila->getAsmString() << "\", \""
1419          << ila->getConstraintString() << "\","
1420          << (ila->hasSideEffects() ? "true" : "false") << ");";
1421      nl(Out);
1422    }
1423    if (call->getNumArgOperands() > 1) {
1424      Out << "std::vector<Value*> " << iName << "_params;";
1425      nl(Out);
1426      for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
1427        Out << iName << "_params.push_back(" << opNames[i] << ");";
1428        nl(Out);
1429      }
1430      Out << "CallInst* " << iName << " = CallInst::Create("
1431          << opNames[call->getNumArgOperands()] << ", "
1432          << iName << "_params, \"";
1433    } else if (call->getNumArgOperands() == 1) {
1434      Out << "CallInst* " << iName << " = CallInst::Create("
1435          << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
1436    } else {
1437      Out << "CallInst* " << iName << " = CallInst::Create("
1438          << opNames[call->getNumArgOperands()] << ", \"";
1439    }
1440    printEscapedString(call->getName());
1441    Out << "\", " << bbname << ");";
1442    nl(Out) << iName << "->setCallingConv(";
1443    printCallingConv(call->getCallingConv());
1444    Out << ");";
1445    nl(Out) << iName << "->setTailCall("
1446        << (call->isTailCall() ? "true" : "false");
1447    Out << ");";
1448    nl(Out);
1449    printAttributes(call->getAttributes(), iName);
1450    Out << iName << "->setAttributes(" << iName << "_PAL);";
1451    nl(Out);
1452    break;
1453  }
1454  case Instruction::Select: {
1455    const SelectInst* sel = cast<SelectInst>(I);
1456    Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
1457    Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1458    printEscapedString(sel->getName());
1459    Out << "\", " << bbname << ");";
1460    break;
1461  }
1462  case Instruction::UserOp1:
1463    /// FALL THROUGH
1464  case Instruction::UserOp2: {
1465    /// FIXME: What should be done here?
1466    break;
1467  }
1468  case Instruction::VAArg: {
1469    const VAArgInst* va = cast<VAArgInst>(I);
1470    Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
1471        << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
1472    printEscapedString(va->getName());
1473    Out << "\", " << bbname << ");";
1474    break;
1475  }
1476  case Instruction::ExtractElement: {
1477    const ExtractElementInst* eei = cast<ExtractElementInst>(I);
1478    Out << "ExtractElementInst* " << getCppName(eei)
1479        << " = new ExtractElementInst(" << opNames[0]
1480        << ", " << opNames[1] << ", \"";
1481    printEscapedString(eei->getName());
1482    Out << "\", " << bbname << ");";
1483    break;
1484  }
1485  case Instruction::InsertElement: {
1486    const InsertElementInst* iei = cast<InsertElementInst>(I);
1487    Out << "InsertElementInst* " << getCppName(iei)
1488        << " = InsertElementInst::Create(" << opNames[0]
1489        << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1490    printEscapedString(iei->getName());
1491    Out << "\", " << bbname << ");";
1492    break;
1493  }
1494  case Instruction::ShuffleVector: {
1495    const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
1496    Out << "ShuffleVectorInst* " << getCppName(svi)
1497        << " = new ShuffleVectorInst(" << opNames[0]
1498        << ", " << opNames[1] << ", " << opNames[2] << ", \"";
1499    printEscapedString(svi->getName());
1500    Out << "\", " << bbname << ");";
1501    break;
1502  }
1503  case Instruction::ExtractValue: {
1504    const ExtractValueInst *evi = cast<ExtractValueInst>(I);
1505    Out << "std::vector<unsigned> " << iName << "_indices;";
1506    nl(Out);
1507    for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
1508      Out << iName << "_indices.push_back("
1509          << evi->idx_begin()[i] << ");";
1510      nl(Out);
1511    }
1512    Out << "ExtractValueInst* " << getCppName(evi)
1513        << " = ExtractValueInst::Create(" << opNames[0]
1514        << ", "
1515        << iName << "_indices, \"";
1516    printEscapedString(evi->getName());
1517    Out << "\", " << bbname << ");";
1518    break;
1519  }
1520  case Instruction::InsertValue: {
1521    const InsertValueInst *ivi = cast<InsertValueInst>(I);
1522    Out << "std::vector<unsigned> " << iName << "_indices;";
1523    nl(Out);
1524    for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
1525      Out << iName << "_indices.push_back("
1526          << ivi->idx_begin()[i] << ");";
1527      nl(Out);
1528    }
1529    Out << "InsertValueInst* " << getCppName(ivi)
1530        << " = InsertValueInst::Create(" << opNames[0]
1531        << ", " << opNames[1] << ", "
1532        << iName << "_indices, \"";
1533    printEscapedString(ivi->getName());
1534    Out << "\", " << bbname << ");";
1535    break;
1536  }
1537  case Instruction::Fence: {
1538    const FenceInst *fi = cast<FenceInst>(I);
1539    StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
1540    StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
1541    Out << "FenceInst* " << iName
1542        << " = new FenceInst(mod->getContext(), "
1543        << Ordering << ", " << CrossThread << ", " << bbname
1544        << ");";
1545    break;
1546  }
1547  case Instruction::AtomicCmpXchg: {
1548    const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
1549    StringRef Ordering = ConvertAtomicOrdering(cxi->getOrdering());
1550    StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
1551    Out << "AtomicCmpXchgInst* " << iName
1552        << " = new AtomicCmpXchgInst("
1553        << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
1554        << Ordering << ", " << CrossThread << ", " << bbname
1555        << ");";
1556    nl(Out) << iName << "->setName(\"";
1557    printEscapedString(cxi->getName());
1558    Out << "\");";
1559    break;
1560  }
1561  case Instruction::AtomicRMW: {
1562    const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
1563    StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
1564    StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
1565    StringRef Operation;
1566    switch (rmwi->getOperation()) {
1567      case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
1568      case AtomicRMWInst::Add:  Operation = "AtomicRMWInst::Add"; break;
1569      case AtomicRMWInst::Sub:  Operation = "AtomicRMWInst::Sub"; break;
1570      case AtomicRMWInst::And:  Operation = "AtomicRMWInst::And"; break;
1571      case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
1572      case AtomicRMWInst::Or:   Operation = "AtomicRMWInst::Or"; break;
1573      case AtomicRMWInst::Xor:  Operation = "AtomicRMWInst::Xor"; break;
1574      case AtomicRMWInst::Max:  Operation = "AtomicRMWInst::Max"; break;
1575      case AtomicRMWInst::Min:  Operation = "AtomicRMWInst::Min"; break;
1576      case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
1577      case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
1578      case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
1579    }
1580    Out << "AtomicRMWInst* " << iName
1581        << " = new AtomicRMWInst("
1582        << Operation << ", "
1583        << opNames[0] << ", " << opNames[1] << ", "
1584        << Ordering << ", " << CrossThread << ", " << bbname
1585        << ");";
1586    nl(Out) << iName << "->setName(\"";
1587    printEscapedString(rmwi->getName());
1588    Out << "\");";
1589    break;
1590  }
1591  case Instruction::LandingPad: {
1592    const LandingPadInst *lpi = cast<LandingPadInst>(I);
1593    Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
1594    printCppName(lpi->getType());
1595    Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
1596    printEscapedString(lpi->getName());
1597    Out << "\", " << bbname << ");";
1598    nl(Out) << iName << "->setCleanup("
1599            << (lpi->isCleanup() ? "true" : "false")
1600            << ");";
1601    for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
1602      nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
1603    break;
1604  }
1605  }
1606  DefinedValues.insert(I);
1607  nl(Out);
1608  delete [] opNames;
1609}
1610
1611// Print out the types, constants and declarations needed by one function
1612void CppWriter::printFunctionUses(const Function* F) {
1613  nl(Out) << "// Type Definitions"; nl(Out);
1614  if (!is_inline) {
1615    // Print the function's return type
1616    printType(F->getReturnType());
1617
1618    // Print the function's function type
1619    printType(F->getFunctionType());
1620
1621    // Print the types of each of the function's arguments
1622    for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1623         AI != AE; ++AI) {
1624      printType(AI->getType());
1625    }
1626  }
1627
1628  // Print type definitions for every type referenced by an instruction and
1629  // make a note of any global values or constants that are referenced
1630  SmallPtrSet<GlobalValue*,64> gvs;
1631  SmallPtrSet<Constant*,64> consts;
1632  for (Function::const_iterator BB = F->begin(), BE = F->end();
1633       BB != BE; ++BB){
1634    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1635         I != E; ++I) {
1636      // Print the type of the instruction itself
1637      printType(I->getType());
1638
1639      // Print the type of each of the instruction's operands
1640      for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1641        Value* operand = I->getOperand(i);
1642        printType(operand->getType());
1643
1644        // If the operand references a GVal or Constant, make a note of it
1645        if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1646          gvs.insert(GV);
1647          if (GenerationType != GenFunction)
1648            if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1649              if (GVar->hasInitializer())
1650                consts.insert(GVar->getInitializer());
1651        } else if (Constant* C = dyn_cast<Constant>(operand)) {
1652          consts.insert(C);
1653          for (unsigned j = 0; j < C->getNumOperands(); ++j) {
1654            // If the operand references a GVal or Constant, make a note of it
1655            Value* operand = C->getOperand(j);
1656            printType(operand->getType());
1657            if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
1658              gvs.insert(GV);
1659              if (GenerationType != GenFunction)
1660                if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1661                  if (GVar->hasInitializer())
1662                    consts.insert(GVar->getInitializer());
1663            }
1664          }
1665        }
1666      }
1667    }
1668  }
1669
1670  // Print the function declarations for any functions encountered
1671  nl(Out) << "// Function Declarations"; nl(Out);
1672  for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1673       I != E; ++I) {
1674    if (Function* Fun = dyn_cast<Function>(*I)) {
1675      if (!is_inline || Fun != F)
1676        printFunctionHead(Fun);
1677    }
1678  }
1679
1680  // Print the global variable declarations for any variables encountered
1681  nl(Out) << "// Global Variable Declarations"; nl(Out);
1682  for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1683       I != E; ++I) {
1684    if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I))
1685      printVariableHead(F);
1686  }
1687
1688  // Print the constants found
1689  nl(Out) << "// Constant Definitions"; nl(Out);
1690  for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(),
1691         E = consts.end(); I != E; ++I) {
1692    printConstant(*I);
1693  }
1694
1695  // Process the global variables definitions now that all the constants have
1696  // been emitted. These definitions just couple the gvars with their constant
1697  // initializers.
1698  if (GenerationType != GenFunction) {
1699    nl(Out) << "// Global Variable Definitions"; nl(Out);
1700    for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end();
1701         I != E; ++I) {
1702      if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I))
1703        printVariableBody(GV);
1704    }
1705  }
1706}
1707
1708void CppWriter::printFunctionHead(const Function* F) {
1709  nl(Out) << "Function* " << getCppName(F);
1710  Out << " = mod->getFunction(\"";
1711  printEscapedString(F->getName());
1712  Out << "\");";
1713  nl(Out) << "if (!" << getCppName(F) << ") {";
1714  nl(Out) << getCppName(F);
1715
1716  Out<< " = Function::Create(";
1717  nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
1718  nl(Out) << "/*Linkage=*/";
1719  printLinkageType(F->getLinkage());
1720  Out << ",";
1721  nl(Out) << "/*Name=*/\"";
1722  printEscapedString(F->getName());
1723  Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
1724  nl(Out,-1);
1725  printCppName(F);
1726  Out << "->setCallingConv(";
1727  printCallingConv(F->getCallingConv());
1728  Out << ");";
1729  nl(Out);
1730  if (F->hasSection()) {
1731    printCppName(F);
1732    Out << "->setSection(\"" << F->getSection() << "\");";
1733    nl(Out);
1734  }
1735  if (F->getAlignment()) {
1736    printCppName(F);
1737    Out << "->setAlignment(" << F->getAlignment() << ");";
1738    nl(Out);
1739  }
1740  if (F->getVisibility() != GlobalValue::DefaultVisibility) {
1741    printCppName(F);
1742    Out << "->setVisibility(";
1743    printVisibilityType(F->getVisibility());
1744    Out << ");";
1745    nl(Out);
1746  }
1747  if (F->hasGC()) {
1748    printCppName(F);
1749    Out << "->setGC(\"" << F->getGC() << "\");";
1750    nl(Out);
1751  }
1752  Out << "}";
1753  nl(Out);
1754  printAttributes(F->getAttributes(), getCppName(F));
1755  printCppName(F);
1756  Out << "->setAttributes(" << getCppName(F) << "_PAL);";
1757  nl(Out);
1758}
1759
1760void CppWriter::printFunctionBody(const Function *F) {
1761  if (F->isDeclaration())
1762    return; // external functions have no bodies.
1763
1764  // Clear the DefinedValues and ForwardRefs maps because we can't have
1765  // cross-function forward refs
1766  ForwardRefs.clear();
1767  DefinedValues.clear();
1768
1769  // Create all the argument values
1770  if (!is_inline) {
1771    if (!F->arg_empty()) {
1772      Out << "Function::arg_iterator args = " << getCppName(F)
1773          << "->arg_begin();";
1774      nl(Out);
1775    }
1776    for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1777         AI != AE; ++AI) {
1778      Out << "Value* " << getCppName(AI) << " = args++;";
1779      nl(Out);
1780      if (AI->hasName()) {
1781        Out << getCppName(AI) << "->setName(\"";
1782        printEscapedString(AI->getName());
1783        Out << "\");";
1784        nl(Out);
1785      }
1786    }
1787  }
1788
1789  // Create all the basic blocks
1790  nl(Out);
1791  for (Function::const_iterator BI = F->begin(), BE = F->end();
1792       BI != BE; ++BI) {
1793    std::string bbname(getCppName(BI));
1794    Out << "BasicBlock* " << bbname <<
1795           " = BasicBlock::Create(mod->getContext(), \"";
1796    if (BI->hasName())
1797      printEscapedString(BI->getName());
1798    Out << "\"," << getCppName(BI->getParent()) << ",0);";
1799    nl(Out);
1800  }
1801
1802  // Output all of its basic blocks... for the function
1803  for (Function::const_iterator BI = F->begin(), BE = F->end();
1804       BI != BE; ++BI) {
1805    std::string bbname(getCppName(BI));
1806    nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
1807    nl(Out);
1808
1809    // Output all of the instructions in the basic block...
1810    for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
1811         I != E; ++I) {
1812      printInstruction(I,bbname);
1813    }
1814  }
1815
1816  // Loop over the ForwardRefs and resolve them now that all instructions
1817  // are generated.
1818  if (!ForwardRefs.empty()) {
1819    nl(Out) << "// Resolve Forward References";
1820    nl(Out);
1821  }
1822
1823  while (!ForwardRefs.empty()) {
1824    ForwardRefMap::iterator I = ForwardRefs.begin();
1825    Out << I->second << "->replaceAllUsesWith("
1826        << getCppName(I->first) << "); delete " << I->second << ";";
1827    nl(Out);
1828    ForwardRefs.erase(I);
1829  }
1830}
1831
1832void CppWriter::printInline(const std::string& fname,
1833                            const std::string& func) {
1834  const Function* F = TheModule->getFunction(func);
1835  if (!F) {
1836    error(std::string("Function '") + func + "' not found in input module");
1837    return;
1838  }
1839  if (F->isDeclaration()) {
1840    error(std::string("Function '") + func + "' is external!");
1841    return;
1842  }
1843  nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
1844          << getCppName(F);
1845  unsigned arg_count = 1;
1846  for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
1847       AI != AE; ++AI) {
1848    Out << ", Value* arg_" << arg_count++;
1849  }
1850  Out << ") {";
1851  nl(Out);
1852  is_inline = true;
1853  printFunctionUses(F);
1854  printFunctionBody(F);
1855  is_inline = false;
1856  Out << "return " << getCppName(F->begin()) << ";";
1857  nl(Out) << "}";
1858  nl(Out);
1859}
1860
1861void CppWriter::printModuleBody() {
1862  // Print out all the type definitions
1863  nl(Out) << "// Type Definitions"; nl(Out);
1864  printTypes(TheModule);
1865
1866  // Functions can call each other and global variables can reference them so
1867  // define all the functions first before emitting their function bodies.
1868  nl(Out) << "// Function Declarations"; nl(Out);
1869  for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1870       I != E; ++I)
1871    printFunctionHead(I);
1872
1873  // Process the global variables declarations. We can't initialze them until
1874  // after the constants are printed so just print a header for each global
1875  nl(Out) << "// Global Variable Declarations\n"; nl(Out);
1876  for (Module::const_global_iterator I = TheModule->global_begin(),
1877         E = TheModule->global_end(); I != E; ++I) {
1878    printVariableHead(I);
1879  }
1880
1881  // Print out all the constants definitions. Constants don't recurse except
1882  // through GlobalValues. All GlobalValues have been declared at this point
1883  // so we can proceed to generate the constants.
1884  nl(Out) << "// Constant Definitions"; nl(Out);
1885  printConstants(TheModule);
1886
1887  // Process the global variables definitions now that all the constants have
1888  // been emitted. These definitions just couple the gvars with their constant
1889  // initializers.
1890  nl(Out) << "// Global Variable Definitions"; nl(Out);
1891  for (Module::const_global_iterator I = TheModule->global_begin(),
1892         E = TheModule->global_end(); I != E; ++I) {
1893    printVariableBody(I);
1894  }
1895
1896  // Finally, we can safely put out all of the function bodies.
1897  nl(Out) << "// Function Definitions"; nl(Out);
1898  for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1899       I != E; ++I) {
1900    if (!I->isDeclaration()) {
1901      nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
1902              << ")";
1903      nl(Out) << "{";
1904      nl(Out,1);
1905      printFunctionBody(I);
1906      nl(Out,-1) << "}";
1907      nl(Out);
1908    }
1909  }
1910}
1911
1912void CppWriter::printProgram(const std::string& fname,
1913                             const std::string& mName) {
1914  Out << "#include <llvm/Pass.h>\n";
1915  Out << "#include <llvm/PassManager.h>\n";
1916
1917  Out << "#include <llvm/ADT/SmallVector.h>\n";
1918  Out << "#include <llvm/Analysis/Verifier.h>\n";
1919  Out << "#include <llvm/Assembly/PrintModulePass.h>\n";
1920  Out << "#include <llvm/IR/BasicBlock.h>\n";
1921  Out << "#include <llvm/IR/CallingConv.h>\n";
1922  Out << "#include <llvm/IR/Constants.h>\n";
1923  Out << "#include <llvm/IR/DerivedTypes.h>\n";
1924  Out << "#include <llvm/IR/Function.h>\n";
1925  Out << "#include <llvm/IR/GlobalVariable.h>\n";
1926  Out << "#include <llvm/IR/InlineAsm.h>\n";
1927  Out << "#include <llvm/IR/Instructions.h>\n";
1928  Out << "#include <llvm/IR/LLVMContext.h>\n";
1929  Out << "#include <llvm/IR/Module.h>\n";
1930  Out << "#include <llvm/Support/FormattedStream.h>\n";
1931  Out << "#include <llvm/Support/MathExtras.h>\n";
1932  Out << "#include <algorithm>\n";
1933  Out << "using namespace llvm;\n\n";
1934  Out << "Module* " << fname << "();\n\n";
1935  Out << "int main(int argc, char**argv) {\n";
1936  Out << "  Module* Mod = " << fname << "();\n";
1937  Out << "  verifyModule(*Mod, PrintMessageAction);\n";
1938  Out << "  PassManager PM;\n";
1939  Out << "  PM.add(createPrintModulePass(&outs()));\n";
1940  Out << "  PM.run(*Mod);\n";
1941  Out << "  return 0;\n";
1942  Out << "}\n\n";
1943  printModule(fname,mName);
1944}
1945
1946void CppWriter::printModule(const std::string& fname,
1947                            const std::string& mName) {
1948  nl(Out) << "Module* " << fname << "() {";
1949  nl(Out,1) << "// Module Construction";
1950  nl(Out) << "Module* mod = new Module(\"";
1951  printEscapedString(mName);
1952  Out << "\", getGlobalContext());";
1953  if (!TheModule->getTargetTriple().empty()) {
1954    nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");";
1955  }
1956  if (!TheModule->getTargetTriple().empty()) {
1957    nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
1958            << "\");";
1959  }
1960
1961  if (!TheModule->getModuleInlineAsm().empty()) {
1962    nl(Out) << "mod->setModuleInlineAsm(\"";
1963    printEscapedString(TheModule->getModuleInlineAsm());
1964    Out << "\");";
1965  }
1966  nl(Out);
1967
1968  printModuleBody();
1969  nl(Out) << "return mod;";
1970  nl(Out,-1) << "}";
1971  nl(Out);
1972}
1973
1974void CppWriter::printContents(const std::string& fname,
1975                              const std::string& mName) {
1976  Out << "\nModule* " << fname << "(Module *mod) {\n";
1977  Out << "\nmod->setModuleIdentifier(\"";
1978  printEscapedString(mName);
1979  Out << "\");\n";
1980  printModuleBody();
1981  Out << "\nreturn mod;\n";
1982  Out << "\n}\n";
1983}
1984
1985void CppWriter::printFunction(const std::string& fname,
1986                              const std::string& funcName) {
1987  const Function* F = TheModule->getFunction(funcName);
1988  if (!F) {
1989    error(std::string("Function '") + funcName + "' not found in input module");
1990    return;
1991  }
1992  Out << "\nFunction* " << fname << "(Module *mod) {\n";
1993  printFunctionUses(F);
1994  printFunctionHead(F);
1995  printFunctionBody(F);
1996  Out << "return " << getCppName(F) << ";\n";
1997  Out << "}\n";
1998}
1999
2000void CppWriter::printFunctions() {
2001  const Module::FunctionListType &funcs = TheModule->getFunctionList();
2002  Module::const_iterator I  = funcs.begin();
2003  Module::const_iterator IE = funcs.end();
2004
2005  for (; I != IE; ++I) {
2006    const Function &func = *I;
2007    if (!func.isDeclaration()) {
2008      std::string name("define_");
2009      name += func.getName();
2010      printFunction(name, func.getName());
2011    }
2012  }
2013}
2014
2015void CppWriter::printVariable(const std::string& fname,
2016                              const std::string& varName) {
2017  const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
2018
2019  if (!GV) {
2020    error(std::string("Variable '") + varName + "' not found in input module");
2021    return;
2022  }
2023  Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
2024  printVariableUses(GV);
2025  printVariableHead(GV);
2026  printVariableBody(GV);
2027  Out << "return " << getCppName(GV) << ";\n";
2028  Out << "}\n";
2029}
2030
2031void CppWriter::printType(const std::string &fname,
2032                          const std::string &typeName) {
2033  Type* Ty = TheModule->getTypeByName(typeName);
2034  if (!Ty) {
2035    error(std::string("Type '") + typeName + "' not found in input module");
2036    return;
2037  }
2038  Out << "\nType* " << fname << "(Module *mod) {\n";
2039  printType(Ty);
2040  Out << "return " << getCppName(Ty) << ";\n";
2041  Out << "}\n";
2042}
2043
2044bool CppWriter::runOnModule(Module &M) {
2045  TheModule = &M;
2046
2047  // Emit a header
2048  Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
2049
2050  // Get the name of the function we're supposed to generate
2051  std::string fname = FuncName.getValue();
2052
2053  // Get the name of the thing we are to generate
2054  std::string tgtname = NameToGenerate.getValue();
2055  if (GenerationType == GenModule ||
2056      GenerationType == GenContents ||
2057      GenerationType == GenProgram ||
2058      GenerationType == GenFunctions) {
2059    if (tgtname == "!bad!") {
2060      if (M.getModuleIdentifier() == "-")
2061        tgtname = "<stdin>";
2062      else
2063        tgtname = M.getModuleIdentifier();
2064    }
2065  } else if (tgtname == "!bad!")
2066    error("You must use the -for option with -gen-{function,variable,type}");
2067
2068  switch (WhatToGenerate(GenerationType)) {
2069   case GenProgram:
2070    if (fname.empty())
2071      fname = "makeLLVMModule";
2072    printProgram(fname,tgtname);
2073    break;
2074   case GenModule:
2075    if (fname.empty())
2076      fname = "makeLLVMModule";
2077    printModule(fname,tgtname);
2078    break;
2079   case GenContents:
2080    if (fname.empty())
2081      fname = "makeLLVMModuleContents";
2082    printContents(fname,tgtname);
2083    break;
2084   case GenFunction:
2085    if (fname.empty())
2086      fname = "makeLLVMFunction";
2087    printFunction(fname,tgtname);
2088    break;
2089   case GenFunctions:
2090    printFunctions();
2091    break;
2092   case GenInline:
2093    if (fname.empty())
2094      fname = "makeLLVMInline";
2095    printInline(fname,tgtname);
2096    break;
2097   case GenVariable:
2098    if (fname.empty())
2099      fname = "makeLLVMVariable";
2100    printVariable(fname,tgtname);
2101    break;
2102   case GenType:
2103    if (fname.empty())
2104      fname = "makeLLVMType";
2105    printType(fname,tgtname);
2106    break;
2107  }
2108
2109  return false;
2110}
2111
2112char CppWriter::ID = 0;
2113
2114//===----------------------------------------------------------------------===//
2115//                       External Interface declaration
2116//===----------------------------------------------------------------------===//
2117
2118bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
2119                                           formatted_raw_ostream &o,
2120                                           CodeGenFileType FileType,
2121                                           bool DisableVerify,
2122                                           AnalysisID StartAfter,
2123                                           AnalysisID StopAfter) {
2124  if (FileType != TargetMachine::CGFT_AssemblyFile) return true;
2125  PM.add(new CppWriter(o));
2126  return false;
2127}
2128