CPPBackend.cpp revision 193323
1193323Sed//===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This file implements the writing of the LLVM IR as a set of C++ calls to the 11193323Sed// LLVM IR interface. The input module is assumed to be verified. 12193323Sed// 13193323Sed//===----------------------------------------------------------------------===// 14193323Sed 15193323Sed#include "CPPTargetMachine.h" 16193323Sed#include "llvm/CallingConv.h" 17193323Sed#include "llvm/Constants.h" 18193323Sed#include "llvm/DerivedTypes.h" 19193323Sed#include "llvm/InlineAsm.h" 20193323Sed#include "llvm/Instruction.h" 21193323Sed#include "llvm/Instructions.h" 22193323Sed#include "llvm/Module.h" 23193323Sed#include "llvm/Pass.h" 24193323Sed#include "llvm/PassManager.h" 25193323Sed#include "llvm/TypeSymbolTable.h" 26193323Sed#include "llvm/Target/TargetMachineRegistry.h" 27193323Sed#include "llvm/ADT/StringExtras.h" 28193323Sed#include "llvm/ADT/STLExtras.h" 29193323Sed#include "llvm/ADT/SmallPtrSet.h" 30193323Sed#include "llvm/Support/CommandLine.h" 31193323Sed#include "llvm/Support/Streams.h" 32193323Sed#include "llvm/Support/raw_ostream.h" 33193323Sed#include "llvm/Config/config.h" 34193323Sed#include <algorithm> 35193323Sed#include <set> 36193323Sed 37193323Sedusing namespace llvm; 38193323Sed 39193323Sedstatic cl::opt<std::string> 40193323SedFuncName("cppfname", cl::desc("Specify the name of the generated function"), 41193323Sed cl::value_desc("function name")); 42193323Sed 43193323Sedenum WhatToGenerate { 44193323Sed GenProgram, 45193323Sed GenModule, 46193323Sed GenContents, 47193323Sed GenFunction, 48193323Sed GenFunctions, 49193323Sed GenInline, 50193323Sed GenVariable, 51193323Sed GenType 52193323Sed}; 53193323Sed 54193323Sedstatic cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional, 55193323Sed cl::desc("Choose what kind of output to generate"), 56193323Sed cl::init(GenProgram), 57193323Sed cl::values( 58193323Sed clEnumValN(GenProgram, "program", "Generate a complete program"), 59193323Sed clEnumValN(GenModule, "module", "Generate a module definition"), 60193323Sed clEnumValN(GenContents, "contents", "Generate contents of a module"), 61193323Sed clEnumValN(GenFunction, "function", "Generate a function definition"), 62193323Sed clEnumValN(GenFunctions,"functions", "Generate all function definitions"), 63193323Sed clEnumValN(GenInline, "inline", "Generate an inline function"), 64193323Sed clEnumValN(GenVariable, "variable", "Generate a variable definition"), 65193323Sed clEnumValN(GenType, "type", "Generate a type definition"), 66193323Sed clEnumValEnd 67193323Sed ) 68193323Sed); 69193323Sed 70193323Sedstatic cl::opt<std::string> NameToGenerate("cppfor", cl::Optional, 71193323Sed cl::desc("Specify the name of the thing to generate"), 72193323Sed cl::init("!bad!")); 73193323Sed 74193323Sed/// CppBackendTargetMachineModule - Note that this is used on hosts 75193323Sed/// that cannot link in a library unless there are references into the 76193323Sed/// library. In particular, it seems that it is not possible to get 77193323Sed/// things to work on Win32 without this. Though it is unused, do not 78193323Sed/// remove it. 79193323Sedextern "C" int CppBackendTargetMachineModule; 80193323Sedint CppBackendTargetMachineModule = 0; 81193323Sed 82193323Sed// Register the target. 83193323Sedstatic RegisterTarget<CPPTargetMachine> X("cpp", "C++ backend"); 84193323Sed 85193323Sednamespace { 86193323Sed typedef std::vector<const Type*> TypeList; 87193323Sed typedef std::map<const Type*,std::string> TypeMap; 88193323Sed typedef std::map<const Value*,std::string> ValueMap; 89193323Sed typedef std::set<std::string> NameSet; 90193323Sed typedef std::set<const Type*> TypeSet; 91193323Sed typedef std::set<const Value*> ValueSet; 92193323Sed typedef std::map<const Value*,std::string> ForwardRefMap; 93193323Sed 94193323Sed /// CppWriter - This class is the main chunk of code that converts an LLVM 95193323Sed /// module to a C++ translation unit. 96193323Sed class CppWriter : public ModulePass { 97193323Sed raw_ostream &Out; 98193323Sed const Module *TheModule; 99193323Sed uint64_t uniqueNum; 100193323Sed TypeMap TypeNames; 101193323Sed ValueMap ValueNames; 102193323Sed TypeMap UnresolvedTypes; 103193323Sed TypeList TypeStack; 104193323Sed NameSet UsedNames; 105193323Sed TypeSet DefinedTypes; 106193323Sed ValueSet DefinedValues; 107193323Sed ForwardRefMap ForwardRefs; 108193323Sed bool is_inline; 109193323Sed 110193323Sed public: 111193323Sed static char ID; 112193323Sed explicit CppWriter(raw_ostream &o) : 113193323Sed ModulePass(&ID), Out(o), uniqueNum(0), is_inline(false) {} 114193323Sed 115193323Sed virtual const char *getPassName() const { return "C++ backend"; } 116193323Sed 117193323Sed bool runOnModule(Module &M); 118193323Sed 119193323Sed void printProgram(const std::string& fname, const std::string& modName ); 120193323Sed void printModule(const std::string& fname, const std::string& modName ); 121193323Sed void printContents(const std::string& fname, const std::string& modName ); 122193323Sed void printFunction(const std::string& fname, const std::string& funcName ); 123193323Sed void printFunctions(); 124193323Sed void printInline(const std::string& fname, const std::string& funcName ); 125193323Sed void printVariable(const std::string& fname, const std::string& varName ); 126193323Sed void printType(const std::string& fname, const std::string& typeName ); 127193323Sed 128193323Sed void error(const std::string& msg); 129193323Sed 130193323Sed private: 131193323Sed void printLinkageType(GlobalValue::LinkageTypes LT); 132193323Sed void printVisibilityType(GlobalValue::VisibilityTypes VisTypes); 133193323Sed void printCallingConv(unsigned cc); 134193323Sed void printEscapedString(const std::string& str); 135193323Sed void printCFP(const ConstantFP* CFP); 136193323Sed 137193323Sed std::string getCppName(const Type* val); 138193323Sed inline void printCppName(const Type* val); 139193323Sed 140193323Sed std::string getCppName(const Value* val); 141193323Sed inline void printCppName(const Value* val); 142193323Sed 143193323Sed void printAttributes(const AttrListPtr &PAL, const std::string &name); 144193323Sed bool printTypeInternal(const Type* Ty); 145193323Sed inline void printType(const Type* Ty); 146193323Sed void printTypes(const Module* M); 147193323Sed 148193323Sed void printConstant(const Constant *CPV); 149193323Sed void printConstants(const Module* M); 150193323Sed 151193323Sed void printVariableUses(const GlobalVariable *GV); 152193323Sed void printVariableHead(const GlobalVariable *GV); 153193323Sed void printVariableBody(const GlobalVariable *GV); 154193323Sed 155193323Sed void printFunctionUses(const Function *F); 156193323Sed void printFunctionHead(const Function *F); 157193323Sed void printFunctionBody(const Function *F); 158193323Sed void printInstruction(const Instruction *I, const std::string& bbname); 159193323Sed std::string getOpName(Value*); 160193323Sed 161193323Sed void printModuleBody(); 162193323Sed }; 163193323Sed 164193323Sed static unsigned indent_level = 0; 165193323Sed inline raw_ostream& nl(raw_ostream& Out, int delta = 0) { 166193323Sed Out << "\n"; 167193323Sed if (delta >= 0 || indent_level >= unsigned(-delta)) 168193323Sed indent_level += delta; 169193323Sed for (unsigned i = 0; i < indent_level; ++i) 170193323Sed Out << " "; 171193323Sed return Out; 172193323Sed } 173193323Sed 174193323Sed inline void in() { indent_level++; } 175193323Sed inline void out() { if (indent_level >0) indent_level--; } 176193323Sed 177193323Sed inline void 178193323Sed sanitize(std::string& str) { 179193323Sed for (size_t i = 0; i < str.length(); ++i) 180193323Sed if (!isalnum(str[i]) && str[i] != '_') 181193323Sed str[i] = '_'; 182193323Sed } 183193323Sed 184193323Sed inline std::string 185193323Sed getTypePrefix(const Type* Ty ) { 186193323Sed switch (Ty->getTypeID()) { 187193323Sed case Type::VoidTyID: return "void_"; 188193323Sed case Type::IntegerTyID: 189193323Sed return std::string("int") + utostr(cast<IntegerType>(Ty)->getBitWidth()) + 190193323Sed "_"; 191193323Sed case Type::FloatTyID: return "float_"; 192193323Sed case Type::DoubleTyID: return "double_"; 193193323Sed case Type::LabelTyID: return "label_"; 194193323Sed case Type::FunctionTyID: return "func_"; 195193323Sed case Type::StructTyID: return "struct_"; 196193323Sed case Type::ArrayTyID: return "array_"; 197193323Sed case Type::PointerTyID: return "ptr_"; 198193323Sed case Type::VectorTyID: return "packed_"; 199193323Sed case Type::OpaqueTyID: return "opaque_"; 200193323Sed default: return "other_"; 201193323Sed } 202193323Sed return "unknown_"; 203193323Sed } 204193323Sed 205193323Sed // Looks up the type in the symbol table and returns a pointer to its name or 206193323Sed // a null pointer if it wasn't found. Note that this isn't the same as the 207193323Sed // Mode::getTypeName function which will return an empty string, not a null 208193323Sed // pointer if the name is not found. 209193323Sed inline const std::string* 210193323Sed findTypeName(const TypeSymbolTable& ST, const Type* Ty) { 211193323Sed TypeSymbolTable::const_iterator TI = ST.begin(); 212193323Sed TypeSymbolTable::const_iterator TE = ST.end(); 213193323Sed for (;TI != TE; ++TI) 214193323Sed if (TI->second == Ty) 215193323Sed return &(TI->first); 216193323Sed return 0; 217193323Sed } 218193323Sed 219193323Sed void CppWriter::error(const std::string& msg) { 220193323Sed cerr << msg << "\n"; 221193323Sed exit(2); 222193323Sed } 223193323Sed 224193323Sed // printCFP - Print a floating point constant .. very carefully :) 225193323Sed // This makes sure that conversion to/from floating yields the same binary 226193323Sed // result so that we don't lose precision. 227193323Sed void CppWriter::printCFP(const ConstantFP *CFP) { 228193323Sed bool ignored; 229193323Sed APFloat APF = APFloat(CFP->getValueAPF()); // copy 230193323Sed if (CFP->getType() == Type::FloatTy) 231193323Sed APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored); 232193323Sed Out << "ConstantFP::get("; 233193323Sed Out << "APFloat("; 234193323Sed#if HAVE_PRINTF_A 235193323Sed char Buffer[100]; 236193323Sed sprintf(Buffer, "%A", APF.convertToDouble()); 237193323Sed if ((!strncmp(Buffer, "0x", 2) || 238193323Sed !strncmp(Buffer, "-0x", 3) || 239193323Sed !strncmp(Buffer, "+0x", 3)) && 240193323Sed APF.bitwiseIsEqual(APFloat(atof(Buffer)))) { 241193323Sed if (CFP->getType() == Type::DoubleTy) 242193323Sed Out << "BitsToDouble(" << Buffer << ")"; 243193323Sed else 244193323Sed Out << "BitsToFloat((float)" << Buffer << ")"; 245193323Sed Out << ")"; 246193323Sed } else { 247193323Sed#endif 248193323Sed std::string StrVal = ftostr(CFP->getValueAPF()); 249193323Sed 250193323Sed while (StrVal[0] == ' ') 251193323Sed StrVal.erase(StrVal.begin()); 252193323Sed 253193323Sed // Check to make sure that the stringized number is not some string like 254193323Sed // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex. 255193323Sed if (((StrVal[0] >= '0' && StrVal[0] <= '9') || 256193323Sed ((StrVal[0] == '-' || StrVal[0] == '+') && 257193323Sed (StrVal[1] >= '0' && StrVal[1] <= '9'))) && 258193323Sed (CFP->isExactlyValue(atof(StrVal.c_str())))) { 259193323Sed if (CFP->getType() == Type::DoubleTy) 260193323Sed Out << StrVal; 261193323Sed else 262193323Sed Out << StrVal << "f"; 263193323Sed } else if (CFP->getType() == Type::DoubleTy) 264193323Sed Out << "BitsToDouble(0x" 265193323Sed << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue()) 266193323Sed << "ULL) /* " << StrVal << " */"; 267193323Sed else 268193323Sed Out << "BitsToFloat(0x" 269193323Sed << utohexstr((uint32_t)CFP->getValueAPF(). 270193323Sed bitcastToAPInt().getZExtValue()) 271193323Sed << "U) /* " << StrVal << " */"; 272193323Sed Out << ")"; 273193323Sed#if HAVE_PRINTF_A 274193323Sed } 275193323Sed#endif 276193323Sed Out << ")"; 277193323Sed } 278193323Sed 279193323Sed void CppWriter::printCallingConv(unsigned cc){ 280193323Sed // Print the calling convention. 281193323Sed switch (cc) { 282193323Sed case CallingConv::C: Out << "CallingConv::C"; break; 283193323Sed case CallingConv::Fast: Out << "CallingConv::Fast"; break; 284193323Sed case CallingConv::Cold: Out << "CallingConv::Cold"; break; 285193323Sed case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break; 286193323Sed default: Out << cc; break; 287193323Sed } 288193323Sed } 289193323Sed 290193323Sed void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) { 291193323Sed switch (LT) { 292193323Sed case GlobalValue::InternalLinkage: 293193323Sed Out << "GlobalValue::InternalLinkage"; break; 294193323Sed case GlobalValue::PrivateLinkage: 295193323Sed Out << "GlobalValue::PrivateLinkage"; break; 296193323Sed case GlobalValue::AvailableExternallyLinkage: 297193323Sed Out << "GlobalValue::AvailableExternallyLinkage "; break; 298193323Sed case GlobalValue::LinkOnceAnyLinkage: 299193323Sed Out << "GlobalValue::LinkOnceAnyLinkage "; break; 300193323Sed case GlobalValue::LinkOnceODRLinkage: 301193323Sed Out << "GlobalValue::LinkOnceODRLinkage "; break; 302193323Sed case GlobalValue::WeakAnyLinkage: 303193323Sed Out << "GlobalValue::WeakAnyLinkage"; break; 304193323Sed case GlobalValue::WeakODRLinkage: 305193323Sed Out << "GlobalValue::WeakODRLinkage"; break; 306193323Sed case GlobalValue::AppendingLinkage: 307193323Sed Out << "GlobalValue::AppendingLinkage"; break; 308193323Sed case GlobalValue::ExternalLinkage: 309193323Sed Out << "GlobalValue::ExternalLinkage"; break; 310193323Sed case GlobalValue::DLLImportLinkage: 311193323Sed Out << "GlobalValue::DLLImportLinkage"; break; 312193323Sed case GlobalValue::DLLExportLinkage: 313193323Sed Out << "GlobalValue::DLLExportLinkage"; break; 314193323Sed case GlobalValue::ExternalWeakLinkage: 315193323Sed Out << "GlobalValue::ExternalWeakLinkage"; break; 316193323Sed case GlobalValue::GhostLinkage: 317193323Sed Out << "GlobalValue::GhostLinkage"; break; 318193323Sed case GlobalValue::CommonLinkage: 319193323Sed Out << "GlobalValue::CommonLinkage"; break; 320193323Sed } 321193323Sed } 322193323Sed 323193323Sed void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) { 324193323Sed switch (VisType) { 325193323Sed default: assert(0 && "Unknown GVar visibility"); 326193323Sed case GlobalValue::DefaultVisibility: 327193323Sed Out << "GlobalValue::DefaultVisibility"; 328193323Sed break; 329193323Sed case GlobalValue::HiddenVisibility: 330193323Sed Out << "GlobalValue::HiddenVisibility"; 331193323Sed break; 332193323Sed case GlobalValue::ProtectedVisibility: 333193323Sed Out << "GlobalValue::ProtectedVisibility"; 334193323Sed break; 335193323Sed } 336193323Sed } 337193323Sed 338193323Sed // printEscapedString - Print each character of the specified string, escaping 339193323Sed // it if it is not printable or if it is an escape char. 340193323Sed void CppWriter::printEscapedString(const std::string &Str) { 341193323Sed for (unsigned i = 0, e = Str.size(); i != e; ++i) { 342193323Sed unsigned char C = Str[i]; 343193323Sed if (isprint(C) && C != '"' && C != '\\') { 344193323Sed Out << C; 345193323Sed } else { 346193323Sed Out << "\\x" 347193323Sed << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 348193323Sed << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 349193323Sed } 350193323Sed } 351193323Sed } 352193323Sed 353193323Sed std::string CppWriter::getCppName(const Type* Ty) { 354193323Sed // First, handle the primitive types .. easy 355193323Sed if (Ty->isPrimitiveType() || Ty->isInteger()) { 356193323Sed switch (Ty->getTypeID()) { 357193323Sed case Type::VoidTyID: return "Type::VoidTy"; 358193323Sed case Type::IntegerTyID: { 359193323Sed unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 360193323Sed return "IntegerType::get(" + utostr(BitWidth) + ")"; 361193323Sed } 362193323Sed case Type::X86_FP80TyID: return "Type::X86_FP80Ty"; 363193323Sed case Type::FloatTyID: return "Type::FloatTy"; 364193323Sed case Type::DoubleTyID: return "Type::DoubleTy"; 365193323Sed case Type::LabelTyID: return "Type::LabelTy"; 366193323Sed default: 367193323Sed error("Invalid primitive type"); 368193323Sed break; 369193323Sed } 370193323Sed return "Type::VoidTy"; // shouldn't be returned, but make it sensible 371193323Sed } 372193323Sed 373193323Sed // Now, see if we've seen the type before and return that 374193323Sed TypeMap::iterator I = TypeNames.find(Ty); 375193323Sed if (I != TypeNames.end()) 376193323Sed return I->second; 377193323Sed 378193323Sed // Okay, let's build a new name for this type. Start with a prefix 379193323Sed const char* prefix = 0; 380193323Sed switch (Ty->getTypeID()) { 381193323Sed case Type::FunctionTyID: prefix = "FuncTy_"; break; 382193323Sed case Type::StructTyID: prefix = "StructTy_"; break; 383193323Sed case Type::ArrayTyID: prefix = "ArrayTy_"; break; 384193323Sed case Type::PointerTyID: prefix = "PointerTy_"; break; 385193323Sed case Type::OpaqueTyID: prefix = "OpaqueTy_"; break; 386193323Sed case Type::VectorTyID: prefix = "VectorTy_"; break; 387193323Sed default: prefix = "OtherTy_"; break; // prevent breakage 388193323Sed } 389193323Sed 390193323Sed // See if the type has a name in the symboltable and build accordingly 391193323Sed const std::string* tName = findTypeName(TheModule->getTypeSymbolTable(), Ty); 392193323Sed std::string name; 393193323Sed if (tName) 394193323Sed name = std::string(prefix) + *tName; 395193323Sed else 396193323Sed name = std::string(prefix) + utostr(uniqueNum++); 397193323Sed sanitize(name); 398193323Sed 399193323Sed // Save the name 400193323Sed return TypeNames[Ty] = name; 401193323Sed } 402193323Sed 403193323Sed void CppWriter::printCppName(const Type* Ty) { 404193323Sed printEscapedString(getCppName(Ty)); 405193323Sed } 406193323Sed 407193323Sed std::string CppWriter::getCppName(const Value* val) { 408193323Sed std::string name; 409193323Sed ValueMap::iterator I = ValueNames.find(val); 410193323Sed if (I != ValueNames.end() && I->first == val) 411193323Sed return I->second; 412193323Sed 413193323Sed if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) { 414193323Sed name = std::string("gvar_") + 415193323Sed getTypePrefix(GV->getType()->getElementType()); 416193323Sed } else if (isa<Function>(val)) { 417193323Sed name = std::string("func_"); 418193323Sed } else if (const Constant* C = dyn_cast<Constant>(val)) { 419193323Sed name = std::string("const_") + getTypePrefix(C->getType()); 420193323Sed } else if (const Argument* Arg = dyn_cast<Argument>(val)) { 421193323Sed if (is_inline) { 422193323Sed unsigned argNum = std::distance(Arg->getParent()->arg_begin(), 423193323Sed Function::const_arg_iterator(Arg)) + 1; 424193323Sed name = std::string("arg_") + utostr(argNum); 425193323Sed NameSet::iterator NI = UsedNames.find(name); 426193323Sed if (NI != UsedNames.end()) 427193323Sed name += std::string("_") + utostr(uniqueNum++); 428193323Sed UsedNames.insert(name); 429193323Sed return ValueNames[val] = name; 430193323Sed } else { 431193323Sed name = getTypePrefix(val->getType()); 432193323Sed } 433193323Sed } else { 434193323Sed name = getTypePrefix(val->getType()); 435193323Sed } 436193323Sed name += (val->hasName() ? val->getName() : utostr(uniqueNum++)); 437193323Sed sanitize(name); 438193323Sed NameSet::iterator NI = UsedNames.find(name); 439193323Sed if (NI != UsedNames.end()) 440193323Sed name += std::string("_") + utostr(uniqueNum++); 441193323Sed UsedNames.insert(name); 442193323Sed return ValueNames[val] = name; 443193323Sed } 444193323Sed 445193323Sed void CppWriter::printCppName(const Value* val) { 446193323Sed printEscapedString(getCppName(val)); 447193323Sed } 448193323Sed 449193323Sed void CppWriter::printAttributes(const AttrListPtr &PAL, 450193323Sed const std::string &name) { 451193323Sed Out << "AttrListPtr " << name << "_PAL;"; 452193323Sed nl(Out); 453193323Sed if (!PAL.isEmpty()) { 454193323Sed Out << '{'; in(); nl(Out); 455193323Sed Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out); 456193323Sed Out << "AttributeWithIndex PAWI;"; nl(Out); 457193323Sed for (unsigned i = 0; i < PAL.getNumSlots(); ++i) { 458193323Sed unsigned index = PAL.getSlot(i).Index; 459193323Sed Attributes attrs = PAL.getSlot(i).Attrs; 460193323Sed Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 "; 461193323Sed#define HANDLE_ATTR(X) \ 462193323Sed if (attrs & Attribute::X) \ 463193323Sed Out << " | Attribute::" #X; \ 464193323Sed attrs &= ~Attribute::X; 465193323Sed 466193323Sed HANDLE_ATTR(SExt); 467193323Sed HANDLE_ATTR(ZExt); 468193323Sed HANDLE_ATTR(NoReturn); 469193323Sed HANDLE_ATTR(InReg); 470193323Sed HANDLE_ATTR(StructRet); 471193323Sed HANDLE_ATTR(NoUnwind); 472193323Sed HANDLE_ATTR(NoAlias); 473193323Sed HANDLE_ATTR(ByVal); 474193323Sed HANDLE_ATTR(Nest); 475193323Sed HANDLE_ATTR(ReadNone); 476193323Sed HANDLE_ATTR(ReadOnly); 477193323Sed HANDLE_ATTR(NoInline); 478193323Sed HANDLE_ATTR(AlwaysInline); 479193323Sed HANDLE_ATTR(OptimizeForSize); 480193323Sed HANDLE_ATTR(StackProtect); 481193323Sed HANDLE_ATTR(StackProtectReq); 482193323Sed HANDLE_ATTR(NoCapture); 483193323Sed#undef HANDLE_ATTR 484193323Sed assert(attrs == 0 && "Unhandled attribute!"); 485193323Sed Out << ";"; 486193323Sed nl(Out); 487193323Sed Out << "Attrs.push_back(PAWI);"; 488193323Sed nl(Out); 489193323Sed } 490193323Sed Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());"; 491193323Sed nl(Out); 492193323Sed out(); nl(Out); 493193323Sed Out << '}'; nl(Out); 494193323Sed } 495193323Sed } 496193323Sed 497193323Sed bool CppWriter::printTypeInternal(const Type* Ty) { 498193323Sed // We don't print definitions for primitive types 499193323Sed if (Ty->isPrimitiveType() || Ty->isInteger()) 500193323Sed return false; 501193323Sed 502193323Sed // If we already defined this type, we don't need to define it again. 503193323Sed if (DefinedTypes.find(Ty) != DefinedTypes.end()) 504193323Sed return false; 505193323Sed 506193323Sed // Everything below needs the name for the type so get it now. 507193323Sed std::string typeName(getCppName(Ty)); 508193323Sed 509193323Sed // Search the type stack for recursion. If we find it, then generate this 510193323Sed // as an OpaqueType, but make sure not to do this multiple times because 511193323Sed // the type could appear in multiple places on the stack. Once the opaque 512193323Sed // definition is issued, it must not be re-issued. Consequently we have to 513193323Sed // check the UnresolvedTypes list as well. 514193323Sed TypeList::const_iterator TI = std::find(TypeStack.begin(), TypeStack.end(), 515193323Sed Ty); 516193323Sed if (TI != TypeStack.end()) { 517193323Sed TypeMap::const_iterator I = UnresolvedTypes.find(Ty); 518193323Sed if (I == UnresolvedTypes.end()) { 519193323Sed Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();"; 520193323Sed nl(Out); 521193323Sed UnresolvedTypes[Ty] = typeName; 522193323Sed } 523193323Sed return true; 524193323Sed } 525193323Sed 526193323Sed // We're going to print a derived type which, by definition, contains other 527193323Sed // types. So, push this one we're printing onto the type stack to assist with 528193323Sed // recursive definitions. 529193323Sed TypeStack.push_back(Ty); 530193323Sed 531193323Sed // Print the type definition 532193323Sed switch (Ty->getTypeID()) { 533193323Sed case Type::FunctionTyID: { 534193323Sed const FunctionType* FT = cast<FunctionType>(Ty); 535193323Sed Out << "std::vector<const Type*>" << typeName << "_args;"; 536193323Sed nl(Out); 537193323Sed FunctionType::param_iterator PI = FT->param_begin(); 538193323Sed FunctionType::param_iterator PE = FT->param_end(); 539193323Sed for (; PI != PE; ++PI) { 540193323Sed const Type* argTy = static_cast<const Type*>(*PI); 541193323Sed bool isForward = printTypeInternal(argTy); 542193323Sed std::string argName(getCppName(argTy)); 543193323Sed Out << typeName << "_args.push_back(" << argName; 544193323Sed if (isForward) 545193323Sed Out << "_fwd"; 546193323Sed Out << ");"; 547193323Sed nl(Out); 548193323Sed } 549193323Sed bool isForward = printTypeInternal(FT->getReturnType()); 550193323Sed std::string retTypeName(getCppName(FT->getReturnType())); 551193323Sed Out << "FunctionType* " << typeName << " = FunctionType::get("; 552193323Sed in(); nl(Out) << "/*Result=*/" << retTypeName; 553193323Sed if (isForward) 554193323Sed Out << "_fwd"; 555193323Sed Out << ","; 556193323Sed nl(Out) << "/*Params=*/" << typeName << "_args,"; 557193323Sed nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");"; 558193323Sed out(); 559193323Sed nl(Out); 560193323Sed break; 561193323Sed } 562193323Sed case Type::StructTyID: { 563193323Sed const StructType* ST = cast<StructType>(Ty); 564193323Sed Out << "std::vector<const Type*>" << typeName << "_fields;"; 565193323Sed nl(Out); 566193323Sed StructType::element_iterator EI = ST->element_begin(); 567193323Sed StructType::element_iterator EE = ST->element_end(); 568193323Sed for (; EI != EE; ++EI) { 569193323Sed const Type* fieldTy = static_cast<const Type*>(*EI); 570193323Sed bool isForward = printTypeInternal(fieldTy); 571193323Sed std::string fieldName(getCppName(fieldTy)); 572193323Sed Out << typeName << "_fields.push_back(" << fieldName; 573193323Sed if (isForward) 574193323Sed Out << "_fwd"; 575193323Sed Out << ");"; 576193323Sed nl(Out); 577193323Sed } 578193323Sed Out << "StructType* " << typeName << " = StructType::get(" 579193323Sed << typeName << "_fields, /*isPacked=*/" 580193323Sed << (ST->isPacked() ? "true" : "false") << ");"; 581193323Sed nl(Out); 582193323Sed break; 583193323Sed } 584193323Sed case Type::ArrayTyID: { 585193323Sed const ArrayType* AT = cast<ArrayType>(Ty); 586193323Sed const Type* ET = AT->getElementType(); 587193323Sed bool isForward = printTypeInternal(ET); 588193323Sed std::string elemName(getCppName(ET)); 589193323Sed Out << "ArrayType* " << typeName << " = ArrayType::get(" 590193323Sed << elemName << (isForward ? "_fwd" : "") 591193323Sed << ", " << utostr(AT->getNumElements()) << ");"; 592193323Sed nl(Out); 593193323Sed break; 594193323Sed } 595193323Sed case Type::PointerTyID: { 596193323Sed const PointerType* PT = cast<PointerType>(Ty); 597193323Sed const Type* ET = PT->getElementType(); 598193323Sed bool isForward = printTypeInternal(ET); 599193323Sed std::string elemName(getCppName(ET)); 600193323Sed Out << "PointerType* " << typeName << " = PointerType::get(" 601193323Sed << elemName << (isForward ? "_fwd" : "") 602193323Sed << ", " << utostr(PT->getAddressSpace()) << ");"; 603193323Sed nl(Out); 604193323Sed break; 605193323Sed } 606193323Sed case Type::VectorTyID: { 607193323Sed const VectorType* PT = cast<VectorType>(Ty); 608193323Sed const Type* ET = PT->getElementType(); 609193323Sed bool isForward = printTypeInternal(ET); 610193323Sed std::string elemName(getCppName(ET)); 611193323Sed Out << "VectorType* " << typeName << " = VectorType::get(" 612193323Sed << elemName << (isForward ? "_fwd" : "") 613193323Sed << ", " << utostr(PT->getNumElements()) << ");"; 614193323Sed nl(Out); 615193323Sed break; 616193323Sed } 617193323Sed case Type::OpaqueTyID: { 618193323Sed Out << "OpaqueType* " << typeName << " = OpaqueType::get();"; 619193323Sed nl(Out); 620193323Sed break; 621193323Sed } 622193323Sed default: 623193323Sed error("Invalid TypeID"); 624193323Sed } 625193323Sed 626193323Sed // If the type had a name, make sure we recreate it. 627193323Sed const std::string* progTypeName = 628193323Sed findTypeName(TheModule->getTypeSymbolTable(),Ty); 629193323Sed if (progTypeName) { 630193323Sed Out << "mod->addTypeName(\"" << *progTypeName << "\", " 631193323Sed << typeName << ");"; 632193323Sed nl(Out); 633193323Sed } 634193323Sed 635193323Sed // Pop us off the type stack 636193323Sed TypeStack.pop_back(); 637193323Sed 638193323Sed // Indicate that this type is now defined. 639193323Sed DefinedTypes.insert(Ty); 640193323Sed 641193323Sed // Early resolve as many unresolved types as possible. Search the unresolved 642193323Sed // types map for the type we just printed. Now that its definition is complete 643193323Sed // we can resolve any previous references to it. This prevents a cascade of 644193323Sed // unresolved types. 645193323Sed TypeMap::iterator I = UnresolvedTypes.find(Ty); 646193323Sed if (I != UnresolvedTypes.end()) { 647193323Sed Out << "cast<OpaqueType>(" << I->second 648193323Sed << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");"; 649193323Sed nl(Out); 650193323Sed Out << I->second << " = cast<"; 651193323Sed switch (Ty->getTypeID()) { 652193323Sed case Type::FunctionTyID: Out << "FunctionType"; break; 653193323Sed case Type::ArrayTyID: Out << "ArrayType"; break; 654193323Sed case Type::StructTyID: Out << "StructType"; break; 655193323Sed case Type::VectorTyID: Out << "VectorType"; break; 656193323Sed case Type::PointerTyID: Out << "PointerType"; break; 657193323Sed case Type::OpaqueTyID: Out << "OpaqueType"; break; 658193323Sed default: Out << "NoSuchDerivedType"; break; 659193323Sed } 660193323Sed Out << ">(" << I->second << "_fwd.get());"; 661193323Sed nl(Out); nl(Out); 662193323Sed UnresolvedTypes.erase(I); 663193323Sed } 664193323Sed 665193323Sed // Finally, separate the type definition from other with a newline. 666193323Sed nl(Out); 667193323Sed 668193323Sed // We weren't a recursive type 669193323Sed return false; 670193323Sed } 671193323Sed 672193323Sed // Prints a type definition. Returns true if it could not resolve all the 673193323Sed // types in the definition but had to use a forward reference. 674193323Sed void CppWriter::printType(const Type* Ty) { 675193323Sed assert(TypeStack.empty()); 676193323Sed TypeStack.clear(); 677193323Sed printTypeInternal(Ty); 678193323Sed assert(TypeStack.empty()); 679193323Sed } 680193323Sed 681193323Sed void CppWriter::printTypes(const Module* M) { 682193323Sed // Walk the symbol table and print out all its types 683193323Sed const TypeSymbolTable& symtab = M->getTypeSymbolTable(); 684193323Sed for (TypeSymbolTable::const_iterator TI = symtab.begin(), TE = symtab.end(); 685193323Sed TI != TE; ++TI) { 686193323Sed 687193323Sed // For primitive types and types already defined, just add a name 688193323Sed TypeMap::const_iterator TNI = TypeNames.find(TI->second); 689193323Sed if (TI->second->isInteger() || TI->second->isPrimitiveType() || 690193323Sed TNI != TypeNames.end()) { 691193323Sed Out << "mod->addTypeName(\""; 692193323Sed printEscapedString(TI->first); 693193323Sed Out << "\", " << getCppName(TI->second) << ");"; 694193323Sed nl(Out); 695193323Sed // For everything else, define the type 696193323Sed } else { 697193323Sed printType(TI->second); 698193323Sed } 699193323Sed } 700193323Sed 701193323Sed // Add all of the global variables to the value table... 702193323Sed for (Module::const_global_iterator I = TheModule->global_begin(), 703193323Sed E = TheModule->global_end(); I != E; ++I) { 704193323Sed if (I->hasInitializer()) 705193323Sed printType(I->getInitializer()->getType()); 706193323Sed printType(I->getType()); 707193323Sed } 708193323Sed 709193323Sed // Add all the functions to the table 710193323Sed for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end(); 711193323Sed FI != FE; ++FI) { 712193323Sed printType(FI->getReturnType()); 713193323Sed printType(FI->getFunctionType()); 714193323Sed // Add all the function arguments 715193323Sed for (Function::const_arg_iterator AI = FI->arg_begin(), 716193323Sed AE = FI->arg_end(); AI != AE; ++AI) { 717193323Sed printType(AI->getType()); 718193323Sed } 719193323Sed 720193323Sed // Add all of the basic blocks and instructions 721193323Sed for (Function::const_iterator BB = FI->begin(), 722193323Sed E = FI->end(); BB != E; ++BB) { 723193323Sed printType(BB->getType()); 724193323Sed for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 725193323Sed ++I) { 726193323Sed printType(I->getType()); 727193323Sed for (unsigned i = 0; i < I->getNumOperands(); ++i) 728193323Sed printType(I->getOperand(i)->getType()); 729193323Sed } 730193323Sed } 731193323Sed } 732193323Sed } 733193323Sed 734193323Sed 735193323Sed // printConstant - Print out a constant pool entry... 736193323Sed void CppWriter::printConstant(const Constant *CV) { 737193323Sed // First, if the constant is actually a GlobalValue (variable or function) 738193323Sed // or its already in the constant list then we've printed it already and we 739193323Sed // can just return. 740193323Sed if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end()) 741193323Sed return; 742193323Sed 743193323Sed std::string constName(getCppName(CV)); 744193323Sed std::string typeName(getCppName(CV->getType())); 745193323Sed 746193323Sed if (isa<GlobalValue>(CV)) { 747193323Sed // Skip variables and functions, we emit them elsewhere 748193323Sed return; 749193323Sed } 750193323Sed 751193323Sed if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 752193323Sed std::string constValue = CI->getValue().toString(10, true); 753193323Sed Out << "ConstantInt* " << constName << " = ConstantInt::get(APInt(" 754193323Sed << cast<IntegerType>(CI->getType())->getBitWidth() << ", \"" 755193323Sed << constValue << "\", " << constValue.length() << ", 10));"; 756193323Sed } else if (isa<ConstantAggregateZero>(CV)) { 757193323Sed Out << "ConstantAggregateZero* " << constName 758193323Sed << " = ConstantAggregateZero::get(" << typeName << ");"; 759193323Sed } else if (isa<ConstantPointerNull>(CV)) { 760193323Sed Out << "ConstantPointerNull* " << constName 761193323Sed << " = ConstantPointerNull::get(" << typeName << ");"; 762193323Sed } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 763193323Sed Out << "ConstantFP* " << constName << " = "; 764193323Sed printCFP(CFP); 765193323Sed Out << ";"; 766193323Sed } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 767193323Sed if (CA->isString() && CA->getType()->getElementType() == Type::Int8Ty) { 768193323Sed Out << "Constant* " << constName << " = ConstantArray::get(\""; 769193323Sed std::string tmp = CA->getAsString(); 770193323Sed bool nullTerminate = false; 771193323Sed if (tmp[tmp.length()-1] == 0) { 772193323Sed tmp.erase(tmp.length()-1); 773193323Sed nullTerminate = true; 774193323Sed } 775193323Sed printEscapedString(tmp); 776193323Sed // Determine if we want null termination or not. 777193323Sed if (nullTerminate) 778193323Sed Out << "\", true"; // Indicate that the null terminator should be 779193323Sed // added. 780193323Sed else 781193323Sed Out << "\", false";// No null terminator 782193323Sed Out << ");"; 783193323Sed } else { 784193323Sed Out << "std::vector<Constant*> " << constName << "_elems;"; 785193323Sed nl(Out); 786193323Sed unsigned N = CA->getNumOperands(); 787193323Sed for (unsigned i = 0; i < N; ++i) { 788193323Sed printConstant(CA->getOperand(i)); // recurse to print operands 789193323Sed Out << constName << "_elems.push_back(" 790193323Sed << getCppName(CA->getOperand(i)) << ");"; 791193323Sed nl(Out); 792193323Sed } 793193323Sed Out << "Constant* " << constName << " = ConstantArray::get(" 794193323Sed << typeName << ", " << constName << "_elems);"; 795193323Sed } 796193323Sed } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 797193323Sed Out << "std::vector<Constant*> " << constName << "_fields;"; 798193323Sed nl(Out); 799193323Sed unsigned N = CS->getNumOperands(); 800193323Sed for (unsigned i = 0; i < N; i++) { 801193323Sed printConstant(CS->getOperand(i)); 802193323Sed Out << constName << "_fields.push_back(" 803193323Sed << getCppName(CS->getOperand(i)) << ");"; 804193323Sed nl(Out); 805193323Sed } 806193323Sed Out << "Constant* " << constName << " = ConstantStruct::get(" 807193323Sed << typeName << ", " << constName << "_fields);"; 808193323Sed } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 809193323Sed Out << "std::vector<Constant*> " << constName << "_elems;"; 810193323Sed nl(Out); 811193323Sed unsigned N = CP->getNumOperands(); 812193323Sed for (unsigned i = 0; i < N; ++i) { 813193323Sed printConstant(CP->getOperand(i)); 814193323Sed Out << constName << "_elems.push_back(" 815193323Sed << getCppName(CP->getOperand(i)) << ");"; 816193323Sed nl(Out); 817193323Sed } 818193323Sed Out << "Constant* " << constName << " = ConstantVector::get(" 819193323Sed << typeName << ", " << constName << "_elems);"; 820193323Sed } else if (isa<UndefValue>(CV)) { 821193323Sed Out << "UndefValue* " << constName << " = UndefValue::get(" 822193323Sed << typeName << ");"; 823193323Sed } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 824193323Sed if (CE->getOpcode() == Instruction::GetElementPtr) { 825193323Sed Out << "std::vector<Constant*> " << constName << "_indices;"; 826193323Sed nl(Out); 827193323Sed printConstant(CE->getOperand(0)); 828193323Sed for (unsigned i = 1; i < CE->getNumOperands(); ++i ) { 829193323Sed printConstant(CE->getOperand(i)); 830193323Sed Out << constName << "_indices.push_back(" 831193323Sed << getCppName(CE->getOperand(i)) << ");"; 832193323Sed nl(Out); 833193323Sed } 834193323Sed Out << "Constant* " << constName 835193323Sed << " = ConstantExpr::getGetElementPtr(" 836193323Sed << getCppName(CE->getOperand(0)) << ", " 837193323Sed << "&" << constName << "_indices[0], " 838193323Sed << constName << "_indices.size()" 839193323Sed << " );"; 840193323Sed } else if (CE->isCast()) { 841193323Sed printConstant(CE->getOperand(0)); 842193323Sed Out << "Constant* " << constName << " = ConstantExpr::getCast("; 843193323Sed switch (CE->getOpcode()) { 844193323Sed default: assert(0 && "Invalid cast opcode"); 845193323Sed case Instruction::Trunc: Out << "Instruction::Trunc"; break; 846193323Sed case Instruction::ZExt: Out << "Instruction::ZExt"; break; 847193323Sed case Instruction::SExt: Out << "Instruction::SExt"; break; 848193323Sed case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break; 849193323Sed case Instruction::FPExt: Out << "Instruction::FPExt"; break; 850193323Sed case Instruction::FPToUI: Out << "Instruction::FPToUI"; break; 851193323Sed case Instruction::FPToSI: Out << "Instruction::FPToSI"; break; 852193323Sed case Instruction::UIToFP: Out << "Instruction::UIToFP"; break; 853193323Sed case Instruction::SIToFP: Out << "Instruction::SIToFP"; break; 854193323Sed case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break; 855193323Sed case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break; 856193323Sed case Instruction::BitCast: Out << "Instruction::BitCast"; break; 857193323Sed } 858193323Sed Out << ", " << getCppName(CE->getOperand(0)) << ", " 859193323Sed << getCppName(CE->getType()) << ");"; 860193323Sed } else { 861193323Sed unsigned N = CE->getNumOperands(); 862193323Sed for (unsigned i = 0; i < N; ++i ) { 863193323Sed printConstant(CE->getOperand(i)); 864193323Sed } 865193323Sed Out << "Constant* " << constName << " = ConstantExpr::"; 866193323Sed switch (CE->getOpcode()) { 867193323Sed case Instruction::Add: Out << "getAdd("; break; 868193323Sed case Instruction::Sub: Out << "getSub("; break; 869193323Sed case Instruction::Mul: Out << "getMul("; break; 870193323Sed case Instruction::UDiv: Out << "getUDiv("; break; 871193323Sed case Instruction::SDiv: Out << "getSDiv("; break; 872193323Sed case Instruction::FDiv: Out << "getFDiv("; break; 873193323Sed case Instruction::URem: Out << "getURem("; break; 874193323Sed case Instruction::SRem: Out << "getSRem("; break; 875193323Sed case Instruction::FRem: Out << "getFRem("; break; 876193323Sed case Instruction::And: Out << "getAnd("; break; 877193323Sed case Instruction::Or: Out << "getOr("; break; 878193323Sed case Instruction::Xor: Out << "getXor("; break; 879193323Sed case Instruction::ICmp: 880193323Sed Out << "getICmp(ICmpInst::ICMP_"; 881193323Sed switch (CE->getPredicate()) { 882193323Sed case ICmpInst::ICMP_EQ: Out << "EQ"; break; 883193323Sed case ICmpInst::ICMP_NE: Out << "NE"; break; 884193323Sed case ICmpInst::ICMP_SLT: Out << "SLT"; break; 885193323Sed case ICmpInst::ICMP_ULT: Out << "ULT"; break; 886193323Sed case ICmpInst::ICMP_SGT: Out << "SGT"; break; 887193323Sed case ICmpInst::ICMP_UGT: Out << "UGT"; break; 888193323Sed case ICmpInst::ICMP_SLE: Out << "SLE"; break; 889193323Sed case ICmpInst::ICMP_ULE: Out << "ULE"; break; 890193323Sed case ICmpInst::ICMP_SGE: Out << "SGE"; break; 891193323Sed case ICmpInst::ICMP_UGE: Out << "UGE"; break; 892193323Sed default: error("Invalid ICmp Predicate"); 893193323Sed } 894193323Sed break; 895193323Sed case Instruction::FCmp: 896193323Sed Out << "getFCmp(FCmpInst::FCMP_"; 897193323Sed switch (CE->getPredicate()) { 898193323Sed case FCmpInst::FCMP_FALSE: Out << "FALSE"; break; 899193323Sed case FCmpInst::FCMP_ORD: Out << "ORD"; break; 900193323Sed case FCmpInst::FCMP_UNO: Out << "UNO"; break; 901193323Sed case FCmpInst::FCMP_OEQ: Out << "OEQ"; break; 902193323Sed case FCmpInst::FCMP_UEQ: Out << "UEQ"; break; 903193323Sed case FCmpInst::FCMP_ONE: Out << "ONE"; break; 904193323Sed case FCmpInst::FCMP_UNE: Out << "UNE"; break; 905193323Sed case FCmpInst::FCMP_OLT: Out << "OLT"; break; 906193323Sed case FCmpInst::FCMP_ULT: Out << "ULT"; break; 907193323Sed case FCmpInst::FCMP_OGT: Out << "OGT"; break; 908193323Sed case FCmpInst::FCMP_UGT: Out << "UGT"; break; 909193323Sed case FCmpInst::FCMP_OLE: Out << "OLE"; break; 910193323Sed case FCmpInst::FCMP_ULE: Out << "ULE"; break; 911193323Sed case FCmpInst::FCMP_OGE: Out << "OGE"; break; 912193323Sed case FCmpInst::FCMP_UGE: Out << "UGE"; break; 913193323Sed case FCmpInst::FCMP_TRUE: Out << "TRUE"; break; 914193323Sed default: error("Invalid FCmp Predicate"); 915193323Sed } 916193323Sed break; 917193323Sed case Instruction::Shl: Out << "getShl("; break; 918193323Sed case Instruction::LShr: Out << "getLShr("; break; 919193323Sed case Instruction::AShr: Out << "getAShr("; break; 920193323Sed case Instruction::Select: Out << "getSelect("; break; 921193323Sed case Instruction::ExtractElement: Out << "getExtractElement("; break; 922193323Sed case Instruction::InsertElement: Out << "getInsertElement("; break; 923193323Sed case Instruction::ShuffleVector: Out << "getShuffleVector("; break; 924193323Sed default: 925193323Sed error("Invalid constant expression"); 926193323Sed break; 927193323Sed } 928193323Sed Out << getCppName(CE->getOperand(0)); 929193323Sed for (unsigned i = 1; i < CE->getNumOperands(); ++i) 930193323Sed Out << ", " << getCppName(CE->getOperand(i)); 931193323Sed Out << ");"; 932193323Sed } 933193323Sed } else { 934193323Sed error("Bad Constant"); 935193323Sed Out << "Constant* " << constName << " = 0; "; 936193323Sed } 937193323Sed nl(Out); 938193323Sed } 939193323Sed 940193323Sed void CppWriter::printConstants(const Module* M) { 941193323Sed // Traverse all the global variables looking for constant initializers 942193323Sed for (Module::const_global_iterator I = TheModule->global_begin(), 943193323Sed E = TheModule->global_end(); I != E; ++I) 944193323Sed if (I->hasInitializer()) 945193323Sed printConstant(I->getInitializer()); 946193323Sed 947193323Sed // Traverse the LLVM functions looking for constants 948193323Sed for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end(); 949193323Sed FI != FE; ++FI) { 950193323Sed // Add all of the basic blocks and instructions 951193323Sed for (Function::const_iterator BB = FI->begin(), 952193323Sed E = FI->end(); BB != E; ++BB) { 953193323Sed for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 954193323Sed ++I) { 955193323Sed for (unsigned i = 0; i < I->getNumOperands(); ++i) { 956193323Sed if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) { 957193323Sed printConstant(C); 958193323Sed } 959193323Sed } 960193323Sed } 961193323Sed } 962193323Sed } 963193323Sed } 964193323Sed 965193323Sed void CppWriter::printVariableUses(const GlobalVariable *GV) { 966193323Sed nl(Out) << "// Type Definitions"; 967193323Sed nl(Out); 968193323Sed printType(GV->getType()); 969193323Sed if (GV->hasInitializer()) { 970193323Sed Constant* Init = GV->getInitializer(); 971193323Sed printType(Init->getType()); 972193323Sed if (Function* F = dyn_cast<Function>(Init)) { 973193323Sed nl(Out)<< "/ Function Declarations"; nl(Out); 974193323Sed printFunctionHead(F); 975193323Sed } else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) { 976193323Sed nl(Out) << "// Global Variable Declarations"; nl(Out); 977193323Sed printVariableHead(gv); 978193323Sed } else { 979193323Sed nl(Out) << "// Constant Definitions"; nl(Out); 980193323Sed printConstant(gv); 981193323Sed } 982193323Sed if (GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) { 983193323Sed nl(Out) << "// Global Variable Definitions"; nl(Out); 984193323Sed printVariableBody(gv); 985193323Sed } 986193323Sed } 987193323Sed } 988193323Sed 989193323Sed void CppWriter::printVariableHead(const GlobalVariable *GV) { 990193323Sed nl(Out) << "GlobalVariable* " << getCppName(GV); 991193323Sed if (is_inline) { 992193323Sed Out << " = mod->getGlobalVariable("; 993193323Sed printEscapedString(GV->getName()); 994193323Sed Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)"; 995193323Sed nl(Out) << "if (!" << getCppName(GV) << ") {"; 996193323Sed in(); nl(Out) << getCppName(GV); 997193323Sed } 998193323Sed Out << " = new GlobalVariable("; 999193323Sed nl(Out) << "/*Type=*/"; 1000193323Sed printCppName(GV->getType()->getElementType()); 1001193323Sed Out << ","; 1002193323Sed nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false"); 1003193323Sed Out << ","; 1004193323Sed nl(Out) << "/*Linkage=*/"; 1005193323Sed printLinkageType(GV->getLinkage()); 1006193323Sed Out << ","; 1007193323Sed nl(Out) << "/*Initializer=*/0, "; 1008193323Sed if (GV->hasInitializer()) { 1009193323Sed Out << "// has initializer, specified below"; 1010193323Sed } 1011193323Sed nl(Out) << "/*Name=*/\""; 1012193323Sed printEscapedString(GV->getName()); 1013193323Sed Out << "\","; 1014193323Sed nl(Out) << "mod);"; 1015193323Sed nl(Out); 1016193323Sed 1017193323Sed if (GV->hasSection()) { 1018193323Sed printCppName(GV); 1019193323Sed Out << "->setSection(\""; 1020193323Sed printEscapedString(GV->getSection()); 1021193323Sed Out << "\");"; 1022193323Sed nl(Out); 1023193323Sed } 1024193323Sed if (GV->getAlignment()) { 1025193323Sed printCppName(GV); 1026193323Sed Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");"; 1027193323Sed nl(Out); 1028193323Sed } 1029193323Sed if (GV->getVisibility() != GlobalValue::DefaultVisibility) { 1030193323Sed printCppName(GV); 1031193323Sed Out << "->setVisibility("; 1032193323Sed printVisibilityType(GV->getVisibility()); 1033193323Sed Out << ");"; 1034193323Sed nl(Out); 1035193323Sed } 1036193323Sed if (is_inline) { 1037193323Sed out(); Out << "}"; nl(Out); 1038193323Sed } 1039193323Sed } 1040193323Sed 1041193323Sed void CppWriter::printVariableBody(const GlobalVariable *GV) { 1042193323Sed if (GV->hasInitializer()) { 1043193323Sed printCppName(GV); 1044193323Sed Out << "->setInitializer("; 1045193323Sed Out << getCppName(GV->getInitializer()) << ");"; 1046193323Sed nl(Out); 1047193323Sed } 1048193323Sed } 1049193323Sed 1050193323Sed std::string CppWriter::getOpName(Value* V) { 1051193323Sed if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end()) 1052193323Sed return getCppName(V); 1053193323Sed 1054193323Sed // See if its alread in the map of forward references, if so just return the 1055193323Sed // name we already set up for it 1056193323Sed ForwardRefMap::const_iterator I = ForwardRefs.find(V); 1057193323Sed if (I != ForwardRefs.end()) 1058193323Sed return I->second; 1059193323Sed 1060193323Sed // This is a new forward reference. Generate a unique name for it 1061193323Sed std::string result(std::string("fwdref_") + utostr(uniqueNum++)); 1062193323Sed 1063193323Sed // Yes, this is a hack. An Argument is the smallest instantiable value that 1064193323Sed // we can make as a placeholder for the real value. We'll replace these 1065193323Sed // Argument instances later. 1066193323Sed Out << "Argument* " << result << " = new Argument(" 1067193323Sed << getCppName(V->getType()) << ");"; 1068193323Sed nl(Out); 1069193323Sed ForwardRefs[V] = result; 1070193323Sed return result; 1071193323Sed } 1072193323Sed 1073193323Sed // printInstruction - This member is called for each Instruction in a function. 1074193323Sed void CppWriter::printInstruction(const Instruction *I, 1075193323Sed const std::string& bbname) { 1076193323Sed std::string iName(getCppName(I)); 1077193323Sed 1078193323Sed // Before we emit this instruction, we need to take care of generating any 1079193323Sed // forward references. So, we get the names of all the operands in advance 1080193323Sed std::string* opNames = new std::string[I->getNumOperands()]; 1081193323Sed for (unsigned i = 0; i < I->getNumOperands(); i++) { 1082193323Sed opNames[i] = getOpName(I->getOperand(i)); 1083193323Sed } 1084193323Sed 1085193323Sed switch (I->getOpcode()) { 1086193323Sed default: 1087193323Sed error("Invalid instruction"); 1088193323Sed break; 1089193323Sed 1090193323Sed case Instruction::Ret: { 1091193323Sed const ReturnInst* ret = cast<ReturnInst>(I); 1092193323Sed Out << "ReturnInst::Create(" 1093193323Sed << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");"; 1094193323Sed break; 1095193323Sed } 1096193323Sed case Instruction::Br: { 1097193323Sed const BranchInst* br = cast<BranchInst>(I); 1098193323Sed Out << "BranchInst::Create(" ; 1099193323Sed if (br->getNumOperands() == 3 ) { 1100193323Sed Out << opNames[2] << ", " 1101193323Sed << opNames[1] << ", " 1102193323Sed << opNames[0] << ", "; 1103193323Sed 1104193323Sed } else if (br->getNumOperands() == 1) { 1105193323Sed Out << opNames[0] << ", "; 1106193323Sed } else { 1107193323Sed error("Branch with 2 operands?"); 1108193323Sed } 1109193323Sed Out << bbname << ");"; 1110193323Sed break; 1111193323Sed } 1112193323Sed case Instruction::Switch: { 1113193323Sed const SwitchInst* sw = cast<SwitchInst>(I); 1114193323Sed Out << "SwitchInst* " << iName << " = SwitchInst::Create(" 1115193323Sed << opNames[0] << ", " 1116193323Sed << opNames[1] << ", " 1117193323Sed << sw->getNumCases() << ", " << bbname << ");"; 1118193323Sed nl(Out); 1119193323Sed for (unsigned i = 2; i < sw->getNumOperands(); i += 2 ) { 1120193323Sed Out << iName << "->addCase(" 1121193323Sed << opNames[i] << ", " 1122193323Sed << opNames[i+1] << ");"; 1123193323Sed nl(Out); 1124193323Sed } 1125193323Sed break; 1126193323Sed } 1127193323Sed case Instruction::Invoke: { 1128193323Sed const InvokeInst* inv = cast<InvokeInst>(I); 1129193323Sed Out << "std::vector<Value*> " << iName << "_params;"; 1130193323Sed nl(Out); 1131193323Sed for (unsigned i = 3; i < inv->getNumOperands(); ++i) { 1132193323Sed Out << iName << "_params.push_back(" 1133193323Sed << opNames[i] << ");"; 1134193323Sed nl(Out); 1135193323Sed } 1136193323Sed Out << "InvokeInst *" << iName << " = InvokeInst::Create(" 1137193323Sed << opNames[0] << ", " 1138193323Sed << opNames[1] << ", " 1139193323Sed << opNames[2] << ", " 1140193323Sed << iName << "_params.begin(), " << iName << "_params.end(), \""; 1141193323Sed printEscapedString(inv->getName()); 1142193323Sed Out << "\", " << bbname << ");"; 1143193323Sed nl(Out) << iName << "->setCallingConv("; 1144193323Sed printCallingConv(inv->getCallingConv()); 1145193323Sed Out << ");"; 1146193323Sed printAttributes(inv->getAttributes(), iName); 1147193323Sed Out << iName << "->setAttributes(" << iName << "_PAL);"; 1148193323Sed nl(Out); 1149193323Sed break; 1150193323Sed } 1151193323Sed case Instruction::Unwind: { 1152193323Sed Out << "new UnwindInst(" 1153193323Sed << bbname << ");"; 1154193323Sed break; 1155193323Sed } 1156193323Sed case Instruction::Unreachable:{ 1157193323Sed Out << "new UnreachableInst(" 1158193323Sed << bbname << ");"; 1159193323Sed break; 1160193323Sed } 1161193323Sed case Instruction::Add: 1162193323Sed case Instruction::Sub: 1163193323Sed case Instruction::Mul: 1164193323Sed case Instruction::UDiv: 1165193323Sed case Instruction::SDiv: 1166193323Sed case Instruction::FDiv: 1167193323Sed case Instruction::URem: 1168193323Sed case Instruction::SRem: 1169193323Sed case Instruction::FRem: 1170193323Sed case Instruction::And: 1171193323Sed case Instruction::Or: 1172193323Sed case Instruction::Xor: 1173193323Sed case Instruction::Shl: 1174193323Sed case Instruction::LShr: 1175193323Sed case Instruction::AShr:{ 1176193323Sed Out << "BinaryOperator* " << iName << " = BinaryOperator::Create("; 1177193323Sed switch (I->getOpcode()) { 1178193323Sed case Instruction::Add: Out << "Instruction::Add"; break; 1179193323Sed case Instruction::Sub: Out << "Instruction::Sub"; break; 1180193323Sed case Instruction::Mul: Out << "Instruction::Mul"; break; 1181193323Sed case Instruction::UDiv:Out << "Instruction::UDiv"; break; 1182193323Sed case Instruction::SDiv:Out << "Instruction::SDiv"; break; 1183193323Sed case Instruction::FDiv:Out << "Instruction::FDiv"; break; 1184193323Sed case Instruction::URem:Out << "Instruction::URem"; break; 1185193323Sed case Instruction::SRem:Out << "Instruction::SRem"; break; 1186193323Sed case Instruction::FRem:Out << "Instruction::FRem"; break; 1187193323Sed case Instruction::And: Out << "Instruction::And"; break; 1188193323Sed case Instruction::Or: Out << "Instruction::Or"; break; 1189193323Sed case Instruction::Xor: Out << "Instruction::Xor"; break; 1190193323Sed case Instruction::Shl: Out << "Instruction::Shl"; break; 1191193323Sed case Instruction::LShr:Out << "Instruction::LShr"; break; 1192193323Sed case Instruction::AShr:Out << "Instruction::AShr"; break; 1193193323Sed default: Out << "Instruction::BadOpCode"; break; 1194193323Sed } 1195193323Sed Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 1196193323Sed printEscapedString(I->getName()); 1197193323Sed Out << "\", " << bbname << ");"; 1198193323Sed break; 1199193323Sed } 1200193323Sed case Instruction::FCmp: { 1201193323Sed Out << "FCmpInst* " << iName << " = new FCmpInst("; 1202193323Sed switch (cast<FCmpInst>(I)->getPredicate()) { 1203193323Sed case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break; 1204193323Sed case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break; 1205193323Sed case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break; 1206193323Sed case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break; 1207193323Sed case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break; 1208193323Sed case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break; 1209193323Sed case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break; 1210193323Sed case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break; 1211193323Sed case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break; 1212193323Sed case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break; 1213193323Sed case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break; 1214193323Sed case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break; 1215193323Sed case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break; 1216193323Sed case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break; 1217193323Sed case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break; 1218193323Sed case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break; 1219193323Sed default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break; 1220193323Sed } 1221193323Sed Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 1222193323Sed printEscapedString(I->getName()); 1223193323Sed Out << "\", " << bbname << ");"; 1224193323Sed break; 1225193323Sed } 1226193323Sed case Instruction::ICmp: { 1227193323Sed Out << "ICmpInst* " << iName << " = new ICmpInst("; 1228193323Sed switch (cast<ICmpInst>(I)->getPredicate()) { 1229193323Sed case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break; 1230193323Sed case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break; 1231193323Sed case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break; 1232193323Sed case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break; 1233193323Sed case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break; 1234193323Sed case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break; 1235193323Sed case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break; 1236193323Sed case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break; 1237193323Sed case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break; 1238193323Sed case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break; 1239193323Sed default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break; 1240193323Sed } 1241193323Sed Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 1242193323Sed printEscapedString(I->getName()); 1243193323Sed Out << "\", " << bbname << ");"; 1244193323Sed break; 1245193323Sed } 1246193323Sed case Instruction::Malloc: { 1247193323Sed const MallocInst* mallocI = cast<MallocInst>(I); 1248193323Sed Out << "MallocInst* " << iName << " = new MallocInst(" 1249193323Sed << getCppName(mallocI->getAllocatedType()) << ", "; 1250193323Sed if (mallocI->isArrayAllocation()) 1251193323Sed Out << opNames[0] << ", " ; 1252193323Sed Out << "\""; 1253193323Sed printEscapedString(mallocI->getName()); 1254193323Sed Out << "\", " << bbname << ");"; 1255193323Sed if (mallocI->getAlignment()) 1256193323Sed nl(Out) << iName << "->setAlignment(" 1257193323Sed << mallocI->getAlignment() << ");"; 1258193323Sed break; 1259193323Sed } 1260193323Sed case Instruction::Free: { 1261193323Sed Out << "FreeInst* " << iName << " = new FreeInst(" 1262193323Sed << getCppName(I->getOperand(0)) << ", " << bbname << ");"; 1263193323Sed break; 1264193323Sed } 1265193323Sed case Instruction::Alloca: { 1266193323Sed const AllocaInst* allocaI = cast<AllocaInst>(I); 1267193323Sed Out << "AllocaInst* " << iName << " = new AllocaInst(" 1268193323Sed << getCppName(allocaI->getAllocatedType()) << ", "; 1269193323Sed if (allocaI->isArrayAllocation()) 1270193323Sed Out << opNames[0] << ", "; 1271193323Sed Out << "\""; 1272193323Sed printEscapedString(allocaI->getName()); 1273193323Sed Out << "\", " << bbname << ");"; 1274193323Sed if (allocaI->getAlignment()) 1275193323Sed nl(Out) << iName << "->setAlignment(" 1276193323Sed << allocaI->getAlignment() << ");"; 1277193323Sed break; 1278193323Sed } 1279193323Sed case Instruction::Load:{ 1280193323Sed const LoadInst* load = cast<LoadInst>(I); 1281193323Sed Out << "LoadInst* " << iName << " = new LoadInst(" 1282193323Sed << opNames[0] << ", \""; 1283193323Sed printEscapedString(load->getName()); 1284193323Sed Out << "\", " << (load->isVolatile() ? "true" : "false" ) 1285193323Sed << ", " << bbname << ");"; 1286193323Sed break; 1287193323Sed } 1288193323Sed case Instruction::Store: { 1289193323Sed const StoreInst* store = cast<StoreInst>(I); 1290193323Sed Out << " new StoreInst(" 1291193323Sed << opNames[0] << ", " 1292193323Sed << opNames[1] << ", " 1293193323Sed << (store->isVolatile() ? "true" : "false") 1294193323Sed << ", " << bbname << ");"; 1295193323Sed break; 1296193323Sed } 1297193323Sed case Instruction::GetElementPtr: { 1298193323Sed const GetElementPtrInst* gep = cast<GetElementPtrInst>(I); 1299193323Sed if (gep->getNumOperands() <= 2) { 1300193323Sed Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create(" 1301193323Sed << opNames[0]; 1302193323Sed if (gep->getNumOperands() == 2) 1303193323Sed Out << ", " << opNames[1]; 1304193323Sed } else { 1305193323Sed Out << "std::vector<Value*> " << iName << "_indices;"; 1306193323Sed nl(Out); 1307193323Sed for (unsigned i = 1; i < gep->getNumOperands(); ++i ) { 1308193323Sed Out << iName << "_indices.push_back(" 1309193323Sed << opNames[i] << ");"; 1310193323Sed nl(Out); 1311193323Sed } 1312193323Sed Out << "Instruction* " << iName << " = GetElementPtrInst::Create(" 1313193323Sed << opNames[0] << ", " << iName << "_indices.begin(), " 1314193323Sed << iName << "_indices.end()"; 1315193323Sed } 1316193323Sed Out << ", \""; 1317193323Sed printEscapedString(gep->getName()); 1318193323Sed Out << "\", " << bbname << ");"; 1319193323Sed break; 1320193323Sed } 1321193323Sed case Instruction::PHI: { 1322193323Sed const PHINode* phi = cast<PHINode>(I); 1323193323Sed 1324193323Sed Out << "PHINode* " << iName << " = PHINode::Create(" 1325193323Sed << getCppName(phi->getType()) << ", \""; 1326193323Sed printEscapedString(phi->getName()); 1327193323Sed Out << "\", " << bbname << ");"; 1328193323Sed nl(Out) << iName << "->reserveOperandSpace(" 1329193323Sed << phi->getNumIncomingValues() 1330193323Sed << ");"; 1331193323Sed nl(Out); 1332193323Sed for (unsigned i = 0; i < phi->getNumOperands(); i+=2) { 1333193323Sed Out << iName << "->addIncoming(" 1334193323Sed << opNames[i] << ", " << opNames[i+1] << ");"; 1335193323Sed nl(Out); 1336193323Sed } 1337193323Sed break; 1338193323Sed } 1339193323Sed case Instruction::Trunc: 1340193323Sed case Instruction::ZExt: 1341193323Sed case Instruction::SExt: 1342193323Sed case Instruction::FPTrunc: 1343193323Sed case Instruction::FPExt: 1344193323Sed case Instruction::FPToUI: 1345193323Sed case Instruction::FPToSI: 1346193323Sed case Instruction::UIToFP: 1347193323Sed case Instruction::SIToFP: 1348193323Sed case Instruction::PtrToInt: 1349193323Sed case Instruction::IntToPtr: 1350193323Sed case Instruction::BitCast: { 1351193323Sed const CastInst* cst = cast<CastInst>(I); 1352193323Sed Out << "CastInst* " << iName << " = new "; 1353193323Sed switch (I->getOpcode()) { 1354193323Sed case Instruction::Trunc: Out << "TruncInst"; break; 1355193323Sed case Instruction::ZExt: Out << "ZExtInst"; break; 1356193323Sed case Instruction::SExt: Out << "SExtInst"; break; 1357193323Sed case Instruction::FPTrunc: Out << "FPTruncInst"; break; 1358193323Sed case Instruction::FPExt: Out << "FPExtInst"; break; 1359193323Sed case Instruction::FPToUI: Out << "FPToUIInst"; break; 1360193323Sed case Instruction::FPToSI: Out << "FPToSIInst"; break; 1361193323Sed case Instruction::UIToFP: Out << "UIToFPInst"; break; 1362193323Sed case Instruction::SIToFP: Out << "SIToFPInst"; break; 1363193323Sed case Instruction::PtrToInt: Out << "PtrToIntInst"; break; 1364193323Sed case Instruction::IntToPtr: Out << "IntToPtrInst"; break; 1365193323Sed case Instruction::BitCast: Out << "BitCastInst"; break; 1366193323Sed default: assert(!"Unreachable"); break; 1367193323Sed } 1368193323Sed Out << "(" << opNames[0] << ", " 1369193323Sed << getCppName(cst->getType()) << ", \""; 1370193323Sed printEscapedString(cst->getName()); 1371193323Sed Out << "\", " << bbname << ");"; 1372193323Sed break; 1373193323Sed } 1374193323Sed case Instruction::Call:{ 1375193323Sed const CallInst* call = cast<CallInst>(I); 1376193323Sed if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) { 1377193323Sed Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get(" 1378193323Sed << getCppName(ila->getFunctionType()) << ", \"" 1379193323Sed << ila->getAsmString() << "\", \"" 1380193323Sed << ila->getConstraintString() << "\"," 1381193323Sed << (ila->hasSideEffects() ? "true" : "false") << ");"; 1382193323Sed nl(Out); 1383193323Sed } 1384193323Sed if (call->getNumOperands() > 2) { 1385193323Sed Out << "std::vector<Value*> " << iName << "_params;"; 1386193323Sed nl(Out); 1387193323Sed for (unsigned i = 1; i < call->getNumOperands(); ++i) { 1388193323Sed Out << iName << "_params.push_back(" << opNames[i] << ");"; 1389193323Sed nl(Out); 1390193323Sed } 1391193323Sed Out << "CallInst* " << iName << " = CallInst::Create(" 1392193323Sed << opNames[0] << ", " << iName << "_params.begin(), " 1393193323Sed << iName << "_params.end(), \""; 1394193323Sed } else if (call->getNumOperands() == 2) { 1395193323Sed Out << "CallInst* " << iName << " = CallInst::Create(" 1396193323Sed << opNames[0] << ", " << opNames[1] << ", \""; 1397193323Sed } else { 1398193323Sed Out << "CallInst* " << iName << " = CallInst::Create(" << opNames[0] 1399193323Sed << ", \""; 1400193323Sed } 1401193323Sed printEscapedString(call->getName()); 1402193323Sed Out << "\", " << bbname << ");"; 1403193323Sed nl(Out) << iName << "->setCallingConv("; 1404193323Sed printCallingConv(call->getCallingConv()); 1405193323Sed Out << ");"; 1406193323Sed nl(Out) << iName << "->setTailCall(" 1407193323Sed << (call->isTailCall() ? "true":"false"); 1408193323Sed Out << ");"; 1409193323Sed printAttributes(call->getAttributes(), iName); 1410193323Sed Out << iName << "->setAttributes(" << iName << "_PAL);"; 1411193323Sed nl(Out); 1412193323Sed break; 1413193323Sed } 1414193323Sed case Instruction::Select: { 1415193323Sed const SelectInst* sel = cast<SelectInst>(I); 1416193323Sed Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create("; 1417193323Sed Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \""; 1418193323Sed printEscapedString(sel->getName()); 1419193323Sed Out << "\", " << bbname << ");"; 1420193323Sed break; 1421193323Sed } 1422193323Sed case Instruction::UserOp1: 1423193323Sed /// FALL THROUGH 1424193323Sed case Instruction::UserOp2: { 1425193323Sed /// FIXME: What should be done here? 1426193323Sed break; 1427193323Sed } 1428193323Sed case Instruction::VAArg: { 1429193323Sed const VAArgInst* va = cast<VAArgInst>(I); 1430193323Sed Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst(" 1431193323Sed << opNames[0] << ", " << getCppName(va->getType()) << ", \""; 1432193323Sed printEscapedString(va->getName()); 1433193323Sed Out << "\", " << bbname << ");"; 1434193323Sed break; 1435193323Sed } 1436193323Sed case Instruction::ExtractElement: { 1437193323Sed const ExtractElementInst* eei = cast<ExtractElementInst>(I); 1438193323Sed Out << "ExtractElementInst* " << getCppName(eei) 1439193323Sed << " = new ExtractElementInst(" << opNames[0] 1440193323Sed << ", " << opNames[1] << ", \""; 1441193323Sed printEscapedString(eei->getName()); 1442193323Sed Out << "\", " << bbname << ");"; 1443193323Sed break; 1444193323Sed } 1445193323Sed case Instruction::InsertElement: { 1446193323Sed const InsertElementInst* iei = cast<InsertElementInst>(I); 1447193323Sed Out << "InsertElementInst* " << getCppName(iei) 1448193323Sed << " = InsertElementInst::Create(" << opNames[0] 1449193323Sed << ", " << opNames[1] << ", " << opNames[2] << ", \""; 1450193323Sed printEscapedString(iei->getName()); 1451193323Sed Out << "\", " << bbname << ");"; 1452193323Sed break; 1453193323Sed } 1454193323Sed case Instruction::ShuffleVector: { 1455193323Sed const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I); 1456193323Sed Out << "ShuffleVectorInst* " << getCppName(svi) 1457193323Sed << " = new ShuffleVectorInst(" << opNames[0] 1458193323Sed << ", " << opNames[1] << ", " << opNames[2] << ", \""; 1459193323Sed printEscapedString(svi->getName()); 1460193323Sed Out << "\", " << bbname << ");"; 1461193323Sed break; 1462193323Sed } 1463193323Sed case Instruction::ExtractValue: { 1464193323Sed const ExtractValueInst *evi = cast<ExtractValueInst>(I); 1465193323Sed Out << "std::vector<unsigned> " << iName << "_indices;"; 1466193323Sed nl(Out); 1467193323Sed for (unsigned i = 0; i < evi->getNumIndices(); ++i) { 1468193323Sed Out << iName << "_indices.push_back(" 1469193323Sed << evi->idx_begin()[i] << ");"; 1470193323Sed nl(Out); 1471193323Sed } 1472193323Sed Out << "ExtractValueInst* " << getCppName(evi) 1473193323Sed << " = ExtractValueInst::Create(" << opNames[0] 1474193323Sed << ", " 1475193323Sed << iName << "_indices.begin(), " << iName << "_indices.end(), \""; 1476193323Sed printEscapedString(evi->getName()); 1477193323Sed Out << "\", " << bbname << ");"; 1478193323Sed break; 1479193323Sed } 1480193323Sed case Instruction::InsertValue: { 1481193323Sed const InsertValueInst *ivi = cast<InsertValueInst>(I); 1482193323Sed Out << "std::vector<unsigned> " << iName << "_indices;"; 1483193323Sed nl(Out); 1484193323Sed for (unsigned i = 0; i < ivi->getNumIndices(); ++i) { 1485193323Sed Out << iName << "_indices.push_back(" 1486193323Sed << ivi->idx_begin()[i] << ");"; 1487193323Sed nl(Out); 1488193323Sed } 1489193323Sed Out << "InsertValueInst* " << getCppName(ivi) 1490193323Sed << " = InsertValueInst::Create(" << opNames[0] 1491193323Sed << ", " << opNames[1] << ", " 1492193323Sed << iName << "_indices.begin(), " << iName << "_indices.end(), \""; 1493193323Sed printEscapedString(ivi->getName()); 1494193323Sed Out << "\", " << bbname << ");"; 1495193323Sed break; 1496193323Sed } 1497193323Sed } 1498193323Sed DefinedValues.insert(I); 1499193323Sed nl(Out); 1500193323Sed delete [] opNames; 1501193323Sed} 1502193323Sed 1503193323Sed // Print out the types, constants and declarations needed by one function 1504193323Sed void CppWriter::printFunctionUses(const Function* F) { 1505193323Sed nl(Out) << "// Type Definitions"; nl(Out); 1506193323Sed if (!is_inline) { 1507193323Sed // Print the function's return type 1508193323Sed printType(F->getReturnType()); 1509193323Sed 1510193323Sed // Print the function's function type 1511193323Sed printType(F->getFunctionType()); 1512193323Sed 1513193323Sed // Print the types of each of the function's arguments 1514193323Sed for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1515193323Sed AI != AE; ++AI) { 1516193323Sed printType(AI->getType()); 1517193323Sed } 1518193323Sed } 1519193323Sed 1520193323Sed // Print type definitions for every type referenced by an instruction and 1521193323Sed // make a note of any global values or constants that are referenced 1522193323Sed SmallPtrSet<GlobalValue*,64> gvs; 1523193323Sed SmallPtrSet<Constant*,64> consts; 1524193323Sed for (Function::const_iterator BB = F->begin(), BE = F->end(); 1525193323Sed BB != BE; ++BB){ 1526193323Sed for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 1527193323Sed I != E; ++I) { 1528193323Sed // Print the type of the instruction itself 1529193323Sed printType(I->getType()); 1530193323Sed 1531193323Sed // Print the type of each of the instruction's operands 1532193323Sed for (unsigned i = 0; i < I->getNumOperands(); ++i) { 1533193323Sed Value* operand = I->getOperand(i); 1534193323Sed printType(operand->getType()); 1535193323Sed 1536193323Sed // If the operand references a GVal or Constant, make a note of it 1537193323Sed if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) { 1538193323Sed gvs.insert(GV); 1539193323Sed if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 1540193323Sed if (GVar->hasInitializer()) 1541193323Sed consts.insert(GVar->getInitializer()); 1542193323Sed } else if (Constant* C = dyn_cast<Constant>(operand)) 1543193323Sed consts.insert(C); 1544193323Sed } 1545193323Sed } 1546193323Sed } 1547193323Sed 1548193323Sed // Print the function declarations for any functions encountered 1549193323Sed nl(Out) << "// Function Declarations"; nl(Out); 1550193323Sed for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 1551193323Sed I != E; ++I) { 1552193323Sed if (Function* Fun = dyn_cast<Function>(*I)) { 1553193323Sed if (!is_inline || Fun != F) 1554193323Sed printFunctionHead(Fun); 1555193323Sed } 1556193323Sed } 1557193323Sed 1558193323Sed // Print the global variable declarations for any variables encountered 1559193323Sed nl(Out) << "// Global Variable Declarations"; nl(Out); 1560193323Sed for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 1561193323Sed I != E; ++I) { 1562193323Sed if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I)) 1563193323Sed printVariableHead(F); 1564193323Sed } 1565193323Sed 1566193323Sed // Print the constants found 1567193323Sed nl(Out) << "// Constant Definitions"; nl(Out); 1568193323Sed for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), 1569193323Sed E = consts.end(); I != E; ++I) { 1570193323Sed printConstant(*I); 1571193323Sed } 1572193323Sed 1573193323Sed // Process the global variables definitions now that all the constants have 1574193323Sed // been emitted. These definitions just couple the gvars with their constant 1575193323Sed // initializers. 1576193323Sed nl(Out) << "// Global Variable Definitions"; nl(Out); 1577193323Sed for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 1578193323Sed I != E; ++I) { 1579193323Sed if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I)) 1580193323Sed printVariableBody(GV); 1581193323Sed } 1582193323Sed } 1583193323Sed 1584193323Sed void CppWriter::printFunctionHead(const Function* F) { 1585193323Sed nl(Out) << "Function* " << getCppName(F); 1586193323Sed if (is_inline) { 1587193323Sed Out << " = mod->getFunction(\""; 1588193323Sed printEscapedString(F->getName()); 1589193323Sed Out << "\", " << getCppName(F->getFunctionType()) << ");"; 1590193323Sed nl(Out) << "if (!" << getCppName(F) << ") {"; 1591193323Sed nl(Out) << getCppName(F); 1592193323Sed } 1593193323Sed Out<< " = Function::Create("; 1594193323Sed nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ","; 1595193323Sed nl(Out) << "/*Linkage=*/"; 1596193323Sed printLinkageType(F->getLinkage()); 1597193323Sed Out << ","; 1598193323Sed nl(Out) << "/*Name=*/\""; 1599193323Sed printEscapedString(F->getName()); 1600193323Sed Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : ""); 1601193323Sed nl(Out,-1); 1602193323Sed printCppName(F); 1603193323Sed Out << "->setCallingConv("; 1604193323Sed printCallingConv(F->getCallingConv()); 1605193323Sed Out << ");"; 1606193323Sed nl(Out); 1607193323Sed if (F->hasSection()) { 1608193323Sed printCppName(F); 1609193323Sed Out << "->setSection(\"" << F->getSection() << "\");"; 1610193323Sed nl(Out); 1611193323Sed } 1612193323Sed if (F->getAlignment()) { 1613193323Sed printCppName(F); 1614193323Sed Out << "->setAlignment(" << F->getAlignment() << ");"; 1615193323Sed nl(Out); 1616193323Sed } 1617193323Sed if (F->getVisibility() != GlobalValue::DefaultVisibility) { 1618193323Sed printCppName(F); 1619193323Sed Out << "->setVisibility("; 1620193323Sed printVisibilityType(F->getVisibility()); 1621193323Sed Out << ");"; 1622193323Sed nl(Out); 1623193323Sed } 1624193323Sed if (F->hasGC()) { 1625193323Sed printCppName(F); 1626193323Sed Out << "->setGC(\"" << F->getGC() << "\");"; 1627193323Sed nl(Out); 1628193323Sed } 1629193323Sed if (is_inline) { 1630193323Sed Out << "}"; 1631193323Sed nl(Out); 1632193323Sed } 1633193323Sed printAttributes(F->getAttributes(), getCppName(F)); 1634193323Sed printCppName(F); 1635193323Sed Out << "->setAttributes(" << getCppName(F) << "_PAL);"; 1636193323Sed nl(Out); 1637193323Sed } 1638193323Sed 1639193323Sed void CppWriter::printFunctionBody(const Function *F) { 1640193323Sed if (F->isDeclaration()) 1641193323Sed return; // external functions have no bodies. 1642193323Sed 1643193323Sed // Clear the DefinedValues and ForwardRefs maps because we can't have 1644193323Sed // cross-function forward refs 1645193323Sed ForwardRefs.clear(); 1646193323Sed DefinedValues.clear(); 1647193323Sed 1648193323Sed // Create all the argument values 1649193323Sed if (!is_inline) { 1650193323Sed if (!F->arg_empty()) { 1651193323Sed Out << "Function::arg_iterator args = " << getCppName(F) 1652193323Sed << "->arg_begin();"; 1653193323Sed nl(Out); 1654193323Sed } 1655193323Sed for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1656193323Sed AI != AE; ++AI) { 1657193323Sed Out << "Value* " << getCppName(AI) << " = args++;"; 1658193323Sed nl(Out); 1659193323Sed if (AI->hasName()) { 1660193323Sed Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");"; 1661193323Sed nl(Out); 1662193323Sed } 1663193323Sed } 1664193323Sed } 1665193323Sed 1666193323Sed // Create all the basic blocks 1667193323Sed nl(Out); 1668193323Sed for (Function::const_iterator BI = F->begin(), BE = F->end(); 1669193323Sed BI != BE; ++BI) { 1670193323Sed std::string bbname(getCppName(BI)); 1671193323Sed Out << "BasicBlock* " << bbname << " = BasicBlock::Create(\""; 1672193323Sed if (BI->hasName()) 1673193323Sed printEscapedString(BI->getName()); 1674193323Sed Out << "\"," << getCppName(BI->getParent()) << ",0);"; 1675193323Sed nl(Out); 1676193323Sed } 1677193323Sed 1678193323Sed // Output all of its basic blocks... for the function 1679193323Sed for (Function::const_iterator BI = F->begin(), BE = F->end(); 1680193323Sed BI != BE; ++BI) { 1681193323Sed std::string bbname(getCppName(BI)); 1682193323Sed nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")"; 1683193323Sed nl(Out); 1684193323Sed 1685193323Sed // Output all of the instructions in the basic block... 1686193323Sed for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); 1687193323Sed I != E; ++I) { 1688193323Sed printInstruction(I,bbname); 1689193323Sed } 1690193323Sed } 1691193323Sed 1692193323Sed // Loop over the ForwardRefs and resolve them now that all instructions 1693193323Sed // are generated. 1694193323Sed if (!ForwardRefs.empty()) { 1695193323Sed nl(Out) << "// Resolve Forward References"; 1696193323Sed nl(Out); 1697193323Sed } 1698193323Sed 1699193323Sed while (!ForwardRefs.empty()) { 1700193323Sed ForwardRefMap::iterator I = ForwardRefs.begin(); 1701193323Sed Out << I->second << "->replaceAllUsesWith(" 1702193323Sed << getCppName(I->first) << "); delete " << I->second << ";"; 1703193323Sed nl(Out); 1704193323Sed ForwardRefs.erase(I); 1705193323Sed } 1706193323Sed } 1707193323Sed 1708193323Sed void CppWriter::printInline(const std::string& fname, 1709193323Sed const std::string& func) { 1710193323Sed const Function* F = TheModule->getFunction(func); 1711193323Sed if (!F) { 1712193323Sed error(std::string("Function '") + func + "' not found in input module"); 1713193323Sed return; 1714193323Sed } 1715193323Sed if (F->isDeclaration()) { 1716193323Sed error(std::string("Function '") + func + "' is external!"); 1717193323Sed return; 1718193323Sed } 1719193323Sed nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *" 1720193323Sed << getCppName(F); 1721193323Sed unsigned arg_count = 1; 1722193323Sed for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1723193323Sed AI != AE; ++AI) { 1724193323Sed Out << ", Value* arg_" << arg_count; 1725193323Sed } 1726193323Sed Out << ") {"; 1727193323Sed nl(Out); 1728193323Sed is_inline = true; 1729193323Sed printFunctionUses(F); 1730193323Sed printFunctionBody(F); 1731193323Sed is_inline = false; 1732193323Sed Out << "return " << getCppName(F->begin()) << ";"; 1733193323Sed nl(Out) << "}"; 1734193323Sed nl(Out); 1735193323Sed } 1736193323Sed 1737193323Sed void CppWriter::printModuleBody() { 1738193323Sed // Print out all the type definitions 1739193323Sed nl(Out) << "// Type Definitions"; nl(Out); 1740193323Sed printTypes(TheModule); 1741193323Sed 1742193323Sed // Functions can call each other and global variables can reference them so 1743193323Sed // define all the functions first before emitting their function bodies. 1744193323Sed nl(Out) << "// Function Declarations"; nl(Out); 1745193323Sed for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 1746193323Sed I != E; ++I) 1747193323Sed printFunctionHead(I); 1748193323Sed 1749193323Sed // Process the global variables declarations. We can't initialze them until 1750193323Sed // after the constants are printed so just print a header for each global 1751193323Sed nl(Out) << "// Global Variable Declarations\n"; nl(Out); 1752193323Sed for (Module::const_global_iterator I = TheModule->global_begin(), 1753193323Sed E = TheModule->global_end(); I != E; ++I) { 1754193323Sed printVariableHead(I); 1755193323Sed } 1756193323Sed 1757193323Sed // Print out all the constants definitions. Constants don't recurse except 1758193323Sed // through GlobalValues. All GlobalValues have been declared at this point 1759193323Sed // so we can proceed to generate the constants. 1760193323Sed nl(Out) << "// Constant Definitions"; nl(Out); 1761193323Sed printConstants(TheModule); 1762193323Sed 1763193323Sed // Process the global variables definitions now that all the constants have 1764193323Sed // been emitted. These definitions just couple the gvars with their constant 1765193323Sed // initializers. 1766193323Sed nl(Out) << "// Global Variable Definitions"; nl(Out); 1767193323Sed for (Module::const_global_iterator I = TheModule->global_begin(), 1768193323Sed E = TheModule->global_end(); I != E; ++I) { 1769193323Sed printVariableBody(I); 1770193323Sed } 1771193323Sed 1772193323Sed // Finally, we can safely put out all of the function bodies. 1773193323Sed nl(Out) << "// Function Definitions"; nl(Out); 1774193323Sed for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 1775193323Sed I != E; ++I) { 1776193323Sed if (!I->isDeclaration()) { 1777193323Sed nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I) 1778193323Sed << ")"; 1779193323Sed nl(Out) << "{"; 1780193323Sed nl(Out,1); 1781193323Sed printFunctionBody(I); 1782193323Sed nl(Out,-1) << "}"; 1783193323Sed nl(Out); 1784193323Sed } 1785193323Sed } 1786193323Sed } 1787193323Sed 1788193323Sed void CppWriter::printProgram(const std::string& fname, 1789193323Sed const std::string& mName) { 1790193323Sed Out << "#include <llvm/Module.h>\n"; 1791193323Sed Out << "#include <llvm/DerivedTypes.h>\n"; 1792193323Sed Out << "#include <llvm/Constants.h>\n"; 1793193323Sed Out << "#include <llvm/GlobalVariable.h>\n"; 1794193323Sed Out << "#include <llvm/Function.h>\n"; 1795193323Sed Out << "#include <llvm/CallingConv.h>\n"; 1796193323Sed Out << "#include <llvm/BasicBlock.h>\n"; 1797193323Sed Out << "#include <llvm/Instructions.h>\n"; 1798193323Sed Out << "#include <llvm/InlineAsm.h>\n"; 1799193323Sed Out << "#include <llvm/Support/MathExtras.h>\n"; 1800193323Sed Out << "#include <llvm/Support/raw_ostream.h>\n"; 1801193323Sed Out << "#include <llvm/Pass.h>\n"; 1802193323Sed Out << "#include <llvm/PassManager.h>\n"; 1803193323Sed Out << "#include <llvm/ADT/SmallVector.h>\n"; 1804193323Sed Out << "#include <llvm/Analysis/Verifier.h>\n"; 1805193323Sed Out << "#include <llvm/Assembly/PrintModulePass.h>\n"; 1806193323Sed Out << "#include <algorithm>\n"; 1807193323Sed Out << "using namespace llvm;\n\n"; 1808193323Sed Out << "Module* " << fname << "();\n\n"; 1809193323Sed Out << "int main(int argc, char**argv) {\n"; 1810193323Sed Out << " Module* Mod = " << fname << "();\n"; 1811193323Sed Out << " verifyModule(*Mod, PrintMessageAction);\n"; 1812193323Sed Out << " outs().flush();\n"; 1813193323Sed Out << " PassManager PM;\n"; 1814193323Sed Out << " PM.add(createPrintModulePass(&outs()));\n"; 1815193323Sed Out << " PM.run(*Mod);\n"; 1816193323Sed Out << " return 0;\n"; 1817193323Sed Out << "}\n\n"; 1818193323Sed printModule(fname,mName); 1819193323Sed } 1820193323Sed 1821193323Sed void CppWriter::printModule(const std::string& fname, 1822193323Sed const std::string& mName) { 1823193323Sed nl(Out) << "Module* " << fname << "() {"; 1824193323Sed nl(Out,1) << "// Module Construction"; 1825193323Sed nl(Out) << "Module* mod = new Module(\"" << mName << "\");"; 1826193323Sed if (!TheModule->getTargetTriple().empty()) { 1827193323Sed nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");"; 1828193323Sed } 1829193323Sed if (!TheModule->getTargetTriple().empty()) { 1830193323Sed nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple() 1831193323Sed << "\");"; 1832193323Sed } 1833193323Sed 1834193323Sed if (!TheModule->getModuleInlineAsm().empty()) { 1835193323Sed nl(Out) << "mod->setModuleInlineAsm(\""; 1836193323Sed printEscapedString(TheModule->getModuleInlineAsm()); 1837193323Sed Out << "\");"; 1838193323Sed } 1839193323Sed nl(Out); 1840193323Sed 1841193323Sed // Loop over the dependent libraries and emit them. 1842193323Sed Module::lib_iterator LI = TheModule->lib_begin(); 1843193323Sed Module::lib_iterator LE = TheModule->lib_end(); 1844193323Sed while (LI != LE) { 1845193323Sed Out << "mod->addLibrary(\"" << *LI << "\");"; 1846193323Sed nl(Out); 1847193323Sed ++LI; 1848193323Sed } 1849193323Sed printModuleBody(); 1850193323Sed nl(Out) << "return mod;"; 1851193323Sed nl(Out,-1) << "}"; 1852193323Sed nl(Out); 1853193323Sed } 1854193323Sed 1855193323Sed void CppWriter::printContents(const std::string& fname, 1856193323Sed const std::string& mName) { 1857193323Sed Out << "\nModule* " << fname << "(Module *mod) {\n"; 1858193323Sed Out << "\nmod->setModuleIdentifier(\"" << mName << "\");\n"; 1859193323Sed printModuleBody(); 1860193323Sed Out << "\nreturn mod;\n"; 1861193323Sed Out << "\n}\n"; 1862193323Sed } 1863193323Sed 1864193323Sed void CppWriter::printFunction(const std::string& fname, 1865193323Sed const std::string& funcName) { 1866193323Sed const Function* F = TheModule->getFunction(funcName); 1867193323Sed if (!F) { 1868193323Sed error(std::string("Function '") + funcName + "' not found in input module"); 1869193323Sed return; 1870193323Sed } 1871193323Sed Out << "\nFunction* " << fname << "(Module *mod) {\n"; 1872193323Sed printFunctionUses(F); 1873193323Sed printFunctionHead(F); 1874193323Sed printFunctionBody(F); 1875193323Sed Out << "return " << getCppName(F) << ";\n"; 1876193323Sed Out << "}\n"; 1877193323Sed } 1878193323Sed 1879193323Sed void CppWriter::printFunctions() { 1880193323Sed const Module::FunctionListType &funcs = TheModule->getFunctionList(); 1881193323Sed Module::const_iterator I = funcs.begin(); 1882193323Sed Module::const_iterator IE = funcs.end(); 1883193323Sed 1884193323Sed for (; I != IE; ++I) { 1885193323Sed const Function &func = *I; 1886193323Sed if (!func.isDeclaration()) { 1887193323Sed std::string name("define_"); 1888193323Sed name += func.getName(); 1889193323Sed printFunction(name, func.getName()); 1890193323Sed } 1891193323Sed } 1892193323Sed } 1893193323Sed 1894193323Sed void CppWriter::printVariable(const std::string& fname, 1895193323Sed const std::string& varName) { 1896193323Sed const GlobalVariable* GV = TheModule->getNamedGlobal(varName); 1897193323Sed 1898193323Sed if (!GV) { 1899193323Sed error(std::string("Variable '") + varName + "' not found in input module"); 1900193323Sed return; 1901193323Sed } 1902193323Sed Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n"; 1903193323Sed printVariableUses(GV); 1904193323Sed printVariableHead(GV); 1905193323Sed printVariableBody(GV); 1906193323Sed Out << "return " << getCppName(GV) << ";\n"; 1907193323Sed Out << "}\n"; 1908193323Sed } 1909193323Sed 1910193323Sed void CppWriter::printType(const std::string& fname, 1911193323Sed const std::string& typeName) { 1912193323Sed const Type* Ty = TheModule->getTypeByName(typeName); 1913193323Sed if (!Ty) { 1914193323Sed error(std::string("Type '") + typeName + "' not found in input module"); 1915193323Sed return; 1916193323Sed } 1917193323Sed Out << "\nType* " << fname << "(Module *mod) {\n"; 1918193323Sed printType(Ty); 1919193323Sed Out << "return " << getCppName(Ty) << ";\n"; 1920193323Sed Out << "}\n"; 1921193323Sed } 1922193323Sed 1923193323Sed bool CppWriter::runOnModule(Module &M) { 1924193323Sed TheModule = &M; 1925193323Sed 1926193323Sed // Emit a header 1927193323Sed Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n"; 1928193323Sed 1929193323Sed // Get the name of the function we're supposed to generate 1930193323Sed std::string fname = FuncName.getValue(); 1931193323Sed 1932193323Sed // Get the name of the thing we are to generate 1933193323Sed std::string tgtname = NameToGenerate.getValue(); 1934193323Sed if (GenerationType == GenModule || 1935193323Sed GenerationType == GenContents || 1936193323Sed GenerationType == GenProgram || 1937193323Sed GenerationType == GenFunctions) { 1938193323Sed if (tgtname == "!bad!") { 1939193323Sed if (M.getModuleIdentifier() == "-") 1940193323Sed tgtname = "<stdin>"; 1941193323Sed else 1942193323Sed tgtname = M.getModuleIdentifier(); 1943193323Sed } 1944193323Sed } else if (tgtname == "!bad!") 1945193323Sed error("You must use the -for option with -gen-{function,variable,type}"); 1946193323Sed 1947193323Sed switch (WhatToGenerate(GenerationType)) { 1948193323Sed case GenProgram: 1949193323Sed if (fname.empty()) 1950193323Sed fname = "makeLLVMModule"; 1951193323Sed printProgram(fname,tgtname); 1952193323Sed break; 1953193323Sed case GenModule: 1954193323Sed if (fname.empty()) 1955193323Sed fname = "makeLLVMModule"; 1956193323Sed printModule(fname,tgtname); 1957193323Sed break; 1958193323Sed case GenContents: 1959193323Sed if (fname.empty()) 1960193323Sed fname = "makeLLVMModuleContents"; 1961193323Sed printContents(fname,tgtname); 1962193323Sed break; 1963193323Sed case GenFunction: 1964193323Sed if (fname.empty()) 1965193323Sed fname = "makeLLVMFunction"; 1966193323Sed printFunction(fname,tgtname); 1967193323Sed break; 1968193323Sed case GenFunctions: 1969193323Sed printFunctions(); 1970193323Sed break; 1971193323Sed case GenInline: 1972193323Sed if (fname.empty()) 1973193323Sed fname = "makeLLVMInline"; 1974193323Sed printInline(fname,tgtname); 1975193323Sed break; 1976193323Sed case GenVariable: 1977193323Sed if (fname.empty()) 1978193323Sed fname = "makeLLVMVariable"; 1979193323Sed printVariable(fname,tgtname); 1980193323Sed break; 1981193323Sed case GenType: 1982193323Sed if (fname.empty()) 1983193323Sed fname = "makeLLVMType"; 1984193323Sed printType(fname,tgtname); 1985193323Sed break; 1986193323Sed default: 1987193323Sed error("Invalid generation option"); 1988193323Sed } 1989193323Sed 1990193323Sed return false; 1991193323Sed } 1992193323Sed} 1993193323Sed 1994193323Sedchar CppWriter::ID = 0; 1995193323Sed 1996193323Sed//===----------------------------------------------------------------------===// 1997193323Sed// External Interface declaration 1998193323Sed//===----------------------------------------------------------------------===// 1999193323Sed 2000193323Sedbool CPPTargetMachine::addPassesToEmitWholeFile(PassManager &PM, 2001193323Sed raw_ostream &o, 2002193323Sed CodeGenFileType FileType, 2003193323Sed CodeGenOpt::Level OptLevel) { 2004193323Sed if (FileType != TargetMachine::AssemblyFile) return true; 2005193323Sed PM.add(new CppWriter(o)); 2006193323Sed return false; 2007193323Sed} 2008