compiler.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _COMPILER_H_
  23. #define _COMPILER_H_
  24. //#define DEBUG_CODESTREAM
  25. #ifdef DEBUG_CODESTREAM
  26. #include <stdio.h>
  27. #endif
  28. #include <string>
  29. #include <unordered_map>
  30. class Stream;
  31. class DataChunker;
  32. #include "platform/platform.h"
  33. #include "console/ast.h"
  34. #include "console/codeBlock.h"
  35. #ifndef _TVECTOR_H_
  36. #include "core/util/tVector.h"
  37. #endif
  38. //------------------------------------------------------------
  39. namespace Compiler
  40. {
  41. /// The opcodes for the TorqueScript VM.
  42. enum CompiledInstructions
  43. {
  44. OP_FUNC_DECL,
  45. OP_CREATE_OBJECT,
  46. OP_ADD_OBJECT,
  47. OP_END_OBJECT,
  48. // Added to fix the stack issue [7/9/2007 Black]
  49. OP_FINISH_OBJECT,
  50. OP_JMPIFFNOT,
  51. OP_JMPIFNOT,
  52. OP_JMPIFF,
  53. OP_JMPIF,
  54. OP_JMPIFNOT_NP,
  55. OP_JMPIF_NP, // 10
  56. OP_JMP,
  57. OP_RETURN,
  58. // fixes a bug when not explicitly returning a value
  59. OP_RETURN_VOID,
  60. OP_RETURN_FLT,
  61. OP_RETURN_UINT,
  62. OP_CMPEQ,
  63. OP_CMPGR,
  64. OP_CMPGE,
  65. OP_CMPLT,
  66. OP_CMPLE,
  67. OP_CMPNE,
  68. OP_XOR, // 20
  69. OP_MOD,
  70. OP_BITAND,
  71. OP_BITOR,
  72. OP_NOT,
  73. OP_NOTF,
  74. OP_ONESCOMPLEMENT,
  75. OP_SHR,
  76. OP_SHL,
  77. OP_AND,
  78. OP_OR, // 30
  79. OP_ADD,
  80. OP_SUB,
  81. OP_MUL,
  82. OP_DIV,
  83. OP_NEG,
  84. OP_INC,
  85. OP_SETCURVAR,
  86. OP_SETCURVAR_CREATE,
  87. OP_SETCURVAR_ARRAY,
  88. OP_SETCURVAR_ARRAY_CREATE,
  89. OP_LOADVAR_UINT,// 40
  90. OP_LOADVAR_FLT,
  91. OP_LOADVAR_STR,
  92. OP_SAVEVAR_UINT,
  93. OP_SAVEVAR_FLT,
  94. OP_SAVEVAR_STR,
  95. OP_LOAD_LOCAL_VAR_UINT,
  96. OP_LOAD_LOCAL_VAR_FLT,
  97. OP_LOAD_LOCAL_VAR_STR,
  98. OP_SAVE_LOCAL_VAR_UINT,
  99. OP_SAVE_LOCAL_VAR_FLT,
  100. OP_SAVE_LOCAL_VAR_STR,
  101. OP_SETCUROBJECT,
  102. OP_SETCUROBJECT_NEW,
  103. OP_SETCUROBJECT_INTERNAL,
  104. OP_SETCURFIELD,
  105. OP_SETCURFIELD_ARRAY, // 50
  106. OP_SETCURFIELD_TYPE,
  107. OP_LOADFIELD_UINT,
  108. OP_LOADFIELD_FLT,
  109. OP_LOADFIELD_STR,
  110. OP_SAVEFIELD_UINT,
  111. OP_SAVEFIELD_FLT,
  112. OP_SAVEFIELD_STR,
  113. OP_POP_STK,
  114. OP_LOADIMMED_UINT,
  115. OP_LOADIMMED_FLT,
  116. OP_TAG_TO_STR,
  117. OP_LOADIMMED_STR, // 70
  118. OP_DOCBLOCK_STR, // 76
  119. OP_LOADIMMED_IDENT,
  120. OP_CALLFUNC,
  121. OP_ADVANCE_STR_APPENDCHAR,
  122. OP_REWIND_STR,
  123. OP_TERMINATE_REWIND_STR,
  124. OP_COMPARE_STR,
  125. OP_PUSH,
  126. OP_PUSH_FRAME,
  127. OP_ASSERT,
  128. OP_BREAK,
  129. OP_ITER_BEGIN, ///< Prepare foreach iterator.
  130. OP_ITER_BEGIN_STR, ///< Prepare foreach$ iterator.
  131. OP_ITER, ///< Enter foreach loop.
  132. OP_ITER_END, ///< End foreach loop.
  133. OP_INVALID, // 90
  134. MAX_OP_CODELEN ///< The amount of op codes.
  135. };
  136. //------------------------------------------------------------
  137. F64 consoleStringToNumber(const char *str, StringTableEntry file = 0, U32 line = 0);
  138. U32 compileBlock(StmtNode *block, CodeStream &codeStream, U32 ip);
  139. //------------------------------------------------------------
  140. struct CompilerIdentTable
  141. {
  142. struct Entry
  143. {
  144. U32 offset;
  145. U32 ip;
  146. Entry *next;
  147. Entry *nextIdent;
  148. };
  149. Entry *list;
  150. void add(StringTableEntry ste, U32 ip);
  151. void reset();
  152. void write(Stream &st);
  153. };
  154. //------------------------------------------------------------
  155. struct CompilerStringTable
  156. {
  157. U32 totalLen;
  158. struct Entry
  159. {
  160. char *string;
  161. U32 start;
  162. U32 len;
  163. bool tag;
  164. Entry *next;
  165. };
  166. Entry *list;
  167. char buf[256];
  168. std::unordered_map<std::string, Entry*> hashTable;
  169. U32 add(const char *str, bool caseSens = true, bool tag = false);
  170. U32 addIntString(U32 value);
  171. U32 addFloatString(F64 value);
  172. void reset();
  173. char *build();
  174. void write(Stream &st);
  175. };
  176. //------------------------------------------------------------
  177. struct CompilerFloatTable
  178. {
  179. struct Entry
  180. {
  181. F64 val;
  182. Entry *next;
  183. };
  184. U32 count;
  185. Entry *list;
  186. U32 add(F64 value);
  187. void reset();
  188. F64 *build();
  189. void write(Stream &st);
  190. };
  191. //------------------------------------------------------------
  192. inline StringTableEntry CodeToSTE(U32 *code, U32 ip)
  193. {
  194. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  195. return (StringTableEntry)(*((U64*)(code + ip)));
  196. #else
  197. return (StringTableEntry)(*(code + ip));
  198. #endif
  199. }
  200. extern void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr);
  201. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr);
  202. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr);
  203. CompilerStringTable *getCurrentStringTable();
  204. CompilerStringTable &getGlobalStringTable();
  205. CompilerStringTable &getFunctionStringTable();
  206. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable();
  207. void setCurrentStringTable(CompilerStringTable* cst);
  208. CompilerFloatTable *getCurrentFloatTable();
  209. CompilerFloatTable &getGlobalFloatTable();
  210. CompilerFloatTable &getFunctionFloatTable();
  211. void setCurrentFloatTable(CompilerFloatTable* cst);
  212. CompilerIdentTable &getIdentTable();
  213. void precompileIdent(StringTableEntry ident);
  214. /// Helper function to reset the float, string, and ident tables to a base
  215. /// starting state.
  216. void resetTables();
  217. void *consoleAlloc(U32 size);
  218. void consoleAllocReset();
  219. extern bool gSyntaxError;
  220. extern bool gIsEvalCompile;
  221. };
  222. class FuncVars
  223. {
  224. struct Var
  225. {
  226. S32 reg;
  227. TypeReq currentType;
  228. StringTableEntry name;
  229. bool isConstant;
  230. };
  231. public:
  232. S32 assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant = false);
  233. S32 lookup(StringTableEntry var, S32 lineNumber);
  234. TypeReq lookupType(StringTableEntry var, S32 lineNumber);
  235. inline S32 count() { return counter; }
  236. std::unordered_map<S32, StringTableEntry> variableNameMap;
  237. void clear();
  238. private:
  239. std::unordered_map<StringTableEntry, Var> vars;
  240. S32 counter = 0;
  241. };
  242. /// Utility class to emit and patch bytecode
  243. class CodeStream
  244. {
  245. public:
  246. enum FixType
  247. {
  248. // For loops
  249. FIXTYPE_LOOPBLOCKSTART,
  250. FIXTYPE_BREAK,
  251. FIXTYPE_CONTINUE
  252. };
  253. enum Constants
  254. {
  255. BlockSize = 16384,
  256. };
  257. protected:
  258. typedef struct PatchEntry
  259. {
  260. U32 addr; ///< Address to patch
  261. U32 value; ///< Value to place at addr
  262. PatchEntry(): addr(0), value(0) { ; }
  263. PatchEntry(U32 a, U32 v) : addr(a), value(v) { ; }
  264. } PatchEntry;
  265. typedef struct CodeData
  266. {
  267. U8 *data; ///< Allocated data (size is BlockSize)
  268. U32 size; ///< Bytes used in data
  269. CodeData *next; ///< Next block
  270. } CodeData;
  271. /// @name Emitted code
  272. /// {
  273. CodeData *mCode;
  274. CodeData *mCodeHead;
  275. U32 mCodePos;
  276. /// }
  277. /// @name Code fixing stacks
  278. /// {
  279. Vector<U32> mFixList;
  280. Vector<U32> mFixStack;
  281. Vector<bool> mFixLoopStack;
  282. Vector<PatchEntry> mPatchList;
  283. /// }
  284. Vector<U32> mBreakLines; ///< Line numbers
  285. public:
  286. CodeStream() : mCode(0), mCodeHead(NULL), mCodePos(0)
  287. {
  288. }
  289. ~CodeStream()
  290. {
  291. reset();
  292. if (mCode)
  293. {
  294. dFree(mCode->data);
  295. delete mCode;
  296. }
  297. }
  298. U8 *allocCode(U32 sz);
  299. inline U32 emit(U32 code)
  300. {
  301. U32 *ptr = (U32*)allocCode(4);
  302. *ptr = code;
  303. #ifdef DEBUG_CODESTREAM
  304. printf("code[%u] = %u\n", mCodePos, code);
  305. #endif
  306. return mCodePos++;
  307. }
  308. inline void patch(U32 addr, U32 code)
  309. {
  310. #ifdef DEBUG_CODESTREAM
  311. printf("patch[%u] = %u\n", addr, code);
  312. #endif
  313. mPatchList.push_back(PatchEntry(addr, code));
  314. }
  315. inline U32 emitSTE(const char *code)
  316. {
  317. U64 *ptr = (U64*)allocCode(8);
  318. *ptr = 0;
  319. Compiler::STEtoCode(code, mCodePos, (U32*)ptr);
  320. #ifdef DEBUG_CODESTREAM
  321. printf("code[%u] = %s\n", mCodePos, code);
  322. #endif
  323. mCodePos += 2;
  324. return mCodePos - 2;
  325. }
  326. inline U32 tell()
  327. {
  328. return mCodePos;
  329. }
  330. inline bool inLoop()
  331. {
  332. for (U32 i = 0; i<mFixLoopStack.size(); i++)
  333. {
  334. if (mFixLoopStack[i])
  335. return true;
  336. }
  337. return false;
  338. }
  339. inline U32 emitFix(FixType type)
  340. {
  341. U32 *ptr = (U32*)allocCode(4);
  342. *ptr = (U32)type;
  343. #ifdef DEBUG_CODESTREAM
  344. printf("code[%u] = [FIX:%u]\n", mCodePos, (U32)type);
  345. #endif
  346. mFixList.push_back(mCodePos);
  347. mFixList.push_back((U32)type);
  348. return mCodePos++;
  349. }
  350. inline void pushFixScope(bool isLoop)
  351. {
  352. mFixStack.push_back(mFixList.size());
  353. mFixLoopStack.push_back(isLoop);
  354. }
  355. inline void popFixScope()
  356. {
  357. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  358. U32 newSize = mFixStack[mFixStack.size() - 1];
  359. while (mFixList.size() > newSize)
  360. mFixList.pop_back();
  361. mFixStack.pop_back();
  362. mFixLoopStack.pop_back();
  363. }
  364. void fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint);
  365. inline void addBreakLine(U32 lineNumber, U32 ip)
  366. {
  367. mBreakLines.push_back(lineNumber);
  368. mBreakLines.push_back(ip);
  369. }
  370. inline U32 getNumLineBreaks()
  371. {
  372. return mBreakLines.size() / 2;
  373. }
  374. void emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks);
  375. void reset();
  376. };
  377. #endif