compiler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 namespaceName, StringTableEntry varName)
  175. {
  176. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  177. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  178. }
  179. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  180. {
  181. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  182. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  183. if (functionPosition != localVarToRegister.end())
  184. {
  185. const auto& table = localVarToRegister[funcLookupTableName].varList;
  186. auto varPosition = std::find(table.begin(), table.end(), varName);
  187. if (varPosition != table.end())
  188. {
  189. return std::distance(table.begin(), varPosition);
  190. }
  191. }
  192. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  193. return -1;
  194. }
  195. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  196. {
  197. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  198. CompilerLocalVariableToRegisterMappingTable table;
  199. table.localVarToRegister = localVarToRegister;
  200. return table;
  201. }
  202. void CompilerLocalVariableToRegisterMappingTable::reset()
  203. {
  204. localVarToRegister.clear();
  205. }
  206. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  207. {
  208. stream.write((U32)localVarToRegister.size());
  209. for (const auto& pair : localVarToRegister)
  210. {
  211. StringTableEntry functionName = pair.first;
  212. stream.writeString(functionName);
  213. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  214. stream.write((U32)localVariableTableForFunction.size());
  215. for (const StringTableEntry& varName : localVariableTableForFunction)
  216. {
  217. stream.writeString(varName);
  218. }
  219. }
  220. }
  221. //------------------------------------------------------------
  222. U32 CompilerFloatTable::add(F64 value)
  223. {
  224. Entry **walk;
  225. U32 i = 0;
  226. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  227. if (value == (*walk)->val)
  228. return i;
  229. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  230. newFloat->val = value;
  231. newFloat->next = NULL;
  232. count++;
  233. *walk = newFloat;
  234. return count - 1;
  235. }
  236. void CompilerFloatTable::reset()
  237. {
  238. list = NULL;
  239. count = 0;
  240. }
  241. F64 *CompilerFloatTable::build()
  242. {
  243. F64 *ret = new F64[count];
  244. U32 i = 0;
  245. for (Entry *walk = list; walk; walk = walk->next, i++)
  246. ret[i] = walk->val;
  247. return ret;
  248. }
  249. void CompilerFloatTable::write(Stream &st)
  250. {
  251. st.write(count);
  252. for (Entry *walk = list; walk; walk = walk->next)
  253. st.write(walk->val);
  254. }
  255. //------------------------------------------------------------
  256. void CompilerIdentTable::reset()
  257. {
  258. list = NULL;
  259. }
  260. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  261. {
  262. U32 index = gGlobalStringTable.add(ste, false);
  263. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  264. newEntry->offset = index;
  265. newEntry->ip = ip;
  266. for (Entry *walk = list; walk; walk = walk->next)
  267. {
  268. if (walk->offset == index)
  269. {
  270. newEntry->nextIdent = walk->nextIdent;
  271. walk->nextIdent = newEntry;
  272. return;
  273. }
  274. }
  275. newEntry->next = list;
  276. list = newEntry;
  277. newEntry->nextIdent = NULL;
  278. }
  279. void CompilerIdentTable::write(Stream &st)
  280. {
  281. U32 count = 0;
  282. Entry * walk;
  283. for (walk = list; walk; walk = walk->next)
  284. count++;
  285. st.write(count);
  286. for (walk = list; walk; walk = walk->next)
  287. {
  288. U32 ec = 0;
  289. Entry * el;
  290. for (el = walk; el; el = el->nextIdent)
  291. ec++;
  292. st.write(walk->offset);
  293. st.write(ec);
  294. for (el = walk; el; el = el->nextIdent)
  295. st.write(el->ip);
  296. }
  297. }
  298. //-------------------------------------------------------------------------
  299. U8 *CodeStream::allocCode(U32 sz)
  300. {
  301. U8 *ptr = NULL;
  302. if (mCodeHead)
  303. {
  304. const U32 bytesLeft = BlockSize - mCodeHead->size;
  305. if (bytesLeft > sz)
  306. {
  307. ptr = mCodeHead->data + mCodeHead->size;
  308. mCodeHead->size += sz;
  309. return ptr;
  310. }
  311. }
  312. CodeData *data = new CodeData;
  313. data->data = (U8*)dMalloc(BlockSize);
  314. data->size = sz;
  315. data->next = NULL;
  316. if (mCodeHead)
  317. mCodeHead->next = data;
  318. mCodeHead = data;
  319. if (mCode == NULL)
  320. mCode = data;
  321. return data->data;
  322. }
  323. //-------------------------------------------------------------------------
  324. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  325. {
  326. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  327. U32 fixStart = mFixStack[mFixStack.size() - 1];
  328. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  329. {
  330. FixType type = (FixType)mFixList[i + 1];
  331. U32 fixedIp = 0;
  332. bool valid = true;
  333. switch (type)
  334. {
  335. case FIXTYPE_LOOPBLOCKSTART:
  336. fixedIp = loopBlockStart;
  337. break;
  338. case FIXTYPE_BREAK:
  339. fixedIp = breakPoint;
  340. break;
  341. case FIXTYPE_CONTINUE:
  342. fixedIp = continuePoint;
  343. break;
  344. default:
  345. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  346. valid = false;
  347. break;
  348. }
  349. if (valid)
  350. {
  351. patch(mFixList[i], fixedIp);
  352. }
  353. }
  354. }
  355. //-------------------------------------------------------------------------
  356. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  357. {
  358. // Alloc stream
  359. U32 numLineBreaks = getNumLineBreaks();
  360. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  361. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  362. *size = mCodePos;
  363. // Dump chunks & line breaks
  364. U32 outBytes = mCodePos * sizeof(U32);
  365. U8 *outPtr = *((U8**)stream);
  366. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  367. {
  368. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  369. dMemcpy(outPtr, itr->data, bytesToCopy);
  370. outPtr += bytesToCopy;
  371. outBytes -= bytesToCopy;
  372. }
  373. *lineBreaks = *stream + mCodePos;
  374. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  375. // Apply patches on top
  376. for (U32 i = 0; i<mPatchList.size(); i++)
  377. {
  378. PatchEntry &e = mPatchList[i];
  379. (*stream)[e.addr] = e.value;
  380. }
  381. }
  382. //-------------------------------------------------------------------------
  383. void CodeStream::reset()
  384. {
  385. mCodePos = 0;
  386. mFixStack.clear();
  387. mFixLoopStack.clear();
  388. mFixList.clear();
  389. mBreakLines.clear();
  390. // Pop down to one code block
  391. CodeData *itr = mCode ? mCode->next : NULL;
  392. while (itr != NULL)
  393. {
  394. CodeData *next = itr->next;
  395. dFree(itr->data);
  396. delete(itr);
  397. itr = next;
  398. }
  399. if (mCode)
  400. {
  401. mCode->size = 0;
  402. mCode->next = NULL;
  403. mCodeHead = mCode;
  404. }
  405. }