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->getValueType());
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(SafeStack);
00517       HANDLE_ATTR(NoCapture);
00518       HANDLE_ATTR(NoRedZone);
00519       HANDLE_ATTR(NoImplicitFloat);
00520       HANDLE_ATTR(Naked);
00521       HANDLE_ATTR(InlineHint);
00522       HANDLE_ATTR(ReturnsTwice);
00523       HANDLE_ATTR(UWTable);
00524       HANDLE_ATTR(NonLazyBind);
00525       HANDLE_ATTR(MinSize);
00526 #undef HANDLE_ATTR
00527 
00528       if (attrs.contains(Attribute::StackAlignment)) {
00529         Out << "B.addStackAlignmentAttr(" << attrs.getStackAlignment()<<')';
00530         nl(Out);
00531         attrs.removeAttribute(Attribute::StackAlignment);
00532       }
00533 
00534       Out << "PAS = AttributeSet::get(mod->getContext(), ";
00535       if (index == ~0U)
00536         Out << "~0U,";
00537       else
00538         Out << index << "U,";
00539       Out << " B);"; out(); nl(Out);
00540       Out << "}"; out(); nl(Out);
00541       nl(Out);
00542       Out << "Attrs.push_back(PAS);"; nl(Out);
00543     }
00544     Out << name << "_PAL = AttributeSet::get(mod->getContext(), Attrs);";
00545     nl(Out);
00546     out(); nl(Out);
00547     Out << '}'; nl(Out);
00548   }
00549 }
00550 
00551 void CppWriter::printType(Type* Ty) {
00552   // We don't print definitions for primitive types
00553   if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() ||
00554       Ty->isLabelTy() || Ty->isMetadataTy() || Ty->isVoidTy() ||
00555       Ty->isTokenTy())
00556     return;
00557 
00558   // If we already defined this type, we don't need to define it again.
00559   if (DefinedTypes.find(Ty) != DefinedTypes.end())
00560     return;
00561 
00562   // Everything below needs the name for the type so get it now.
00563   std::string typeName(getCppName(Ty));
00564 
00565   // Print the type definition
00566   switch (Ty->getTypeID()) {
00567   case Type::FunctionTyID:  {
00568     FunctionType* FT = cast<FunctionType>(Ty);
00569     Out << "std::vector<Type*>" << typeName << "_args;";
00570     nl(Out);
00571     FunctionType::param_iterator PI = FT->param_begin();
00572     FunctionType::param_iterator PE = FT->param_end();
00573     for (; PI != PE; ++PI) {
00574       Type* argTy = static_cast<Type*>(*PI);
00575       printType(argTy);
00576       std::string argName(getCppName(argTy));
00577       Out << typeName << "_args.push_back(" << argName;
00578       Out << ");";
00579       nl(Out);
00580     }
00581     printType(FT->getReturnType());
00582     std::string retTypeName(getCppName(FT->getReturnType()));
00583     Out << "FunctionType* " << typeName << " = FunctionType::get(";
00584     in(); nl(Out) << "/*Result=*/" << retTypeName;
00585     Out << ",";
00586     nl(Out) << "/*Params=*/" << typeName << "_args,";
00587     nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");";
00588     out();
00589     nl(Out);
00590     break;
00591   }
00592   case Type::StructTyID: {
00593     StructType* ST = cast<StructType>(Ty);
00594     if (!ST->isLiteral()) {
00595       Out << "StructType *" << typeName << " = mod->getTypeByName(\"";
00596       printEscapedString(ST->getName());
00597       Out << "\");";
00598       nl(Out);
00599       Out << "if (!" << typeName << ") {";
00600       nl(Out);
00601       Out << typeName << " = ";
00602       Out << "StructType::create(mod->getContext(), \"";
00603       printEscapedString(ST->getName());
00604       Out << "\");";
00605       nl(Out);
00606       Out << "}";
00607       nl(Out);
00608       // Indicate that this type is now defined.
00609       DefinedTypes.insert(Ty);
00610     }
00611 
00612     Out << "std::vector<Type*>" << typeName << "_fields;";
00613     nl(Out);
00614     StructType::element_iterator EI = ST->element_begin();
00615     StructType::element_iterator EE = ST->element_end();
00616     for (; EI != EE; ++EI) {
00617       Type* fieldTy = static_cast<Type*>(*EI);
00618       printType(fieldTy);
00619       std::string fieldName(getCppName(fieldTy));
00620       Out << typeName << "_fields.push_back(" << fieldName;
00621       Out << ");";
00622       nl(Out);
00623     }
00624 
00625     if (ST->isLiteral()) {
00626       Out << "StructType *" << typeName << " = ";
00627       Out << "StructType::get(" << "mod->getContext(), ";
00628     } else {
00629       Out << "if (" << typeName << "->isOpaque()) {";
00630       nl(Out);
00631       Out << typeName << "->setBody(";
00632     }
00633 
00634     Out << typeName << "_fields, /*isPacked=*/"
00635         << (ST->isPacked() ? "true" : "false") << ");";
00636     nl(Out);
00637     if (!ST->isLiteral()) {
00638       Out << "}";
00639       nl(Out);
00640     }
00641     break;
00642   }
00643   case Type::ArrayTyID: {
00644     ArrayType* AT = cast<ArrayType>(Ty);
00645     Type* ET = AT->getElementType();
00646     printType(ET);
00647     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00648       std::string elemName(getCppName(ET));
00649       Out << "ArrayType* " << typeName << " = ArrayType::get("
00650           << elemName << ", " << AT->getNumElements() << ");";
00651       nl(Out);
00652     }
00653     break;
00654   }
00655   case Type::PointerTyID: {
00656     PointerType* PT = cast<PointerType>(Ty);
00657     Type* ET = PT->getElementType();
00658     printType(ET);
00659     if (DefinedTypes.find(Ty) == DefinedTypes.end()) {
00660       std::string elemName(getCppName(ET));
00661       Out << "PointerType* " << typeName << " = PointerType::get("
00662           << elemName << ", " << 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 << ", " << PT->getNumElements() << ");";
00675       nl(Out);
00676     }
00677     break;
00678   }
00679   default:
00680     error("Invalid TypeID");
00681   }
00682 
00683   // Indicate that this type is now defined.
00684   DefinedTypes.insert(Ty);
00685 
00686   // Finally, separate the type definition from other with a newline.
00687   nl(Out);
00688 }
00689 
00690 void CppWriter::printTypes(const Module* M) {
00691   // Add all of the global variables to the value table.
00692   for (Module::const_global_iterator I = TheModule->global_begin(),
00693          E = TheModule->global_end(); I != E; ++I) {
00694     if (I->hasInitializer())
00695       printType(I->getInitializer()->getType());
00696     printType(I->getType());
00697   }
00698 
00699   // Add all the functions to the table
00700   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
00701        FI != FE; ++FI) {
00702     printType(FI->getReturnType());
00703     printType(FI->getFunctionType());
00704     // Add all the function arguments
00705     for (Function::const_arg_iterator AI = FI->arg_begin(),
00706            AE = FI->arg_end(); AI != AE; ++AI) {
00707       printType(AI->getType());
00708     }
00709 
00710     // Add all of the basic blocks and instructions
00711     for (Function::const_iterator BB = FI->begin(),
00712            E = FI->end(); BB != E; ++BB) {
00713       printType(BB->getType());
00714       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
00715            ++I) {
00716         printType(I->getType());
00717         for (unsigned i = 0; i < I->getNumOperands(); ++i)
00718           printType(I->getOperand(i)->getType());
00719       }
00720     }
00721   }
00722 }
00723 
00724 
00725 // printConstant - Print out a constant pool entry...
00726 void CppWriter::printConstant(const Constant *CV) {
00727   // First, if the constant is actually a GlobalValue (variable or function)
00728   // or its already in the constant list then we've printed it already and we
00729   // can just return.
00730   if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end())
00731     return;
00732 
00733   std::string constName(getCppName(CV));
00734   std::string typeName(getCppName(CV->getType()));
00735 
00736   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00737     std::string constValue = CI->getValue().toString(10, true);
00738     Out << "ConstantInt* " << constName
00739         << " = ConstantInt::get(mod->getContext(), APInt("
00740         << cast<IntegerType>(CI->getType())->getBitWidth()
00741         << ", StringRef(\"" <<  constValue << "\"), 10));";
00742   } else if (isa<ConstantAggregateZero>(CV)) {
00743     Out << "ConstantAggregateZero* " << constName
00744         << " = ConstantAggregateZero::get(" << typeName << ");";
00745   } else if (isa<ConstantPointerNull>(CV)) {
00746     Out << "ConstantPointerNull* " << constName
00747         << " = ConstantPointerNull::get(" << typeName << ");";
00748   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00749     Out << "ConstantFP* " << constName << " = ";
00750     printCFP(CFP);
00751     Out << ";";
00752   } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
00753     Out << "std::vector<Constant*> " << constName << "_elems;";
00754     nl(Out);
00755     unsigned N = CA->getNumOperands();
00756     for (unsigned i = 0; i < N; ++i) {
00757       printConstant(CA->getOperand(i)); // recurse to print operands
00758       Out << constName << "_elems.push_back("
00759           << getCppName(CA->getOperand(i)) << ");";
00760       nl(Out);
00761     }
00762     Out << "Constant* " << constName << " = ConstantArray::get("
00763         << typeName << ", " << constName << "_elems);";
00764   } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
00765     Out << "std::vector<Constant*> " << constName << "_fields;";
00766     nl(Out);
00767     unsigned N = CS->getNumOperands();
00768     for (unsigned i = 0; i < N; i++) {
00769       printConstant(CS->getOperand(i));
00770       Out << constName << "_fields.push_back("
00771           << getCppName(CS->getOperand(i)) << ");";
00772       nl(Out);
00773     }
00774     Out << "Constant* " << constName << " = ConstantStruct::get("
00775         << typeName << ", " << constName << "_fields);";
00776   } else if (const ConstantVector *CVec = dyn_cast<ConstantVector>(CV)) {
00777     Out << "std::vector<Constant*> " << constName << "_elems;";
00778     nl(Out);
00779     unsigned N = CVec->getNumOperands();
00780     for (unsigned i = 0; i < N; ++i) {
00781       printConstant(CVec->getOperand(i));
00782       Out << constName << "_elems.push_back("
00783           << getCppName(CVec->getOperand(i)) << ");";
00784       nl(Out);
00785     }
00786     Out << "Constant* " << constName << " = ConstantVector::get("
00787         << typeName << ", " << constName << "_elems);";
00788   } else if (isa<UndefValue>(CV)) {
00789     Out << "UndefValue* " << constName << " = UndefValue::get("
00790         << typeName << ");";
00791   } else if (const ConstantDataSequential *CDS =
00792                dyn_cast<ConstantDataSequential>(CV)) {
00793     if (CDS->isString()) {
00794       Out << "Constant *" << constName <<
00795       " = ConstantDataArray::getString(mod->getContext(), \"";
00796       StringRef Str = CDS->getAsString();
00797       bool nullTerminate = false;
00798       if (Str.back() == 0) {
00799         Str = Str.drop_back();
00800         nullTerminate = true;
00801       }
00802       printEscapedString(Str);
00803       // Determine if we want null termination or not.
00804       if (nullTerminate)
00805         Out << "\", true);";
00806       else
00807         Out << "\", false);";// No null terminator
00808     } else {
00809       // TODO: Could generate more efficient code generating CDS calls instead.
00810       Out << "std::vector<Constant*> " << constName << "_elems;";
00811       nl(Out);
00812       for (unsigned i = 0; i != CDS->getNumElements(); ++i) {
00813         Constant *Elt = CDS->getElementAsConstant(i);
00814         printConstant(Elt);
00815         Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
00816         nl(Out);
00817       }
00818       Out << "Constant* " << constName;
00819       
00820       if (isa<ArrayType>(CDS->getType()))
00821         Out << " = ConstantArray::get(";
00822       else
00823         Out << " = ConstantVector::get(";
00824       Out << typeName << ", " << constName << "_elems);";
00825     }
00826   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
00827     if (CE->getOpcode() == Instruction::GetElementPtr) {
00828       Out << "std::vector<Constant*> " << constName << "_indices;";
00829       nl(Out);
00830       printConstant(CE->getOperand(0));
00831       for (unsigned i = 1; i < CE->getNumOperands(); ++i ) {
00832         printConstant(CE->getOperand(i));
00833         Out << constName << "_indices.push_back("
00834             << getCppName(CE->getOperand(i)) << ");";
00835         nl(Out);
00836       }
00837       Out << "Constant* " << constName
00838           << " = ConstantExpr::getGetElementPtr("
00839           << getCppName(CE->getOperand(0)) << ", "
00840           << constName << "_indices);";
00841     } else if (CE->isCast()) {
00842       printConstant(CE->getOperand(0));
00843       Out << "Constant* " << constName << " = ConstantExpr::getCast(";
00844       switch (CE->getOpcode()) {
00845       default: llvm_unreachable("Invalid cast opcode");
00846       case Instruction::Trunc: Out << "Instruction::Trunc"; break;
00847       case Instruction::ZExt:  Out << "Instruction::ZExt"; break;
00848       case Instruction::SExt:  Out << "Instruction::SExt"; break;
00849       case Instruction::FPTrunc:  Out << "Instruction::FPTrunc"; break;
00850       case Instruction::FPExt:  Out << "Instruction::FPExt"; break;
00851       case Instruction::FPToUI:  Out << "Instruction::FPToUI"; break;
00852       case Instruction::FPToSI:  Out << "Instruction::FPToSI"; break;
00853       case Instruction::UIToFP:  Out << "Instruction::UIToFP"; break;
00854       case Instruction::SIToFP:  Out << "Instruction::SIToFP"; break;
00855       case Instruction::PtrToInt:  Out << "Instruction::PtrToInt"; break;
00856       case Instruction::IntToPtr:  Out << "Instruction::IntToPtr"; break;
00857       case Instruction::BitCast:  Out << "Instruction::BitCast"; break;
00858       }
00859       Out << ", " << getCppName(CE->getOperand(0)) << ", "
00860           << getCppName(CE->getType()) << ");";
00861     } else {
00862       unsigned N = CE->getNumOperands();
00863       for (unsigned i = 0; i < N; ++i ) {
00864         printConstant(CE->getOperand(i));
00865       }
00866       Out << "Constant* " << constName << " = ConstantExpr::";
00867       switch (CE->getOpcode()) {
00868       case Instruction::Add:    Out << "getAdd(";  break;
00869       case Instruction::FAdd:   Out << "getFAdd(";  break;
00870       case Instruction::Sub:    Out << "getSub("; break;
00871       case Instruction::FSub:   Out << "getFSub("; break;
00872       case Instruction::Mul:    Out << "getMul("; break;
00873       case Instruction::FMul:   Out << "getFMul("; break;
00874       case Instruction::UDiv:   Out << "getUDiv("; break;
00875       case Instruction::SDiv:   Out << "getSDiv("; break;
00876       case Instruction::FDiv:   Out << "getFDiv("; break;
00877       case Instruction::URem:   Out << "getURem("; break;
00878       case Instruction::SRem:   Out << "getSRem("; break;
00879       case Instruction::FRem:   Out << "getFRem("; break;
00880       case Instruction::And:    Out << "getAnd("; break;
00881       case Instruction::Or:     Out << "getOr("; break;
00882       case Instruction::Xor:    Out << "getXor("; break;
00883       case Instruction::ICmp:
00884         Out << "getICmp(ICmpInst::ICMP_";
00885         switch (CE->getPredicate()) {
00886         case ICmpInst::ICMP_EQ:  Out << "EQ"; break;
00887         case ICmpInst::ICMP_NE:  Out << "NE"; break;
00888         case ICmpInst::ICMP_SLT: Out << "SLT"; break;
00889         case ICmpInst::ICMP_ULT: Out << "ULT"; break;
00890         case ICmpInst::ICMP_SGT: Out << "SGT"; break;
00891         case ICmpInst::ICMP_UGT: Out << "UGT"; break;
00892         case ICmpInst::ICMP_SLE: Out << "SLE"; break;
00893         case ICmpInst::ICMP_ULE: Out << "ULE"; break;
00894         case ICmpInst::ICMP_SGE: Out << "SGE"; break;
00895         case ICmpInst::ICMP_UGE: Out << "UGE"; break;
00896         default: error("Invalid ICmp Predicate");
00897         }
00898         break;
00899       case Instruction::FCmp:
00900         Out << "getFCmp(FCmpInst::FCMP_";
00901         switch (CE->getPredicate()) {
00902         case FCmpInst::FCMP_FALSE: Out << "FALSE"; break;
00903         case FCmpInst::FCMP_ORD:   Out << "ORD"; break;
00904         case FCmpInst::FCMP_UNO:   Out << "UNO"; break;
00905         case FCmpInst::FCMP_OEQ:   Out << "OEQ"; break;
00906         case FCmpInst::FCMP_UEQ:   Out << "UEQ"; break;
00907         case FCmpInst::FCMP_ONE:   Out << "ONE"; break;
00908         case FCmpInst::FCMP_UNE:   Out << "UNE"; break;
00909         case FCmpInst::FCMP_OLT:   Out << "OLT"; break;
00910         case FCmpInst::FCMP_ULT:   Out << "ULT"; break;
00911         case FCmpInst::FCMP_OGT:   Out << "OGT"; break;
00912         case FCmpInst::FCMP_UGT:   Out << "UGT"; break;
00913         case FCmpInst::FCMP_OLE:   Out << "OLE"; break;
00914         case FCmpInst::FCMP_ULE:   Out << "ULE"; break;
00915         case FCmpInst::FCMP_OGE:   Out << "OGE"; break;
00916         case FCmpInst::FCMP_UGE:   Out << "UGE"; break;
00917         case FCmpInst::FCMP_TRUE:  Out << "TRUE"; break;
00918         default: error("Invalid FCmp Predicate");
00919         }
00920         break;
00921       case Instruction::Shl:     Out << "getShl("; break;
00922       case Instruction::LShr:    Out << "getLShr("; break;
00923       case Instruction::AShr:    Out << "getAShr("; break;
00924       case Instruction::Select:  Out << "getSelect("; break;
00925       case Instruction::ExtractElement: Out << "getExtractElement("; break;
00926       case Instruction::InsertElement:  Out << "getInsertElement("; break;
00927       case Instruction::ShuffleVector:  Out << "getShuffleVector("; break;
00928       default:
00929         error("Invalid constant expression");
00930         break;
00931       }
00932       Out << getCppName(CE->getOperand(0));
00933       for (unsigned i = 1; i < CE->getNumOperands(); ++i)
00934         Out << ", " << getCppName(CE->getOperand(i));
00935       Out << ");";
00936     }
00937   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
00938     Out << "Constant* " << constName << " = ";
00939     Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");";
00940   } else {
00941     error("Bad Constant");
00942     Out << "Constant* " << constName << " = 0; ";
00943   }
00944   nl(Out);
00945 }
00946 
00947 void CppWriter::printConstants(const Module* M) {
00948   // Traverse all the global variables looking for constant initializers
00949   for (Module::const_global_iterator I = TheModule->global_begin(),
00950          E = TheModule->global_end(); I != E; ++I)
00951     if (I->hasInitializer())
00952       printConstant(I->getInitializer());
00953 
00954   // Traverse the LLVM functions looking for constants
00955   for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
00956        FI != FE; ++FI) {
00957     // Add all of the basic blocks and instructions
00958     for (Function::const_iterator BB = FI->begin(),
00959            E = FI->end(); BB != E; ++BB) {
00960       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
00961            ++I) {
00962         for (unsigned i = 0; i < I->getNumOperands(); ++i) {
00963           if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) {
00964             printConstant(C);
00965           }
00966         }
00967       }
00968     }
00969   }
00970 }
00971 
00972 void CppWriter::printVariableUses(const GlobalVariable *GV) {
00973   nl(Out) << "// Type Definitions";
00974   nl(Out);
00975   printType(GV->getType());
00976   if (GV->hasInitializer()) {
00977     const Constant *Init = GV->getInitializer();
00978     printType(Init->getType());
00979     if (const Function *F = dyn_cast<Function>(Init)) {
00980       nl(Out)<< "/ Function Declarations"; nl(Out);
00981       printFunctionHead(F);
00982     } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) {
00983       nl(Out) << "// Global Variable Declarations"; nl(Out);
00984       printVariableHead(gv);
00985       
00986       nl(Out) << "// Global Variable Definitions"; nl(Out);
00987       printVariableBody(gv);
00988     } else  {
00989       nl(Out) << "// Constant Definitions"; nl(Out);
00990       printConstant(Init);
00991     }
00992   }
00993 }
00994 
00995 void CppWriter::printVariableHead(const GlobalVariable *GV) {
00996   nl(Out) << "GlobalVariable* " << getCppName(GV);
00997   if (is_inline) {
00998     Out << " = mod->getGlobalVariable(mod->getContext(), ";
00999     printEscapedString(GV->getName());
01000     Out << ", " << getCppName(GV->getValueType()) << ",true)";
01001     nl(Out) << "if (!" << getCppName(GV) << ") {";
01002     in(); nl(Out) << getCppName(GV);
01003   }
01004   Out << " = new GlobalVariable(/*Module=*/*mod, ";
01005   nl(Out) << "/*Type=*/";
01006   printCppName(GV->getValueType());
01007   Out << ",";
01008   nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false");
01009   Out << ",";
01010   nl(Out) << "/*Linkage=*/";
01011   printLinkageType(GV->getLinkage());
01012   Out << ",";
01013   nl(Out) << "/*Initializer=*/0, ";
01014   if (GV->hasInitializer()) {
01015     Out << "// has initializer, specified below";
01016   }
01017   nl(Out) << "/*Name=*/\"";
01018   printEscapedString(GV->getName());
01019   Out << "\");";
01020   nl(Out);
01021 
01022   if (GV->hasSection()) {
01023     printCppName(GV);
01024     Out << "->setSection(\"";
01025     printEscapedString(GV->getSection());
01026     Out << "\");";
01027     nl(Out);
01028   }
01029   if (GV->getAlignment()) {
01030     printCppName(GV);
01031     Out << "->setAlignment(" << GV->getAlignment() << ");";
01032     nl(Out);
01033   }
01034   if (GV->getVisibility() != GlobalValue::DefaultVisibility) {
01035     printCppName(GV);
01036     Out << "->setVisibility(";
01037     printVisibilityType(GV->getVisibility());
01038     Out << ");";
01039     nl(Out);
01040   }
01041   if (GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
01042     printCppName(GV);
01043     Out << "->setDLLStorageClass(";
01044     printDLLStorageClassType(GV->getDLLStorageClass());
01045     Out << ");";
01046     nl(Out);
01047   }
01048   if (GV->isThreadLocal()) {
01049     printCppName(GV);
01050     Out << "->setThreadLocalMode(";
01051     printThreadLocalMode(GV->getThreadLocalMode());
01052     Out << ");";
01053     nl(Out);
01054   }
01055   if (is_inline) {
01056     out(); Out << "}"; nl(Out);
01057   }
01058 }
01059 
01060 void CppWriter::printVariableBody(const GlobalVariable *GV) {
01061   if (GV->hasInitializer()) {
01062     printCppName(GV);
01063     Out << "->setInitializer(";
01064     Out << getCppName(GV->getInitializer()) << ");";
01065     nl(Out);
01066   }
01067 }
01068 
01069 std::string CppWriter::getOpName(const Value* V) {
01070   if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end())
01071     return getCppName(V);
01072 
01073   // See if its alread in the map of forward references, if so just return the
01074   // name we already set up for it
01075   ForwardRefMap::const_iterator I = ForwardRefs.find(V);
01076   if (I != ForwardRefs.end())
01077     return I->second;
01078 
01079   // This is a new forward reference. Generate a unique name for it
01080   std::string result(std::string("fwdref_") + utostr(uniqueNum++));
01081 
01082   // Yes, this is a hack. An Argument is the smallest instantiable value that
01083   // we can make as a placeholder for the real value. We'll replace these
01084   // Argument instances later.
01085   Out << "Argument* " << result << " = new Argument("
01086       << getCppName(V->getType()) << ");";
01087   nl(Out);
01088   ForwardRefs[V] = result;
01089   return result;
01090 }
01091 
01092 static StringRef ConvertAtomicOrdering(AtomicOrdering Ordering) {
01093   switch (Ordering) {
01094     case NotAtomic: return "NotAtomic";
01095     case Unordered: return "Unordered";
01096     case Monotonic: return "Monotonic";
01097     case Acquire: return "Acquire";
01098     case Release: return "Release";
01099     case AcquireRelease: return "AcquireRelease";
01100     case SequentiallyConsistent: return "SequentiallyConsistent";
01101   }
01102   llvm_unreachable("Unknown ordering");
01103 }
01104 
01105 static StringRef ConvertAtomicSynchScope(SynchronizationScope SynchScope) {
01106   switch (SynchScope) {
01107     case SingleThread: return "SingleThread";
01108     case CrossThread: return "CrossThread";
01109   }
01110   llvm_unreachable("Unknown synch scope");
01111 }
01112 
01113 // printInstruction - This member is called for each Instruction in a function.
01114 void CppWriter::printInstruction(const Instruction *I,
01115                                  const std::string& bbname) {
01116   std::string iName(getCppName(I));
01117 
01118   // Before we emit this instruction, we need to take care of generating any
01119   // forward references. So, we get the names of all the operands in advance
01120   const unsigned Ops(I->getNumOperands());
01121   std::string* opNames = new std::string[Ops];
01122   for (unsigned i = 0; i < Ops; i++)
01123     opNames[i] = getOpName(I->getOperand(i));
01124 
01125   switch (I->getOpcode()) {
01126   default:
01127     error("Invalid instruction");
01128     break;
01129 
01130   case Instruction::Ret: {
01131     const ReturnInst* ret =  cast<ReturnInst>(I);
01132     Out << "ReturnInst::Create(mod->getContext(), "
01133         << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");";
01134     break;
01135   }
01136   case Instruction::Br: {
01137     const BranchInst* br = cast<BranchInst>(I);
01138     Out << "BranchInst::Create(" ;
01139     if (br->getNumOperands() == 3) {
01140       Out << opNames[2] << ", "
01141           << opNames[1] << ", "
01142           << opNames[0] << ", ";
01143 
01144     } else if (br->getNumOperands() == 1) {
01145       Out << opNames[0] << ", ";
01146     } else {
01147       error("Branch with 2 operands?");
01148     }
01149     Out << bbname << ");";
01150     break;
01151   }
01152   case Instruction::Switch: {
01153     const SwitchInst *SI = cast<SwitchInst>(I);
01154     Out << "SwitchInst* " << iName << " = SwitchInst::Create("
01155         << getOpName(SI->getCondition()) << ", "
01156         << getOpName(SI->getDefaultDest()) << ", "
01157         << SI->getNumCases() << ", " << bbname << ");";
01158     nl(Out);
01159     for (SwitchInst::ConstCaseIt i = SI->case_begin(), e = SI->case_end();
01160          i != e; ++i) {
01161       const ConstantInt* CaseVal = i.getCaseValue();
01162       const BasicBlock *BB = i.getCaseSuccessor();
01163       Out << iName << "->addCase("
01164           << getOpName(CaseVal) << ", "
01165           << getOpName(BB) << ");";
01166       nl(Out);
01167     }
01168     break;
01169   }
01170   case Instruction::IndirectBr: {
01171     const IndirectBrInst *IBI = cast<IndirectBrInst>(I);
01172     Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create("
01173         << opNames[0] << ", " << IBI->getNumDestinations() << ");";
01174     nl(Out);
01175     for (unsigned i = 1; i != IBI->getNumOperands(); ++i) {
01176       Out << iName << "->addDestination(" << opNames[i] << ");";
01177       nl(Out);
01178     }
01179     break;
01180   }
01181   case Instruction::Resume: {
01182     Out << "ResumeInst::Create(" << opNames[0] << ", " << bbname << ");";
01183     break;
01184   }
01185   case Instruction::Invoke: {
01186     const InvokeInst* inv = cast<InvokeInst>(I);
01187     Out << "std::vector<Value*> " << iName << "_params;";
01188     nl(Out);
01189     for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) {
01190       Out << iName << "_params.push_back("
01191           << getOpName(inv->getArgOperand(i)) << ");";
01192       nl(Out);
01193     }
01194     // FIXME: This shouldn't use magic numbers -3, -2, and -1.
01195     Out << "InvokeInst *" << iName << " = InvokeInst::Create("
01196         << getOpName(inv->getCalledValue()) << ", "
01197         << getOpName(inv->getNormalDest()) << ", "
01198         << getOpName(inv->getUnwindDest()) << ", "
01199         << iName << "_params, \"";
01200     printEscapedString(inv->getName());
01201     Out << "\", " << bbname << ");";
01202     nl(Out) << iName << "->setCallingConv(";
01203     printCallingConv(inv->getCallingConv());
01204     Out << ");";
01205     printAttributes(inv->getAttributes(), iName);
01206     Out << iName << "->setAttributes(" << iName << "_PAL);";
01207     nl(Out);
01208     break;
01209   }
01210   case Instruction::Unreachable: {
01211     Out << "new UnreachableInst("
01212         << "mod->getContext(), "
01213         << bbname << ");";
01214     break;
01215   }
01216   case Instruction::Add:
01217   case Instruction::FAdd:
01218   case Instruction::Sub:
01219   case Instruction::FSub:
01220   case Instruction::Mul:
01221   case Instruction::FMul:
01222   case Instruction::UDiv:
01223   case Instruction::SDiv:
01224   case Instruction::FDiv:
01225   case Instruction::URem:
01226   case Instruction::SRem:
01227   case Instruction::FRem:
01228   case Instruction::And:
01229   case Instruction::Or:
01230   case Instruction::Xor:
01231   case Instruction::Shl:
01232   case Instruction::LShr:
01233   case Instruction::AShr:{
01234     Out << "BinaryOperator* " << iName << " = BinaryOperator::Create(";
01235     switch (I->getOpcode()) {
01236     case Instruction::Add: Out << "Instruction::Add"; break;
01237     case Instruction::FAdd: Out << "Instruction::FAdd"; break;
01238     case Instruction::Sub: Out << "Instruction::Sub"; break;
01239     case Instruction::FSub: Out << "Instruction::FSub"; break;
01240     case Instruction::Mul: Out << "Instruction::Mul"; break;
01241     case Instruction::FMul: Out << "Instruction::FMul"; break;
01242     case Instruction::UDiv:Out << "Instruction::UDiv"; break;
01243     case Instruction::SDiv:Out << "Instruction::SDiv"; break;
01244     case Instruction::FDiv:Out << "Instruction::FDiv"; break;
01245     case Instruction::URem:Out << "Instruction::URem"; break;
01246     case Instruction::SRem:Out << "Instruction::SRem"; break;
01247     case Instruction::FRem:Out << "Instruction::FRem"; break;
01248     case Instruction::And: Out << "Instruction::And"; break;
01249     case Instruction::Or:  Out << "Instruction::Or";  break;
01250     case Instruction::Xor: Out << "Instruction::Xor"; break;
01251     case Instruction::Shl: Out << "Instruction::Shl"; break;
01252     case Instruction::LShr:Out << "Instruction::LShr"; break;
01253     case Instruction::AShr:Out << "Instruction::AShr"; break;
01254     default: Out << "Instruction::BadOpCode"; break;
01255     }
01256     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01257     printEscapedString(I->getName());
01258     Out << "\", " << bbname << ");";
01259     break;
01260   }
01261   case Instruction::FCmp: {
01262     Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", ";
01263     switch (cast<FCmpInst>(I)->getPredicate()) {
01264     case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break;
01265     case FCmpInst::FCMP_OEQ  : Out << "FCmpInst::FCMP_OEQ"; break;
01266     case FCmpInst::FCMP_OGT  : Out << "FCmpInst::FCMP_OGT"; break;
01267     case FCmpInst::FCMP_OGE  : Out << "FCmpInst::FCMP_OGE"; break;
01268     case FCmpInst::FCMP_OLT  : Out << "FCmpInst::FCMP_OLT"; break;
01269     case FCmpInst::FCMP_OLE  : Out << "FCmpInst::FCMP_OLE"; break;
01270     case FCmpInst::FCMP_ONE  : Out << "FCmpInst::FCMP_ONE"; break;
01271     case FCmpInst::FCMP_ORD  : Out << "FCmpInst::FCMP_ORD"; break;
01272     case FCmpInst::FCMP_UNO  : Out << "FCmpInst::FCMP_UNO"; break;
01273     case FCmpInst::FCMP_UEQ  : Out << "FCmpInst::FCMP_UEQ"; break;
01274     case FCmpInst::FCMP_UGT  : Out << "FCmpInst::FCMP_UGT"; break;
01275     case FCmpInst::FCMP_UGE  : Out << "FCmpInst::FCMP_UGE"; break;
01276     case FCmpInst::FCMP_ULT  : Out << "FCmpInst::FCMP_ULT"; break;
01277     case FCmpInst::FCMP_ULE  : Out << "FCmpInst::FCMP_ULE"; break;
01278     case FCmpInst::FCMP_UNE  : Out << "FCmpInst::FCMP_UNE"; break;
01279     case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break;
01280     default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break;
01281     }
01282     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01283     printEscapedString(I->getName());
01284     Out << "\");";
01285     break;
01286   }
01287   case Instruction::ICmp: {
01288     Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", ";
01289     switch (cast<ICmpInst>(I)->getPredicate()) {
01290     case ICmpInst::ICMP_EQ:  Out << "ICmpInst::ICMP_EQ";  break;
01291     case ICmpInst::ICMP_NE:  Out << "ICmpInst::ICMP_NE";  break;
01292     case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break;
01293     case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break;
01294     case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break;
01295     case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break;
01296     case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break;
01297     case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break;
01298     case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break;
01299     case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break;
01300     default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break;
01301     }
01302     Out << ", " << opNames[0] << ", " << opNames[1] << ", \"";
01303     printEscapedString(I->getName());
01304     Out << "\");";
01305     break;
01306   }
01307   case Instruction::Alloca: {
01308     const AllocaInst* allocaI = cast<AllocaInst>(I);
01309     Out << "AllocaInst* " << iName << " = new AllocaInst("
01310         << getCppName(allocaI->getAllocatedType()) << ", ";
01311     if (allocaI->isArrayAllocation())
01312       Out << opNames[0] << ", ";
01313     Out << "\"";
01314     printEscapedString(allocaI->getName());
01315     Out << "\", " << bbname << ");";
01316     if (allocaI->getAlignment())
01317       nl(Out) << iName << "->setAlignment("
01318           << allocaI->getAlignment() << ");";
01319     break;
01320   }
01321   case Instruction::Load: {
01322     const LoadInst* load = cast<LoadInst>(I);
01323     Out << "LoadInst* " << iName << " = new LoadInst("
01324         << opNames[0] << ", \"";
01325     printEscapedString(load->getName());
01326     Out << "\", " << (load->isVolatile() ? "true" : "false" )
01327         << ", " << bbname << ");";
01328     if (load->getAlignment())
01329       nl(Out) << iName << "->setAlignment("
01330               << load->getAlignment() << ");";
01331     if (load->isAtomic()) {
01332       StringRef Ordering = ConvertAtomicOrdering(load->getOrdering());
01333       StringRef CrossThread = ConvertAtomicSynchScope(load->getSynchScope());
01334       nl(Out) << iName << "->setAtomic("
01335               << Ordering << ", " << CrossThread << ");";
01336     }
01337     break;
01338   }
01339   case Instruction::Store: {
01340     const StoreInst* store = cast<StoreInst>(I);
01341     Out << "StoreInst* " << iName << " = new StoreInst("
01342         << opNames[0] << ", "
01343         << opNames[1] << ", "
01344         << (store->isVolatile() ? "true" : "false")
01345         << ", " << bbname << ");";
01346     if (store->getAlignment())
01347       nl(Out) << iName << "->setAlignment("
01348               << store->getAlignment() << ");";
01349     if (store->isAtomic()) {
01350       StringRef Ordering = ConvertAtomicOrdering(store->getOrdering());
01351       StringRef CrossThread = ConvertAtomicSynchScope(store->getSynchScope());
01352       nl(Out) << iName << "->setAtomic("
01353               << Ordering << ", " << CrossThread << ");";
01354     }
01355     break;
01356   }
01357   case Instruction::GetElementPtr: {
01358     const GetElementPtrInst* gep = cast<GetElementPtrInst>(I);
01359     Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create("
01360         << getCppName(gep->getSourceElementType()) << ", " << opNames[0] << ", {";
01361     in();
01362     for (unsigned i = 1; i < gep->getNumOperands(); ++i ) {
01363       if (i != 1) {
01364         Out << ", ";
01365       }
01366       nl(Out);
01367       Out << opNames[i];
01368     }
01369     out();
01370     nl(Out) << "}, \"";
01371     printEscapedString(gep->getName());
01372     Out << "\", " << bbname << ");";
01373     break;
01374   }
01375   case Instruction::PHI: {
01376     const PHINode* phi = cast<PHINode>(I);
01377 
01378     Out << "PHINode* " << iName << " = PHINode::Create("
01379         << getCppName(phi->getType()) << ", "
01380         << phi->getNumIncomingValues() << ", \"";
01381     printEscapedString(phi->getName());
01382     Out << "\", " << bbname << ");";
01383     nl(Out);
01384     for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) {
01385       Out << iName << "->addIncoming("
01386           << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", "
01387           << getOpName(phi->getIncomingBlock(i)) << ");";
01388       nl(Out);
01389     }
01390     break;
01391   }
01392   case Instruction::Trunc:
01393   case Instruction::ZExt:
01394   case Instruction::SExt:
01395   case Instruction::FPTrunc:
01396   case Instruction::FPExt:
01397   case Instruction::FPToUI:
01398   case Instruction::FPToSI:
01399   case Instruction::UIToFP:
01400   case Instruction::SIToFP:
01401   case Instruction::PtrToInt:
01402   case Instruction::IntToPtr:
01403   case Instruction::BitCast: {
01404     const CastInst* cst = cast<CastInst>(I);
01405     Out << "CastInst* " << iName << " = new ";
01406     switch (I->getOpcode()) {
01407     case Instruction::Trunc:    Out << "TruncInst"; break;
01408     case Instruction::ZExt:     Out << "ZExtInst"; break;
01409     case Instruction::SExt:     Out << "SExtInst"; break;
01410     case Instruction::FPTrunc:  Out << "FPTruncInst"; break;
01411     case Instruction::FPExt:    Out << "FPExtInst"; break;
01412     case Instruction::FPToUI:   Out << "FPToUIInst"; break;
01413     case Instruction::FPToSI:   Out << "FPToSIInst"; break;
01414     case Instruction::UIToFP:   Out << "UIToFPInst"; break;
01415     case Instruction::SIToFP:   Out << "SIToFPInst"; break;
01416     case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
01417     case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
01418     case Instruction::BitCast:  Out << "BitCastInst"; break;
01419     default: llvm_unreachable("Unreachable");
01420     }
01421     Out << "(" << opNames[0] << ", "
01422         << getCppName(cst->getType()) << ", \"";
01423     printEscapedString(cst->getName());
01424     Out << "\", " << bbname << ");";
01425     break;
01426   }
01427   case Instruction::Call: {
01428     const CallInst* call = cast<CallInst>(I);
01429     if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) {
01430       Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get("
01431           << getCppName(ila->getFunctionType()) << ", \""
01432           << ila->getAsmString() << "\", \""
01433           << ila->getConstraintString() << "\","
01434           << (ila->hasSideEffects() ? "true" : "false") << ");";
01435       nl(Out);
01436     }
01437     if (call->getNumArgOperands() > 1) {
01438       Out << "std::vector<Value*> " << iName << "_params;";
01439       nl(Out);
01440       for (unsigned i = 0; i < call->getNumArgOperands(); ++i) {
01441         Out << iName << "_params.push_back(" << opNames[i] << ");";
01442         nl(Out);
01443       }
01444       Out << "CallInst* " << iName << " = CallInst::Create("
01445           << opNames[call->getNumArgOperands()] << ", "
01446           << iName << "_params, \"";
01447     } else if (call->getNumArgOperands() == 1) {
01448       Out << "CallInst* " << iName << " = CallInst::Create("
01449           << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \"";
01450     } else {
01451       Out << "CallInst* " << iName << " = CallInst::Create("
01452           << opNames[call->getNumArgOperands()] << ", \"";
01453     }
01454     printEscapedString(call->getName());
01455     Out << "\", " << bbname << ");";
01456     nl(Out) << iName << "->setCallingConv(";
01457     printCallingConv(call->getCallingConv());
01458     Out << ");";
01459     nl(Out) << iName << "->setTailCall("
01460         << (call->isTailCall() ? "true" : "false");
01461     Out << ");";
01462     nl(Out);
01463     printAttributes(call->getAttributes(), iName);
01464     Out << iName << "->setAttributes(" << iName << "_PAL);";
01465     nl(Out);
01466     break;
01467   }
01468   case Instruction::Select: {
01469     const SelectInst* sel = cast<SelectInst>(I);
01470     Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create(";
01471     Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01472     printEscapedString(sel->getName());
01473     Out << "\", " << bbname << ");";
01474     break;
01475   }
01476   case Instruction::UserOp1:
01477     /// FALL THROUGH
01478   case Instruction::UserOp2: {
01479     /// FIXME: What should be done here?
01480     break;
01481   }
01482   case Instruction::VAArg: {
01483     const VAArgInst* va = cast<VAArgInst>(I);
01484     Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst("
01485         << opNames[0] << ", " << getCppName(va->getType()) << ", \"";
01486     printEscapedString(va->getName());
01487     Out << "\", " << bbname << ");";
01488     break;
01489   }
01490   case Instruction::ExtractElement: {
01491     const ExtractElementInst* eei = cast<ExtractElementInst>(I);
01492     Out << "ExtractElementInst* " << getCppName(eei)
01493         << " = new ExtractElementInst(" << opNames[0]
01494         << ", " << opNames[1] << ", \"";
01495     printEscapedString(eei->getName());
01496     Out << "\", " << bbname << ");";
01497     break;
01498   }
01499   case Instruction::InsertElement: {
01500     const InsertElementInst* iei = cast<InsertElementInst>(I);
01501     Out << "InsertElementInst* " << getCppName(iei)
01502         << " = InsertElementInst::Create(" << opNames[0]
01503         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01504     printEscapedString(iei->getName());
01505     Out << "\", " << bbname << ");";
01506     break;
01507   }
01508   case Instruction::ShuffleVector: {
01509     const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I);
01510     Out << "ShuffleVectorInst* " << getCppName(svi)
01511         << " = new ShuffleVectorInst(" << opNames[0]
01512         << ", " << opNames[1] << ", " << opNames[2] << ", \"";
01513     printEscapedString(svi->getName());
01514     Out << "\", " << bbname << ");";
01515     break;
01516   }
01517   case Instruction::ExtractValue: {
01518     const ExtractValueInst *evi = cast<ExtractValueInst>(I);
01519     Out << "std::vector<unsigned> " << iName << "_indices;";
01520     nl(Out);
01521     for (unsigned i = 0; i < evi->getNumIndices(); ++i) {
01522       Out << iName << "_indices.push_back("
01523           << evi->idx_begin()[i] << ");";
01524       nl(Out);
01525     }
01526     Out << "ExtractValueInst* " << getCppName(evi)
01527         << " = ExtractValueInst::Create(" << opNames[0]
01528         << ", "
01529         << iName << "_indices, \"";
01530     printEscapedString(evi->getName());
01531     Out << "\", " << bbname << ");";
01532     break;
01533   }
01534   case Instruction::InsertValue: {
01535     const InsertValueInst *ivi = cast<InsertValueInst>(I);
01536     Out << "std::vector<unsigned> " << iName << "_indices;";
01537     nl(Out);
01538     for (unsigned i = 0; i < ivi->getNumIndices(); ++i) {
01539       Out << iName << "_indices.push_back("
01540           << ivi->idx_begin()[i] << ");";
01541       nl(Out);
01542     }
01543     Out << "InsertValueInst* " << getCppName(ivi)
01544         << " = InsertValueInst::Create(" << opNames[0]
01545         << ", " << opNames[1] << ", "
01546         << iName << "_indices, \"";
01547     printEscapedString(ivi->getName());
01548     Out << "\", " << bbname << ");";
01549     break;
01550   }
01551   case Instruction::Fence: {
01552     const FenceInst *fi = cast<FenceInst>(I);
01553     StringRef Ordering = ConvertAtomicOrdering(fi->getOrdering());
01554     StringRef CrossThread = ConvertAtomicSynchScope(fi->getSynchScope());
01555     Out << "FenceInst* " << iName
01556         << " = new FenceInst(mod->getContext(), "
01557         << Ordering << ", " << CrossThread << ", " << bbname
01558         << ");";
01559     break;
01560   }
01561   case Instruction::AtomicCmpXchg: {
01562     const AtomicCmpXchgInst *cxi = cast<AtomicCmpXchgInst>(I);
01563     StringRef SuccessOrdering =
01564         ConvertAtomicOrdering(cxi->getSuccessOrdering());
01565     StringRef FailureOrdering =
01566         ConvertAtomicOrdering(cxi->getFailureOrdering());
01567     StringRef CrossThread = ConvertAtomicSynchScope(cxi->getSynchScope());
01568     Out << "AtomicCmpXchgInst* " << iName
01569         << " = new AtomicCmpXchgInst("
01570         << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", "
01571         << SuccessOrdering << ", " << FailureOrdering << ", "
01572         << CrossThread << ", " << bbname
01573         << ");";
01574     nl(Out) << iName << "->setName(\"";
01575     printEscapedString(cxi->getName());
01576     Out << "\");";
01577     nl(Out) << iName << "->setVolatile("
01578             << (cxi->isVolatile() ? "true" : "false") << ");";
01579     nl(Out) << iName << "->setWeak("
01580             << (cxi->isWeak() ? "true" : "false") << ");";
01581     break;
01582   }
01583   case Instruction::AtomicRMW: {
01584     const AtomicRMWInst *rmwi = cast<AtomicRMWInst>(I);
01585     StringRef Ordering = ConvertAtomicOrdering(rmwi->getOrdering());
01586     StringRef CrossThread = ConvertAtomicSynchScope(rmwi->getSynchScope());
01587     StringRef Operation;
01588     switch (rmwi->getOperation()) {
01589       case AtomicRMWInst::Xchg: Operation = "AtomicRMWInst::Xchg"; break;
01590       case AtomicRMWInst::Add:  Operation = "AtomicRMWInst::Add"; break;
01591       case AtomicRMWInst::Sub:  Operation = "AtomicRMWInst::Sub"; break;
01592       case AtomicRMWInst::And:  Operation = "AtomicRMWInst::And"; break;
01593       case AtomicRMWInst::Nand: Operation = "AtomicRMWInst::Nand"; break;
01594       case AtomicRMWInst::Or:   Operation = "AtomicRMWInst::Or"; break;
01595       case AtomicRMWInst::Xor:  Operation = "AtomicRMWInst::Xor"; break;
01596       case AtomicRMWInst::Max:  Operation = "AtomicRMWInst::Max"; break;
01597       case AtomicRMWInst::Min:  Operation = "AtomicRMWInst::Min"; break;
01598       case AtomicRMWInst::UMax: Operation = "AtomicRMWInst::UMax"; break;
01599       case AtomicRMWInst::UMin: Operation = "AtomicRMWInst::UMin"; break;
01600       case AtomicRMWInst::BAD_BINOP: llvm_unreachable("Bad atomic operation");
01601     }
01602     Out << "AtomicRMWInst* " << iName
01603         << " = new AtomicRMWInst("
01604         << Operation << ", "
01605         << opNames[0] << ", " << opNames[1] << ", "
01606         << Ordering << ", " << CrossThread << ", " << bbname
01607         << ");";
01608     nl(Out) << iName << "->setName(\"";
01609     printEscapedString(rmwi->getName());
01610     Out << "\");";
01611     nl(Out) << iName << "->setVolatile("
01612             << (rmwi->isVolatile() ? "true" : "false") << ");";
01613     break;
01614   }
01615   case Instruction::LandingPad: {
01616     const LandingPadInst *lpi = cast<LandingPadInst>(I);
01617     Out << "LandingPadInst* " << iName << " = LandingPadInst::Create(";
01618     printCppName(lpi->getType());
01619     Out << ", " << opNames[0] << ", " << lpi->getNumClauses() << ", \"";
01620     printEscapedString(lpi->getName());
01621     Out << "\", " << bbname << ");";
01622     nl(Out) << iName << "->setCleanup("
01623             << (lpi->isCleanup() ? "true" : "false")
01624             << ");";
01625     for (unsigned i = 0, e = lpi->getNumClauses(); i != e; ++i)
01626       nl(Out) << iName << "->addClause(" << opNames[i+1] << ");";
01627     break;
01628   }
01629   }
01630   DefinedValues.insert(I);
01631   nl(Out);
01632   delete [] opNames;
01633 }
01634 
01635 // Print out the types, constants and declarations needed by one function
01636 void CppWriter::printFunctionUses(const Function* F) {
01637   nl(Out) << "// Type Definitions"; nl(Out);
01638   if (!is_inline) {
01639     // Print the function's return type
01640     printType(F->getReturnType());
01641 
01642     // Print the function's function type
01643     printType(F->getFunctionType());
01644 
01645     // Print the types of each of the function's arguments
01646     for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01647          AI != AE; ++AI) {
01648       printType(AI->getType());
01649     }
01650   }
01651 
01652   // Print type definitions for every type referenced by an instruction and
01653   // make a note of any global values or constants that are referenced
01654   SmallPtrSet<GlobalValue*,64> gvs;
01655   SmallPtrSet<Constant*,64> consts;
01656   for (Function::const_iterator BB = F->begin(), BE = F->end();
01657        BB != BE; ++BB){
01658     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01659          I != E; ++I) {
01660       // Print the type of the instruction itself
01661       printType(I->getType());
01662 
01663       // Print the type of each of the instruction's operands
01664       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
01665         Value* operand = I->getOperand(i);
01666         printType(operand->getType());
01667 
01668         // If the operand references a GVal or Constant, make a note of it
01669         if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
01670           gvs.insert(GV);
01671           if (GenerationType != GenFunction)
01672             if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
01673               if (GVar->hasInitializer())
01674                 consts.insert(GVar->getInitializer());
01675         } else if (Constant* C = dyn_cast<Constant>(operand)) {
01676           consts.insert(C);
01677           for (Value* operand : C->operands()) {
01678             // If the operand references a GVal or Constant, make a note of it
01679             printType(operand->getType());
01680             if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) {
01681               gvs.insert(GV);
01682               if (GenerationType != GenFunction)
01683                 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
01684                   if (GVar->hasInitializer())
01685                     consts.insert(GVar->getInitializer());
01686             }
01687           }
01688         }
01689       }
01690     }
01691   }
01692 
01693   // Print the function declarations for any functions encountered
01694   nl(Out) << "// Function Declarations"; nl(Out);
01695   for (auto *GV : gvs) {
01696     if (Function *Fun = dyn_cast<Function>(GV)) {
01697       if (!is_inline || Fun != F)
01698         printFunctionHead(Fun);
01699     }
01700   }
01701 
01702   // Print the global variable declarations for any variables encountered
01703   nl(Out) << "// Global Variable Declarations"; nl(Out);
01704   for (auto *GV : gvs) {
01705     if (GlobalVariable *F = dyn_cast<GlobalVariable>(GV))
01706       printVariableHead(F);
01707   }
01708 
01709   // Print the constants found
01710   nl(Out) << "// Constant Definitions"; nl(Out);
01711   for (const auto *C : consts) {
01712     printConstant(C);
01713   }
01714 
01715   // Process the global variables definitions now that all the constants have
01716   // been emitted. These definitions just couple the gvars with their constant
01717   // initializers.
01718   if (GenerationType != GenFunction) {
01719     nl(Out) << "// Global Variable Definitions"; nl(Out);
01720     for (auto *GV : gvs) {
01721       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(GV))
01722         printVariableBody(Var);
01723     }
01724   }
01725 }
01726 
01727 void CppWriter::printFunctionHead(const Function* F) {
01728   nl(Out) << "Function* " << getCppName(F);
01729   Out << " = mod->getFunction(\"";
01730   printEscapedString(F->getName());
01731   Out << "\");";
01732   nl(Out) << "if (!" << getCppName(F) << ") {";
01733   nl(Out) << getCppName(F);
01734 
01735   Out<< " = Function::Create(";
01736   nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ",";
01737   nl(Out) << "/*Linkage=*/";
01738   printLinkageType(F->getLinkage());
01739   Out << ",";
01740   nl(Out) << "/*Name=*/\"";
01741   printEscapedString(F->getName());
01742   Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : "");
01743   nl(Out,-1);
01744   printCppName(F);
01745   Out << "->setCallingConv(";
01746   printCallingConv(F->getCallingConv());
01747   Out << ");";
01748   nl(Out);
01749   if (F->hasSection()) {
01750     printCppName(F);
01751     Out << "->setSection(\"" << F->getSection() << "\");";
01752     nl(Out);
01753   }
01754   if (F->getAlignment()) {
01755     printCppName(F);
01756     Out << "->setAlignment(" << F->getAlignment() << ");";
01757     nl(Out);
01758   }
01759   if (F->getVisibility() != GlobalValue::DefaultVisibility) {
01760     printCppName(F);
01761     Out << "->setVisibility(";
01762     printVisibilityType(F->getVisibility());
01763     Out << ");";
01764     nl(Out);
01765   }
01766   if (F->getDLLStorageClass() != GlobalValue::DefaultStorageClass) {
01767     printCppName(F);
01768     Out << "->setDLLStorageClass(";
01769     printDLLStorageClassType(F->getDLLStorageClass());
01770     Out << ");";
01771     nl(Out);
01772   }
01773   if (F->hasGC()) {
01774     printCppName(F);
01775     Out << "->setGC(\"" << F->getGC() << "\");";
01776     nl(Out);
01777   }
01778   Out << "}";
01779   nl(Out);
01780   printAttributes(F->getAttributes(), getCppName(F));
01781   printCppName(F);
01782   Out << "->setAttributes(" << getCppName(F) << "_PAL);";
01783   nl(Out);
01784 }
01785 
01786 void CppWriter::printFunctionBody(const Function *F) {
01787   if (F->isDeclaration())
01788     return; // external functions have no bodies.
01789 
01790   // Clear the DefinedValues and ForwardRefs maps because we can't have
01791   // cross-function forward refs
01792   ForwardRefs.clear();
01793   DefinedValues.clear();
01794 
01795   // Create all the argument values
01796   if (!is_inline) {
01797     if (!F->arg_empty()) {
01798       Out << "Function::arg_iterator args = " << getCppName(F)
01799           << "->arg_begin();";
01800       nl(Out);
01801     }
01802     for (const Argument &AI : F->args()) {
01803       Out << "Value* " << getCppName(&AI) << " = args++;";
01804       nl(Out);
01805       if (AI.hasName()) {
01806         Out << getCppName(&AI) << "->setName(\"";
01807         printEscapedString(AI.getName());
01808         Out << "\");";
01809         nl(Out);
01810       }
01811     }
01812   }
01813 
01814   // Create all the basic blocks
01815   nl(Out);
01816   for (const BasicBlock &BI : *F) {
01817     std::string bbname(getCppName(&BI));
01818     Out << "BasicBlock* " << bbname <<
01819            " = BasicBlock::Create(mod->getContext(), \"";
01820     if (BI.hasName())
01821       printEscapedString(BI.getName());
01822     Out << "\"," << getCppName(BI.getParent()) << ",0);";
01823     nl(Out);
01824   }
01825 
01826   // Output all of its basic blocks... for the function
01827   for (const BasicBlock &BI : *F) {
01828     std::string bbname(getCppName(&BI));
01829     nl(Out) << "// Block " << BI.getName() << " (" << bbname << ")";
01830     nl(Out);
01831 
01832     // Output all of the instructions in the basic block...
01833     for (const Instruction &I : BI)
01834       printInstruction(&I, bbname);
01835   }
01836 
01837   // Loop over the ForwardRefs and resolve them now that all instructions
01838   // are generated.
01839   if (!ForwardRefs.empty()) {
01840     nl(Out) << "// Resolve Forward References";
01841     nl(Out);
01842   }
01843 
01844   while (!ForwardRefs.empty()) {
01845     ForwardRefMap::iterator I = ForwardRefs.begin();
01846     Out << I->second << "->replaceAllUsesWith("
01847         << getCppName(I->first) << "); delete " << I->second << ";";
01848     nl(Out);
01849     ForwardRefs.erase(I);
01850   }
01851 }
01852 
01853 void CppWriter::printInline(const std::string& fname,
01854                             const std::string& func) {
01855   const Function* F = TheModule->getFunction(func);
01856   if (!F) {
01857     error(std::string("Function '") + func + "' not found in input module");
01858     return;
01859   }
01860   if (F->isDeclaration()) {
01861     error(std::string("Function '") + func + "' is external!");
01862     return;
01863   }
01864   nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *"
01865           << getCppName(F);
01866   unsigned arg_count = 1;
01867   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01868        AI != AE; ++AI) {
01869     Out << ", Value* arg_" << arg_count++;
01870   }
01871   Out << ") {";
01872   nl(Out);
01873   is_inline = true;
01874   printFunctionUses(F);
01875   printFunctionBody(F);
01876   is_inline = false;
01877   Out << "return " << getCppName(&F->front()) << ";";
01878   nl(Out) << "}";
01879   nl(Out);
01880 }
01881 
01882 void CppWriter::printModuleBody() {
01883   // Print out all the type definitions
01884   nl(Out) << "// Type Definitions"; nl(Out);
01885   printTypes(TheModule);
01886 
01887   // Functions can call each other and global variables can reference them so
01888   // define all the functions first before emitting their function bodies.
01889   nl(Out) << "// Function Declarations"; nl(Out);
01890   for (const Function &I : *TheModule)
01891     printFunctionHead(&I);
01892 
01893   // Process the global variables declarations. We can't initialze them until
01894   // after the constants are printed so just print a header for each global
01895   nl(Out) << "// Global Variable Declarations\n"; nl(Out);
01896   for (const GlobalVariable &I : TheModule->globals())
01897     printVariableHead(&I);
01898 
01899   // Print out all the constants definitions. Constants don't recurse except
01900   // through GlobalValues. All GlobalValues have been declared at this point
01901   // so we can proceed to generate the constants.
01902   nl(Out) << "// Constant Definitions"; nl(Out);
01903   printConstants(TheModule);
01904 
01905   // Process the global variables definitions now that all the constants have
01906   // been emitted. These definitions just couple the gvars with their constant
01907   // initializers.
01908   nl(Out) << "// Global Variable Definitions"; nl(Out);
01909   for (const GlobalVariable &I : TheModule->globals())
01910     printVariableBody(&I);
01911 
01912   // Finally, we can safely put out all of the function bodies.
01913   nl(Out) << "// Function Definitions"; nl(Out);
01914   for (const Function &I : *TheModule) {
01915     if (!I.isDeclaration()) {
01916       nl(Out) << "// Function: " << I.getName() << " (" << getCppName(&I)
01917               << ")";
01918       nl(Out) << "{";
01919       nl(Out,1);
01920       printFunctionBody(&I);
01921       nl(Out,-1) << "}";
01922       nl(Out);
01923     }
01924   }
01925 }
01926 
01927 void CppWriter::printProgram(const std::string& fname,
01928                              const std::string& mName) {
01929   Out << "#include <llvm/Pass.h>\n";
01930 
01931   Out << "#include <llvm/ADT/SmallVector.h>\n";
01932   Out << "#include <llvm/Analysis/Verifier.h>\n";
01933   Out << "#include <llvm/IR/BasicBlock.h>\n";
01934   Out << "#include <llvm/IR/CallingConv.h>\n";
01935   Out << "#include <llvm/IR/Constants.h>\n";
01936   Out << "#include <llvm/IR/DerivedTypes.h>\n";
01937   Out << "#include <llvm/IR/Function.h>\n";
01938   Out << "#include <llvm/IR/GlobalVariable.h>\n";
01939   Out << "#include <llvm/IR/IRPrintingPasses.h>\n";
01940   Out << "#include <llvm/IR/InlineAsm.h>\n";
01941   Out << "#include <llvm/IR/Instructions.h>\n";
01942   Out << "#include <llvm/IR/LLVMContext.h>\n";
01943   Out << "#include <llvm/IR/LegacyPassManager.h>\n";
01944   Out << "#include <llvm/IR/Module.h>\n";
01945   Out << "#include <llvm/Support/FormattedStream.h>\n";
01946   Out << "#include <llvm/Support/MathExtras.h>\n";
01947   Out << "#include <algorithm>\n";
01948   Out << "using namespace llvm;\n\n";
01949   Out << "Module* " << fname << "();\n\n";
01950   Out << "int main(int argc, char**argv) {\n";
01951   Out << "  Module* Mod = " << fname << "();\n";
01952   Out << "  verifyModule(*Mod, PrintMessageAction);\n";
01953   Out << "  PassManager PM;\n";
01954   Out << "  PM.add(createPrintModulePass(&outs()));\n";
01955   Out << "  PM.run(*Mod);\n";
01956   Out << "  return 0;\n";
01957   Out << "}\n\n";
01958   printModule(fname,mName);
01959 }
01960 
01961 void CppWriter::printModule(const std::string& fname,
01962                             const std::string& mName) {
01963   nl(Out) << "Module* " << fname << "() {";
01964   nl(Out,1) << "// Module Construction";
01965   nl(Out) << "Module* mod = new Module(\"";
01966   printEscapedString(mName);
01967   Out << "\", getGlobalContext());";
01968   if (!TheModule->getTargetTriple().empty()) {
01969     nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
01970             << "\");";
01971   }
01972   if (!TheModule->getTargetTriple().empty()) {
01973     nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()
01974             << "\");";
01975   }
01976 
01977   if (!TheModule->getModuleInlineAsm().empty()) {
01978     nl(Out) << "mod->setModuleInlineAsm(\"";
01979     printEscapedString(TheModule->getModuleInlineAsm());
01980     Out << "\");";
01981   }
01982   nl(Out);
01983 
01984   printModuleBody();
01985   nl(Out) << "return mod;";
01986   nl(Out,-1) << "}";
01987   nl(Out);
01988 }
01989 
01990 void CppWriter::printContents(const std::string& fname,
01991                               const std::string& mName) {
01992   Out << "\nModule* " << fname << "(Module *mod) {\n";
01993   Out << "\nmod->setModuleIdentifier(\"";
01994   printEscapedString(mName);
01995   Out << "\");\n";
01996   printModuleBody();
01997   Out << "\nreturn mod;\n";
01998   Out << "\n}\n";
01999 }
02000 
02001 void CppWriter::printFunction(const std::string& fname,
02002                               const std::string& funcName) {
02003   const Function* F = TheModule->getFunction(funcName);
02004   if (!F) {
02005     error(std::string("Function '") + funcName + "' not found in input module");
02006     return;
02007   }
02008   Out << "\nFunction* " << fname << "(Module *mod) {\n";
02009   printFunctionUses(F);
02010   printFunctionHead(F);
02011   printFunctionBody(F);
02012   Out << "return " << getCppName(F) << ";\n";
02013   Out << "}\n";
02014 }
02015 
02016 void CppWriter::printFunctions() {
02017   const Module::FunctionListType &funcs = TheModule->getFunctionList();
02018   Module::const_iterator I  = funcs.begin();
02019   Module::const_iterator IE = funcs.end();
02020 
02021   for (; I != IE; ++I) {
02022     const Function &func = *I;
02023     if (!func.isDeclaration()) {
02024       std::string name("define_");
02025       name += func.getName();
02026       printFunction(name, func.getName());
02027     }
02028   }
02029 }
02030 
02031 void CppWriter::printVariable(const std::string& fname,
02032                               const std::string& varName) {
02033   const GlobalVariable* GV = TheModule->getNamedGlobal(varName);
02034 
02035   if (!GV) {
02036     error(std::string("Variable '") + varName + "' not found in input module");
02037     return;
02038   }
02039   Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n";
02040   printVariableUses(GV);
02041   printVariableHead(GV);
02042   printVariableBody(GV);
02043   Out << "return " << getCppName(GV) << ";\n";
02044   Out << "}\n";
02045 }
02046 
02047 void CppWriter::printType(const std::string &fname,
02048                           const std::string &typeName) {
02049   Type* Ty = TheModule->getTypeByName(typeName);
02050   if (!Ty) {
02051     error(std::string("Type '") + typeName + "' not found in input module");
02052     return;
02053   }
02054   Out << "\nType* " << fname << "(Module *mod) {\n";
02055   printType(Ty);
02056   Out << "return " << getCppName(Ty) << ";\n";
02057   Out << "}\n";
02058 }
02059 
02060 bool CppWriter::runOnModule(Module &M) {
02061   TheModule = &M;
02062 
02063   // Emit a header
02064   Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n";
02065 
02066   // Get the name of the function we're supposed to generate
02067   std::string fname = FuncName.getValue();
02068 
02069   // Get the name of the thing we are to generate
02070   std::string tgtname = NameToGenerate.getValue();
02071   if (GenerationType == GenModule ||
02072       GenerationType == GenContents ||
02073       GenerationType == GenProgram ||
02074       GenerationType == GenFunctions) {
02075     if (tgtname == "!bad!") {
02076       if (M.getModuleIdentifier() == "-")
02077         tgtname = "<stdin>";
02078       else
02079         tgtname = M.getModuleIdentifier();
02080     }
02081   } else if (tgtname == "!bad!")
02082     error("You must use the -for option with -gen-{function,variable,type}");
02083 
02084   switch (WhatToGenerate(GenerationType)) {
02085    case GenProgram:
02086     if (fname.empty())
02087       fname = "makeLLVMModule";
02088     printProgram(fname,tgtname);
02089     break;
02090    case GenModule:
02091     if (fname.empty())
02092       fname = "makeLLVMModule";
02093     printModule(fname,tgtname);
02094     break;
02095    case GenContents:
02096     if (fname.empty())
02097       fname = "makeLLVMModuleContents";
02098     printContents(fname,tgtname);
02099     break;
02100    case GenFunction:
02101     if (fname.empty())
02102       fname = "makeLLVMFunction";
02103     printFunction(fname,tgtname);
02104     break;
02105    case GenFunctions:
02106     printFunctions();
02107     break;
02108    case GenInline:
02109     if (fname.empty())
02110       fname = "makeLLVMInline";
02111     printInline(fname,tgtname);
02112     break;
02113    case GenVariable:
02114     if (fname.empty())
02115       fname = "makeLLVMVariable";
02116     printVariable(fname,tgtname);
02117     break;
02118    case GenType:
02119     if (fname.empty())
02120       fname = "makeLLVMType";
02121     printType(fname,tgtname);
02122     break;
02123   }
02124 
02125   return false;
02126 }
02127 
02128 char CppWriter::ID = 0;
02129 
02130 //===----------------------------------------------------------------------===//
02131 //                       External Interface declaration
02132 //===----------------------------------------------------------------------===//
02133 
02134 bool CPPTargetMachine::addPassesToEmitFile(
02135     PassManagerBase &PM, raw_pwrite_stream &o, CodeGenFileType FileType,
02136     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
02137     AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
02138   if (FileType != TargetMachine::CGFT_AssemblyFile)
02139     return true;
02140   auto FOut = llvm::make_unique<formatted_raw_ostream>(o);
02141   PM.add(new CppWriter(std::move(FOut)));
02142   return false;
02143 }