compiler.h 10 KB

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