1 //===-- CPPBackend.cpp - Library for converting LLVM code to C++ code -----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the writing of the LLVM IR as a set of C++ calls to the 11 // LLVM IR interface. The input module is assumed to be verified. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CPPTargetMachine.h" 16 #include "llvm/CallingConv.h" 17 #include "llvm/Constants.h" 18 #include "llvm/DerivedTypes.h" 19 #include "llvm/InlineAsm.h" 20 #include "llvm/Instruction.h" 21 #include "llvm/Instructions.h" 22 #include "llvm/Module.h" 23 #include "llvm/Pass.h" 24 #include "llvm/PassManager.h" 25 #include "llvm/MC/MCAsmInfo.h" 26 #include "llvm/MC/MCInstrInfo.h" 27 #include "llvm/MC/MCSubtargetInfo.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/FormattedStream.h" 32 #include "llvm/Target/TargetRegistry.h" 33 #include "llvm/ADT/StringExtras.h" 34 #include "llvm/Config/config.h" 35 #include <algorithm> 36 #include <set> 37 #include <map> 38 using namespace llvm; 39 40 static cl::opt<std::string> 41 FuncName("cppfname", cl::desc("Specify the name of the generated function"), 42 cl::value_desc("function name")); 43 44 enum WhatToGenerate { 45 GenProgram, 46 GenModule, 47 GenContents, 48 GenFunction, 49 GenFunctions, 50 GenInline, 51 GenVariable, 52 GenType 53 }; 54 55 static cl::opt<WhatToGenerate> GenerationType("cppgen", cl::Optional, 56 cl::desc("Choose what kind of output to generate"), 57 cl::init(GenProgram), 58 cl::values( 59 clEnumValN(GenProgram, "program", "Generate a complete program"), 60 clEnumValN(GenModule, "module", "Generate a module definition"), 61 clEnumValN(GenContents, "contents", "Generate contents of a module"), 62 clEnumValN(GenFunction, "function", "Generate a function definition"), 63 clEnumValN(GenFunctions,"functions", "Generate all function definitions"), 64 clEnumValN(GenInline, "inline", "Generate an inline function"), 65 clEnumValN(GenVariable, "variable", "Generate a variable definition"), 66 clEnumValN(GenType, "type", "Generate a type definition"), 67 clEnumValEnd 68 ) 69 ); 70 71 static cl::opt<std::string> NameToGenerate("cppfor", cl::Optional, 72 cl::desc("Specify the name of the thing to generate"), 73 cl::init("!bad!")); 74 75 extern "C" void LLVMInitializeCppBackendTarget() { 76 // Register the target. 77 RegisterTargetMachine<CPPTargetMachine> X(TheCppBackendTarget); 78 } 79 80 extern "C" void LLVMInitializeCppBackendMCAsmInfo() {} 81 82 extern "C" void LLVMInitializeCppBackendMCRegisterInfo() {} 83 84 extern "C" void LLVMInitializeCppBackendMCInstrInfo() {} 85 86 extern "C" void LLVMInitializeCppBackendMCSubtargetInfo() {} 87 88 extern "C" void LLVMInitializeCppBackendMCCodeGenInfo() {} 89 90 namespace { 91 typedef std::vector<Type*> TypeList; 92 typedef std::map<Type*,std::string> TypeMap; 93 typedef std::map<const Value*,std::string> ValueMap; 94 typedef std::set<std::string> NameSet; 95 typedef std::set<Type*> TypeSet; 96 typedef std::set<const Value*> ValueSet; 97 typedef std::map<const Value*,std::string> ForwardRefMap; 98 99 /// CppWriter - This class is the main chunk of code that converts an LLVM 100 /// module to a C++ translation unit. 101 class CppWriter : public ModulePass { 102 formatted_raw_ostream &Out; 103 const Module *TheModule; 104 uint64_t uniqueNum; 105 TypeMap TypeNames; 106 ValueMap ValueNames; 107 NameSet UsedNames; 108 TypeSet DefinedTypes; 109 ValueSet DefinedValues; 110 ForwardRefMap ForwardRefs; 111 bool is_inline; 112 unsigned indent_level; 113 114 public: 115 static char ID; 116 explicit CppWriter(formatted_raw_ostream &o) : 117 ModulePass(ID), Out(o), uniqueNum(0), is_inline(false), indent_level(0){} 118 119 virtual const char *getPassName() const { return "C++ backend"; } 120 121 bool runOnModule(Module &M); 122 123 void printProgram(const std::string& fname, const std::string& modName ); 124 void printModule(const std::string& fname, const std::string& modName ); 125 void printContents(const std::string& fname, const std::string& modName ); 126 void printFunction(const std::string& fname, const std::string& funcName ); 127 void printFunctions(); 128 void printInline(const std::string& fname, const std::string& funcName ); 129 void printVariable(const std::string& fname, const std::string& varName ); 130 void printType(const std::string& fname, const std::string& typeName ); 131 132 void error(const std::string& msg); 133 134 135 formatted_raw_ostream& nl(formatted_raw_ostream &Out, int delta = 0); 136 inline void in() { indent_level++; } 137 inline void out() { if (indent_level >0) indent_level--; } 138 139 private: 140 void printLinkageType(GlobalValue::LinkageTypes LT); 141 void printVisibilityType(GlobalValue::VisibilityTypes VisTypes); 142 void printCallingConv(CallingConv::ID cc); 143 void printEscapedString(const std::string& str); 144 void printCFP(const ConstantFP* CFP); 145 146 std::string getCppName(Type* val); 147 inline void printCppName(Type* val); 148 149 std::string getCppName(const Value* val); 150 inline void printCppName(const Value* val); 151 152 void printAttributes(const AttrListPtr &PAL, const std::string &name); 153 void printType(Type* Ty); 154 void printTypes(const Module* M); 155 156 void printConstant(const Constant *CPV); 157 void printConstants(const Module* M); 158 159 void printVariableUses(const GlobalVariable *GV); 160 void printVariableHead(const GlobalVariable *GV); 161 void printVariableBody(const GlobalVariable *GV); 162 163 void printFunctionUses(const Function *F); 164 void printFunctionHead(const Function *F); 165 void printFunctionBody(const Function *F); 166 void printInstruction(const Instruction *I, const std::string& bbname); 167 std::string getOpName(Value*); 168 169 void printModuleBody(); 170 }; 171 } // end anonymous namespace. 172 173 formatted_raw_ostream &CppWriter::nl(formatted_raw_ostream &Out, int delta) { 174 Out << '\n'; 175 if (delta >= 0 || indent_level >= unsigned(-delta)) 176 indent_level += delta; 177 Out.indent(indent_level); 178 return Out; 179 } 180 181 static inline void sanitize(std::string &str) { 182 for (size_t i = 0; i < str.length(); ++i) 183 if (!isalnum(str[i]) && str[i] != '_') 184 str[i] = '_'; 185 } 186 187 static std::string getTypePrefix(Type *Ty) { 188 switch (Ty->getTypeID()) { 189 case Type::VoidTyID: return "void_"; 190 case Type::IntegerTyID: 191 return "int" + utostr(cast<IntegerType>(Ty)->getBitWidth()) + "_"; 192 case Type::FloatTyID: return "float_"; 193 case Type::DoubleTyID: return "double_"; 194 case Type::LabelTyID: return "label_"; 195 case Type::FunctionTyID: return "func_"; 196 case Type::StructTyID: return "struct_"; 197 case Type::ArrayTyID: return "array_"; 198 case Type::PointerTyID: return "ptr_"; 199 case Type::VectorTyID: return "packed_"; 200 default: return "other_"; 201 } 202 return "unknown_"; 203 } 204 205 void CppWriter::error(const std::string& msg) { 206 report_fatal_error(msg); 207 } 208 209 // printCFP - Print a floating point constant .. very carefully :) 210 // This makes sure that conversion to/from floating yields the same binary 211 // result so that we don't lose precision. 212 void CppWriter::printCFP(const ConstantFP *CFP) { 213 bool ignored; 214 APFloat APF = APFloat(CFP->getValueAPF()); // copy 215 if (CFP->getType() == Type::getFloatTy(CFP->getContext())) 216 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored); 217 Out << "ConstantFP::get(mod->getContext(), "; 218 Out << "APFloat("; 219 #if HAVE_PRINTF_A 220 char Buffer[100]; 221 sprintf(Buffer, "%A", APF.convertToDouble()); 222 if ((!strncmp(Buffer, "0x", 2) || 223 !strncmp(Buffer, "-0x", 3) || 224 !strncmp(Buffer, "+0x", 3)) && 225 APF.bitwiseIsEqual(APFloat(atof(Buffer)))) { 226 if (CFP->getType() == Type::getDoubleTy(CFP->getContext())) 227 Out << "BitsToDouble(" << Buffer << ")"; 228 else 229 Out << "BitsToFloat((float)" << Buffer << ")"; 230 Out << ")"; 231 } else { 232 #endif 233 std::string StrVal = ftostr(CFP->getValueAPF()); 234 235 while (StrVal[0] == ' ') 236 StrVal.erase(StrVal.begin()); 237 238 // Check to make sure that the stringized number is not some string like 239 // "Inf" or NaN. Check that the string matches the "[-+]?[0-9]" regex. 240 if (((StrVal[0] >= '0' && StrVal[0] <= '9') || 241 ((StrVal[0] == '-' || StrVal[0] == '+') && 242 (StrVal[1] >= '0' && StrVal[1] <= '9'))) && 243 (CFP->isExactlyValue(atof(StrVal.c_str())))) { 244 if (CFP->getType() == Type::getDoubleTy(CFP->getContext())) 245 Out << StrVal; 246 else 247 Out << StrVal << "f"; 248 } else if (CFP->getType() == Type::getDoubleTy(CFP->getContext())) 249 Out << "BitsToDouble(0x" 250 << utohexstr(CFP->getValueAPF().bitcastToAPInt().getZExtValue()) 251 << "ULL) /* " << StrVal << " */"; 252 else 253 Out << "BitsToFloat(0x" 254 << utohexstr((uint32_t)CFP->getValueAPF(). 255 bitcastToAPInt().getZExtValue()) 256 << "U) /* " << StrVal << " */"; 257 Out << ")"; 258 #if HAVE_PRINTF_A 259 } 260 #endif 261 Out << ")"; 262 } 263 264 void CppWriter::printCallingConv(CallingConv::ID cc){ 265 // Print the calling convention. 266 switch (cc) { 267 case CallingConv::C: Out << "CallingConv::C"; break; 268 case CallingConv::Fast: Out << "CallingConv::Fast"; break; 269 case CallingConv::Cold: Out << "CallingConv::Cold"; break; 270 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break; 271 default: Out << cc; break; 272 } 273 } 274 275 void CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) { 276 switch (LT) { 277 case GlobalValue::InternalLinkage: 278 Out << "GlobalValue::InternalLinkage"; break; 279 case GlobalValue::PrivateLinkage: 280 Out << "GlobalValue::PrivateLinkage"; break; 281 case GlobalValue::LinkerPrivateLinkage: 282 Out << "GlobalValue::LinkerPrivateLinkage"; break; 283 case GlobalValue::LinkerPrivateWeakLinkage: 284 Out << "GlobalValue::LinkerPrivateWeakLinkage"; break; 285 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: 286 Out << "GlobalValue::LinkerPrivateWeakDefAutoLinkage"; break; 287 case GlobalValue::AvailableExternallyLinkage: 288 Out << "GlobalValue::AvailableExternallyLinkage "; break; 289 case GlobalValue::LinkOnceAnyLinkage: 290 Out << "GlobalValue::LinkOnceAnyLinkage "; break; 291 case GlobalValue::LinkOnceODRLinkage: 292 Out << "GlobalValue::LinkOnceODRLinkage "; break; 293 case GlobalValue::WeakAnyLinkage: 294 Out << "GlobalValue::WeakAnyLinkage"; break; 295 case GlobalValue::WeakODRLinkage: 296 Out << "GlobalValue::WeakODRLinkage"; break; 297 case GlobalValue::AppendingLinkage: 298 Out << "GlobalValue::AppendingLinkage"; break; 299 case GlobalValue::ExternalLinkage: 300 Out << "GlobalValue::ExternalLinkage"; break; 301 case GlobalValue::DLLImportLinkage: 302 Out << "GlobalValue::DLLImportLinkage"; break; 303 case GlobalValue::DLLExportLinkage: 304 Out << "GlobalValue::DLLExportLinkage"; break; 305 case GlobalValue::ExternalWeakLinkage: 306 Out << "GlobalValue::ExternalWeakLinkage"; break; 307 case GlobalValue::CommonLinkage: 308 Out << "GlobalValue::CommonLinkage"; break; 309 } 310 } 311 312 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) { 313 switch (VisType) { 314 default: llvm_unreachable("Unknown GVar visibility"); 315 case GlobalValue::DefaultVisibility: 316 Out << "GlobalValue::DefaultVisibility"; 317 break; 318 case GlobalValue::HiddenVisibility: 319 Out << "GlobalValue::HiddenVisibility"; 320 break; 321 case GlobalValue::ProtectedVisibility: 322 Out << "GlobalValue::ProtectedVisibility"; 323 break; 324 } 325 } 326 327 // printEscapedString - Print each character of the specified string, escaping 328 // it if it is not printable or if it is an escape char. 329 void CppWriter::printEscapedString(const std::string &Str) { 330 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 331 unsigned char C = Str[i]; 332 if (isprint(C) && C != '"' && C != '\\') { 333 Out << C; 334 } else { 335 Out << "\\x" 336 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A')) 337 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A')); 338 } 339 } 340 } 341 342 std::string CppWriter::getCppName(Type* Ty) { 343 // First, handle the primitive types .. easy 344 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) { 345 switch (Ty->getTypeID()) { 346 case Type::VoidTyID: return "Type::getVoidTy(mod->getContext())"; 347 case Type::IntegerTyID: { 348 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth(); 349 return "IntegerType::get(mod->getContext(), " + utostr(BitWidth) + ")"; 350 } 351 case Type::X86_FP80TyID: return "Type::getX86_FP80Ty(mod->getContext())"; 352 case Type::FloatTyID: return "Type::getFloatTy(mod->getContext())"; 353 case Type::DoubleTyID: return "Type::getDoubleTy(mod->getContext())"; 354 case Type::LabelTyID: return "Type::getLabelTy(mod->getContext())"; 355 case Type::X86_MMXTyID: return "Type::getX86_MMXTy(mod->getContext())"; 356 default: 357 error("Invalid primitive type"); 358 break; 359 } 360 // shouldn't be returned, but make it sensible 361 return "Type::getVoidTy(mod->getContext())"; 362 } 363 364 // Now, see if we've seen the type before and return that 365 TypeMap::iterator I = TypeNames.find(Ty); 366 if (I != TypeNames.end()) 367 return I->second; 368 369 // Okay, let's build a new name for this type. Start with a prefix 370 const char* prefix = 0; 371 switch (Ty->getTypeID()) { 372 case Type::FunctionTyID: prefix = "FuncTy_"; break; 373 case Type::StructTyID: prefix = "StructTy_"; break; 374 case Type::ArrayTyID: prefix = "ArrayTy_"; break; 375 case Type::PointerTyID: prefix = "PointerTy_"; break; 376 case Type::VectorTyID: prefix = "VectorTy_"; break; 377 default: prefix = "OtherTy_"; break; // prevent breakage 378 } 379 380 // See if the type has a name in the symboltable and build accordingly 381 std::string name; 382 if (StructType *STy = dyn_cast<StructType>(Ty)) 383 if (STy->hasName()) 384 name = STy->getName(); 385 386 if (name.empty()) 387 name = utostr(uniqueNum++); 388 389 name = std::string(prefix) + name; 390 sanitize(name); 391 392 // Save the name 393 return TypeNames[Ty] = name; 394 } 395 396 void CppWriter::printCppName(Type* Ty) { 397 printEscapedString(getCppName(Ty)); 398 } 399 400 std::string CppWriter::getCppName(const Value* val) { 401 std::string name; 402 ValueMap::iterator I = ValueNames.find(val); 403 if (I != ValueNames.end() && I->first == val) 404 return I->second; 405 406 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(val)) { 407 name = std::string("gvar_") + 408 getTypePrefix(GV->getType()->getElementType()); 409 } else if (isa<Function>(val)) { 410 name = std::string("func_"); 411 } else if (const Constant* C = dyn_cast<Constant>(val)) { 412 name = std::string("const_") + getTypePrefix(C->getType()); 413 } else if (const Argument* Arg = dyn_cast<Argument>(val)) { 414 if (is_inline) { 415 unsigned argNum = std::distance(Arg->getParent()->arg_begin(), 416 Function::const_arg_iterator(Arg)) + 1; 417 name = std::string("arg_") + utostr(argNum); 418 NameSet::iterator NI = UsedNames.find(name); 419 if (NI != UsedNames.end()) 420 name += std::string("_") + utostr(uniqueNum++); 421 UsedNames.insert(name); 422 return ValueNames[val] = name; 423 } else { 424 name = getTypePrefix(val->getType()); 425 } 426 } else { 427 name = getTypePrefix(val->getType()); 428 } 429 if (val->hasName()) 430 name += val->getName(); 431 else 432 name += utostr(uniqueNum++); 433 sanitize(name); 434 NameSet::iterator NI = UsedNames.find(name); 435 if (NI != UsedNames.end()) 436 name += std::string("_") + utostr(uniqueNum++); 437 UsedNames.insert(name); 438 return ValueNames[val] = name; 439 } 440 441 void CppWriter::printCppName(const Value* val) { 442 printEscapedString(getCppName(val)); 443 } 444 445 void CppWriter::printAttributes(const AttrListPtr &PAL, 446 const std::string &name) { 447 Out << "AttrListPtr " << name << "_PAL;"; 448 nl(Out); 449 if (!PAL.isEmpty()) { 450 Out << '{'; in(); nl(Out); 451 Out << "SmallVector<AttributeWithIndex, 4> Attrs;"; nl(Out); 452 Out << "AttributeWithIndex PAWI;"; nl(Out); 453 for (unsigned i = 0; i < PAL.getNumSlots(); ++i) { 454 unsigned index = PAL.getSlot(i).Index; 455 Attributes attrs = PAL.getSlot(i).Attrs; 456 Out << "PAWI.Index = " << index << "U; PAWI.Attrs = 0 "; 457 #define HANDLE_ATTR(X) \ 458 if (attrs & Attribute::X) \ 459 Out << " | Attribute::" #X; \ 460 attrs &= ~Attribute::X; 461 462 HANDLE_ATTR(SExt); 463 HANDLE_ATTR(ZExt); 464 HANDLE_ATTR(NoReturn); 465 HANDLE_ATTR(InReg); 466 HANDLE_ATTR(StructRet); 467 HANDLE_ATTR(NoUnwind); 468 HANDLE_ATTR(NoAlias); 469 HANDLE_ATTR(ByVal); 470 HANDLE_ATTR(Nest); 471 HANDLE_ATTR(ReadNone); 472 HANDLE_ATTR(ReadOnly); 473 HANDLE_ATTR(NoInline); 474 HANDLE_ATTR(AlwaysInline); 475 HANDLE_ATTR(OptimizeForSize); 476 HANDLE_ATTR(StackProtect); 477 HANDLE_ATTR(StackProtectReq); 478 HANDLE_ATTR(NoCapture); 479 HANDLE_ATTR(NoRedZone); 480 HANDLE_ATTR(NoImplicitFloat); 481 HANDLE_ATTR(Naked); 482 HANDLE_ATTR(InlineHint); 483 #undef HANDLE_ATTR 484 if (attrs & Attribute::StackAlignment) 485 Out << " | Attribute::constructStackAlignmentFromInt(" 486 << Attribute::getStackAlignmentFromAttrs(attrs) 487 << ")"; 488 attrs &= ~Attribute::StackAlignment; 489 assert(attrs == 0 && "Unhandled attribute!"); 490 Out << ";"; 491 nl(Out); 492 Out << "Attrs.push_back(PAWI);"; 493 nl(Out); 494 } 495 Out << name << "_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());"; 496 nl(Out); 497 out(); nl(Out); 498 Out << '}'; nl(Out); 499 } 500 } 501 502 void CppWriter::printType(Type* Ty) { 503 // We don't print definitions for primitive types 504 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) 505 return; 506 507 // If we already defined this type, we don't need to define it again. 508 if (DefinedTypes.find(Ty) != DefinedTypes.end()) 509 return; 510 511 // Everything below needs the name for the type so get it now. 512 std::string typeName(getCppName(Ty)); 513 514 // Print the type definition 515 switch (Ty->getTypeID()) { 516 case Type::FunctionTyID: { 517 FunctionType* FT = cast<FunctionType>(Ty); 518 Out << "std::vector<Type*>" << typeName << "_args;"; 519 nl(Out); 520 FunctionType::param_iterator PI = FT->param_begin(); 521 FunctionType::param_iterator PE = FT->param_end(); 522 for (; PI != PE; ++PI) { 523 Type* argTy = static_cast<Type*>(*PI); 524 printType(argTy); 525 std::string argName(getCppName(argTy)); 526 Out << typeName << "_args.push_back(" << argName; 527 Out << ");"; 528 nl(Out); 529 } 530 printType(FT->getReturnType()); 531 std::string retTypeName(getCppName(FT->getReturnType())); 532 Out << "FunctionType* " << typeName << " = FunctionType::get("; 533 in(); nl(Out) << "/*Result=*/" << retTypeName; 534 Out << ","; 535 nl(Out) << "/*Params=*/" << typeName << "_args,"; 536 nl(Out) << "/*isVarArg=*/" << (FT->isVarArg() ? "true" : "false") << ");"; 537 out(); 538 nl(Out); 539 break; 540 } 541 case Type::StructTyID: { 542 StructType* ST = cast<StructType>(Ty); 543 if (!ST->isAnonymous()) { 544 Out << "StructType *" << typeName << " = "; 545 Out << "StructType::createNamed(mod->getContext(), \""; 546 printEscapedString(ST->getName()); 547 Out << "\");"; 548 nl(Out); 549 // Indicate that this type is now defined. 550 DefinedTypes.insert(Ty); 551 } 552 553 Out << "std::vector<Type*>" << typeName << "_fields;"; 554 nl(Out); 555 StructType::element_iterator EI = ST->element_begin(); 556 StructType::element_iterator EE = ST->element_end(); 557 for (; EI != EE; ++EI) { 558 Type* fieldTy = static_cast<Type*>(*EI); 559 printType(fieldTy); 560 std::string fieldName(getCppName(fieldTy)); 561 Out << typeName << "_fields.push_back(" << fieldName; 562 Out << ");"; 563 nl(Out); 564 } 565 566 if (ST->isAnonymous()) { 567 Out << "StructType *" << typeName << " = "; 568 Out << "StructType::get(" << "mod->getContext(), "; 569 } else { 570 Out << typeName << "->setBody("; 571 } 572 573 Out << typeName << "_fields, /*isPacked=*/" 574 << (ST->isPacked() ? "true" : "false") << ");"; 575 nl(Out); 576 break; 577 } 578 case Type::ArrayTyID: { 579 ArrayType* AT = cast<ArrayType>(Ty); 580 Type* ET = AT->getElementType(); 581 printType(ET); 582 if (DefinedTypes.find(Ty) == DefinedTypes.end()) { 583 std::string elemName(getCppName(ET)); 584 Out << "ArrayType* " << typeName << " = ArrayType::get(" 585 << elemName 586 << ", " << utostr(AT->getNumElements()) << ");"; 587 nl(Out); 588 } 589 break; 590 } 591 case Type::PointerTyID: { 592 PointerType* PT = cast<PointerType>(Ty); 593 Type* ET = PT->getElementType(); 594 printType(ET); 595 if (DefinedTypes.find(Ty) == DefinedTypes.end()) { 596 std::string elemName(getCppName(ET)); 597 Out << "PointerType* " << typeName << " = PointerType::get(" 598 << elemName 599 << ", " << utostr(PT->getAddressSpace()) << ");"; 600 nl(Out); 601 } 602 break; 603 } 604 case Type::VectorTyID: { 605 VectorType* PT = cast<VectorType>(Ty); 606 Type* ET = PT->getElementType(); 607 printType(ET); 608 if (DefinedTypes.find(Ty) == DefinedTypes.end()) { 609 std::string elemName(getCppName(ET)); 610 Out << "VectorType* " << typeName << " = VectorType::get(" 611 << elemName 612 << ", " << utostr(PT->getNumElements()) << ");"; 613 nl(Out); 614 } 615 break; 616 } 617 default: 618 error("Invalid TypeID"); 619 } 620 621 // Indicate that this type is now defined. 622 DefinedTypes.insert(Ty); 623 624 // Finally, separate the type definition from other with a newline. 625 nl(Out); 626 } 627 628 void CppWriter::printTypes(const Module* M) { 629 // Add all of the global variables to the value table. 630 for (Module::const_global_iterator I = TheModule->global_begin(), 631 E = TheModule->global_end(); I != E; ++I) { 632 if (I->hasInitializer()) 633 printType(I->getInitializer()->getType()); 634 printType(I->getType()); 635 } 636 637 // Add all the functions to the table 638 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end(); 639 FI != FE; ++FI) { 640 printType(FI->getReturnType()); 641 printType(FI->getFunctionType()); 642 // Add all the function arguments 643 for (Function::const_arg_iterator AI = FI->arg_begin(), 644 AE = FI->arg_end(); AI != AE; ++AI) { 645 printType(AI->getType()); 646 } 647 648 // Add all of the basic blocks and instructions 649 for (Function::const_iterator BB = FI->begin(), 650 E = FI->end(); BB != E; ++BB) { 651 printType(BB->getType()); 652 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 653 ++I) { 654 printType(I->getType()); 655 for (unsigned i = 0; i < I->getNumOperands(); ++i) 656 printType(I->getOperand(i)->getType()); 657 } 658 } 659 } 660 } 661 662 663 // printConstant - Print out a constant pool entry... 664 void CppWriter::printConstant(const Constant *CV) { 665 // First, if the constant is actually a GlobalValue (variable or function) 666 // or its already in the constant list then we've printed it already and we 667 // can just return. 668 if (isa<GlobalValue>(CV) || ValueNames.find(CV) != ValueNames.end()) 669 return; 670 671 std::string constName(getCppName(CV)); 672 std::string typeName(getCppName(CV->getType())); 673 674 if (isa<GlobalValue>(CV)) { 675 // Skip variables and functions, we emit them elsewhere 676 return; 677 } 678 679 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 680 std::string constValue = CI->getValue().toString(10, true); 681 Out << "ConstantInt* " << constName 682 << " = ConstantInt::get(mod->getContext(), APInt(" 683 << cast<IntegerType>(CI->getType())->getBitWidth() 684 << ", StringRef(\"" << constValue << "\"), 10));"; 685 } else if (isa<ConstantAggregateZero>(CV)) { 686 Out << "ConstantAggregateZero* " << constName 687 << " = ConstantAggregateZero::get(" << typeName << ");"; 688 } else if (isa<ConstantPointerNull>(CV)) { 689 Out << "ConstantPointerNull* " << constName 690 << " = ConstantPointerNull::get(" << typeName << ");"; 691 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 692 Out << "ConstantFP* " << constName << " = "; 693 printCFP(CFP); 694 Out << ";"; 695 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) { 696 if (CA->isString() && 697 CA->getType()->getElementType() == 698 Type::getInt8Ty(CA->getContext())) { 699 Out << "Constant* " << constName << 700 " = ConstantArray::get(mod->getContext(), \""; 701 std::string tmp = CA->getAsString(); 702 bool nullTerminate = false; 703 if (tmp[tmp.length()-1] == 0) { 704 tmp.erase(tmp.length()-1); 705 nullTerminate = true; 706 } 707 printEscapedString(tmp); 708 // Determine if we want null termination or not. 709 if (nullTerminate) 710 Out << "\", true"; // Indicate that the null terminator should be 711 // added. 712 else 713 Out << "\", false";// No null terminator 714 Out << ");"; 715 } else { 716 Out << "std::vector<Constant*> " << constName << "_elems;"; 717 nl(Out); 718 unsigned N = CA->getNumOperands(); 719 for (unsigned i = 0; i < N; ++i) { 720 printConstant(CA->getOperand(i)); // recurse to print operands 721 Out << constName << "_elems.push_back(" 722 << getCppName(CA->getOperand(i)) << ");"; 723 nl(Out); 724 } 725 Out << "Constant* " << constName << " = ConstantArray::get(" 726 << typeName << ", " << constName << "_elems);"; 727 } 728 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) { 729 Out << "std::vector<Constant*> " << constName << "_fields;"; 730 nl(Out); 731 unsigned N = CS->getNumOperands(); 732 for (unsigned i = 0; i < N; i++) { 733 printConstant(CS->getOperand(i)); 734 Out << constName << "_fields.push_back(" 735 << getCppName(CS->getOperand(i)) << ");"; 736 nl(Out); 737 } 738 Out << "Constant* " << constName << " = ConstantStruct::get(" 739 << typeName << ", " << constName << "_fields);"; 740 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 741 Out << "std::vector<Constant*> " << constName << "_elems;"; 742 nl(Out); 743 unsigned N = CP->getNumOperands(); 744 for (unsigned i = 0; i < N; ++i) { 745 printConstant(CP->getOperand(i)); 746 Out << constName << "_elems.push_back(" 747 << getCppName(CP->getOperand(i)) << ");"; 748 nl(Out); 749 } 750 Out << "Constant* " << constName << " = ConstantVector::get(" 751 << typeName << ", " << constName << "_elems);"; 752 } else if (isa<UndefValue>(CV)) { 753 Out << "UndefValue* " << constName << " = UndefValue::get(" 754 << typeName << ");"; 755 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 756 if (CE->getOpcode() == Instruction::GetElementPtr) { 757 Out << "std::vector<Constant*> " << constName << "_indices;"; 758 nl(Out); 759 printConstant(CE->getOperand(0)); 760 for (unsigned i = 1; i < CE->getNumOperands(); ++i ) { 761 printConstant(CE->getOperand(i)); 762 Out << constName << "_indices.push_back(" 763 << getCppName(CE->getOperand(i)) << ");"; 764 nl(Out); 765 } 766 Out << "Constant* " << constName 767 << " = ConstantExpr::getGetElementPtr(" 768 << getCppName(CE->getOperand(0)) << ", " 769 << "&" << constName << "_indices[0], " 770 << constName << "_indices.size()" 771 << ");"; 772 } else if (CE->isCast()) { 773 printConstant(CE->getOperand(0)); 774 Out << "Constant* " << constName << " = ConstantExpr::getCast("; 775 switch (CE->getOpcode()) { 776 default: llvm_unreachable("Invalid cast opcode"); 777 case Instruction::Trunc: Out << "Instruction::Trunc"; break; 778 case Instruction::ZExt: Out << "Instruction::ZExt"; break; 779 case Instruction::SExt: Out << "Instruction::SExt"; break; 780 case Instruction::FPTrunc: Out << "Instruction::FPTrunc"; break; 781 case Instruction::FPExt: Out << "Instruction::FPExt"; break; 782 case Instruction::FPToUI: Out << "Instruction::FPToUI"; break; 783 case Instruction::FPToSI: Out << "Instruction::FPToSI"; break; 784 case Instruction::UIToFP: Out << "Instruction::UIToFP"; break; 785 case Instruction::SIToFP: Out << "Instruction::SIToFP"; break; 786 case Instruction::PtrToInt: Out << "Instruction::PtrToInt"; break; 787 case Instruction::IntToPtr: Out << "Instruction::IntToPtr"; break; 788 case Instruction::BitCast: Out << "Instruction::BitCast"; break; 789 } 790 Out << ", " << getCppName(CE->getOperand(0)) << ", " 791 << getCppName(CE->getType()) << ");"; 792 } else { 793 unsigned N = CE->getNumOperands(); 794 for (unsigned i = 0; i < N; ++i ) { 795 printConstant(CE->getOperand(i)); 796 } 797 Out << "Constant* " << constName << " = ConstantExpr::"; 798 switch (CE->getOpcode()) { 799 case Instruction::Add: Out << "getAdd("; break; 800 case Instruction::FAdd: Out << "getFAdd("; break; 801 case Instruction::Sub: Out << "getSub("; break; 802 case Instruction::FSub: Out << "getFSub("; break; 803 case Instruction::Mul: Out << "getMul("; break; 804 case Instruction::FMul: Out << "getFMul("; break; 805 case Instruction::UDiv: Out << "getUDiv("; break; 806 case Instruction::SDiv: Out << "getSDiv("; break; 807 case Instruction::FDiv: Out << "getFDiv("; break; 808 case Instruction::URem: Out << "getURem("; break; 809 case Instruction::SRem: Out << "getSRem("; break; 810 case Instruction::FRem: Out << "getFRem("; break; 811 case Instruction::And: Out << "getAnd("; break; 812 case Instruction::Or: Out << "getOr("; break; 813 case Instruction::Xor: Out << "getXor("; break; 814 case Instruction::ICmp: 815 Out << "getICmp(ICmpInst::ICMP_"; 816 switch (CE->getPredicate()) { 817 case ICmpInst::ICMP_EQ: Out << "EQ"; break; 818 case ICmpInst::ICMP_NE: Out << "NE"; break; 819 case ICmpInst::ICMP_SLT: Out << "SLT"; break; 820 case ICmpInst::ICMP_ULT: Out << "ULT"; break; 821 case ICmpInst::ICMP_SGT: Out << "SGT"; break; 822 case ICmpInst::ICMP_UGT: Out << "UGT"; break; 823 case ICmpInst::ICMP_SLE: Out << "SLE"; break; 824 case ICmpInst::ICMP_ULE: Out << "ULE"; break; 825 case ICmpInst::ICMP_SGE: Out << "SGE"; break; 826 case ICmpInst::ICMP_UGE: Out << "UGE"; break; 827 default: error("Invalid ICmp Predicate"); 828 } 829 break; 830 case Instruction::FCmp: 831 Out << "getFCmp(FCmpInst::FCMP_"; 832 switch (CE->getPredicate()) { 833 case FCmpInst::FCMP_FALSE: Out << "FALSE"; break; 834 case FCmpInst::FCMP_ORD: Out << "ORD"; break; 835 case FCmpInst::FCMP_UNO: Out << "UNO"; break; 836 case FCmpInst::FCMP_OEQ: Out << "OEQ"; break; 837 case FCmpInst::FCMP_UEQ: Out << "UEQ"; break; 838 case FCmpInst::FCMP_ONE: Out << "ONE"; break; 839 case FCmpInst::FCMP_UNE: Out << "UNE"; break; 840 case FCmpInst::FCMP_OLT: Out << "OLT"; break; 841 case FCmpInst::FCMP_ULT: Out << "ULT"; break; 842 case FCmpInst::FCMP_OGT: Out << "OGT"; break; 843 case FCmpInst::FCMP_UGT: Out << "UGT"; break; 844 case FCmpInst::FCMP_OLE: Out << "OLE"; break; 845 case FCmpInst::FCMP_ULE: Out << "ULE"; break; 846 case FCmpInst::FCMP_OGE: Out << "OGE"; break; 847 case FCmpInst::FCMP_UGE: Out << "UGE"; break; 848 case FCmpInst::FCMP_TRUE: Out << "TRUE"; break; 849 default: error("Invalid FCmp Predicate"); 850 } 851 break; 852 case Instruction::Shl: Out << "getShl("; break; 853 case Instruction::LShr: Out << "getLShr("; break; 854 case Instruction::AShr: Out << "getAShr("; break; 855 case Instruction::Select: Out << "getSelect("; break; 856 case Instruction::ExtractElement: Out << "getExtractElement("; break; 857 case Instruction::InsertElement: Out << "getInsertElement("; break; 858 case Instruction::ShuffleVector: Out << "getShuffleVector("; break; 859 default: 860 error("Invalid constant expression"); 861 break; 862 } 863 Out << getCppName(CE->getOperand(0)); 864 for (unsigned i = 1; i < CE->getNumOperands(); ++i) 865 Out << ", " << getCppName(CE->getOperand(i)); 866 Out << ");"; 867 } 868 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 869 Out << "Constant* " << constName << " = "; 870 Out << "BlockAddress::get(" << getOpName(BA->getBasicBlock()) << ");"; 871 } else { 872 error("Bad Constant"); 873 Out << "Constant* " << constName << " = 0; "; 874 } 875 nl(Out); 876 } 877 878 void CppWriter::printConstants(const Module* M) { 879 // Traverse all the global variables looking for constant initializers 880 for (Module::const_global_iterator I = TheModule->global_begin(), 881 E = TheModule->global_end(); I != E; ++I) 882 if (I->hasInitializer()) 883 printConstant(I->getInitializer()); 884 885 // Traverse the LLVM functions looking for constants 886 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end(); 887 FI != FE; ++FI) { 888 // Add all of the basic blocks and instructions 889 for (Function::const_iterator BB = FI->begin(), 890 E = FI->end(); BB != E; ++BB) { 891 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; 892 ++I) { 893 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 894 if (Constant* C = dyn_cast<Constant>(I->getOperand(i))) { 895 printConstant(C); 896 } 897 } 898 } 899 } 900 } 901 } 902 903 void CppWriter::printVariableUses(const GlobalVariable *GV) { 904 nl(Out) << "// Type Definitions"; 905 nl(Out); 906 printType(GV->getType()); 907 if (GV->hasInitializer()) { 908 const Constant *Init = GV->getInitializer(); 909 printType(Init->getType()); 910 if (const Function *F = dyn_cast<Function>(Init)) { 911 nl(Out)<< "/ Function Declarations"; nl(Out); 912 printFunctionHead(F); 913 } else if (const GlobalVariable* gv = dyn_cast<GlobalVariable>(Init)) { 914 nl(Out) << "// Global Variable Declarations"; nl(Out); 915 printVariableHead(gv); 916 917 nl(Out) << "// Global Variable Definitions"; nl(Out); 918 printVariableBody(gv); 919 } else { 920 nl(Out) << "// Constant Definitions"; nl(Out); 921 printConstant(Init); 922 } 923 } 924 } 925 926 void CppWriter::printVariableHead(const GlobalVariable *GV) { 927 nl(Out) << "GlobalVariable* " << getCppName(GV); 928 if (is_inline) { 929 Out << " = mod->getGlobalVariable(mod->getContext(), "; 930 printEscapedString(GV->getName()); 931 Out << ", " << getCppName(GV->getType()->getElementType()) << ",true)"; 932 nl(Out) << "if (!" << getCppName(GV) << ") {"; 933 in(); nl(Out) << getCppName(GV); 934 } 935 Out << " = new GlobalVariable(/*Module=*/*mod, "; 936 nl(Out) << "/*Type=*/"; 937 printCppName(GV->getType()->getElementType()); 938 Out << ","; 939 nl(Out) << "/*isConstant=*/" << (GV->isConstant()?"true":"false"); 940 Out << ","; 941 nl(Out) << "/*Linkage=*/"; 942 printLinkageType(GV->getLinkage()); 943 Out << ","; 944 nl(Out) << "/*Initializer=*/0, "; 945 if (GV->hasInitializer()) { 946 Out << "// has initializer, specified below"; 947 } 948 nl(Out) << "/*Name=*/\""; 949 printEscapedString(GV->getName()); 950 Out << "\");"; 951 nl(Out); 952 953 if (GV->hasSection()) { 954 printCppName(GV); 955 Out << "->setSection(\""; 956 printEscapedString(GV->getSection()); 957 Out << "\");"; 958 nl(Out); 959 } 960 if (GV->getAlignment()) { 961 printCppName(GV); 962 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");"; 963 nl(Out); 964 } 965 if (GV->getVisibility() != GlobalValue::DefaultVisibility) { 966 printCppName(GV); 967 Out << "->setVisibility("; 968 printVisibilityType(GV->getVisibility()); 969 Out << ");"; 970 nl(Out); 971 } 972 if (GV->isThreadLocal()) { 973 printCppName(GV); 974 Out << "->setThreadLocal(true);"; 975 nl(Out); 976 } 977 if (is_inline) { 978 out(); Out << "}"; nl(Out); 979 } 980 } 981 982 void CppWriter::printVariableBody(const GlobalVariable *GV) { 983 if (GV->hasInitializer()) { 984 printCppName(GV); 985 Out << "->setInitializer("; 986 Out << getCppName(GV->getInitializer()) << ");"; 987 nl(Out); 988 } 989 } 990 991 std::string CppWriter::getOpName(Value* V) { 992 if (!isa<Instruction>(V) || DefinedValues.find(V) != DefinedValues.end()) 993 return getCppName(V); 994 995 // See if its alread in the map of forward references, if so just return the 996 // name we already set up for it 997 ForwardRefMap::const_iterator I = ForwardRefs.find(V); 998 if (I != ForwardRefs.end()) 999 return I->second; 1000 1001 // This is a new forward reference. Generate a unique name for it 1002 std::string result(std::string("fwdref_") + utostr(uniqueNum++)); 1003 1004 // Yes, this is a hack. An Argument is the smallest instantiable value that 1005 // we can make as a placeholder for the real value. We'll replace these 1006 // Argument instances later. 1007 Out << "Argument* " << result << " = new Argument(" 1008 << getCppName(V->getType()) << ");"; 1009 nl(Out); 1010 ForwardRefs[V] = result; 1011 return result; 1012 } 1013 1014 // printInstruction - This member is called for each Instruction in a function. 1015 void CppWriter::printInstruction(const Instruction *I, 1016 const std::string& bbname) { 1017 std::string iName(getCppName(I)); 1018 1019 // Before we emit this instruction, we need to take care of generating any 1020 // forward references. So, we get the names of all the operands in advance 1021 const unsigned Ops(I->getNumOperands()); 1022 std::string* opNames = new std::string[Ops]; 1023 for (unsigned i = 0; i < Ops; i++) 1024 opNames[i] = getOpName(I->getOperand(i)); 1025 1026 switch (I->getOpcode()) { 1027 default: 1028 error("Invalid instruction"); 1029 break; 1030 1031 case Instruction::Ret: { 1032 const ReturnInst* ret = cast<ReturnInst>(I); 1033 Out << "ReturnInst::Create(mod->getContext(), " 1034 << (ret->getReturnValue() ? opNames[0] + ", " : "") << bbname << ");"; 1035 break; 1036 } 1037 case Instruction::Br: { 1038 const BranchInst* br = cast<BranchInst>(I); 1039 Out << "BranchInst::Create(" ; 1040 if (br->getNumOperands() == 3) { 1041 Out << opNames[2] << ", " 1042 << opNames[1] << ", " 1043 << opNames[0] << ", "; 1044 1045 } else if (br->getNumOperands() == 1) { 1046 Out << opNames[0] << ", "; 1047 } else { 1048 error("Branch with 2 operands?"); 1049 } 1050 Out << bbname << ");"; 1051 break; 1052 } 1053 case Instruction::Switch: { 1054 const SwitchInst *SI = cast<SwitchInst>(I); 1055 Out << "SwitchInst* " << iName << " = SwitchInst::Create(" 1056 << opNames[0] << ", " 1057 << opNames[1] << ", " 1058 << SI->getNumCases() << ", " << bbname << ");"; 1059 nl(Out); 1060 for (unsigned i = 2; i != SI->getNumOperands(); i += 2) { 1061 Out << iName << "->addCase(" 1062 << opNames[i] << ", " 1063 << opNames[i+1] << ");"; 1064 nl(Out); 1065 } 1066 break; 1067 } 1068 case Instruction::IndirectBr: { 1069 const IndirectBrInst *IBI = cast<IndirectBrInst>(I); 1070 Out << "IndirectBrInst *" << iName << " = IndirectBrInst::Create(" 1071 << opNames[0] << ", " << IBI->getNumDestinations() << ");"; 1072 nl(Out); 1073 for (unsigned i = 1; i != IBI->getNumOperands(); ++i) { 1074 Out << iName << "->addDestination(" << opNames[i] << ");"; 1075 nl(Out); 1076 } 1077 break; 1078 } 1079 case Instruction::Invoke: { 1080 const InvokeInst* inv = cast<InvokeInst>(I); 1081 Out << "std::vector<Value*> " << iName << "_params;"; 1082 nl(Out); 1083 for (unsigned i = 0; i < inv->getNumArgOperands(); ++i) { 1084 Out << iName << "_params.push_back(" 1085 << getOpName(inv->getArgOperand(i)) << ");"; 1086 nl(Out); 1087 } 1088 // FIXME: This shouldn't use magic numbers -3, -2, and -1. 1089 Out << "InvokeInst *" << iName << " = InvokeInst::Create(" 1090 << getOpName(inv->getCalledFunction()) << ", " 1091 << getOpName(inv->getNormalDest()) << ", " 1092 << getOpName(inv->getUnwindDest()) << ", " 1093 << iName << "_params.begin(), " 1094 << iName << "_params.end(), \""; 1095 printEscapedString(inv->getName()); 1096 Out << "\", " << bbname << ");"; 1097 nl(Out) << iName << "->setCallingConv("; 1098 printCallingConv(inv->getCallingConv()); 1099 Out << ");"; 1100 printAttributes(inv->getAttributes(), iName); 1101 Out << iName << "->setAttributes(" << iName << "_PAL);"; 1102 nl(Out); 1103 break; 1104 } 1105 case Instruction::Unwind: { 1106 Out << "new UnwindInst(" 1107 << bbname << ");"; 1108 break; 1109 } 1110 case Instruction::Unreachable: { 1111 Out << "new UnreachableInst(" 1112 << "mod->getContext(), " 1113 << bbname << ");"; 1114 break; 1115 } 1116 case Instruction::Add: 1117 case Instruction::FAdd: 1118 case Instruction::Sub: 1119 case Instruction::FSub: 1120 case Instruction::Mul: 1121 case Instruction::FMul: 1122 case Instruction::UDiv: 1123 case Instruction::SDiv: 1124 case Instruction::FDiv: 1125 case Instruction::URem: 1126 case Instruction::SRem: 1127 case Instruction::FRem: 1128 case Instruction::And: 1129 case Instruction::Or: 1130 case Instruction::Xor: 1131 case Instruction::Shl: 1132 case Instruction::LShr: 1133 case Instruction::AShr:{ 1134 Out << "BinaryOperator* " << iName << " = BinaryOperator::Create("; 1135 switch (I->getOpcode()) { 1136 case Instruction::Add: Out << "Instruction::Add"; break; 1137 case Instruction::FAdd: Out << "Instruction::FAdd"; break; 1138 case Instruction::Sub: Out << "Instruction::Sub"; break; 1139 case Instruction::FSub: Out << "Instruction::FSub"; break; 1140 case Instruction::Mul: Out << "Instruction::Mul"; break; 1141 case Instruction::FMul: Out << "Instruction::FMul"; break; 1142 case Instruction::UDiv:Out << "Instruction::UDiv"; break; 1143 case Instruction::SDiv:Out << "Instruction::SDiv"; break; 1144 case Instruction::FDiv:Out << "Instruction::FDiv"; break; 1145 case Instruction::URem:Out << "Instruction::URem"; break; 1146 case Instruction::SRem:Out << "Instruction::SRem"; break; 1147 case Instruction::FRem:Out << "Instruction::FRem"; break; 1148 case Instruction::And: Out << "Instruction::And"; break; 1149 case Instruction::Or: Out << "Instruction::Or"; break; 1150 case Instruction::Xor: Out << "Instruction::Xor"; break; 1151 case Instruction::Shl: Out << "Instruction::Shl"; break; 1152 case Instruction::LShr:Out << "Instruction::LShr"; break; 1153 case Instruction::AShr:Out << "Instruction::AShr"; break; 1154 default: Out << "Instruction::BadOpCode"; break; 1155 } 1156 Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 1157 printEscapedString(I->getName()); 1158 Out << "\", " << bbname << ");"; 1159 break; 1160 } 1161 case Instruction::FCmp: { 1162 Out << "FCmpInst* " << iName << " = new FCmpInst(*" << bbname << ", "; 1163 switch (cast<FCmpInst>(I)->getPredicate()) { 1164 case FCmpInst::FCMP_FALSE: Out << "FCmpInst::FCMP_FALSE"; break; 1165 case FCmpInst::FCMP_OEQ : Out << "FCmpInst::FCMP_OEQ"; break; 1166 case FCmpInst::FCMP_OGT : Out << "FCmpInst::FCMP_OGT"; break; 1167 case FCmpInst::FCMP_OGE : Out << "FCmpInst::FCMP_OGE"; break; 1168 case FCmpInst::FCMP_OLT : Out << "FCmpInst::FCMP_OLT"; break; 1169 case FCmpInst::FCMP_OLE : Out << "FCmpInst::FCMP_OLE"; break; 1170 case FCmpInst::FCMP_ONE : Out << "FCmpInst::FCMP_ONE"; break; 1171 case FCmpInst::FCMP_ORD : Out << "FCmpInst::FCMP_ORD"; break; 1172 case FCmpInst::FCMP_UNO : Out << "FCmpInst::FCMP_UNO"; break; 1173 case FCmpInst::FCMP_UEQ : Out << "FCmpInst::FCMP_UEQ"; break; 1174 case FCmpInst::FCMP_UGT : Out << "FCmpInst::FCMP_UGT"; break; 1175 case FCmpInst::FCMP_UGE : Out << "FCmpInst::FCMP_UGE"; break; 1176 case FCmpInst::FCMP_ULT : Out << "FCmpInst::FCMP_ULT"; break; 1177 case FCmpInst::FCMP_ULE : Out << "FCmpInst::FCMP_ULE"; break; 1178 case FCmpInst::FCMP_UNE : Out << "FCmpInst::FCMP_UNE"; break; 1179 case FCmpInst::FCMP_TRUE : Out << "FCmpInst::FCMP_TRUE"; break; 1180 default: Out << "FCmpInst::BAD_ICMP_PREDICATE"; break; 1181 } 1182 Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 1183 printEscapedString(I->getName()); 1184 Out << "\");"; 1185 break; 1186 } 1187 case Instruction::ICmp: { 1188 Out << "ICmpInst* " << iName << " = new ICmpInst(*" << bbname << ", "; 1189 switch (cast<ICmpInst>(I)->getPredicate()) { 1190 case ICmpInst::ICMP_EQ: Out << "ICmpInst::ICMP_EQ"; break; 1191 case ICmpInst::ICMP_NE: Out << "ICmpInst::ICMP_NE"; break; 1192 case ICmpInst::ICMP_ULE: Out << "ICmpInst::ICMP_ULE"; break; 1193 case ICmpInst::ICMP_SLE: Out << "ICmpInst::ICMP_SLE"; break; 1194 case ICmpInst::ICMP_UGE: Out << "ICmpInst::ICMP_UGE"; break; 1195 case ICmpInst::ICMP_SGE: Out << "ICmpInst::ICMP_SGE"; break; 1196 case ICmpInst::ICMP_ULT: Out << "ICmpInst::ICMP_ULT"; break; 1197 case ICmpInst::ICMP_SLT: Out << "ICmpInst::ICMP_SLT"; break; 1198 case ICmpInst::ICMP_UGT: Out << "ICmpInst::ICMP_UGT"; break; 1199 case ICmpInst::ICMP_SGT: Out << "ICmpInst::ICMP_SGT"; break; 1200 default: Out << "ICmpInst::BAD_ICMP_PREDICATE"; break; 1201 } 1202 Out << ", " << opNames[0] << ", " << opNames[1] << ", \""; 1203 printEscapedString(I->getName()); 1204 Out << "\");"; 1205 break; 1206 } 1207 case Instruction::Alloca: { 1208 const AllocaInst* allocaI = cast<AllocaInst>(I); 1209 Out << "AllocaInst* " << iName << " = new AllocaInst(" 1210 << getCppName(allocaI->getAllocatedType()) << ", "; 1211 if (allocaI->isArrayAllocation()) 1212 Out << opNames[0] << ", "; 1213 Out << "\""; 1214 printEscapedString(allocaI->getName()); 1215 Out << "\", " << bbname << ");"; 1216 if (allocaI->getAlignment()) 1217 nl(Out) << iName << "->setAlignment(" 1218 << allocaI->getAlignment() << ");"; 1219 break; 1220 } 1221 case Instruction::Load: { 1222 const LoadInst* load = cast<LoadInst>(I); 1223 Out << "LoadInst* " << iName << " = new LoadInst(" 1224 << opNames[0] << ", \""; 1225 printEscapedString(load->getName()); 1226 Out << "\", " << (load->isVolatile() ? "true" : "false" ) 1227 << ", " << bbname << ");"; 1228 break; 1229 } 1230 case Instruction::Store: { 1231 const StoreInst* store = cast<StoreInst>(I); 1232 Out << " new StoreInst(" 1233 << opNames[0] << ", " 1234 << opNames[1] << ", " 1235 << (store->isVolatile() ? "true" : "false") 1236 << ", " << bbname << ");"; 1237 break; 1238 } 1239 case Instruction::GetElementPtr: { 1240 const GetElementPtrInst* gep = cast<GetElementPtrInst>(I); 1241 if (gep->getNumOperands() <= 2) { 1242 Out << "GetElementPtrInst* " << iName << " = GetElementPtrInst::Create(" 1243 << opNames[0]; 1244 if (gep->getNumOperands() == 2) 1245 Out << ", " << opNames[1]; 1246 } else { 1247 Out << "std::vector<Value*> " << iName << "_indices;"; 1248 nl(Out); 1249 for (unsigned i = 1; i < gep->getNumOperands(); ++i ) { 1250 Out << iName << "_indices.push_back(" 1251 << opNames[i] << ");"; 1252 nl(Out); 1253 } 1254 Out << "Instruction* " << iName << " = GetElementPtrInst::Create(" 1255 << opNames[0] << ", " << iName << "_indices.begin(), " 1256 << iName << "_indices.end()"; 1257 } 1258 Out << ", \""; 1259 printEscapedString(gep->getName()); 1260 Out << "\", " << bbname << ");"; 1261 break; 1262 } 1263 case Instruction::PHI: { 1264 const PHINode* phi = cast<PHINode>(I); 1265 1266 Out << "PHINode* " << iName << " = PHINode::Create(" 1267 << getCppName(phi->getType()) << ", " 1268 << phi->getNumIncomingValues() << ", \""; 1269 printEscapedString(phi->getName()); 1270 Out << "\", " << bbname << ");"; 1271 nl(Out); 1272 for (unsigned i = 0; i < phi->getNumIncomingValues(); ++i) { 1273 Out << iName << "->addIncoming(" 1274 << opNames[PHINode::getOperandNumForIncomingValue(i)] << ", " 1275 << getOpName(phi->getIncomingBlock(i)) << ");"; 1276 nl(Out); 1277 } 1278 break; 1279 } 1280 case Instruction::Trunc: 1281 case Instruction::ZExt: 1282 case Instruction::SExt: 1283 case Instruction::FPTrunc: 1284 case Instruction::FPExt: 1285 case Instruction::FPToUI: 1286 case Instruction::FPToSI: 1287 case Instruction::UIToFP: 1288 case Instruction::SIToFP: 1289 case Instruction::PtrToInt: 1290 case Instruction::IntToPtr: 1291 case Instruction::BitCast: { 1292 const CastInst* cst = cast<CastInst>(I); 1293 Out << "CastInst* " << iName << " = new "; 1294 switch (I->getOpcode()) { 1295 case Instruction::Trunc: Out << "TruncInst"; break; 1296 case Instruction::ZExt: Out << "ZExtInst"; break; 1297 case Instruction::SExt: Out << "SExtInst"; break; 1298 case Instruction::FPTrunc: Out << "FPTruncInst"; break; 1299 case Instruction::FPExt: Out << "FPExtInst"; break; 1300 case Instruction::FPToUI: Out << "FPToUIInst"; break; 1301 case Instruction::FPToSI: Out << "FPToSIInst"; break; 1302 case Instruction::UIToFP: Out << "UIToFPInst"; break; 1303 case Instruction::SIToFP: Out << "SIToFPInst"; break; 1304 case Instruction::PtrToInt: Out << "PtrToIntInst"; break; 1305 case Instruction::IntToPtr: Out << "IntToPtrInst"; break; 1306 case Instruction::BitCast: Out << "BitCastInst"; break; 1307 default: assert(!"Unreachable"); break; 1308 } 1309 Out << "(" << opNames[0] << ", " 1310 << getCppName(cst->getType()) << ", \""; 1311 printEscapedString(cst->getName()); 1312 Out << "\", " << bbname << ");"; 1313 break; 1314 } 1315 case Instruction::Call: { 1316 const CallInst* call = cast<CallInst>(I); 1317 if (const InlineAsm* ila = dyn_cast<InlineAsm>(call->getCalledValue())) { 1318 Out << "InlineAsm* " << getCppName(ila) << " = InlineAsm::get(" 1319 << getCppName(ila->getFunctionType()) << ", \"" 1320 << ila->getAsmString() << "\", \"" 1321 << ila->getConstraintString() << "\"," 1322 << (ila->hasSideEffects() ? "true" : "false") << ");"; 1323 nl(Out); 1324 } 1325 if (call->getNumArgOperands() > 1) { 1326 Out << "std::vector<Value*> " << iName << "_params;"; 1327 nl(Out); 1328 for (unsigned i = 0; i < call->getNumArgOperands(); ++i) { 1329 Out << iName << "_params.push_back(" << opNames[i] << ");"; 1330 nl(Out); 1331 } 1332 Out << "CallInst* " << iName << " = CallInst::Create(" 1333 << opNames[call->getNumArgOperands()] << ", " 1334 << iName << "_params.begin(), " 1335 << iName << "_params.end(), \""; 1336 } else if (call->getNumArgOperands() == 1) { 1337 Out << "CallInst* " << iName << " = CallInst::Create(" 1338 << opNames[call->getNumArgOperands()] << ", " << opNames[0] << ", \""; 1339 } else { 1340 Out << "CallInst* " << iName << " = CallInst::Create(" 1341 << opNames[call->getNumArgOperands()] << ", \""; 1342 } 1343 printEscapedString(call->getName()); 1344 Out << "\", " << bbname << ");"; 1345 nl(Out) << iName << "->setCallingConv("; 1346 printCallingConv(call->getCallingConv()); 1347 Out << ");"; 1348 nl(Out) << iName << "->setTailCall(" 1349 << (call->isTailCall() ? "true" : "false"); 1350 Out << ");"; 1351 nl(Out); 1352 printAttributes(call->getAttributes(), iName); 1353 Out << iName << "->setAttributes(" << iName << "_PAL);"; 1354 nl(Out); 1355 break; 1356 } 1357 case Instruction::Select: { 1358 const SelectInst* sel = cast<SelectInst>(I); 1359 Out << "SelectInst* " << getCppName(sel) << " = SelectInst::Create("; 1360 Out << opNames[0] << ", " << opNames[1] << ", " << opNames[2] << ", \""; 1361 printEscapedString(sel->getName()); 1362 Out << "\", " << bbname << ");"; 1363 break; 1364 } 1365 case Instruction::UserOp1: 1366 /// FALL THROUGH 1367 case Instruction::UserOp2: { 1368 /// FIXME: What should be done here? 1369 break; 1370 } 1371 case Instruction::VAArg: { 1372 const VAArgInst* va = cast<VAArgInst>(I); 1373 Out << "VAArgInst* " << getCppName(va) << " = new VAArgInst(" 1374 << opNames[0] << ", " << getCppName(va->getType()) << ", \""; 1375 printEscapedString(va->getName()); 1376 Out << "\", " << bbname << ");"; 1377 break; 1378 } 1379 case Instruction::ExtractElement: { 1380 const ExtractElementInst* eei = cast<ExtractElementInst>(I); 1381 Out << "ExtractElementInst* " << getCppName(eei) 1382 << " = new ExtractElementInst(" << opNames[0] 1383 << ", " << opNames[1] << ", \""; 1384 printEscapedString(eei->getName()); 1385 Out << "\", " << bbname << ");"; 1386 break; 1387 } 1388 case Instruction::InsertElement: { 1389 const InsertElementInst* iei = cast<InsertElementInst>(I); 1390 Out << "InsertElementInst* " << getCppName(iei) 1391 << " = InsertElementInst::Create(" << opNames[0] 1392 << ", " << opNames[1] << ", " << opNames[2] << ", \""; 1393 printEscapedString(iei->getName()); 1394 Out << "\", " << bbname << ");"; 1395 break; 1396 } 1397 case Instruction::ShuffleVector: { 1398 const ShuffleVectorInst* svi = cast<ShuffleVectorInst>(I); 1399 Out << "ShuffleVectorInst* " << getCppName(svi) 1400 << " = new ShuffleVectorInst(" << opNames[0] 1401 << ", " << opNames[1] << ", " << opNames[2] << ", \""; 1402 printEscapedString(svi->getName()); 1403 Out << "\", " << bbname << ");"; 1404 break; 1405 } 1406 case Instruction::ExtractValue: { 1407 const ExtractValueInst *evi = cast<ExtractValueInst>(I); 1408 Out << "std::vector<unsigned> " << iName << "_indices;"; 1409 nl(Out); 1410 for (unsigned i = 0; i < evi->getNumIndices(); ++i) { 1411 Out << iName << "_indices.push_back(" 1412 << evi->idx_begin()[i] << ");"; 1413 nl(Out); 1414 } 1415 Out << "ExtractValueInst* " << getCppName(evi) 1416 << " = ExtractValueInst::Create(" << opNames[0] 1417 << ", " 1418 << iName << "_indices.begin(), " << iName << "_indices.end(), \""; 1419 printEscapedString(evi->getName()); 1420 Out << "\", " << bbname << ");"; 1421 break; 1422 } 1423 case Instruction::InsertValue: { 1424 const InsertValueInst *ivi = cast<InsertValueInst>(I); 1425 Out << "std::vector<unsigned> " << iName << "_indices;"; 1426 nl(Out); 1427 for (unsigned i = 0; i < ivi->getNumIndices(); ++i) { 1428 Out << iName << "_indices.push_back(" 1429 << ivi->idx_begin()[i] << ");"; 1430 nl(Out); 1431 } 1432 Out << "InsertValueInst* " << getCppName(ivi) 1433 << " = InsertValueInst::Create(" << opNames[0] 1434 << ", " << opNames[1] << ", " 1435 << iName << "_indices.begin(), " << iName << "_indices.end(), \""; 1436 printEscapedString(ivi->getName()); 1437 Out << "\", " << bbname << ");"; 1438 break; 1439 } 1440 } 1441 DefinedValues.insert(I); 1442 nl(Out); 1443 delete [] opNames; 1444 } 1445 1446 // Print out the types, constants and declarations needed by one function 1447 void CppWriter::printFunctionUses(const Function* F) { 1448 nl(Out) << "// Type Definitions"; nl(Out); 1449 if (!is_inline) { 1450 // Print the function's return type 1451 printType(F->getReturnType()); 1452 1453 // Print the function's function type 1454 printType(F->getFunctionType()); 1455 1456 // Print the types of each of the function's arguments 1457 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1458 AI != AE; ++AI) { 1459 printType(AI->getType()); 1460 } 1461 } 1462 1463 // Print type definitions for every type referenced by an instruction and 1464 // make a note of any global values or constants that are referenced 1465 SmallPtrSet<GlobalValue*,64> gvs; 1466 SmallPtrSet<Constant*,64> consts; 1467 for (Function::const_iterator BB = F->begin(), BE = F->end(); 1468 BB != BE; ++BB){ 1469 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 1470 I != E; ++I) { 1471 // Print the type of the instruction itself 1472 printType(I->getType()); 1473 1474 // Print the type of each of the instruction's operands 1475 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 1476 Value* operand = I->getOperand(i); 1477 printType(operand->getType()); 1478 1479 // If the operand references a GVal or Constant, make a note of it 1480 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) { 1481 gvs.insert(GV); 1482 if (GenerationType != GenFunction) 1483 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 1484 if (GVar->hasInitializer()) 1485 consts.insert(GVar->getInitializer()); 1486 } else if (Constant* C = dyn_cast<Constant>(operand)) { 1487 consts.insert(C); 1488 for (unsigned j = 0; j < C->getNumOperands(); ++j) { 1489 // If the operand references a GVal or Constant, make a note of it 1490 Value* operand = C->getOperand(j); 1491 printType(operand->getType()); 1492 if (GlobalValue* GV = dyn_cast<GlobalValue>(operand)) { 1493 gvs.insert(GV); 1494 if (GenerationType != GenFunction) 1495 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 1496 if (GVar->hasInitializer()) 1497 consts.insert(GVar->getInitializer()); 1498 } 1499 } 1500 } 1501 } 1502 } 1503 } 1504 1505 // Print the function declarations for any functions encountered 1506 nl(Out) << "// Function Declarations"; nl(Out); 1507 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 1508 I != E; ++I) { 1509 if (Function* Fun = dyn_cast<Function>(*I)) { 1510 if (!is_inline || Fun != F) 1511 printFunctionHead(Fun); 1512 } 1513 } 1514 1515 // Print the global variable declarations for any variables encountered 1516 nl(Out) << "// Global Variable Declarations"; nl(Out); 1517 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 1518 I != E; ++I) { 1519 if (GlobalVariable* F = dyn_cast<GlobalVariable>(*I)) 1520 printVariableHead(F); 1521 } 1522 1523 // Print the constants found 1524 nl(Out) << "// Constant Definitions"; nl(Out); 1525 for (SmallPtrSet<Constant*,64>::iterator I = consts.begin(), 1526 E = consts.end(); I != E; ++I) { 1527 printConstant(*I); 1528 } 1529 1530 // Process the global variables definitions now that all the constants have 1531 // been emitted. These definitions just couple the gvars with their constant 1532 // initializers. 1533 if (GenerationType != GenFunction) { 1534 nl(Out) << "// Global Variable Definitions"; nl(Out); 1535 for (SmallPtrSet<GlobalValue*,64>::iterator I = gvs.begin(), E = gvs.end(); 1536 I != E; ++I) { 1537 if (GlobalVariable* GV = dyn_cast<GlobalVariable>(*I)) 1538 printVariableBody(GV); 1539 } 1540 } 1541 } 1542 1543 void CppWriter::printFunctionHead(const Function* F) { 1544 nl(Out) << "Function* " << getCppName(F); 1545 if (is_inline) { 1546 Out << " = mod->getFunction(\""; 1547 printEscapedString(F->getName()); 1548 Out << "\", " << getCppName(F->getFunctionType()) << ");"; 1549 nl(Out) << "if (!" << getCppName(F) << ") {"; 1550 nl(Out) << getCppName(F); 1551 } 1552 Out<< " = Function::Create("; 1553 nl(Out,1) << "/*Type=*/" << getCppName(F->getFunctionType()) << ","; 1554 nl(Out) << "/*Linkage=*/"; 1555 printLinkageType(F->getLinkage()); 1556 Out << ","; 1557 nl(Out) << "/*Name=*/\""; 1558 printEscapedString(F->getName()); 1559 Out << "\", mod); " << (F->isDeclaration()? "// (external, no body)" : ""); 1560 nl(Out,-1); 1561 printCppName(F); 1562 Out << "->setCallingConv("; 1563 printCallingConv(F->getCallingConv()); 1564 Out << ");"; 1565 nl(Out); 1566 if (F->hasSection()) { 1567 printCppName(F); 1568 Out << "->setSection(\"" << F->getSection() << "\");"; 1569 nl(Out); 1570 } 1571 if (F->getAlignment()) { 1572 printCppName(F); 1573 Out << "->setAlignment(" << F->getAlignment() << ");"; 1574 nl(Out); 1575 } 1576 if (F->getVisibility() != GlobalValue::DefaultVisibility) { 1577 printCppName(F); 1578 Out << "->setVisibility("; 1579 printVisibilityType(F->getVisibility()); 1580 Out << ");"; 1581 nl(Out); 1582 } 1583 if (F->hasGC()) { 1584 printCppName(F); 1585 Out << "->setGC(\"" << F->getGC() << "\");"; 1586 nl(Out); 1587 } 1588 if (is_inline) { 1589 Out << "}"; 1590 nl(Out); 1591 } 1592 printAttributes(F->getAttributes(), getCppName(F)); 1593 printCppName(F); 1594 Out << "->setAttributes(" << getCppName(F) << "_PAL);"; 1595 nl(Out); 1596 } 1597 1598 void CppWriter::printFunctionBody(const Function *F) { 1599 if (F->isDeclaration()) 1600 return; // external functions have no bodies. 1601 1602 // Clear the DefinedValues and ForwardRefs maps because we can't have 1603 // cross-function forward refs 1604 ForwardRefs.clear(); 1605 DefinedValues.clear(); 1606 1607 // Create all the argument values 1608 if (!is_inline) { 1609 if (!F->arg_empty()) { 1610 Out << "Function::arg_iterator args = " << getCppName(F) 1611 << "->arg_begin();"; 1612 nl(Out); 1613 } 1614 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1615 AI != AE; ++AI) { 1616 Out << "Value* " << getCppName(AI) << " = args++;"; 1617 nl(Out); 1618 if (AI->hasName()) { 1619 Out << getCppName(AI) << "->setName(\"" << AI->getName() << "\");"; 1620 nl(Out); 1621 } 1622 } 1623 } 1624 1625 // Create all the basic blocks 1626 nl(Out); 1627 for (Function::const_iterator BI = F->begin(), BE = F->end(); 1628 BI != BE; ++BI) { 1629 std::string bbname(getCppName(BI)); 1630 Out << "BasicBlock* " << bbname << 1631 " = BasicBlock::Create(mod->getContext(), \""; 1632 if (BI->hasName()) 1633 printEscapedString(BI->getName()); 1634 Out << "\"," << getCppName(BI->getParent()) << ",0);"; 1635 nl(Out); 1636 } 1637 1638 // Output all of its basic blocks... for the function 1639 for (Function::const_iterator BI = F->begin(), BE = F->end(); 1640 BI != BE; ++BI) { 1641 std::string bbname(getCppName(BI)); 1642 nl(Out) << "// Block " << BI->getName() << " (" << bbname << ")"; 1643 nl(Out); 1644 1645 // Output all of the instructions in the basic block... 1646 for (BasicBlock::const_iterator I = BI->begin(), E = BI->end(); 1647 I != E; ++I) { 1648 printInstruction(I,bbname); 1649 } 1650 } 1651 1652 // Loop over the ForwardRefs and resolve them now that all instructions 1653 // are generated. 1654 if (!ForwardRefs.empty()) { 1655 nl(Out) << "// Resolve Forward References"; 1656 nl(Out); 1657 } 1658 1659 while (!ForwardRefs.empty()) { 1660 ForwardRefMap::iterator I = ForwardRefs.begin(); 1661 Out << I->second << "->replaceAllUsesWith(" 1662 << getCppName(I->first) << "); delete " << I->second << ";"; 1663 nl(Out); 1664 ForwardRefs.erase(I); 1665 } 1666 } 1667 1668 void CppWriter::printInline(const std::string& fname, 1669 const std::string& func) { 1670 const Function* F = TheModule->getFunction(func); 1671 if (!F) { 1672 error(std::string("Function '") + func + "' not found in input module"); 1673 return; 1674 } 1675 if (F->isDeclaration()) { 1676 error(std::string("Function '") + func + "' is external!"); 1677 return; 1678 } 1679 nl(Out) << "BasicBlock* " << fname << "(Module* mod, Function *" 1680 << getCppName(F); 1681 unsigned arg_count = 1; 1682 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1683 AI != AE; ++AI) { 1684 Out << ", Value* arg_" << arg_count; 1685 } 1686 Out << ") {"; 1687 nl(Out); 1688 is_inline = true; 1689 printFunctionUses(F); 1690 printFunctionBody(F); 1691 is_inline = false; 1692 Out << "return " << getCppName(F->begin()) << ";"; 1693 nl(Out) << "}"; 1694 nl(Out); 1695 } 1696 1697 void CppWriter::printModuleBody() { 1698 // Print out all the type definitions 1699 nl(Out) << "// Type Definitions"; nl(Out); 1700 printTypes(TheModule); 1701 1702 // Functions can call each other and global variables can reference them so 1703 // define all the functions first before emitting their function bodies. 1704 nl(Out) << "// Function Declarations"; nl(Out); 1705 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 1706 I != E; ++I) 1707 printFunctionHead(I); 1708 1709 // Process the global variables declarations. We can't initialze them until 1710 // after the constants are printed so just print a header for each global 1711 nl(Out) << "// Global Variable Declarations\n"; nl(Out); 1712 for (Module::const_global_iterator I = TheModule->global_begin(), 1713 E = TheModule->global_end(); I != E; ++I) { 1714 printVariableHead(I); 1715 } 1716 1717 // Print out all the constants definitions. Constants don't recurse except 1718 // through GlobalValues. All GlobalValues have been declared at this point 1719 // so we can proceed to generate the constants. 1720 nl(Out) << "// Constant Definitions"; nl(Out); 1721 printConstants(TheModule); 1722 1723 // Process the global variables definitions now that all the constants have 1724 // been emitted. These definitions just couple the gvars with their constant 1725 // initializers. 1726 nl(Out) << "// Global Variable Definitions"; nl(Out); 1727 for (Module::const_global_iterator I = TheModule->global_begin(), 1728 E = TheModule->global_end(); I != E; ++I) { 1729 printVariableBody(I); 1730 } 1731 1732 // Finally, we can safely put out all of the function bodies. 1733 nl(Out) << "// Function Definitions"; nl(Out); 1734 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end(); 1735 I != E; ++I) { 1736 if (!I->isDeclaration()) { 1737 nl(Out) << "// Function: " << I->getName() << " (" << getCppName(I) 1738 << ")"; 1739 nl(Out) << "{"; 1740 nl(Out,1); 1741 printFunctionBody(I); 1742 nl(Out,-1) << "}"; 1743 nl(Out); 1744 } 1745 } 1746 } 1747 1748 void CppWriter::printProgram(const std::string& fname, 1749 const std::string& mName) { 1750 Out << "#include <llvm/LLVMContext.h>\n"; 1751 Out << "#include <llvm/Module.h>\n"; 1752 Out << "#include <llvm/DerivedTypes.h>\n"; 1753 Out << "#include <llvm/Constants.h>\n"; 1754 Out << "#include <llvm/GlobalVariable.h>\n"; 1755 Out << "#include <llvm/Function.h>\n"; 1756 Out << "#include <llvm/CallingConv.h>\n"; 1757 Out << "#include <llvm/BasicBlock.h>\n"; 1758 Out << "#include <llvm/Instructions.h>\n"; 1759 Out << "#include <llvm/InlineAsm.h>\n"; 1760 Out << "#include <llvm/Support/FormattedStream.h>\n"; 1761 Out << "#include <llvm/Support/MathExtras.h>\n"; 1762 Out << "#include <llvm/Pass.h>\n"; 1763 Out << "#include <llvm/PassManager.h>\n"; 1764 Out << "#include <llvm/ADT/SmallVector.h>\n"; 1765 Out << "#include <llvm/Analysis/Verifier.h>\n"; 1766 Out << "#include <llvm/Assembly/PrintModulePass.h>\n"; 1767 Out << "#include <algorithm>\n"; 1768 Out << "using namespace llvm;\n\n"; 1769 Out << "Module* " << fname << "();\n\n"; 1770 Out << "int main(int argc, char**argv) {\n"; 1771 Out << " Module* Mod = " << fname << "();\n"; 1772 Out << " verifyModule(*Mod, PrintMessageAction);\n"; 1773 Out << " PassManager PM;\n"; 1774 Out << " PM.add(createPrintModulePass(&outs()));\n"; 1775 Out << " PM.run(*Mod);\n"; 1776 Out << " return 0;\n"; 1777 Out << "}\n\n"; 1778 printModule(fname,mName); 1779 } 1780 1781 void CppWriter::printModule(const std::string& fname, 1782 const std::string& mName) { 1783 nl(Out) << "Module* " << fname << "() {"; 1784 nl(Out,1) << "// Module Construction"; 1785 nl(Out) << "Module* mod = new Module(\""; 1786 printEscapedString(mName); 1787 Out << "\", getGlobalContext());"; 1788 if (!TheModule->getTargetTriple().empty()) { 1789 nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");"; 1790 } 1791 if (!TheModule->getTargetTriple().empty()) { 1792 nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple() 1793 << "\");"; 1794 } 1795 1796 if (!TheModule->getModuleInlineAsm().empty()) { 1797 nl(Out) << "mod->setModuleInlineAsm(\""; 1798 printEscapedString(TheModule->getModuleInlineAsm()); 1799 Out << "\");"; 1800 } 1801 nl(Out); 1802 1803 // Loop over the dependent libraries and emit them. 1804 Module::lib_iterator LI = TheModule->lib_begin(); 1805 Module::lib_iterator LE = TheModule->lib_end(); 1806 while (LI != LE) { 1807 Out << "mod->addLibrary(\"" << *LI << "\");"; 1808 nl(Out); 1809 ++LI; 1810 } 1811 printModuleBody(); 1812 nl(Out) << "return mod;"; 1813 nl(Out,-1) << "}"; 1814 nl(Out); 1815 } 1816 1817 void CppWriter::printContents(const std::string& fname, 1818 const std::string& mName) { 1819 Out << "\nModule* " << fname << "(Module *mod) {\n"; 1820 Out << "\nmod->setModuleIdentifier(\""; 1821 printEscapedString(mName); 1822 Out << "\");\n"; 1823 printModuleBody(); 1824 Out << "\nreturn mod;\n"; 1825 Out << "\n}\n"; 1826 } 1827 1828 void CppWriter::printFunction(const std::string& fname, 1829 const std::string& funcName) { 1830 const Function* F = TheModule->getFunction(funcName); 1831 if (!F) { 1832 error(std::string("Function '") + funcName + "' not found in input module"); 1833 return; 1834 } 1835 Out << "\nFunction* " << fname << "(Module *mod) {\n"; 1836 printFunctionUses(F); 1837 printFunctionHead(F); 1838 printFunctionBody(F); 1839 Out << "return " << getCppName(F) << ";\n"; 1840 Out << "}\n"; 1841 } 1842 1843 void CppWriter::printFunctions() { 1844 const Module::FunctionListType &funcs = TheModule->getFunctionList(); 1845 Module::const_iterator I = funcs.begin(); 1846 Module::const_iterator IE = funcs.end(); 1847 1848 for (; I != IE; ++I) { 1849 const Function &func = *I; 1850 if (!func.isDeclaration()) { 1851 std::string name("define_"); 1852 name += func.getName(); 1853 printFunction(name, func.getName()); 1854 } 1855 } 1856 } 1857 1858 void CppWriter::printVariable(const std::string& fname, 1859 const std::string& varName) { 1860 const GlobalVariable* GV = TheModule->getNamedGlobal(varName); 1861 1862 if (!GV) { 1863 error(std::string("Variable '") + varName + "' not found in input module"); 1864 return; 1865 } 1866 Out << "\nGlobalVariable* " << fname << "(Module *mod) {\n"; 1867 printVariableUses(GV); 1868 printVariableHead(GV); 1869 printVariableBody(GV); 1870 Out << "return " << getCppName(GV) << ";\n"; 1871 Out << "}\n"; 1872 } 1873 1874 void CppWriter::printType(const std::string &fname, 1875 const std::string &typeName) { 1876 Type* Ty = TheModule->getTypeByName(typeName); 1877 if (!Ty) { 1878 error(std::string("Type '") + typeName + "' not found in input module"); 1879 return; 1880 } 1881 Out << "\nType* " << fname << "(Module *mod) {\n"; 1882 printType(Ty); 1883 Out << "return " << getCppName(Ty) << ";\n"; 1884 Out << "}\n"; 1885 } 1886 1887 bool CppWriter::runOnModule(Module &M) { 1888 TheModule = &M; 1889 1890 // Emit a header 1891 Out << "// Generated by llvm2cpp - DO NOT MODIFY!\n\n"; 1892 1893 // Get the name of the function we're supposed to generate 1894 std::string fname = FuncName.getValue(); 1895 1896 // Get the name of the thing we are to generate 1897 std::string tgtname = NameToGenerate.getValue(); 1898 if (GenerationType == GenModule || 1899 GenerationType == GenContents || 1900 GenerationType == GenProgram || 1901 GenerationType == GenFunctions) { 1902 if (tgtname == "!bad!") { 1903 if (M.getModuleIdentifier() == "-") 1904 tgtname = "<stdin>"; 1905 else 1906 tgtname = M.getModuleIdentifier(); 1907 } 1908 } else if (tgtname == "!bad!") 1909 error("You must use the -for option with -gen-{function,variable,type}"); 1910 1911 switch (WhatToGenerate(GenerationType)) { 1912 case GenProgram: 1913 if (fname.empty()) 1914 fname = "makeLLVMModule"; 1915 printProgram(fname,tgtname); 1916 break; 1917 case GenModule: 1918 if (fname.empty()) 1919 fname = "makeLLVMModule"; 1920 printModule(fname,tgtname); 1921 break; 1922 case GenContents: 1923 if (fname.empty()) 1924 fname = "makeLLVMModuleContents"; 1925 printContents(fname,tgtname); 1926 break; 1927 case GenFunction: 1928 if (fname.empty()) 1929 fname = "makeLLVMFunction"; 1930 printFunction(fname,tgtname); 1931 break; 1932 case GenFunctions: 1933 printFunctions(); 1934 break; 1935 case GenInline: 1936 if (fname.empty()) 1937 fname = "makeLLVMInline"; 1938 printInline(fname,tgtname); 1939 break; 1940 case GenVariable: 1941 if (fname.empty()) 1942 fname = "makeLLVMVariable"; 1943 printVariable(fname,tgtname); 1944 break; 1945 case GenType: 1946 if (fname.empty()) 1947 fname = "makeLLVMType"; 1948 printType(fname,tgtname); 1949 break; 1950 default: 1951 error("Invalid generation option"); 1952 } 1953 1954 return false; 1955 } 1956 1957 char CppWriter::ID = 0; 1958 1959 //===----------------------------------------------------------------------===// 1960 // External Interface declaration 1961 //===----------------------------------------------------------------------===// 1962 1963 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM, 1964 formatted_raw_ostream &o, 1965 CodeGenFileType FileType, 1966 CodeGenOpt::Level OptLevel, 1967 bool DisableVerify) { 1968 if (FileType != TargetMachine::CGFT_AssemblyFile) return true; 1969 PM.add(new CppWriter(o)); 1970 return false; 1971 } 1972