CPPBackend.cpp 71 KB

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