CPPBackend.cpp 71 KB

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