compiler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 "compiler.h"
  25. #include "console/simBase.h"
  26. extern FuncVars gEvalFuncVars;
  27. extern FuncVars gGlobalScopeFuncVars;
  28. extern FuncVars *gFuncVars;
  29. namespace Con
  30. {
  31. extern bool scriptWarningsAsAsserts;
  32. };
  33. namespace Compiler
  34. {
  35. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  36. {
  37. F64 val = dAtof(str);
  38. if (val != 0)
  39. return val;
  40. else if (!dStricmp(str, "true"))
  41. return 1;
  42. else if (!dStricmp(str, "false"))
  43. return 0;
  44. else if (file)
  45. {
  46. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  47. return 0;
  48. }
  49. return 0;
  50. }
  51. //------------------------------------------------------------
  52. CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
  53. CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
  54. DataChunker gConsoleAllocator;
  55. CompilerIdentTable gIdentTable;
  56. CompilerLocalVariableToRegisterMappingTable gFunctionVariableMappingTable;
  57. //------------------------------------------------------------
  58. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  59. {
  60. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  61. *(U64*)(ptr) = (U64)ste;
  62. #else
  63. *ptr = (U32)ste;
  64. #endif
  65. }
  66. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  67. {
  68. if (ste)
  69. getIdentTable().add(ste, ip);
  70. *ptr = 0;
  71. *(ptr + 1) = 0;
  72. }
  73. void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr) = evalSTEtoCode;
  74. //------------------------------------------------------------
  75. bool gSyntaxError = false;
  76. bool gIsEvalCompile = false;
  77. //------------------------------------------------------------
  78. CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
  79. CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
  80. CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
  81. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable() { return gFunctionVariableMappingTable; }
  82. void setCurrentStringTable(CompilerStringTable* cst) { gCurrentStringTable = cst; }
  83. CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
  84. CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
  85. CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
  86. void setCurrentFloatTable(CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
  87. CompilerIdentTable &getIdentTable() { return gIdentTable; }
  88. void precompileIdent(StringTableEntry ident)
  89. {
  90. if (ident)
  91. gGlobalStringTable.add(ident);
  92. }
  93. void resetTables()
  94. {
  95. setCurrentStringTable(&gGlobalStringTable);
  96. setCurrentFloatTable(&gGlobalFloatTable);
  97. getGlobalFloatTable().reset();
  98. getGlobalStringTable().reset();
  99. getFunctionFloatTable().reset();
  100. getFunctionStringTable().reset();
  101. getIdentTable().reset();
  102. getFunctionVariableMappingTable().reset();
  103. gGlobalScopeFuncVars.clear();
  104. gFuncVars = gIsEvalCompile ? &gEvalFuncVars : &gGlobalScopeFuncVars;
  105. }
  106. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  107. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  108. void scriptErrorHandler(const char* str)
  109. {
  110. if (Con::scriptWarningsAsAsserts)
  111. {
  112. AssertISV(false, str);
  113. }
  114. else
  115. {
  116. Con::warnf(ConsoleLogEntry::Type::Script, "%s", str);
  117. }
  118. }
  119. }
  120. //-------------------------------------------------------------------------
  121. using namespace Compiler;
  122. S32 FuncVars::assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant)
  123. {
  124. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  125. if (found != vars.end())
  126. {
  127. // if we are calling assign more than once AND it changes type, we don't know what the variable type is as this is a
  128. // dynamically typed language. So we will assign to None and bail. None will be taken care of by the code to always
  129. // load what the default type is (What Globals and arrays use, type None).
  130. if (currentType != found->second.currentType && found->second.currentType != TypeReqNone)
  131. found->second.currentType = TypeReqNone;
  132. if (found->second.isConstant)
  133. {
  134. const char* str = avar("Script Warning: Reassigning variable %s when it is a constant. File: %s Line : %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  135. scriptErrorHandler(str);
  136. }
  137. return found->second.reg;
  138. }
  139. S32 id = counter++;
  140. vars[var] = { id, currentType, var, isConstant };
  141. variableNameMap[id] = var;
  142. return id;
  143. }
  144. S32 FuncVars::lookup(StringTableEntry var, S32 lineNumber)
  145. {
  146. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  147. if (found == vars.end())
  148. {
  149. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  150. scriptErrorHandler(str);
  151. return assign(var, TypeReqString, lineNumber, false);
  152. }
  153. return found->second.reg;
  154. }
  155. TypeReq FuncVars::lookupType(StringTableEntry var, S32 lineNumber)
  156. {
  157. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  158. if (found == vars.end())
  159. {
  160. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  161. scriptErrorHandler(str);
  162. assign(var, TypeReqString, lineNumber, false);
  163. return vars.find(var)->second.currentType;
  164. }
  165. return found->second.currentType;
  166. }
  167. void FuncVars::clear()
  168. {
  169. vars.clear();
  170. variableNameMap.clear();
  171. counter = 0;
  172. }
  173. //-------------------------------------------------------------------------
  174. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  175. {
  176. // Is it already in?
  177. Entry **walk;
  178. for (walk = &list; *walk; walk = &((*walk)->next))
  179. {
  180. if ((*walk)->tag != tag)
  181. continue;
  182. if (caseSens)
  183. {
  184. if (!String::compare((*walk)->string, str))
  185. return (*walk)->start;
  186. }
  187. else
  188. {
  189. if (!dStricmp((*walk)->string, str))
  190. return (*walk)->start;
  191. }
  192. }
  193. // Write it out.
  194. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  195. *walk = newStr;
  196. newStr->next = NULL;
  197. newStr->start = totalLen;
  198. U32 len = dStrlen(str) + 1;
  199. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  200. len = 7;
  201. totalLen += len;
  202. newStr->string = (char *)consoleAlloc(len);
  203. newStr->len = len;
  204. newStr->tag = tag;
  205. dStrcpy(newStr->string, str, len);
  206. // Put into the hash table.
  207. hashTable[str] = newStr;
  208. return newStr->start;
  209. }
  210. U32 CompilerStringTable::addIntString(U32 value)
  211. {
  212. dSprintf(buf, sizeof(buf), "%d", value);
  213. return add(buf);
  214. }
  215. U32 CompilerStringTable::addFloatString(F64 value)
  216. {
  217. dSprintf(buf, sizeof(buf), "%g", value);
  218. return add(buf);
  219. }
  220. void CompilerStringTable::reset()
  221. {
  222. list = NULL;
  223. totalLen = 0;
  224. }
  225. char *CompilerStringTable::build()
  226. {
  227. char *ret = new char[totalLen];
  228. dMemset(ret, 0, totalLen);
  229. for (Entry *walk = list; walk; walk = walk->next)
  230. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  231. return ret;
  232. }
  233. void CompilerStringTable::write(Stream &st)
  234. {
  235. st.write(totalLen);
  236. for (Entry *walk = list; walk; walk = walk->next)
  237. st.write(walk->len, walk->string);
  238. }
  239. //------------------------------------------------------------
  240. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry namespaceName, StringTableEntry varName)
  241. {
  242. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  243. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  244. }
  245. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  246. {
  247. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  248. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  249. if (functionPosition != localVarToRegister.end())
  250. {
  251. const auto& table = localVarToRegister[funcLookupTableName].varList;
  252. auto varPosition = std::find(table.begin(), table.end(), varName);
  253. if (varPosition != table.end())
  254. {
  255. return std::distance(table.begin(), varPosition);
  256. }
  257. }
  258. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  259. return -1;
  260. }
  261. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  262. {
  263. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  264. CompilerLocalVariableToRegisterMappingTable table;
  265. table.localVarToRegister = localVarToRegister;
  266. return table;
  267. }
  268. void CompilerLocalVariableToRegisterMappingTable::reset()
  269. {
  270. localVarToRegister.clear();
  271. }
  272. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  273. {
  274. stream.write((U32)localVarToRegister.size());
  275. for (const auto& pair : localVarToRegister)
  276. {
  277. StringTableEntry functionName = pair.first;
  278. stream.writeString(functionName);
  279. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  280. stream.write((U32)localVariableTableForFunction.size());
  281. for (const StringTableEntry& varName : localVariableTableForFunction)
  282. {
  283. stream.writeString(varName);
  284. }
  285. }
  286. }
  287. //------------------------------------------------------------
  288. U32 CompilerFloatTable::add(F64 value)
  289. {
  290. Entry **walk;
  291. U32 i = 0;
  292. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  293. if (value == (*walk)->val)
  294. return i;
  295. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  296. newFloat->val = value;
  297. newFloat->next = NULL;
  298. count++;
  299. *walk = newFloat;
  300. return count - 1;
  301. }
  302. void CompilerFloatTable::reset()
  303. {
  304. list = NULL;
  305. count = 0;
  306. }
  307. F64 *CompilerFloatTable::build()
  308. {
  309. F64 *ret = new F64[count];
  310. U32 i = 0;
  311. for (Entry *walk = list; walk; walk = walk->next, i++)
  312. ret[i] = walk->val;
  313. return ret;
  314. }
  315. void CompilerFloatTable::write(Stream &st)
  316. {
  317. st.write(count);
  318. for (Entry *walk = list; walk; walk = walk->next)
  319. st.write(walk->val);
  320. }
  321. //------------------------------------------------------------
  322. void CompilerIdentTable::reset()
  323. {
  324. list = NULL;
  325. }
  326. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  327. {
  328. U32 index = gGlobalStringTable.add(ste, false);
  329. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  330. newEntry->offset = index;
  331. newEntry->ip = ip;
  332. for (Entry *walk = list; walk; walk = walk->next)
  333. {
  334. if (walk->offset == index)
  335. {
  336. newEntry->nextIdent = walk->nextIdent;
  337. walk->nextIdent = newEntry;
  338. return;
  339. }
  340. }
  341. newEntry->next = list;
  342. list = newEntry;
  343. newEntry->nextIdent = NULL;
  344. }
  345. void CompilerIdentTable::write(Stream &st)
  346. {
  347. U32 count = 0;
  348. Entry * walk;
  349. for (walk = list; walk; walk = walk->next)
  350. count++;
  351. st.write(count);
  352. for (walk = list; walk; walk = walk->next)
  353. {
  354. U32 ec = 0;
  355. Entry * el;
  356. for (el = walk; el; el = el->nextIdent)
  357. ec++;
  358. st.write(walk->offset);
  359. st.write(ec);
  360. for (el = walk; el; el = el->nextIdent)
  361. st.write(el->ip);
  362. }
  363. }
  364. //-------------------------------------------------------------------------
  365. U8 *CodeStream::allocCode(U32 sz)
  366. {
  367. U8 *ptr = NULL;
  368. if (mCodeHead)
  369. {
  370. const U32 bytesLeft = BlockSize - mCodeHead->size;
  371. if (bytesLeft > sz)
  372. {
  373. ptr = mCodeHead->data + mCodeHead->size;
  374. mCodeHead->size += sz;
  375. return ptr;
  376. }
  377. }
  378. CodeData *data = new CodeData;
  379. data->data = (U8*)dMalloc(BlockSize);
  380. data->size = sz;
  381. data->next = NULL;
  382. if (mCodeHead)
  383. mCodeHead->next = data;
  384. mCodeHead = data;
  385. if (mCode == NULL)
  386. mCode = data;
  387. return data->data;
  388. }
  389. //-------------------------------------------------------------------------
  390. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  391. {
  392. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  393. U32 fixStart = mFixStack[mFixStack.size() - 1];
  394. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  395. {
  396. FixType type = (FixType)mFixList[i + 1];
  397. U32 fixedIp = 0;
  398. bool valid = true;
  399. switch (type)
  400. {
  401. case FIXTYPE_LOOPBLOCKSTART:
  402. fixedIp = loopBlockStart;
  403. break;
  404. case FIXTYPE_BREAK:
  405. fixedIp = breakPoint;
  406. break;
  407. case FIXTYPE_CONTINUE:
  408. fixedIp = continuePoint;
  409. break;
  410. default:
  411. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  412. valid = false;
  413. break;
  414. }
  415. if (valid)
  416. {
  417. patch(mFixList[i], fixedIp);
  418. }
  419. }
  420. }
  421. //-------------------------------------------------------------------------
  422. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  423. {
  424. // Alloc stream
  425. U32 numLineBreaks = getNumLineBreaks();
  426. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  427. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  428. *size = mCodePos;
  429. // Dump chunks & line breaks
  430. U32 outBytes = mCodePos * sizeof(U32);
  431. U8 *outPtr = *((U8**)stream);
  432. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  433. {
  434. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  435. dMemcpy(outPtr, itr->data, bytesToCopy);
  436. outPtr += bytesToCopy;
  437. outBytes -= bytesToCopy;
  438. }
  439. *lineBreaks = *stream + mCodePos;
  440. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  441. // Apply patches on top
  442. for (U32 i = 0; i<mPatchList.size(); i++)
  443. {
  444. PatchEntry &e = mPatchList[i];
  445. (*stream)[e.addr] = e.value;
  446. }
  447. }
  448. //-------------------------------------------------------------------------
  449. void CodeStream::reset()
  450. {
  451. mCodePos = 0;
  452. mFixStack.clear();
  453. mFixLoopStack.clear();
  454. mFixList.clear();
  455. mBreakLines.clear();
  456. // Pop down to one code block
  457. CodeData *itr = mCode ? mCode->next : NULL;
  458. while (itr != NULL)
  459. {
  460. CodeData *next = itr->next;
  461. dFree(itr->data);
  462. delete(itr);
  463. itr = next;
  464. }
  465. if (mCode)
  466. {
  467. mCode->size = 0;
  468. mCode->next = NULL;
  469. mCodeHead = mCode;
  470. }
  471. }