LLVM API Documentation

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