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