CPPBackend.cpp 74 KB

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