CPPBackend.cpp 73 KB

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