LLVM  mainline
CPPBackend.cpp
Go to the documentation of this file.
00001 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the writing of the LLVM IR as a set of C++ calls to the
00011 // LLVM IR interface. The input module is assumed to be verified.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "CPPTargetMachine.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/Config/config.h"
00020 #include "llvm/IR/CallingConv.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/InlineAsm.h"
00024 #include "llvm/IR/Instruction.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/LegacyPassManager.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/MC/MCAsmInfo.h"
00029 #include "llvm/MC/MCInstrInfo.h"
00030 #include "llvm/MC/MCSubtargetInfo.h"
00031 #include "llvm/Pass.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include "llvm/Support/FormattedStream.h"
00035 #include "llvm/Support/TargetRegistry.h"
00036 #include <algorithm>
00037 #include <cctype>
00038 #include <cstdio>
00039 #include <map>
00040 #include <set>
00041 using namespace llvm;
00042 
00043 static cl::opt<std::string>
00044 FuncName("cppfname", cl::desc("Specify the name of the generated function"),
00045          cl::value_desc("function name"));
00046 
00047 enum WhatToGenerate {
00048   GenProgram,
00049   GenModule,
00050   GenContents,
00051   GenFunction,
00052   GenFunctions,
00053   GenInline,
00054   GenVariable,
00055   GenType
00056 };
00057 
00058 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional,
00059   cl::desc("Choose what kind of output to generate"),
00060   cl::init(GenProgram),
00061   cl::values(
00062     clEnumValN(GenProgram,  "program",   "Generate a complete program"),
00063     clEnumValN(GenModule,   "module",    "Generate a module definition"),
00064     clEnumValN(GenContents, "contents",  "Generate contents of a module"),
00065     clEnumValN(GenFunction, "function",  "Generate a function definition"),
00066     clEnumValN(GenFunctions,"functions", "Generate all function definitions"),
00067     clEnumValN(GenInline,   "inline",    "Generate an inline function"),
00068     clEnumValN(GenVariable, "variable",  "Generate a variable definition"),
00069     clEnumValN(GenType,     "type",      "Generate a type definition"),
00070     clEnumValEnd
00071   )
00072 );
00073 
00074 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional,
00075   cl::desc("Specify the name of the thing to generate"),
00076   cl::init("!bad!"));
00077 
00078 extern "C" void LLVMInitializeCppBackendTarget() {
00079   // Register the target.
00080   RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget);
00081 }
00082 
00083 namespace {
00084   typedef std::vector<Type*> TypeList;
00085   typedef std::map<Type*,std::string> TypeMap;
00086   typedef std::map<const Value*,std::string> ValueMap;
00087   typedef std::set<std::string> NameSet;
00088   typedef std::set<Type*> TypeSet;
00089   typedef std::set<const Value*> ValueSet;
00090   typedef std::map<const Value*,std::string> ForwardRefMap;
00091 
00092   /// CppWriter - This class is the main chunk of code that converts an LLVM
00093   /// module to a C++ translation unit.
00094   class CppWriter : public ModulePass {
00095     std::unique_ptr<formatted_raw_ostream> OutOwner;
00096     formatted_raw_ostream &Out;
00097     const Module *TheModule;
00098     uint64_t uniqueNum;
00099     TypeMap TypeNames;
00100     ValueMap ValueNames;
00101     NameSet UsedNames;
00102     TypeSet DefinedTypes;
00103     ValueSet DefinedValues;
00104     ForwardRefMap ForwardRefs;
00105     bool is_inline;
00106     unsigned indent_level;
00107 
00108   public:
00109     static char ID;
00110     explicit CppWriter(std::unique_ptr<formatted_raw_ostream> o)
00111         : ModulePass(ID), OutOwner(std::move(o)), Out(*OutOwner), uniqueNum(0),
00112           is_inline(false), indent_level(0) {}
00113 
00114     const char *getPassName() const override { return "C++ backend"; }
00115 
00116     bool runOnModule(Module &M) override;
00117 
00118     void printProgram(const std::string& fname, const std::string& modName );
00119     void printModule(const std::string& fname, const std::string& modName );
00120     void printContents(const std::string& fname, const std::string& modName );
00121     void printFunction(const std::string& fname, const std::string& funcName );
00122     void printFunctions();
00123     void printInline(const std::string& fname, const std::string& funcName );
00124     void printVariable(const std::string& fname, const std::string& varName );
00125     void printType(const std::string& fname, const std::string& typeName );
00126 
00127     void error(const std::string& msg);
00128 
00129     
00130     formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0);
00131     inline void in() { indent_level++; }
00132     inline void out() { if (indent_level >0) indent_level--; }
00133     
00134   private:
00135     void printLinkageType(GlobalValue::LinkageTypes LT);
00136     void printVisibilityType(GlobalValue::VisibilityTypes VisTypes);
00137     void printDLLStorageClassType(GlobalValue::DLLStorageClassTypes DSCType);
00138     void printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM);
00139     void printCallingConv(CallingConv::ID cc);
00140     void printEscapedString(const std::string& str);
00141     void printCFP(const ConstantFP* CFP);
00142 
00143     std::string getCppName(Type* val);
00144     inline void printCppName(Type* val);
00145 
00146     std::string getCppName(const Value* val);
00147     inline void printCppName(const Value* val);
00148 
00149     void printAttributes(const AttributeSet &PAL, const std::string &name);
00150     void printType(Type* Ty);
00151     void printTypes(const Module* M);
00152 
00153     void printConstant(const Constant *CPV);
00154     void printConstants(const Module* M);
00155 
00156     void printVariableUses(const GlobalVariable *GV);
00157     void printVariableHead(const GlobalVariable *GV);
00158     void printVariableBody(const GlobalVariable *GV);
00159 
00160     void printFunctionUses(const Function *F);
00161     void printFunctionHead(const Function *F);
00162     void printFunctionBody(const Function *F);
00163     void printInstruction(const Instruction *I, const std::string& bbname);
00164     std::string getOpName(const Value*);
00165 
00166     void printModuleBody();
00167   };
00168 } // end anonymous namespace.
00169 
00170 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) {
00171   Out << '\n';
00172   if (delta >= 0 || indent_level >= unsigned(-delta))
00173     indent_level += delta;
00174   Out.indent(indent_level);
00175   return Out;
00176 }
00177 
00178 static inline void sanitize(std::string &str) {
00179   for (size_t i = 0; i < str.length(); ++i)
00180     if (!isalnum(str[i]) && str[i] != '_')
00181       str[i] = '_';
00182 }
00183 
00184 static std::string getTypePrefix(Type *Ty) {
00185   switch (Ty->getTypeID()) {
00186   case Type::VoidTyID:     return "void_";
00187   case Type::IntegerTyID:
00188     return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_";
00189   case Type::FloatTyID:    return "float_";
00190   case Type::DoubleTyID:   return "double_";
00191   case Type::LabelTyID:    return "label_";
00192   case Type::FunctionTyID: return "func_";
00193   case Type::StructTyID:   return "struct_";
00194   case Type::ArrayTyID:    return "array_";
00195   case Type::PointerTyID:  return "ptr_";
00196   case Type::VectorTyID:   return "packed_";
00197   default:                 return "other_";
00198   }
00199 }
00200 
00201 void CppWriter::error(const std::string& msg) {
00202   report_fatal_error(msg);
00203 }
00204 
00205 static inline std::string ftostr(const APFloat& V) {
00206   std::string Buf;
00207   if (&V.getSemantics() == &APFloat::IEEEdouble) {
00208     raw_string_ostream(Buf) << V.convertToDouble();
00209     return Buf;
00210   } else if (&V.getSemantics() == &APFloat::IEEEsingle) {
00211     raw_string_ostream(Buf) << (double)V.convertToFloat();
00212     return Buf;
00213   }
00214   return "<unknown format in ftostr>"; // error
00215 }
00216 
00217 // printCFP - Print a floating point constant .. very carefully :)
00218 // This makes sure that conversion to/from floating yields the same binary
00219 // result so that we don't lose precision.
00220 void CppWriter::printCFP(const ConstantFP *CFP) {
00221   bool ignored;
00222   APFloat APF = APFloat(CFP->getValueAPF());  // copy
00223   if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
00224     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
00225   Out << "ConstantFP::get(mod->getContext(), ";
00226   Out << "APFloat(";
00227 #if HAVE_PRINTF_A
00228   char Buffer[100];
00229   sprintf(Buffer, "%A", APF.convertToDouble());
00230   if ((!strncmp(Buffer, "0x", 2) ||
00231        !strncmp(Buffer, "-0x", 3) ||
00232        !strncmp(Buffer, "+0x", 3)) &&
00233       APF.bitwiseIsEqual(APFloat(atof(Buffer)))) {
00234     if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
00235       Out << "BitsToDouble(" << Buffer << ")";
00236     else
00237       Out << "BitsToFloat((float)" << Buffer << ")";
00238     Out << ")";
00239   } else {
00240 #endif
00241     std::string StrVal = ftostr(CFP->getValueAPF());
00242 
00243     while (StrVal[0] == ' ')
00244       StrVal.erase(StrVal.begin());
00245 
00246     // Check to make sure that the stringized number is not some string like
00247     // "Inf" or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
00248     if (((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00249          ((StrVal[0] == '-' || StrVal[0] == '+') &&
00250           (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
00251         (CFP->isExactlyValue(atof(StrVal.c_str())))) {
00252       if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
00253         Out <<  StrVal;
00254       else
00255         Out << StrVal << "f";
00256     } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
00257       Out << "BitsToDouble(0x"
00258           << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue())
00259           << "ULL) /* " << StrVal << " */";
00260     else
00261       Out << "BitsToFloat(0x"
00262           << utohexstr((uint32_t)CFP->getValueAPF().
00263                                       bitcastToAPInt().getZExtValue())
00264           << "U) /* " << StrVal << " */";
00265     Out << ")";
00266 #if HAVE_PRINTF_A
00267   }
00268 #endif
00269   Out << ")";
00270 }
00271 
00272 void CppWriter::printCallingConv(CallingConv::ID cc){
00273   // Print the calling convention.
00274   switch (cc) {
00275   case CallingConv::C:     Out << "CallingConv::C"; break;
00276   case CallingConv::Fast:  Out << "CallingConv::Fast"; break;
00277   case CallingConv::Cold:  Out << "CallingConv::Cold"; break;
00278   case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
00279   default:                 Out << cc; break;
00280   }
00281 }
00282 
00283 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
00284   switch (LT) {
00285   case GlobalValue::InternalLinkage:
00286     Out << "GlobalValue::InternalLinkage"; break;
00287   case GlobalValue::PrivateLinkage:
00288     Out << "GlobalValue::PrivateLinkage"; break;
00289   case GlobalValue::AvailableExternallyLinkage:
00290     Out << "GlobalValue::AvailableExternallyLinkage "; break;
00291   case GlobalValue::LinkOnceAnyLinkage:
00292     Out << "GlobalValue::LinkOnceAnyLinkage "; break;
00293   case GlobalValue::LinkOnceODRLinkage:
00294     Out << "GlobalValue::LinkOnceODRLinkage "; break;
00295   case GlobalValue::WeakAnyLinkage:
00296     Out << "GlobalValue::WeakAnyLinkage"; break;
00297   case GlobalValue::WeakODRLinkage:
00298     Out << "GlobalValue::WeakODRLinkage"; break;
00299   case GlobalValue::AppendingLinkage:
00300     Out << "GlobalValue::AppendingLinkage"; break;
00301   case GlobalValue::ExternalLinkage:
00302     Out << "GlobalValue::ExternalLinkage"; break;
00303   case GlobalValue::ExternalWeakLinkage:
00304     Out << "GlobalValue::ExternalWeakLinkage"; break;
00305   case GlobalValue::CommonLinkage:
00306     Out << "GlobalValue::CommonLinkage"; break;
00307   }
00308 }
00309 
00310 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
00311   switch (VisType) {
00312   case GlobalValue::DefaultVisibility:
00313     Out << "GlobalValue::DefaultVisibility";
00314     break;
00315   case GlobalValue::HiddenVisibility:
00316     Out << "GlobalValue::HiddenVisibility";
00317     break;
00318   case GlobalValue::ProtectedVisibility:
00319     Out << "GlobalValue::ProtectedVisibility";
00320     break;
00321   }
00322 }
00323 
00324 void CppWriter::printDLLStorageClassType(
00325                                     GlobalValue::DLLStorageClassTypes DSCType) {
00326   switch (DSCType) {
00327   case GlobalValue::DefaultStorageClass:
00328     Out << "GlobalValue::DefaultStorageClass";
00329     break;
00330   case GlobalValue::DLLImportStorageClass:
00331     Out << "GlobalValue::DLLImportStorageClass";
00332     break;
00333   case GlobalValue::DLLExportStorageClass:
00334     Out << "GlobalValue::DLLExportStorageClass";
00335     break;
00336   }
00337 }
00338 
00339 void CppWriter::printThreadLocalMode(GlobalVariable::ThreadLocalMode TLM) {
00340   switch (TLM) {
00341     case GlobalVariable::NotThreadLocal:
00342       Out << "GlobalVariable::NotThreadLocal";
00343       break;
00344     case GlobalVariable::GeneralDynamicTLSModel:
00345       Out << "GlobalVariable::GeneralDynamicTLSModel";
00346       break;
00347     case GlobalVariable::LocalDynamicTLSModel:
00348       Out << "GlobalVariable::LocalDynamicTLSModel";
00349       break;
00350     case GlobalVariable::InitialExecTLSModel:
00351       Out << "GlobalVariable::InitialExecTLSModel";
00352       break;
00353     case GlobalVariable::LocalExecTLSModel:
00354       Out << "GlobalVariable::LocalExecTLSModel";
00355       break;
00356   }
00357 }
00358 
00359 // printEscapedString - Print each character of the specified string, escaping
00360 // it if it is not printable or if it is an escape char.
00361 void CppWriter::printEscapedString(const std::string &Str) {
00362   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00363     unsigned char C = Str[i];
00364     if (isprint(C) && C != '"' && C != '\\') {
00365       Out << C;
00366     } else {
00367       Out << "\\x"
00368           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
00369           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
00370     }
00371   }
00372 }
00373 
00374 std::string CppWriter::getCppName(Type* Ty) {
00375   switch (Ty->getTypeID()) {
00376   default:
00377     break;
00378   case Type::VoidTyID:
00379     return "Type::getVoidTy(mod->getContext())";
00380   case Type::IntegerTyID: {
00381     unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
00382     return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")";
00383   }
00384   case Type::X86_FP80TyID:
00385     return "Type::getX86_FP80Ty(mod->getContext())";
00386   case Type::FloatTyID:
00387     return "Type::getFloatTy(mod->getContext())";
00388   case Type::DoubleTyID:
00389     return "Type::getDoubleTy(mod->getContext())";
00390   case Type::LabelTyID:
00391     return "Type::getLabelTy(mod->getContext())";
00392   case Type::X86_MMXTyID:
00393     return "Type::getX86_MMXTy(mod->getContext())";
00394   }
00395 
00396   // Now, see if we've seen the type before and return that
00397   TypeMap::iterator I = TypeNames.find(Ty);
00398   if (I != TypeNames.end())
00399     return I->second;
00400 
00401   // Okay, let's build a new name for this type. Start with a prefix
00402   const char* prefix = nullptr;
00403   switch (Ty->getTypeID()) {
00404   case Type::FunctionTyID:    prefix = "FuncTy_"; break;
00405   case Type::StructTyID:      prefix = "StructTy_"; break;
00406   case Type::ArrayTyID:       prefix = "ArrayTy_"; break;
00407   case Type::PointerTyID:     prefix = "PointerTy_"; break;
00408   case Type::VectorTyID:      prefix = "VectorTy_"; break;
00409   default:                    prefix = "OtherTy_"; break; // prevent breakage
00410   }
00411 
00412   // See if the type has a name in the symboltable and build accordingly
00413   std::string name;
00414   if (StructType *STy = dyn_cast<StructType>(Ty))
00415     if (STy->hasName())
00416       name = STy->getName();
00417   
00418   if (name.empty())
00419     name = utostr(uniqueNum++);
00420   
00421   name = std::string(prefix) + name;
00422   sanitize(name);
00423 
00424   // Save the name
00425   return TypeNames[Ty] = name;
00426 }
00427 
00428 void CppWriter::printCppName(Type* Ty) {
00429   printEscapedString(getCppName(Ty));
00430 }
00431 
00432 std::string CppWriter::getCppName(const Value* val) {
00433   std::string name;
00434   ValueMap::iterator I = ValueNames.find(val);
00435   if (I != ValueNames.end() && I->first == val)
00436     return  I->second;
00437 
00438   if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) {
00439     name = std::string("gvar_") +
00440       getTypePrefix(GV->getType()->getElementType());
00441   } else if (isa<Function>(val)) {
00442     name = std::string("func_");
00443   } else if (const Constant* C = dyn_cast<Constant>(val)) {
00444     name = std::string("const_") + getTypePrefix(C->getType());
00445   } else if (const Argument* Arg = dyn_cast<Argument>(val)) {
00446     if (is_inline) {
00447       unsigned argNum = std::distance(Arg->getParent()->arg_begin(),
00448                                       Function::const_arg_iterator(Arg)) + 1;
00449       name = std::string("arg_") + utostr(argNum);
00450       NameSet::iterator NI = UsedNames.find(name);
00451       if (NI != UsedNames.end())
00452         name += std::string("_") + utostr(uniqueNum++);
00453       UsedNames.insert(name);
00454       return ValueNames[val] = name;
00455     } else {
00456       name = getTypePrefix(val->getType());
00457     }
00458   } else {
00459     name = getTypePrefix(val->getType());
00460   }
00461   if (val->hasName())
00462     name += val->getName();
00463   else
00464     name += utostr(uniqueNum++);
00465   sanitize(name);
00466   NameSet::iterator NI = UsedNames.find(name);
00467   if (NI != UsedNames.end())
00468     name += std::string("_") + utostr(uniqueNum++);
00469   UsedNames.insert(name);
00470   return ValueNames[val] = name;
00471 }
00472 
00473 void CppWriter::printCppName(const Value* val) {
00474   printEscapedString(getCppName(val));
00475 }
00476 
00477 void CppWriter::printAttributes(const AttributeSet &PAL,
00478                                 const std::string &name) {
00479   Out << "AttributeSet " << name << "_PAL;";
00480   nl(Out);
00481   if (!PAL.isEmpty()) {
00482     Out << '{'; in(); nl(Out);
00483     Out << "SmallVector<AttributeSet, 4> Attrs;"; nl(Out);
00484     Out << "AttributeSet PAS;"; in(); nl(Out);
00485     for (unsigned i = 0; i < PAL.getNumSlots(); ++i) {
00486       unsigned index = PAL.getSlotIndex(i);
00487       AttrBuilder attrs(PAL.getSlotAttributes(i), index);
00488       Out << "{"; in(); nl(Out);
00489       Out << "AttrBuilder B;"; nl(Out);
00490 
00491 #define HANDLE_ATTR(X)                                                  \
00492       if (attrs.contains(Attribute::X)) {                               \
00493         Out << "B.addAttribute(Attribute::" #X ");"; nl(Out);           \
00494         attrs.removeAttribute(Attribute::X);                            \
00495       }
00496 
00497       HANDLE_ATTR(SExt);
00498       HANDLE_ATTR(ZExt);
00499       HANDLE_ATTR(NoReturn);
00500       HANDLE_ATTR(InReg);
00501       HANDLE_ATTR(StructRet);
00502       HANDLE_ATTR(NoUnwind);
00503       HANDLE_ATTR(NoAlias);
00504       HANDLE_ATTR(ByVal);
00505       HANDLE_ATTR(InAlloca);
00506       HANDLE_ATTR(Nest);
00507       HANDLE_ATTR(ReadNone);
00508       HANDLE_ATTR(ReadOnly);
00509       HANDLE_ATTR(NoInline);
00510       HANDLE_ATTR(AlwaysInline);
00511       HANDLE_ATTR(OptimizeNone);
00512       HANDLE_ATTR(OptimizeForSize);
00513       HANDLE_ATTR(StackProtect);
00514       HANDLE_ATTR(StackProtectReq);
00515       HANDLE_ATTR(StackProtectStrong);
00516       HANDLE_ATTR(NoCapture);
00517       HANDLE_ATTR(NoRedZone);
00518       HANDLE_ATTR(NoImplicitFloat);
00519       HANDLE_ATTR(Naked);
00520       HANDLE_ATTR(InlineHint);
00521       HANDLE_ATTR(ReturnsTwice);
00522       HANDLE_ATTR(UWTable);
00523       HANDLE_ATTR(NonLazyBind);
00524       HANDLE_ATTR(MinSize);
00525 #undef HANDLE_ATTR
00526 
00527       if (attrs.contains(Attribute::StackAlignment)) {
00528         Out << "B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<')';
00529         nl(Out);
00530         attrs.removeAttribute(Attribute::StackAlignment);
00531       }
00532 
00533       Out << "PAS = AttributeSet::get(mod->getContext(), ";
00534       if (index == ~0U)
00535         Out << "~0U,";
00536       else
00537         Out << index << "U,";
00538       Out << " B);"; out(); nl(Out);
00539       Out << "}"; out(); nl(Out);
00540       nl(Out);
00541       Out << "Attrs.push_back(PAS);"; nl(Out);
00542     }
00543     Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
00544     nl(Out);
00545     out(); nl(Out);
00546     Out << '}'; nl(Out);
00547   }
00548 }
00549 
00550 void CppWriter::printType(Type* Ty) {
00551   // We don't print definitions for primitive types
00552   if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() ||
00553       Ty->isLabelTy() || Ty->isMetadataTy() || Ty->isVoidTy())
00554     return;
00555 
00556   // If we already defined this type, we don't need to define it again.
00557   if (DefinedTypes.find(Ty) != DefinedTypes.end())
00558     return;
00559 
00560   // Everything below needs the name for the type so get it now.
00561   std::string typeName(getCppName(Ty));
00562 
00563   // Print the type definition
00564   switch (Ty->getTypeID()) {
00565   case Type::FunctionTyID:  {
00566     FunctionType* FT = cast<FunctionType>(Ty);
00567     Out << "std::vector<Type*>" << typeName << "_args;";
00568     nl(Out);
00569     FunctionType::param_iterator PI = FT->param_begin();
00570     FunctionType::param_iterator PE = FT->param_end();
00571     for (; PI != PE; ++PI) {
00572       Type* argTy = static_cast<Type*>(*PI);
00573       printType(argTy);
00574       std::string argName(getCppName(argTy));
00575       Out << typeName << "_args.push_back(" << argName;
00576       Out << ");";
00577       nl(Out);
00578     }
00579     printType(FT->getReturnType());
00580     std::string retTypeName(getCppName(FT->getReturnType()));
00581     Out << "FunctionType* " << typeName << " = FunctionType::get(";
00582     in(); nl(Out) << "/*Result=*/" << retTypeName;
00583     Out << ",";
00584     nl(Out) << "/*Params=*/" << typeName << "_args,";
00585     nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
00586     out();
00587     nl(Out);
00588     break;
00589   }
00590   case Type::StructTyID: {
00591     StructType* ST = cast<StructType>(Ty);
00592     if (!ST->isLiteral()) {
00593       Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
00594       printEscapedString(ST->getName());
00595       Out << "\");";
00596       nl(Out);
00597       Out << "if (!" << typeName << ") {";
00598       nl(Out);
00599       Out << typeName << " = ";
00600       Out << "StructType::create(mod->getContext(), \"";
00601       printEscapedString(ST->getName());
00602       Out << "\");";
00603       nl(Out);
00604       Out << "}";
00605       nl(Out);
00606       // Indicate that this type is now defined.
00607       DefinedTypes.insert(Ty);
00608     }
00609 
00610     Out << "std::vector<Type*>" << typeName << "_fields;";
00611     nl(Out);
00612     StructType::element_iterator EI = ST->element_begin();
00613     StructType::element_iterator EE = ST->element_end();
00614     for (; EI != EE; ++EI) {
00615       Type* fieldTy = static_cast<Type*>(*EI);
00616       printType(fieldTy);
00617       std::string fieldName(getCppName(fieldTy));
00618       Out << typeName << "_fields.push_back(" << fieldName;
00619       Out << ");";
00620       nl(Out);
00621     }
00622 
00623     if (ST->isLiteral()) {
00624       Out << "StructType *" << typeName << " = ";
00625       Out << "StructType::get(" << "mod->getContext(), ";
00626     } else {
00627       Out << "if (" << typeName << "->isOpaque()) {";
00628       nl(Out);
00629       Out << typeName << "->setBody(";
00630     }
00631 
00632     Out << typeName << "_fields, /*isPacked=*/"
00633         << (ST->isPacked() ? "true" : "false") << ");";
00634     nl(Out);
00635     if (!ST->isLiteral()) {
00636       Out << "}";
00637       nl(Out);
00638     }
00639     break;
00640   }
00641   case Type::ArrayTyID: {
00642     ArrayType* AT = cast<ArrayType>(Ty);
00643     Type* ET = AT->getElementType();
00644     printType(ET);
00645     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00646       std::string elemName(getCppName(ET));
00647       Out << "ArrayType* " << typeName << " = ArrayType::get("
00648           << elemName
00649           << ", " << utostr(AT->getNumElements()) << ");";
00650       nl(Out);
00651     }
00652     break;
00653   }
00654   case Type::PointerTyID: {
00655     PointerType* PT = cast<PointerType>(Ty);
00656     Type* ET = PT->getElementType();
00657     printType(ET);
00658     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00659       std::string elemName(getCppName(ET));
00660       Out << "PointerType* " << typeName << " = PointerType::get("
00661           << elemName
00662           << ", " << utostr(PT->getAddressSpace()) << ");";
00663       nl(Out);
00664     }
00665     break;
00666   }
00667   case Type::VectorTyID: {
00668     VectorType* PT = cast<VectorType>(Ty);
00669     Type* ET = PT->getElementType();
00670     printType(ET);
00671     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00672       std::string elemName(getCppName(ET));
00673       Out << "VectorType* " << typeName << " = VectorType::get("
00674           << elemName
00675           << ", " << utostr(PT->getNumElements()) << ");";
00676       nl(Out);
00677     }
00678     break;
00679   }
00680   default:
00681     error("Invalid TypeID");
00682   }
00683 
00684   // Indicate that this type is now defined.
00685   DefinedTypes.insert(Ty);
00686 
00687   // Finally, separate the type definition from other with a newline.
00688   nl(Out);
00689 }
00690 
00691 void CppWriter::printTypes(const Module* M) {
00692   // Add all of the global variables to the value table.
00693   for (Module::const_global_iterator I = TheModule->global_begin(),
00694          E = TheModule->global_end(); I != E; ++I) {
00695     if (I->hasInitializer())
00696       printType(I->getInitializer()->getType());
00697     printType(I->getType());
00698   }
00699 
00700   // Add all the functions to the table
00701   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
00702        FI != FE; ++FI) {
00703     printType(FI->getReturnType());
00704     printType(FI->getFunctionType());
00705     // Add all the function arguments
00706     for (Function::const_arg_iterator AI = FI->arg_begin(),
00707            AE = FI->arg_end(); AI != AE; ++AI) {
00708       printType(AI->getType());
00709     }
00710 
00711     // Add all of the basic blocks and instructions
00712     for (Function::const_iterator BB = FI->begin(),
00713            E = FI->end(); BB != E; ++BB) {
00714       printType(BB->getType());
00715       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
00716            ++I) {
00717         printType(I->getType());
00718         for (unsigned i = 0; i < I->getNumOperands(); ++i)
00719           printType(I->getOperand(i)->getType());
00720       }
00721     }
00722   }
00723 }
00724 
00725 
00726 // printConstant - Print out a constant pool entry...
00727 void CppWriter::printConstant(const Constant *CV) {
00728   // First, if the constant is actually a GlobalValue (variable or function)
00729   // or its already in the constant list then we've printed it already and we
00730   // can just return.
00731   if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
00732     return;
00733 
00734   std::string constName(getCppName(CV));
00735   std::string typeName(getCppName(CV->getType()));
00736 
00737   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00738     std::string constValue = CI->getValue().toString(10, true);
00739     Out << "ConstantInt* " << constName
00740         << " = ConstantInt::get(mod->getContext(), APInt("
00741         << cast<IntegerType>(CI->getType())->getBitWidth()
00742         << ", StringRef(\"" <<  constValue << "\"), 10));";
00743   } else if (isa<ConstantAggregateZero>(CV)) {
00744     Out << "ConstantAggregateZero* " << constName
00745         << " = ConstantAggregateZero::get(" << typeName << ");";
00746   } else if (isa<ConstantPointerNull>(CV)) {
00747     Out << "ConstantPointerNull* " << constName
00748         << " = ConstantPointerNull::get(" << typeName << ");";
00749   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00750     Out << "ConstantFP* " << constName << " = ";
00751     printCFP(CFP);
00752     Out << ";";
00753   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
00754     Out << "std::vector<Constant*> " << constName << "_elems;";
00755     nl(Out);
00756     unsigned N = CA->getNumOperands();
00757     for (unsigned i = 0; i < N; ++i) {
00758       printConstant(CA->getOperand(i)); // recurse to print operands
00759       Out << constName << "_elems.push_back("
00760           << getCppName(CA->getOperand(i)) << ");";
00761       nl(Out);
00762     }
00763     Out << "Constant* " << constName << " = ConstantArray::get("
00764         << typeName << ", " << constName << "_elems);";
00765   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
00766     Out << "std::vector<Constant*> " << constName << "_fields;";
00767     nl(Out);
00768     unsigned N = CS->getNumOperands();
00769     for (unsigned i = 0; i < N; i++) {
00770       printConstant(CS->getOperand(i));
00771       Out << constName << "_fields.push_back("
00772           << getCppName(CS->getOperand(i)) << ");";
00773       nl(Out);
00774     }
00775     Out << "Constant* " << constName << " = ConstantStruct::get("
00776         << typeName << ", " << constName << "_fields);";
00777   } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
00778     Out << "std::vector<Constant*> " << constName << "_elems;";
00779     nl(Out);
00780     unsigned N = CVec->getNumOperands();
00781     for (unsigned i = 0; i < N; ++i) {
00782       printConstant(CVec->getOperand(i));
00783       Out << constName << "_elems.push_back("
00784           << getCppName(CVec->getOperand(i)) << ");";
00785       nl(Out);
00786     }
00787     Out << "Constant* " << constName << " = ConstantVector::get("
00788         << typeName << ", " << constName << "_elems);";
00789   } else if (isa<UndefValue>(CV)) {
00790     Out << "UndefValue* " << constName << " = UndefValue::get("
00791         << typeName << ");";
00792   } else if (const ConstantDataSequential *CDS =
00793                dyn_cast<ConstantDataSequential>(CV)) {
00794     if (CDS->isString()) {
00795       Out << "Constant *" << constName <<
00796       " = ConstantDataArray::getString(mod->getContext(), \"";
00797       StringRef Str = CDS->getAsString();
00798       bool nullTerminate = false;
00799       if (Str.back() == 0) {
00800         Str = Str.drop_back();
00801         nullTerminate = true;
00802       }
00803       printEscapedString(Str);
00804       // Determine if we want null termination or not.
00805       if (nullTerminate)
00806         Out << "\", true);";
00807       else
00808         Out << "\", false);";// No null terminator
00809     } else {
00810       // TODO: Could generate more efficient code generating CDS calls instead.
00811       Out << "std::vector<Constant*> " << constName << "_elems;";
00812       nl(Out);
00813       for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
00814         Constant *Elt = CDS->getElementAsConstant(i);
00815         printConstant(Elt);
00816         Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
00817         nl(Out);
00818       }
00819       Out << "Constant* " << constName;
00820       
00821       if (isa<ArrayType>(CDS->getType()))
00822         Out << " = ConstantArray::get(";
00823       else
00824         Out << " = ConstantVector::get(";
00825       Out << typeName << ", " << constName << "_elems);";
00826     }
00827   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
00828     if (CE->getOpcode() == Instruction::GetElementPtr) {
00829       Out << "std::vector<Constant*> " << constName << "_indices;";
00830       nl(Out);
00831       printConstant(CE->getOperand(0));
00832       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
00833         printConstant(CE->getOperand(i));
00834         Out << constName << "_indices.push_back("
00835             << getCppName(CE->getOperand(i)) << ");";
00836         nl(Out);
00837       }
00838       Out << "Constant* " << constName
00839           << " = ConstantExpr::getGetElementPtr("
00840           << getCppName(CE->getOperand(0)) << ", "
00841           << constName << "_indices);";
00842     } else if (CE->isCast()) {
00843       printConstant(CE->getOperand(0));
00844       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
00845       switch (CE->getOpcode()) {
00846       default: llvm_unreachable("Invalid cast opcode");
00847       case Instruction::Trunc: Out << "Instruction::Trunc"; break;
00848       case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
00849       case Instruction::SExt:  Out << "Instruction::SExt"; break;
00850       case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
00851       case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
00852       case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
00853       case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
00854       case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
00855       case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
00856       case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
00857       case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
00858       case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
00859       }
00860       Out << ", " << getCppName(CE->getOperand(0)) << ", "
00861           << getCppName(CE->getType()) << ");";
00862     } else {
00863       unsigned N = CE->getNumOperands();
00864       for (unsigned i = 0; i < N; ++i ) {
00865         printConstant(CE->getOperand(i));
00866       }
00867       Out << "Constant* " << constName << " = ConstantExpr::";
00868       switch (CE->getOpcode()) {
00869       case Instruction::Add:    Out << "getAdd(";  break;
00870       case Instruction::FAdd:   Out << "getFAdd(";  break;
00871       case Instruction::Sub:    Out << "getSub("; break;
00872       case Instruction::FSub:   Out << "getFSub("; break;
00873       case Instruction::Mul:    Out << "getMul("; break;
00874       case Instruction::FMul:   Out << "getFMul("; break;
00875       case Instruction::UDiv:   Out << "getUDiv("; break;
00876       case Instruction::SDiv:   Out << "getSDiv("; break;
00877       case Instruction::FDiv:   Out << "getFDiv("; break;
00878       case Instruction::URem:   Out << "getURem("; break;
00879       case Instruction::SRem:   Out << "getSRem("; break;
00880       case Instruction::FRem:   Out << "getFRem("; break;
00881       case Instruction::And:    Out << "getAnd("; break;
00882       case Instruction::Or:     Out << "getOr("; break;
00883       case Instruction::Xor:    Out << "getXor("; break;
00884       case Instruction::ICmp:
00885         Out << "getICmp(ICmpInst::ICMP_";
00886         switch (CE->getPredicate()) {
00887         case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
00888         case ICmpInst::ICMP_NE:  Out << "NE"; break;
00889         case ICmpInst::ICMP_SLT: Out << "SLT"; break;
00890         case ICmpInst::ICMP_ULT: Out << "ULT"; break;
00891         case ICmpInst::ICMP_SGT: Out << "SGT"; break;
00892         case ICmpInst::ICMP_UGT: Out << "UGT"; break;
00893         case ICmpInst::ICMP_SLE: Out << "SLE"; break;
00894         case ICmpInst::ICMP_ULE: Out << "ULE"; break;
00895         case ICmpInst::ICMP_SGE: Out << "SGE"; break;
00896         case ICmpInst::ICMP_UGE: Out << "UGE"; break;
00897         default: error("Invalid ICmp Predicate");
00898         }
00899         break;
00900       case Instruction::FCmp:
00901         Out << "getFCmp(FCmpInst::FCMP_";
00902         switch (CE->getPredicate()) {
00903         case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
00904         case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
00905         case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
00906         case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
00907         case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
00908         case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
00909         case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
00910         case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
00911         case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
00912         case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
00913         case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
00914         case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
00915         case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
00916         case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
00917         case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
00918         case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
00919         default: error("Invalid FCmp Predicate");
00920         }
00921         break;
00922       case Instruction::Shl:     Out << "getShl("; break;
00923       case Instruction::LShr:    Out << "getLShr("; break;
00924       case Instruction::AShr:    Out << "getAShr("; break;
00925       case Instruction::Select:  Out << "getSelect("; break;
00926       case Instruction::ExtractElement: Out << "getExtractElement("; break;
00927       case Instruction::InsertElement:  Out << "getInsertElement("; break;
00928       case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
00929       default:
00930         error("Invalid constant expression");
00931         break;
00932       }
00933       Out << getCppName(CE->getOperand(0));
00934       for (unsigned i = 1; i < CE->getNumOperands(); ++i)
00935         Out << ", " << getCppName(CE->getOperand(i));
00936       Out << ");";
00937     }
00938   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
00939     Out << "Constant* " << constName << " = ";
00940     Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
00941   } else {
00942     error("Bad Constant");
00943     Out << "Constant* " << constName << " = 0; ";
00944   }
00945   nl(Out);
00946 }
00947 
00948 void CppWriter::printConstants(const Module* M) {
00949   // Traverse all the global variables looking for constant initializers
00950   for (Module::const_global_iterator I = TheModule->global_begin(),
00951          E = TheModule->global_end(); I != E; ++I)
00952     if (I->hasInitializer())
00953       printConstant(I->getInitializer());
00954 
00955   // Traverse the LLVM functions looking for constants
00956   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
00957        FI != FE; ++FI) {
00958     // Add all of the basic blocks and instructions
00959     for (Function::const_iterator BB = FI->begin(),
00960            E = FI->end(); BB != E; ++BB) {
00961       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
00962            ++I) {
00963         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
00964           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
00965             printConstant(C);
00966           }
00967         }
00968       }
00969     }
00970   }
00971 }
00972 
00973 void CppWriter::printVariableUses(const GlobalVariable *GV) {
00974   nl(Out) << "// Type Definitions";
00975   nl(Out);
00976   printType(GV->getType());
00977   if (GV->hasInitializer()) {
00978     const Constant *Init = GV->getInitializer();
00979     printType(Init->getType());
00980     if (const Function *F = dyn_cast<Function>(Init)) {
00981       nl(Out)<< "/ Function Declarations"; nl(Out);
00982       printFunctionHead(F);
00983     } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
00984       nl(Out) << "// Global Variable Declarations"; nl(Out);
00985       printVariableHead(gv);
00986       
00987       nl(Out) << "// Global Variable Definitions"; nl(Out);
00988       printVariableBody(gv);
00989     } else  {
00990       nl(Out) << "// Constant Definitions"; nl(Out);
00991       printConstant(Init);
00992     }
00993   }
00994 }
00995 
00996 void CppWriter::printVariableHead(const GlobalVariable *GV) {
00997   nl(Out) << "GlobalVariable* " << getCppName(GV);
00998   if (is_inline) {
00999     Out << " = mod->getGlobalVariable(mod->getContext(), ";
01000     printEscapedString(GV->getName());
01001     Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)";
01002     nl(Out) << "if (!" << getCppName(GV) << ") {";
01003     in(); nl(Out) << getCppName(GV);
01004   }
01005   Out << " = new GlobalVariable(/*Module=*/*mod, ";
01006   nl(Out) << "/*Type=*/";
01007   printCppName(GV->getType()->getElementType());
01008   Out << ",";
01009   nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
01010   Out << ",";
01011   nl(Out) << "/*Linkage=*/";
01012   printLinkageType(GV->getLinkage());
01013   Out << ",";
01014   nl(Out) << "/*Initializer=*/0, ";
01015   if (GV->hasInitializer()) {
01016     Out << "// has initializer, specified below";
01017   }
01018   nl(Out) << "/*Name=*/\"";
01019   printEscapedString(GV->getName());
01020   Out << "\");";
01021   nl(Out);
01022 
01023   if (GV->hasSection()) {
01024     printCppName(GV);
01025     Out << "->setSection(\"";
01026     printEscapedString(GV->getSection());
01027     Out << "\");";
01028     nl(Out);
01029   }
01030   if (GV->getAlignment()) {
01031     printCppName(GV);
01032     Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");";
01033     nl(Out);
01034   }
01035   if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
01036     printCppName(GV);
01037     Out << "->setVisibility(";
01038     printVisibilityType(GV->getVisibility());
01039     Out << ");";
01040     nl(Out);
01041   }
01042   if (GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
01043     printCppName(GV);
01044     Out << "->setDLLStorageClass(";
01045     printDLLStorageClassType(GV->getDLLStorageClass());
01046     Out << ");";
01047     nl(Out);
01048   }
01049   if (GV->isThreadLocal()) {
01050     printCppName(GV);
01051     Out << "->setThreadLocalMode(";
01052     printThreadLocalMode(GV->getThreadLocalMode());
01053     Out << ");";
01054     nl(Out);
01055   }
01056   if (is_inline) {
01057     out(); Out << "}"; nl(Out);
01058   }
01059 }
01060 
01061 void CppWriter::printVariableBody(const GlobalVariable *GV) {
01062   if (GV->hasInitializer()) {
01063     printCppName(GV);
01064     Out << "->setInitializer(";
01065     Out << getCppName(GV->getInitializer()) << ");";
01066     nl(Out);
01067   }
01068 }
01069 
01070 std::string CppWriter::getOpName(const Value* V) {
01071   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
01072     return getCppName(V);
01073 
01074   // See if its alread in the map of forward references, if so just return the
01075   // name we already set up for it
01076   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
01077   if (I != ForwardRefs.end())
01078     return I->second;
01079 
01080   // This is a new forward reference. Generate a unique name for it
01081   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
01082 
01083   // Yes, this is a hack. An Argument is the smallest instantiable value that
01084   // we can make as a placeholder for the real value. We'll replace these
01085   // Argument instances later.
01086   Out << "Argument* " << result << " = new Argument("
01087       << getCppName(V->getType()) << ");";
01088   nl(Out);
01089   ForwardRefs[V] = result;
01090   return result;
01091 }
01092 
01093 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
01094   switch (Ordering) {
01095     case NotAtomic: return "NotAtomic";
01096     case Unordered: return "Unordered";
01097     case Monotonic: return "Monotonic";
01098     case Acquire: return "Acquire";
01099     case Release: return "Release";
01100     case AcquireRelease: return "AcquireRelease";
01101     case SequentiallyConsistent: return "SequentiallyConsistent";
01102   }
01103   llvm_unreachable("Unknown ordering");
01104 }
01105 
01106 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
01107   switch (SynchScope) {
01108     case SingleThread: return "SingleThread";
01109     case CrossThread: return "CrossThread";
01110   }
01111   llvm_unreachable("Unknown synch scope");
01112 }
01113 
01114 // printInstruction - This member is called for each Instruction in a function.
01115 void CppWriter::printInstruction(const Instruction *I,
01116                                  const std::string& bbname) {
01117   std::string iName(getCppName(I));
01118 
01119   // Before we emit this instruction, we need to take care of generating any
01120   // forward references. So, we get the names of all the operands in advance
01121   const unsigned Ops(I->getNumOperands());
01122   std::string* opNames = new std::string[Ops];
01123   for (unsigned i = 0; i < Ops; i++)
01124     opNames[i] = getOpName(I->getOperand(i));
01125 
01126   switch (I->getOpcode()) {
01127   default:
01128     error("Invalid instruction");
01129     break;
01130 
01131   case Instruction::Ret: {
01132     const ReturnInst* ret =  cast<ReturnInst>(I);
01133     Out << "ReturnInst::Create(mod->getContext(), "
01134         << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
01135     break;
01136   }
01137   case Instruction::Br: {
01138     const BranchInst* br = cast<BranchInst>(I);
01139     Out << "BranchInst::Create(" ;
01140     if (br->getNumOperands() == 3) {
01141       Out << opNames[2] << ", "
01142           << opNames[1] << ", "
01143           << opNames[0] << ", ";
01144 
01145     } else if (br->getNumOperands() == 1) {
01146       Out << opNames[0] << ", ";
01147     } else {
01148       error("Branch with 2 operands?");
01149     }
01150     Out << bbname << ");";
01151     break;
01152   }
01153   case Instruction::Switch: {
01154     const SwitchInst *SI = cast<SwitchInst>(I);
01155     Out << "SwitchInst* " << iName << " = SwitchInst::Create("
01156         << getOpName(SI->getCondition()) << ", "
01157         << getOpName(SI->getDefaultDest()) << ", "
01158         << SI->getNumCases() << ", " << bbname << ");";
01159     nl(Out);
01160     for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
01161          i != e; ++i) {
01162       const ConstantInt* CaseVal = i.getCaseValue();
01163       const BasicBlock *BB = i.getCaseSuccessor();
01164       Out << iName << "->addCase("
01165           << getOpName(CaseVal) << ", "
01166           << getOpName(BB) << ");";
01167       nl(Out);
01168     }
01169     break;
01170   }
01171   case Instruction::IndirectBr: {
01172     const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
01173     Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
01174         << opNames[0] << ", " << IBI->getNumDestinations() << ");";
01175     nl(Out);
01176     for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
01177       Out << iName << "->addDestination(" << opNames[i] << ");";
01178       nl(Out);
01179     }
01180     break;
01181   }
01182   case Instruction::Resume: {
01183     Out << "ResumeInst::Create(" << opNames[0] << ", " << bbname << ");";
01184     break;
01185   }
01186   case Instruction::Invoke: {
01187     const InvokeInst* inv = cast<InvokeInst>(I);
01188     Out << "std::vector<Value*> " << iName << "_params;";
01189     nl(Out);
01190     for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
01191       Out << iName << "_params.push_back("
01192           << getOpName(inv->getArgOperand(i)) << ");";
01193       nl(Out);
01194     }
01195     // FIXME: This shouldn't use magic numbers -3, -2, and -1.
01196     Out << "InvokeInst *" << iName << " = InvokeInst::Create("
01197         << getOpName(inv->getCalledValue()) << ", "
01198         << getOpName(inv->getNormalDest()) << ", "
01199         << getOpName(inv->getUnwindDest()) << ", "
01200         << iName << "_params, \"";
01201     printEscapedString(inv->getName());
01202     Out << "\", " << bbname << ");";
01203     nl(Out) << iName << "->setCallingConv(";
01204     printCallingConv(inv->getCallingConv());
01205     Out << ");";
01206     printAttributes(inv->getAttributes(), iName);
01207     Out << iName << "->setAttributes(" << iName << "_PAL);";
01208     nl(Out);
01209     break;
01210   }
01211   case Instruction::Unreachable: {
01212     Out << "new UnreachableInst("
01213         << "mod->getContext(), "
01214         << bbname << ");";
01215     break;
01216   }
01217   case Instruction::Add:
01218   case Instruction::FAdd:
01219   case Instruction::Sub:
01220   case Instruction::FSub:
01221   case Instruction::Mul:
01222   case Instruction::FMul:
01223   case Instruction::UDiv:
01224   case Instruction::SDiv:
01225   case Instruction::FDiv:
01226   case Instruction::URem:
01227   case Instruction::SRem:
01228   case Instruction::FRem:
01229   case Instruction::And:
01230   case Instruction::Or:
01231   case Instruction::Xor:
01232   case Instruction::Shl:
01233   case Instruction::LShr:
01234   case Instruction::AShr:{
01235     Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
01236     switch (I->getOpcode()) {
01237     case Instruction::Add: Out << "Instruction::Add"; break;
01238     case Instruction::FAdd: Out << "Instruction::FAdd"; break;
01239     case Instruction::Sub: Out << "Instruction::Sub"; break;
01240     case Instruction::FSub: Out << "Instruction::FSub"; break;
01241     case Instruction::Mul: Out << "Instruction::Mul"; break;
01242     case Instruction::FMul: Out << "Instruction::FMul"; break;
01243     case Instruction::UDiv:Out << "Instruction::UDiv"; break;
01244     case Instruction::SDiv:Out << "Instruction::SDiv"; break;
01245     case Instruction::FDiv:Out << "Instruction::FDiv"; break;
01246     case Instruction::URem:Out << "Instruction::URem"; break;
01247     case Instruction::SRem:Out << "Instruction::SRem"; break;
01248     case Instruction::FRem:Out << "Instruction::FRem"; break;
01249     case Instruction::And: Out << "Instruction::And"; break;
01250     case Instruction::Or:  Out << "Instruction::Or";  break;
01251     case Instruction::Xor: Out << "Instruction::Xor"; break;
01252     case Instruction::Shl: Out << "Instruction::Shl"; break;
01253     case Instruction::LShr:Out << "Instruction::LShr"; break;
01254     case Instruction::AShr:Out << "Instruction::AShr"; break;
01255     default: Out << "Instruction::BadOpCode"; break;
01256     }
01257     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01258     printEscapedString(I->getName());
01259     Out << "\", " << bbname << ");";
01260     break;
01261   }
01262   case Instruction::FCmp: {
01263     Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
01264     switch (cast<FCmpInst>(I)->getPredicate()) {
01265     case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
01266     case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
01267     case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
01268     case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
01269     case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
01270     case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
01271     case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
01272     case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
01273     case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
01274     case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
01275     case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
01276     case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
01277     case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
01278     case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
01279     case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
01280     case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
01281     default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
01282     }
01283     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01284     printEscapedString(I->getName());
01285     Out << "\");";
01286     break;
01287   }
01288   case Instruction::ICmp: {
01289     Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
01290     switch (cast<ICmpInst>(I)->getPredicate()) {
01291     case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
01292     case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
01293     case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
01294     case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
01295     case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
01296     case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
01297     case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
01298     case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
01299     case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
01300     case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
01301     default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
01302     }
01303     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01304     printEscapedString(I->getName());
01305     Out << "\");";
01306     break;
01307   }
01308   case Instruction::Alloca: {
01309     const AllocaInst* allocaI = cast<AllocaInst>(I);
01310     Out << "AllocaInst* " << iName << " = new AllocaInst("
01311         << getCppName(allocaI->getAllocatedType()) << ", ";
01312     if (allocaI->isArrayAllocation())
01313       Out << opNames[0] << ", ";
01314     Out << "\"";
01315     printEscapedString(allocaI->getName());
01316     Out << "\", " << bbname << ");";
01317     if (allocaI->getAlignment())
01318       nl(Out) << iName << "->setAlignment("
01319           << allocaI->getAlignment() << ");";
01320     break;
01321   }
01322   case Instruction::Load: {
01323     const LoadInst* load = cast<LoadInst>(I);
01324     Out << "LoadInst* " << iName << " = new LoadInst("
01325         << opNames[0] << ", \"";
01326     printEscapedString(load->getName());
01327     Out << "\", " << (load->isVolatile() ? "true" : "false" )
01328         << ", " << bbname << ");";
01329     if (load->getAlignment())
01330       nl(Out) << iName << "->setAlignment("
01331               << load->getAlignment() << ");";
01332     if (load->isAtomic()) {
01333       StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
01334       StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
01335       nl(Out) << iName << "->setAtomic("
01336               << Ordering << ", " << CrossThread << ");";
01337     }
01338     break;
01339   }
01340   case Instruction::Store: {
01341     const StoreInst* store = cast<StoreInst>(I);
01342     Out << "StoreInst* " << iName << " = new StoreInst("
01343         << opNames[0] << ", "
01344         << opNames[1] << ", "
01345         << (store->isVolatile() ? "true" : "false")
01346         << ", " << bbname << ");";
01347     if (store->getAlignment())
01348       nl(Out) << iName << "->setAlignment("
01349               << store->getAlignment() << ");";
01350     if (store->isAtomic()) {
01351       StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
01352       StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
01353       nl(Out) << iName << "->setAtomic("
01354               << Ordering << ", " << CrossThread << ");";
01355     }
01356     break;
01357   }
01358   case Instruction::GetElementPtr: {
01359     const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
01360     if (gep->getNumOperands() <= 2) {
01361       Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
01362           << opNames[0];
01363       if (gep->getNumOperands() == 2)
01364         Out << ", " << opNames[1];
01365     } else {
01366       Out << "std::vector<Value*> " << iName << "_indices;";
01367       nl(Out);
01368       for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
01369         Out << iName << "_indices.push_back("
01370             << opNames[i] << ");";
01371         nl(Out);
01372       }
01373       Out << "Instruction* " << iName << " = GetElementPtrInst::Create("
01374           << opNames[0] << ", " << iName << "_indices";
01375     }
01376     Out << ", \"";
01377     printEscapedString(gep->getName());
01378     Out << "\", " << bbname << ");";
01379     break;
01380   }
01381   case Instruction::PHI: {
01382     const PHINode* phi = cast<PHINode>(I);
01383 
01384     Out << "PHINode* " << iName << " = PHINode::Create("
01385         << getCppName(phi->getType()) << ", "
01386         << phi->getNumIncomingValues() << ", \"";
01387     printEscapedString(phi->getName());
01388     Out << "\", " << bbname << ");";
01389     nl(Out);
01390     for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
01391       Out << iName << "->addIncoming("
01392           << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
01393           << getOpName(phi->getIncomingBlock(i)) << ");";
01394       nl(Out);
01395     }
01396     break;
01397   }
01398   case Instruction::Trunc:
01399   case Instruction::ZExt:
01400   case Instruction::SExt:
01401   case Instruction::FPTrunc:
01402   case Instruction::FPExt:
01403   case Instruction::FPToUI:
01404   case Instruction::FPToSI:
01405   case Instruction::UIToFP:
01406   case Instruction::SIToFP:
01407   case Instruction::PtrToInt:
01408   case Instruction::IntToPtr:
01409   case Instruction::BitCast: {
01410     const CastInst* cst = cast<CastInst>(I);
01411     Out << "CastInst* " << iName << " = new ";
01412     switch (I->getOpcode()) {
01413     case Instruction::Trunc:    Out << "TruncInst"; break;
01414     case Instruction::ZExt:     Out << "ZExtInst"; break;
01415     case Instruction::SExt:     Out << "SExtInst"; break;
01416     case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
01417     case Instruction::FPExt:    Out << "FPExtInst"; break;
01418     case Instruction::FPToUI:   Out << "FPToUIInst"; break;
01419     case Instruction::FPToSI:   Out << "FPToSIInst"; break;
01420     case Instruction::UIToFP:   Out << "UIToFPInst"; break;
01421     case Instruction::SIToFP:   Out << "SIToFPInst"; break;
01422     case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
01423     case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
01424     case Instruction::BitCast:  Out << "BitCastInst"; break;
01425     default: llvm_unreachable("Unreachable");
01426     }
01427     Out << "(" << opNames[0] << ", "
01428         << getCppName(cst->getType()) << ", \"";
01429     printEscapedString(cst->getName());
01430     Out << "\", " << bbname << ");";
01431     break;
01432   }
01433   case Instruction::Call: {
01434     const CallInst* call = cast<CallInst>(I);
01435     if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
01436       Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
01437           << getCppName(ila->getFunctionType()) << ", \""
01438           << ila->getAsmString() << "\", \""
01439           << ila->getConstraintString() << "\","
01440           << (ila->hasSideEffects() ? "true" : "false") << ");";
01441       nl(Out);
01442     }
01443     if (call->getNumArgOperands() > 1) {
01444       Out << "std::vector<Value*> " << iName << "_params;";
01445       nl(Out);
01446       for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
01447         Out << iName << "_params.push_back(" << opNames[i] << ");";
01448         nl(Out);
01449       }
01450       Out << "CallInst* " << iName << " = CallInst::Create("
01451           << opNames[call->getNumArgOperands()] << ", "
01452           << iName << "_params, \"";
01453     } else if (call->getNumArgOperands() == 1) {
01454       Out << "CallInst* " << iName << " = CallInst::Create("
01455           << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
01456     } else {
01457       Out << "CallInst* " << iName << " = CallInst::Create("
01458           << opNames[call->getNumArgOperands()] << ", \"";
01459     }
01460     printEscapedString(call->getName());
01461     Out << "\", " << bbname << ");";
01462     nl(Out) << iName << "->setCallingConv(";
01463     printCallingConv(call->getCallingConv());
01464     Out << ");";
01465     nl(Out) << iName << "->setTailCall("
01466         << (call->isTailCall() ? "true" : "false");
01467     Out << ");";
01468     nl(Out);
01469     printAttributes(call->getAttributes(), iName);
01470     Out << iName << "->setAttributes(" << iName << "_PAL);";
01471     nl(Out);
01472     break;
01473   }
01474   case Instruction::Select: {
01475     const SelectInst* sel = cast<SelectInst>(I);
01476     Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
01477     Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01478     printEscapedString(sel->getName());
01479     Out << "\", " << bbname << ");";
01480     break;
01481   }
01482   case Instruction::UserOp1:
01483     /// FALL THROUGH
01484   case Instruction::UserOp2: {
01485     /// FIXME: What should be done here?
01486     break;
01487   }
01488   case Instruction::VAArg: {
01489     const VAArgInst* va = cast<VAArgInst>(I);
01490     Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
01491         << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
01492     printEscapedString(va->getName());
01493     Out << "\", " << bbname << ");";
01494     break;
01495   }
01496   case Instruction::ExtractElement: {
01497     const ExtractElementInst* eei = cast<ExtractElementInst>(I);
01498     Out << "ExtractElementInst* " << getCppName(eei)
01499         << " = new ExtractElementInst(" << opNames[0]
01500         << ", " << opNames[1] << ", \"";
01501     printEscapedString(eei->getName());
01502     Out << "\", " << bbname << ");";
01503     break;
01504   }
01505   case Instruction::InsertElement: {
01506     const InsertElementInst* iei = cast<InsertElementInst>(I);
01507     Out << "InsertElementInst* " << getCppName(iei)
01508         << " = InsertElementInst::Create(" << opNames[0]
01509         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01510     printEscapedString(iei->getName());
01511     Out << "\", " << bbname << ");";
01512     break;
01513   }
01514   case Instruction::ShuffleVector: {
01515     const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
01516     Out << "ShuffleVectorInst* " << getCppName(svi)
01517         << " = new ShuffleVectorInst(" << opNames[0]
01518         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01519     printEscapedString(svi->getName());
01520     Out << "\", " << bbname << ");";
01521     break;
01522   }
01523   case Instruction::ExtractValue: {
01524     const ExtractValueInst *evi = cast<ExtractValueInst>(I);
01525     Out << "std::vector<unsigned> " << iName << "_indices;";
01526     nl(Out);
01527     for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
01528       Out << iName << "_indices.push_back("
01529           << evi->idx_begin()[i] << ");";
01530       nl(Out);
01531     }
01532     Out << "ExtractValueInst* " << getCppName(evi)
01533         << " = ExtractValueInst::Create(" << opNames[0]
01534         << ", "
01535         << iName << "_indices, \"";
01536     printEscapedString(evi->getName());
01537     Out << "\", " << bbname << ");";
01538     break;
01539   }
01540   case Instruction::InsertValue: {
01541     const InsertValueInst *ivi = cast<InsertValueInst>(I);
01542     Out << "std::vector<unsigned> " << iName << "_indices;";
01543     nl(Out);
01544     for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
01545       Out << iName << "_indices.push_back("
01546           << ivi->idx_begin()[i] << ");";
01547       nl(Out);
01548     }
01549     Out << "InsertValueInst* " << getCppName(ivi)
01550         << " = InsertValueInst::Create(" << opNames[0]
01551         << ", " << opNames[1] << ", "
01552         << iName << "_indices, \"";
01553     printEscapedString(ivi->getName());
01554     Out << "\", " << bbname << ");";
01555     break;
01556   }
01557   case Instruction::Fence: {
01558     const FenceInst *fi = cast<FenceInst>(I);
01559     StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
01560     StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
01561     Out << "FenceInst* " << iName
01562         << " = new FenceInst(mod->getContext(), "
01563         << Ordering << ", " << CrossThread << ", " << bbname
01564         << ");";
01565     break;
01566   }
01567   case Instruction::AtomicCmpXchg: {
01568     const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
01569     StringRef SuccessOrdering =
01570         ConvertAtomicOrdering(cxi->getSuccessOrdering());
01571     StringRef FailureOrdering =
01572         ConvertAtomicOrdering(cxi->getFailureOrdering());
01573     StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
01574     Out << "AtomicCmpXchgInst* " << iName
01575         << " = new AtomicCmpXchgInst("
01576         << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
01577         << SuccessOrdering << ", " << FailureOrdering << ", "
01578         << CrossThread << ", " << bbname
01579         << ");";
01580     nl(Out) << iName << "->setName(\"";
01581     printEscapedString(cxi->getName());
01582     Out << "\");";
01583     nl(Out) << iName << "->setVolatile("
01584             << (cxi->isVolatile() ? "true" : "false") << ");";
01585     nl(Out) << iName << "->setWeak("
01586             << (cxi->isWeak() ? "true" : "false") << ");";
01587     break;
01588   }
01589   case Instruction::AtomicRMW: {
01590     const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
01591     StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
01592     StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
01593     StringRef Operation;
01594     switch (rmwi->getOperation()) {
01595       case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
01596       case AtomicRMWInst::Add:  Operation = "AtomicRMWInst::Add"; break;
01597       case AtomicRMWInst::Sub:  Operation = "AtomicRMWInst::Sub"; break;
01598       case AtomicRMWInst::And:  Operation = "AtomicRMWInst::And"; break;
01599       case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
01600       case AtomicRMWInst::Or:   Operation = "AtomicRMWInst::Or"; break;
01601       case AtomicRMWInst::Xor:  Operation = "AtomicRMWInst::Xor"; break;
01602       case AtomicRMWInst::Max:  Operation = "AtomicRMWInst::Max"; break;
01603       case AtomicRMWInst::Min:  Operation = "AtomicRMWInst::Min"; break;
01604       case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
01605       case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
01606       case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
01607     }
01608     Out << "AtomicRMWInst* " << iName
01609         << " = new AtomicRMWInst("
01610         << Operation << ", "
01611         << opNames[0] << ", " << opNames[1] << ", "
01612         << Ordering << ", " << CrossThread << ", " << bbname
01613         << ");";
01614     nl(Out) << iName << "->setName(\"";
01615     printEscapedString(rmwi->getName());
01616     Out << "\");";
01617     nl(Out) << iName << "->setVolatile("
01618             << (rmwi->isVolatile() ? "true" : "false") << ");";
01619     break;
01620   }
01621   case Instruction::LandingPad: {
01622     const LandingPadInst *lpi = cast<LandingPadInst>(I);
01623     Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
01624     printCppName(lpi->getType());
01625     Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
01626     printEscapedString(lpi->getName());
01627     Out << "\", " << bbname << ");";
01628     nl(Out) << iName << "->setCleanup("
01629             << (lpi->isCleanup() ? "true" : "false")
01630             << ");";
01631     for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
01632       nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
01633     break;
01634   }
01635   }
01636   DefinedValues.insert(I);
01637   nl(Out);
01638   delete [] opNames;
01639 }
01640 
01641 // Print out the types, constants and declarations needed by one function
01642 void CppWriter::printFunctionUses(const Function* F) {
01643   nl(Out) << "// Type Definitions"; nl(Out);
01644   if (!is_inline) {
01645     // Print the function's return type
01646     printType(F->getReturnType());
01647 
01648     // Print the function's function type
01649     printType(F->getFunctionType());
01650 
01651     // Print the types of each of the function's arguments
01652     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01653          AI != AE; ++AI) {
01654       printType(AI->getType());
01655     }
01656   }
01657 
01658   // Print type definitions for every type referenced by an instruction and
01659   // make a note of any global values or constants that are referenced
01660   SmallPtrSet<GlobalValue*,64> gvs;
01661   SmallPtrSet<Constant*,64> consts;
01662   for (Function::const_iterator BB = F->begin(), BE = F->end();
01663        BB != BE; ++BB){
01664     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01665          I != E; ++I) {
01666       // Print the type of the instruction itself
01667       printType(I->getType());
01668 
01669       // Print the type of each of the instruction's operands
01670       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
01671         Value* operand = I->getOperand(i);
01672         printType(operand->getType());
01673 
01674         // If the operand references a GVal or Constant, make a note of it
01675         if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
01676           gvs.insert(GV);
01677           if (GenerationType != GenFunction)
01678             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
01679               if (GVar->hasInitializer())
01680                 consts.insert(GVar->getInitializer());
01681         } else if (Constant* C = dyn_cast<Constant>(operand)) {
01682           consts.insert(C);
01683           for (unsigned j = 0; j < C->getNumOperands(); ++j) {
01684             // If the operand references a GVal or Constant, make a note of it
01685             Value* operand = C->getOperand(j);
01686             printType(operand->getType());
01687             if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
01688               gvs.insert(GV);
01689               if (GenerationType != GenFunction)
01690                 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
01691                   if (GVar->hasInitializer())
01692                     consts.insert(GVar->getInitializer());
01693             }
01694           }
01695         }
01696       }
01697     }
01698   }
01699 
01700   // Print the function declarations for any functions encountered
01701   nl(Out) << "// Function Declarations"; nl(Out);
01702   for (auto *GV : gvs) {
01703     if (Function *Fun = dyn_cast<Function>(GV)) {
01704       if (!is_inline || Fun != F)
01705         printFunctionHead(Fun);
01706     }
01707   }
01708 
01709   // Print the global variable declarations for any variables encountered
01710   nl(Out) << "// Global Variable Declarations"; nl(Out);
01711   for (auto *GV : gvs) {
01712     if (GlobalVariable *F = dyn_cast<GlobalVariable>(GV))
01713       printVariableHead(F);
01714   }
01715 
01716   // Print the constants found
01717   nl(Out) << "// Constant Definitions"; nl(Out);
01718   for (const auto *C : consts) {
01719     printConstant(C);
01720   }
01721 
01722   // Process the global variables definitions now that all the constants have
01723   // been emitted. These definitions just couple the gvars with their constant
01724   // initializers.
01725   if (GenerationType != GenFunction) {
01726     nl(Out) << "// Global Variable Definitions"; nl(Out);
01727     for (auto *GV : gvs) {
01728       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(GV))
01729         printVariableBody(Var);
01730     }
01731   }
01732 }
01733 
01734 void CppWriter::printFunctionHead(const Function* F) {
01735   nl(Out) << "Function* " << getCppName(F);
01736   Out << " = mod->getFunction(\"";
01737   printEscapedString(F->getName());
01738   Out << "\");";
01739   nl(Out) << "if (!" << getCppName(F) << ") {";
01740   nl(Out) << getCppName(F);
01741 
01742   Out<< " = Function::Create(";
01743   nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
01744   nl(Out) << "/*Linkage=*/";
01745   printLinkageType(F->getLinkage());
01746   Out << ",";
01747   nl(Out) << "/*Name=*/\"";
01748   printEscapedString(F->getName());
01749   Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
01750   nl(Out,-1);
01751   printCppName(F);
01752   Out << "->setCallingConv(";
01753   printCallingConv(F->getCallingConv());
01754   Out << ");";
01755   nl(Out);
01756   if (F->hasSection()) {
01757     printCppName(F);
01758     Out << "->setSection(\"" << F->getSection() << "\");";
01759     nl(Out);
01760   }
01761   if (F->getAlignment()) {
01762     printCppName(F);
01763     Out << "->setAlignment(" << F->getAlignment() << ");";
01764     nl(Out);
01765   }
01766   if (F->getVisibility() != GlobalValue::DefaultVisibility) {
01767     printCppName(F);
01768     Out << "->setVisibility(";
01769     printVisibilityType(F->getVisibility());
01770     Out << ");";
01771     nl(Out);
01772   }
01773   if (F->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
01774     printCppName(F);
01775     Out << "->setDLLStorageClass(";
01776     printDLLStorageClassType(F->getDLLStorageClass());
01777     Out << ");";
01778     nl(Out);
01779   }
01780   if (F->hasGC()) {
01781     printCppName(F);
01782     Out << "->setGC(\"" << F->getGC() << "\");";
01783     nl(Out);
01784   }
01785   Out << "}";
01786   nl(Out);
01787   printAttributes(F->getAttributes(), getCppName(F));
01788   printCppName(F);
01789   Out << "->setAttributes(" << getCppName(F) << "_PAL);";
01790   nl(Out);
01791 }
01792 
01793 void CppWriter::printFunctionBody(const Function *F) {
01794   if (F->isDeclaration())
01795     return; // external functions have no bodies.
01796 
01797   // Clear the DefinedValues and ForwardRefs maps because we can't have
01798   // cross-function forward refs
01799   ForwardRefs.clear();
01800   DefinedValues.clear();
01801 
01802   // Create all the argument values
01803   if (!is_inline) {
01804     if (!F->arg_empty()) {
01805       Out << "Function::arg_iterator args = " << getCppName(F)
01806           << "->arg_begin();";
01807       nl(Out);
01808     }
01809     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01810          AI != AE; ++AI) {
01811       Out << "Value* " << getCppName(AI) << " = args++;";
01812       nl(Out);
01813       if (AI->hasName()) {
01814         Out << getCppName(AI) << "->setName(\"";
01815         printEscapedString(AI->getName());
01816         Out << "\");";
01817         nl(Out);
01818       }
01819     }
01820   }
01821 
01822   // Create all the basic blocks
01823   nl(Out);
01824   for (Function::const_iterator BI = F->begin(), BE = F->end();
01825        BI != BE; ++BI) {
01826     std::string bbname(getCppName(BI));
01827     Out << "BasicBlock* " << bbname <<
01828            " = BasicBlock::Create(mod->getContext(), \"";
01829     if (BI->hasName())
01830       printEscapedString(BI->getName());
01831     Out << "\"," << getCppName(BI->getParent()) << ",0);";
01832     nl(Out);
01833   }
01834 
01835   // Output all of its basic blocks... for the function
01836   for (Function::const_iterator BI = F->begin(), BE = F->end();
01837        BI != BE; ++BI) {
01838     std::string bbname(getCppName(BI));
01839     nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")";
01840     nl(Out);
01841 
01842     // Output all of the instructions in the basic block...
01843     for (BasicBlock::const_iterator I = BI->begin(), E = BI->end();
01844          I != E; ++I) {
01845       printInstruction(I,bbname);
01846     }
01847   }
01848 
01849   // Loop over the ForwardRefs and resolve them now that all instructions
01850   // are generated.
01851   if (!ForwardRefs.empty()) {
01852     nl(Out) << "// Resolve Forward References";
01853     nl(Out);
01854   }
01855 
01856   while (!ForwardRefs.empty()) {
01857     ForwardRefMap::iterator I = ForwardRefs.begin();
01858     Out << I->second << "->replaceAllUsesWith("
01859         << getCppName(I->first) << "); delete " << I->second << ";";
01860     nl(Out);
01861     ForwardRefs.erase(I);
01862   }
01863 }
01864 
01865 void CppWriter::printInline(const std::string& fname,
01866                             const std::string& func) {
01867   const Function* F = TheModule->getFunction(func);
01868   if (!F) {
01869     error(std::string("Function '") + func + "' not found in input module");
01870     return;
01871   }
01872   if (F->isDeclaration()) {
01873     error(std::string("Function '") + func + "' is external!");
01874     return;
01875   }
01876   nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
01877           << getCppName(F);
01878   unsigned arg_count = 1;
01879   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01880        AI != AE; ++AI) {
01881     Out << ", Value* arg_" << arg_count++;
01882   }
01883   Out << ") {";
01884   nl(Out);
01885   is_inline = true;
01886   printFunctionUses(F);
01887   printFunctionBody(F);
01888   is_inline = false;
01889   Out << "return " << getCppName(F->begin()) << ";";
01890   nl(Out) << "}";
01891   nl(Out);
01892 }
01893 
01894 void CppWriter::printModuleBody() {
01895   // Print out all the type definitions
01896   nl(Out) << "// Type Definitions"; nl(Out);
01897   printTypes(TheModule);
01898 
01899   // Functions can call each other and global variables can reference them so
01900   // define all the functions first before emitting their function bodies.
01901   nl(Out) << "// Function Declarations"; nl(Out);
01902   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
01903        I != E; ++I)
01904     printFunctionHead(I);
01905 
01906   // Process the global variables declarations. We can't initialze them until
01907   // after the constants are printed so just print a header for each global
01908   nl(Out) << "// Global Variable Declarations\n"; nl(Out);
01909   for (Module::const_global_iterator I = TheModule->global_begin(),
01910          E = TheModule->global_end(); I != E; ++I) {
01911     printVariableHead(I);
01912   }
01913 
01914   // Print out all the constants definitions. Constants don't recurse except
01915   // through GlobalValues. All GlobalValues have been declared at this point
01916   // so we can proceed to generate the constants.
01917   nl(Out) << "// Constant Definitions"; nl(Out);
01918   printConstants(TheModule);
01919 
01920   // Process the global variables definitions now that all the constants have
01921   // been emitted. These definitions just couple the gvars with their constant
01922   // initializers.
01923   nl(Out) << "// Global Variable Definitions"; nl(Out);
01924   for (Module::const_global_iterator I = TheModule->global_begin(),
01925          E = TheModule->global_end(); I != E; ++I) {
01926     printVariableBody(I);
01927   }
01928 
01929   // Finally, we can safely put out all of the function bodies.
01930   nl(Out) << "// Function Definitions"; nl(Out);
01931   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
01932        I != E; ++I) {
01933     if (!I->isDeclaration()) {
01934       nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I)
01935               << ")";
01936       nl(Out) << "{";
01937       nl(Out,1);
01938       printFunctionBody(I);
01939       nl(Out,-1) << "}";
01940       nl(Out);
01941     }
01942   }
01943 }
01944 
01945 void CppWriter::printProgram(const std::string& fname,
01946                              const std::string& mName) {
01947   Out << "#include <llvm/Pass.h>\n";
01948 
01949   Out << "#include <llvm/ADT/SmallVector.h>\n";
01950   Out << "#include <llvm/Analysis/Verifier.h>\n";
01951   Out << "#include <llvm/IR/BasicBlock.h>\n";
01952   Out << "#include <llvm/IR/CallingConv.h>\n";
01953   Out << "#include <llvm/IR/Constants.h>\n";
01954   Out << "#include <llvm/IR/DerivedTypes.h>\n";
01955   Out << "#include <llvm/IR/Function.h>\n";
01956   Out << "#include <llvm/IR/GlobalVariable.h>\n";
01957   Out << "#include <llvm/IR/IRPrintingPasses.h>\n";
01958   Out << "#include <llvm/IR/InlineAsm.h>\n";
01959   Out << "#include <llvm/IR/Instructions.h>\n";
01960   Out << "#include <llvm/IR/LLVMContext.h>\n";
01961   Out << "#include <llvm/IR/LegacyPassManager.h>\n";
01962   Out << "#include <llvm/IR/Module.h>\n";
01963   Out << "#include <llvm/Support/FormattedStream.h>\n";
01964   Out << "#include <llvm/Support/MathExtras.h>\n";
01965   Out << "#include <algorithm>\n";
01966   Out << "using namespace llvm;\n\n";
01967   Out << "Module* " << fname << "();\n\n";
01968   Out << "int main(int argc, char**argv) {\n";
01969   Out << "  Module* Mod = " << fname << "();\n";
01970   Out << "  verifyModule(*Mod, PrintMessageAction);\n";
01971   Out << "  PassManager PM;\n";
01972   Out << "  PM.add(createPrintModulePass(&outs()));\n";
01973   Out << "  PM.run(*Mod);\n";
01974   Out << "  return 0;\n";
01975   Out << "}\n\n";
01976   printModule(fname,mName);
01977 }
01978 
01979 void CppWriter::printModule(const std::string& fname,
01980                             const std::string& mName) {
01981   nl(Out) << "Module* " << fname << "() {";
01982   nl(Out,1) << "// Module Construction";
01983   nl(Out) << "Module* mod = new Module(\"";
01984   printEscapedString(mName);
01985   Out << "\", getGlobalContext());";
01986   if (!TheModule->getTargetTriple().empty()) {
01987     nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
01988             << "\");";
01989   }
01990   if (!TheModule->getTargetTriple().empty()) {
01991     nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
01992             << "\");";
01993   }
01994 
01995   if (!TheModule->getModuleInlineAsm().empty()) {
01996     nl(Out) << "mod->setModuleInlineAsm(\"";
01997     printEscapedString(TheModule->getModuleInlineAsm());
01998     Out << "\");";
01999   }
02000   nl(Out);
02001 
02002   printModuleBody();
02003   nl(Out) << "return mod;";
02004   nl(Out,-1) << "}";
02005   nl(Out);
02006 }
02007 
02008 void CppWriter::printContents(const std::string& fname,
02009                               const std::string& mName) {
02010   Out << "\nModule* " << fname << "(Module *mod) {\n";
02011   Out << "\nmod->setModuleIdentifier(\"";
02012   printEscapedString(mName);
02013   Out << "\");\n";
02014   printModuleBody();
02015   Out << "\nreturn mod;\n";
02016   Out << "\n}\n";
02017 }
02018 
02019 void CppWriter::printFunction(const std::string& fname,
02020                               const std::string& funcName) {
02021   const Function* F = TheModule->getFunction(funcName);
02022   if (!F) {
02023     error(std::string("Function '") + funcName + "' not found in input module");
02024     return;
02025   }
02026   Out << "\nFunction* " << fname << "(Module *mod) {\n";
02027   printFunctionUses(F);
02028   printFunctionHead(F);
02029   printFunctionBody(F);
02030   Out << "return " << getCppName(F) << ";\n";
02031   Out << "}\n";
02032 }
02033 
02034 void CppWriter::printFunctions() {
02035   const Module::FunctionListType &funcs = TheModule->getFunctionList();
02036   Module::const_iterator I  = funcs.begin();
02037   Module::const_iterator IE = funcs.end();
02038 
02039   for (; I != IE; ++I) {
02040     const Function &func = *I;
02041     if (!func.isDeclaration()) {
02042       std::string name("define_");
02043       name += func.getName();
02044       printFunction(name, func.getName());
02045     }
02046   }
02047 }
02048 
02049 void CppWriter::printVariable(const std::string& fname,
02050                               const std::string& varName) {
02051   const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
02052 
02053   if (!GV) {
02054     error(std::string("Variable '") + varName + "' not found in input module");
02055     return;
02056   }
02057   Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
02058   printVariableUses(GV);
02059   printVariableHead(GV);
02060   printVariableBody(GV);
02061   Out << "return " << getCppName(GV) << ";\n";
02062   Out << "}\n";
02063 }
02064 
02065 void CppWriter::printType(const std::string &fname,
02066                           const std::string &typeName) {
02067   Type* Ty = TheModule->getTypeByName(typeName);
02068   if (!Ty) {
02069     error(std::string("Type '") + typeName + "' not found in input module");
02070     return;
02071   }
02072   Out << "\nType* " << fname << "(Module *mod) {\n";
02073   printType(Ty);
02074   Out << "return " << getCppName(Ty) << ";\n";
02075   Out << "}\n";
02076 }
02077 
02078 bool CppWriter::runOnModule(Module &M) {
02079   TheModule = &M;
02080 
02081   // Emit a header
02082   Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
02083 
02084   // Get the name of the function we're supposed to generate
02085   std::string fname = FuncName.getValue();
02086 
02087   // Get the name of the thing we are to generate
02088   std::string tgtname = NameToGenerate.getValue();
02089   if (GenerationType == GenModule ||
02090       GenerationType == GenContents ||
02091       GenerationType == GenProgram ||
02092       GenerationType == GenFunctions) {
02093     if (tgtname == "!bad!") {
02094       if (M.getModuleIdentifier() == "-")
02095         tgtname = "<stdin>";
02096       else
02097         tgtname = M.getModuleIdentifier();
02098     }
02099   } else if (tgtname == "!bad!")
02100     error("You must use the -for option with -gen-{function,variable,type}");
02101 
02102   switch (WhatToGenerate(GenerationType)) {
02103    case GenProgram:
02104     if (fname.empty())
02105       fname = "makeLLVMModule";
02106     printProgram(fname,tgtname);
02107     break;
02108    case GenModule:
02109     if (fname.empty())
02110       fname = "makeLLVMModule";
02111     printModule(fname,tgtname);
02112     break;
02113    case GenContents:
02114     if (fname.empty())
02115       fname = "makeLLVMModuleContents";
02116     printContents(fname,tgtname);
02117     break;
02118    case GenFunction:
02119     if (fname.empty())
02120       fname = "makeLLVMFunction";
02121     printFunction(fname,tgtname);
02122     break;
02123    case GenFunctions:
02124     printFunctions();
02125     break;
02126    case GenInline:
02127     if (fname.empty())
02128       fname = "makeLLVMInline";
02129     printInline(fname,tgtname);
02130     break;
02131    case GenVariable:
02132     if (fname.empty())
02133       fname = "makeLLVMVariable";
02134     printVariable(fname,tgtname);
02135     break;
02136    case GenType:
02137     if (fname.empty())
02138       fname = "makeLLVMType";
02139     printType(fname,tgtname);
02140     break;
02141   }
02142 
02143   return false;
02144 }
02145 
02146 char CppWriter::ID = 0;
02147 
02148 //===----------------------------------------------------------------------===//
02149 //                       External Interface declaration
02150 //===----------------------------------------------------------------------===//
02151 
02152 bool CPPTargetMachine::addPassesToEmitFile(
02153     PassManagerBase &PM, raw_pwrite_stream &o, CodeGenFileType FileType,
02154     bool DisableVerify, AnalysisID StartAfter, AnalysisID StopAfter) {
02155   if (FileType != TargetMachine::CGFT_AssemblyFile)
02156     return true;
02157   auto FOut = llvm::make_unique<formatted_raw_ostream>(o);
02158   PM.add(new CppWriter(std::move(FOut)));
02159   return false;
02160 }