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