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