compiler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "console/telnetDebugger.h"
  25. #include "console/ast.h"
  26. #include "core/tAlgorithm.h"
  27. #include "core/strings/findMatch.h"
  28. #include "console/consoleInternal.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/compiler.h"
  31. #include "console/simBase.h"
  32. namespace Compiler
  33. {
  34. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  35. {
  36. F64 val = dAtof(str);
  37. if (val != 0)
  38. return val;
  39. else if (!dStricmp(str, "true"))
  40. return 1;
  41. else if (!dStricmp(str, "false"))
  42. return 0;
  43. else if (file)
  44. {
  45. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  46. return 0;
  47. }
  48. return 0;
  49. }
  50. //------------------------------------------------------------
  51. CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
  52. CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
  53. DataChunker gConsoleAllocator;
  54. CompilerIdentTable gIdentTable;
  55. CompilerLocalVariableToRegisterMappingTable gFunctionVariableMappingTable;
  56. //------------------------------------------------------------
  57. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  58. {
  59. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  60. *(U64*)(ptr) = (U64)ste;
  61. #else
  62. *ptr = (U32)ste;
  63. #endif
  64. }
  65. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  66. {
  67. if (ste)
  68. getIdentTable().add(ste, ip);
  69. *ptr = 0;
  70. *(ptr + 1) = 0;
  71. }
  72. void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr) = evalSTEtoCode;
  73. //------------------------------------------------------------
  74. bool gSyntaxError = false;
  75. //------------------------------------------------------------
  76. CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
  77. CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
  78. CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
  79. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable() { return gFunctionVariableMappingTable; }
  80. void setCurrentStringTable(CompilerStringTable* cst) { gCurrentStringTable = cst; }
  81. CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
  82. CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
  83. CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
  84. void setCurrentFloatTable(CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
  85. CompilerIdentTable &getIdentTable() { return gIdentTable; }
  86. void precompileIdent(StringTableEntry ident)
  87. {
  88. if (ident)
  89. gGlobalStringTable.add(ident);
  90. }
  91. void resetTables()
  92. {
  93. setCurrentStringTable(&gGlobalStringTable);
  94. setCurrentFloatTable(&gGlobalFloatTable);
  95. getGlobalFloatTable().reset();
  96. getGlobalStringTable().reset();
  97. getFunctionFloatTable().reset();
  98. getFunctionStringTable().reset();
  99. getIdentTable().reset();
  100. getFunctionVariableMappingTable().reset();
  101. }
  102. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  103. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  104. }
  105. //-------------------------------------------------------------------------
  106. using namespace Compiler;
  107. //-------------------------------------------------------------------------
  108. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  109. {
  110. // Is it already in?
  111. Entry **walk;
  112. for (walk = &list; *walk; walk = &((*walk)->next))
  113. {
  114. if ((*walk)->tag != tag)
  115. continue;
  116. if (caseSens)
  117. {
  118. if (!String::compare((*walk)->string, str))
  119. return (*walk)->start;
  120. }
  121. else
  122. {
  123. if (!dStricmp((*walk)->string, str))
  124. return (*walk)->start;
  125. }
  126. }
  127. // Write it out.
  128. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  129. *walk = newStr;
  130. newStr->next = NULL;
  131. newStr->start = totalLen;
  132. U32 len = dStrlen(str) + 1;
  133. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  134. len = 7;
  135. totalLen += len;
  136. newStr->string = (char *)consoleAlloc(len);
  137. newStr->len = len;
  138. newStr->tag = tag;
  139. dStrcpy(newStr->string, str, len);
  140. // Put into the hash table.
  141. hashTable[str] = newStr;
  142. return newStr->start;
  143. }
  144. U32 CompilerStringTable::addIntString(U32 value)
  145. {
  146. dSprintf(buf, sizeof(buf), "%d", value);
  147. return add(buf);
  148. }
  149. U32 CompilerStringTable::addFloatString(F64 value)
  150. {
  151. dSprintf(buf, sizeof(buf), "%g", value);
  152. return add(buf);
  153. }
  154. void CompilerStringTable::reset()
  155. {
  156. list = NULL;
  157. totalLen = 0;
  158. }
  159. char *CompilerStringTable::build()
  160. {
  161. char *ret = new char[totalLen];
  162. dMemset(ret, 0, totalLen);
  163. for (Entry *walk = list; walk; walk = walk->next)
  164. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  165. return ret;
  166. }
  167. void CompilerStringTable::write(Stream &st)
  168. {
  169. st.write(totalLen);
  170. for (Entry *walk = list; walk; walk = walk->next)
  171. st.write(walk->len, walk->string);
  172. }
  173. //------------------------------------------------------------
  174. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry varName, S32 reg)
  175. {
  176. localVarToRegister[functionName].table[varName] = reg;
  177. }
  178. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry functionName, StringTableEntry varName)
  179. {
  180. auto functionPosition = localVarToRegister.find(functionName);
  181. if (functionPosition != localVarToRegister.end())
  182. {
  183. const auto& table = localVarToRegister[functionName].table;
  184. auto varPosition = table.find(varName);
  185. if (varPosition != table.end())
  186. {
  187. return varPosition->second;
  188. }
  189. }
  190. Con::errorf("Unable to find local variable %s in function name %s", varName, functionName);
  191. return -1;
  192. }
  193. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  194. {
  195. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  196. CompilerLocalVariableToRegisterMappingTable table;
  197. table.localVarToRegister = localVarToRegister;
  198. return std::move(table);
  199. }
  200. void CompilerLocalVariableToRegisterMappingTable::reset()
  201. {
  202. localVarToRegister.clear();
  203. }
  204. //------------------------------------------------------------
  205. U32 CompilerFloatTable::add(F64 value)
  206. {
  207. Entry **walk;
  208. U32 i = 0;
  209. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  210. if (value == (*walk)->val)
  211. return i;
  212. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  213. newFloat->val = value;
  214. newFloat->next = NULL;
  215. count++;
  216. *walk = newFloat;
  217. return count - 1;
  218. }
  219. void CompilerFloatTable::reset()
  220. {
  221. list = NULL;
  222. count = 0;
  223. }
  224. F64 *CompilerFloatTable::build()
  225. {
  226. F64 *ret = new F64[count];
  227. U32 i = 0;
  228. for (Entry *walk = list; walk; walk = walk->next, i++)
  229. ret[i] = walk->val;
  230. return ret;
  231. }
  232. void CompilerFloatTable::write(Stream &st)
  233. {
  234. st.write(count);
  235. for (Entry *walk = list; walk; walk = walk->next)
  236. st.write(walk->val);
  237. }
  238. //------------------------------------------------------------
  239. void CompilerIdentTable::reset()
  240. {
  241. list = NULL;
  242. }
  243. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  244. {
  245. U32 index = gGlobalStringTable.add(ste, false);
  246. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  247. newEntry->offset = index;
  248. newEntry->ip = ip;
  249. for (Entry *walk = list; walk; walk = walk->next)
  250. {
  251. if (walk->offset == index)
  252. {
  253. newEntry->nextIdent = walk->nextIdent;
  254. walk->nextIdent = newEntry;
  255. return;
  256. }
  257. }
  258. newEntry->next = list;
  259. list = newEntry;
  260. newEntry->nextIdent = NULL;
  261. }
  262. void CompilerIdentTable::write(Stream &st)
  263. {
  264. U32 count = 0;
  265. Entry * walk;
  266. for (walk = list; walk; walk = walk->next)
  267. count++;
  268. st.write(count);
  269. for (walk = list; walk; walk = walk->next)
  270. {
  271. U32 ec = 0;
  272. Entry * el;
  273. for (el = walk; el; el = el->nextIdent)
  274. ec++;
  275. st.write(walk->offset);
  276. st.write(ec);
  277. for (el = walk; el; el = el->nextIdent)
  278. st.write(el->ip);
  279. }
  280. }
  281. //-------------------------------------------------------------------------
  282. U8 *CodeStream::allocCode(U32 sz)
  283. {
  284. U8 *ptr = NULL;
  285. if (mCodeHead)
  286. {
  287. const U32 bytesLeft = BlockSize - mCodeHead->size;
  288. if (bytesLeft > sz)
  289. {
  290. ptr = mCodeHead->data + mCodeHead->size;
  291. mCodeHead->size += sz;
  292. return ptr;
  293. }
  294. }
  295. CodeData *data = new CodeData;
  296. data->data = (U8*)dMalloc(BlockSize);
  297. data->size = sz;
  298. data->next = NULL;
  299. if (mCodeHead)
  300. mCodeHead->next = data;
  301. mCodeHead = data;
  302. if (mCode == NULL)
  303. mCode = data;
  304. return data->data;
  305. }
  306. //-------------------------------------------------------------------------
  307. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  308. {
  309. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  310. U32 fixStart = mFixStack[mFixStack.size() - 1];
  311. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  312. {
  313. FixType type = (FixType)mFixList[i + 1];
  314. U32 fixedIp = 0;
  315. bool valid = true;
  316. switch (type)
  317. {
  318. case FIXTYPE_LOOPBLOCKSTART:
  319. fixedIp = loopBlockStart;
  320. break;
  321. case FIXTYPE_BREAK:
  322. fixedIp = breakPoint;
  323. break;
  324. case FIXTYPE_CONTINUE:
  325. fixedIp = continuePoint;
  326. break;
  327. default:
  328. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  329. valid = false;
  330. break;
  331. }
  332. if (valid)
  333. {
  334. patch(mFixList[i], fixedIp);
  335. }
  336. }
  337. }
  338. //-------------------------------------------------------------------------
  339. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  340. {
  341. // Alloc stream
  342. U32 numLineBreaks = getNumLineBreaks();
  343. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  344. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  345. *size = mCodePos;
  346. // Dump chunks & line breaks
  347. U32 outBytes = mCodePos * sizeof(U32);
  348. U8 *outPtr = *((U8**)stream);
  349. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  350. {
  351. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  352. dMemcpy(outPtr, itr->data, bytesToCopy);
  353. outPtr += bytesToCopy;
  354. outBytes -= bytesToCopy;
  355. }
  356. *lineBreaks = *stream + mCodePos;
  357. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  358. // Apply patches on top
  359. for (U32 i = 0; i<mPatchList.size(); i++)
  360. {
  361. PatchEntry &e = mPatchList[i];
  362. (*stream)[e.addr] = e.value;
  363. }
  364. }
  365. //-------------------------------------------------------------------------
  366. void CodeStream::reset()
  367. {
  368. mCodePos = 0;
  369. mFixStack.clear();
  370. mFixLoopStack.clear();
  371. mFixList.clear();
  372. mBreakLines.clear();
  373. // Pop down to one code block
  374. CodeData *itr = mCode ? mCode->next : NULL;
  375. while (itr != NULL)
  376. {
  377. CodeData *next = itr->next;
  378. dFree(itr->data);
  379. delete(itr);
  380. itr = next;
  381. }
  382. if (mCode)
  383. {
  384. mCode->size = 0;
  385. mCode->next = NULL;
  386. mCodeHead = mCode;
  387. }
  388. }