BytecodeGenerator.cpp 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513
  1. /*
  2. * Copyright (C) 2008, 2009, 2012, 2013 Apple Inc. All rights reserved.
  3. * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
  4. * Copyright (C) 2012 Igalia, S.L.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
  16. * its contributors may be used to endorse or promote products derived
  17. * from this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
  20. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  21. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22. * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
  23. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  25. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  26. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  28. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "config.h"
  31. #include "BytecodeGenerator.h"
  32. #include "BatchedTransitionOptimizer.h"
  33. #include "Interpreter.h"
  34. #include "JSActivation.h"
  35. #include "JSFunction.h"
  36. #include "JSNameScope.h"
  37. #include "LowLevelInterpreter.h"
  38. #include "Operations.h"
  39. #include "Options.h"
  40. #include "StrongInlines.h"
  41. #include "UnlinkedCodeBlock.h"
  42. #include <wtf/text/WTFString.h>
  43. using namespace std;
  44. namespace JSC {
  45. void Label::setLocation(unsigned location)
  46. {
  47. m_location = location;
  48. unsigned size = m_unresolvedJumps.size();
  49. for (unsigned i = 0; i < size; ++i)
  50. m_generator->m_instructions[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
  51. }
  52. #ifndef NDEBUG
  53. void ResolveResult::checkValidity()
  54. {
  55. switch (m_type) {
  56. case Register:
  57. case ReadOnlyRegister:
  58. ASSERT(m_local);
  59. return;
  60. case Dynamic:
  61. ASSERT(!m_local);
  62. return;
  63. case Lexical:
  64. case ReadOnlyLexical:
  65. ASSERT(!m_local);
  66. return;
  67. default:
  68. RELEASE_ASSERT_NOT_REACHED();
  69. }
  70. }
  71. #endif
  72. ParserError BytecodeGenerator::generate()
  73. {
  74. SamplingRegion samplingRegion("Bytecode Generation");
  75. m_codeBlock->setThisRegister(m_thisRegister.index());
  76. m_scopeNode->emitBytecode(*this);
  77. m_staticPropertyAnalyzer.kill();
  78. for (unsigned i = 0; i < m_tryRanges.size(); ++i) {
  79. TryRange& range = m_tryRanges[i];
  80. int start = range.start->bind();
  81. int end = range.end->bind();
  82. // This will happen for empty try blocks and for some cases of finally blocks:
  83. //
  84. // try {
  85. // try {
  86. // } finally {
  87. // return 42;
  88. // // *HERE*
  89. // }
  90. // } finally {
  91. // print("things");
  92. // }
  93. //
  94. // The return will pop scopes to execute the outer finally block. But this includes
  95. // popping the try context for the inner try. The try context is live in the fall-through
  96. // part of the finally block not because we will emit a handler that overlaps the finally,
  97. // but because we haven't yet had a chance to plant the catch target. Then when we finish
  98. // emitting code for the outer finally block, we repush the try contex, this time with a
  99. // new start index. But that means that the start index for the try range corresponding
  100. // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
  101. // than the end index of the try block. This is harmless since end < start handlers will
  102. // never get matched in our logic, but we do the runtime a favor and choose to not emit
  103. // such handlers at all.
  104. if (end <= start)
  105. continue;
  106. ASSERT(range.tryData->targetScopeDepth != UINT_MAX);
  107. UnlinkedHandlerInfo info = {
  108. static_cast<uint32_t>(start), static_cast<uint32_t>(end),
  109. static_cast<uint32_t>(range.tryData->target->bind()),
  110. range.tryData->targetScopeDepth
  111. };
  112. m_codeBlock->addExceptionHandler(info);
  113. }
  114. m_codeBlock->instructions() = RefCountedArray_shared<UnlinkedInstruction>(m_instructions);
  115. m_codeBlock->shrinkToFit();
  116. if (m_expressionTooDeep)
  117. return ParserError(ParserError::OutOfMemory);
  118. return ParserError(ParserError::ErrorNone);
  119. }
  120. bool BytecodeGenerator::addVar(const Identifier& ident, bool isConstant, RegisterID*& r0)
  121. {
  122. int index = m_calleeRegisters.size();
  123. SymbolTableEntry newEntry(index, isConstant ? ReadOnly : 0);
  124. SymbolTable::AddResult result = symbolTable().add(ident.impl(), newEntry);
  125. if (!result.isNewEntry) {
  126. r0 = &registerFor(result.iterator->value.getIndex());
  127. return false;
  128. }
  129. r0 = addVar();
  130. return true;
  131. }
  132. void BytecodeGenerator::preserveLastVar()
  133. {
  134. if ((m_firstConstantIndex = m_calleeRegisters.size()) != 0)
  135. m_lastVar = &m_calleeRegisters.last();
  136. }
  137. BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope*, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
  138. : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn)
  139. , m_shouldEmitProfileHooks(profilerMode == ProfilerOn)
  140. , m_symbolTable(0)
  141. , m_scopeNode(programNode)
  142. , m_codeBlock(vm, codeBlock)
  143. , m_thisRegister(CallFrame::thisArgumentOffset())
  144. , m_emptyValueRegister(0)
  145. , m_globalObjectRegister(0)
  146. , m_finallyDepth(0)
  147. , m_dynamicScopeDepth(0)
  148. , m_codeType(GlobalCode)
  149. , m_nextConstantOffset(0)
  150. , m_globalConstantIndex(0)
  151. , m_hasCreatedActivation(true)
  152. , m_firstLazyFunction(0)
  153. , m_lastLazyFunction(0)
  154. , m_staticPropertyAnalyzer(&m_instructions)
  155. , m_vm(&vm)
  156. , m_lastOpcodeID(op_end)
  157. #ifndef NDEBUG
  158. , m_lastOpcodePosition(0)
  159. #endif
  160. , m_stack(wtfThreadData().stack())
  161. , m_usesExceptions(false)
  162. , m_expressionTooDeep(false)
  163. {
  164. if (m_shouldEmitDebugHooks)
  165. m_codeBlock->setNeedsFullScopeChain(true);
  166. m_codeBlock->setNumParameters(1); // Allocate space for "this"
  167. emitOpcode(op_enter);
  168. const VarStack& varStack = programNode->varStack();
  169. const FunctionStack& functionStack = programNode->functionStack();
  170. for (size_t i = 0; i < functionStack.size(); ++i) {
  171. FunctionBodyNode* function = functionStack[i];
  172. UnlinkedFunctionExecutable* unlinkedFunction = makeFunction(function);
  173. codeBlock->addFunctionDeclaration(*m_vm, function->ident(), unlinkedFunction);
  174. }
  175. for (size_t i = 0; i < varStack.size(); ++i)
  176. codeBlock->addVariableDeclaration(*varStack[i].first, !!(varStack[i].second & DeclarationStacks::IsConstant));
  177. }
  178. BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, FunctionBodyNode* functionBody, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
  179. : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn)
  180. , m_shouldEmitProfileHooks(profilerMode == ProfilerOn)
  181. , m_symbolTable(codeBlock->symbolTable())
  182. , m_scopeNode(functionBody)
  183. , m_scope(vm, scope)
  184. , m_codeBlock(vm, codeBlock)
  185. , m_activationRegister(0)
  186. , m_emptyValueRegister(0)
  187. , m_globalObjectRegister(0)
  188. , m_finallyDepth(0)
  189. , m_dynamicScopeDepth(0)
  190. , m_codeType(FunctionCode)
  191. , m_nextConstantOffset(0)
  192. , m_globalConstantIndex(0)
  193. , m_hasCreatedActivation(false)
  194. , m_firstLazyFunction(0)
  195. , m_lastLazyFunction(0)
  196. , m_staticPropertyAnalyzer(&m_instructions)
  197. , m_vm(&vm)
  198. , m_lastOpcodeID(op_end)
  199. #ifndef NDEBUG
  200. , m_lastOpcodePosition(0)
  201. #endif
  202. , m_stack(wtfThreadData().stack())
  203. , m_usesExceptions(false)
  204. , m_expressionTooDeep(false)
  205. {
  206. if (m_shouldEmitDebugHooks)
  207. m_codeBlock->setNeedsFullScopeChain(true);
  208. m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode());
  209. m_symbolTable->setParameterCountIncludingThis(functionBody->parameters()->size() + 1);
  210. emitOpcode(op_enter);
  211. if (m_codeBlock->needsFullScopeChain()) {
  212. m_activationRegister = addVar();
  213. emitInitLazyRegister(m_activationRegister);
  214. m_codeBlock->setActivationRegister(m_activationRegister->index());
  215. }
  216. m_symbolTable->setCaptureStart(m_codeBlock->m_numVars);
  217. if (functionBody->usesArguments() || codeBlock->usesEval() || m_shouldEmitDebugHooks) { // May reify arguments object.
  218. RegisterID* unmodifiedArgumentsRegister = addVar(); // Anonymous, so it can't be modified by user code.
  219. RegisterID* argumentsRegister = addVar(propertyNames().arguments, false); // Can be changed by assigning to 'arguments'.
  220. // We can save a little space by hard-coding the knowledge that the two
  221. // 'arguments' values are stored in consecutive registers, and storing
  222. // only the index of the assignable one.
  223. codeBlock->setArgumentsRegister(argumentsRegister->index());
  224. ASSERT_UNUSED(unmodifiedArgumentsRegister, unmodifiedArgumentsRegister->index() == JSC::unmodifiedArgumentsRegister(codeBlock->argumentsRegister()));
  225. emitInitLazyRegister(argumentsRegister);
  226. emitInitLazyRegister(unmodifiedArgumentsRegister);
  227. if (m_codeBlock->isStrictMode()) {
  228. emitOpcode(op_create_arguments);
  229. instructions().append(argumentsRegister->index());
  230. }
  231. // The debugger currently retrieves the arguments object from an activation rather than pulling
  232. // it from a call frame. In the long-term it should stop doing that (<rdar://problem/6911886>),
  233. // but for now we force eager creation of the arguments object when debugging.
  234. if (m_shouldEmitDebugHooks) {
  235. emitOpcode(op_create_arguments);
  236. instructions().append(argumentsRegister->index());
  237. }
  238. }
  239. bool shouldCaptureAllTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
  240. bool capturesAnyArgumentByName = false;
  241. Vector<RegisterID*, 0, UnsafeVectorOverflow> capturedArguments;
  242. if (functionBody->hasCapturedVariables() || shouldCaptureAllTheThings) {
  243. FunctionParameters& parameters = *functionBody->parameters();
  244. capturedArguments.resize(parameters.size());
  245. for (size_t i = 0; i < parameters.size(); ++i) {
  246. capturedArguments[i] = 0;
  247. if (!functionBody->captures(parameters.at(i)) && !shouldCaptureAllTheThings)
  248. continue;
  249. capturesAnyArgumentByName = true;
  250. capturedArguments[i] = addVar();
  251. }
  252. }
  253. if (capturesAnyArgumentByName && !codeBlock->isStrictMode()) {
  254. size_t parameterCount = m_symbolTable->parameterCount();
  255. OwnArrayPtr<SlowArgument> slowArguments = adoptArrayPtr(new SlowArgument[parameterCount]);
  256. for (size_t i = 0; i < parameterCount; ++i) {
  257. if (!capturedArguments[i]) {
  258. ASSERT(slowArguments[i].status == SlowArgument::Normal);
  259. slowArguments[i].index = CallFrame::argumentOffset(i);
  260. continue;
  261. }
  262. slowArguments[i].status = SlowArgument::Captured;
  263. slowArguments[i].index = capturedArguments[i]->index();
  264. }
  265. m_symbolTable->setSlowArguments(slowArguments.release());
  266. }
  267. RegisterID* calleeRegister = resolveCallee(functionBody); // May push to the scope chain and/or add a captured var.
  268. const DeclarationStacks::FunctionStack& functionStack = functionBody->functionStack();
  269. const DeclarationStacks::VarStack& varStack = functionBody->varStack();
  270. // Captured variables and functions go first so that activations don't have
  271. // to step over the non-captured locals to mark them.
  272. m_hasCreatedActivation = false;
  273. if (functionBody->hasCapturedVariables()) {
  274. for (size_t i = 0; i < functionStack.size(); ++i) {
  275. FunctionBodyNode* function = functionStack[i];
  276. const Identifier& ident = function->ident();
  277. if (functionBody->captures(ident)) {
  278. if (!m_hasCreatedActivation) {
  279. m_hasCreatedActivation = true;
  280. emitOpcode(op_create_activation);
  281. instructions().append(m_activationRegister->index());
  282. }
  283. m_functions.add(ident.impl());
  284. emitNewFunction(addVar(ident, false), function);
  285. }
  286. }
  287. for (size_t i = 0; i < varStack.size(); ++i) {
  288. const Identifier& ident = *varStack[i].first;
  289. if (functionBody->captures(ident))
  290. addVar(ident, varStack[i].second & DeclarationStacks::IsConstant);
  291. }
  292. }
  293. bool canLazilyCreateFunctions = !functionBody->needsActivationForMoreThanVariables() && !m_shouldEmitDebugHooks;
  294. if (!canLazilyCreateFunctions && !m_hasCreatedActivation) {
  295. m_hasCreatedActivation = true;
  296. emitOpcode(op_create_activation);
  297. instructions().append(m_activationRegister->index());
  298. }
  299. m_symbolTable->setCaptureEnd(codeBlock->m_numVars);
  300. m_firstLazyFunction = codeBlock->m_numVars;
  301. for (size_t i = 0; i < functionStack.size(); ++i) {
  302. FunctionBodyNode* function = functionStack[i];
  303. const Identifier& ident = function->ident();
  304. if (!functionBody->captures(ident)) {
  305. m_functions.add(ident.impl());
  306. RefPtr<RegisterID> reg = addVar(ident, false);
  307. // Don't lazily create functions that override the name 'arguments'
  308. // as this would complicate lazy instantiation of actual arguments.
  309. if (!canLazilyCreateFunctions || ident == propertyNames().arguments)
  310. emitNewFunction(reg.get(), function);
  311. else {
  312. emitInitLazyRegister(reg.get());
  313. m_lazyFunctions.set(reg->index(), function);
  314. }
  315. }
  316. }
  317. m_lastLazyFunction = canLazilyCreateFunctions ? codeBlock->m_numVars : m_firstLazyFunction;
  318. for (size_t i = 0; i < varStack.size(); ++i) {
  319. const Identifier& ident = *varStack[i].first;
  320. if (!functionBody->captures(ident))
  321. addVar(ident, varStack[i].second & DeclarationStacks::IsConstant);
  322. }
  323. if (shouldCaptureAllTheThings)
  324. m_symbolTable->setCaptureEnd(codeBlock->m_numVars);
  325. FunctionParameters& parameters = *functionBody->parameters();
  326. m_parameters.grow(parameters.size() + 1); // reserve space for "this"
  327. // Add "this" as a parameter
  328. int nextParameterIndex = CallFrame::thisArgumentOffset();
  329. m_thisRegister.setIndex(nextParameterIndex--);
  330. m_codeBlock->addParameter();
  331. for (size_t i = 0; i < parameters.size(); ++i, --nextParameterIndex) {
  332. int index = nextParameterIndex;
  333. if (capturedArguments.size() && capturedArguments[i]) {
  334. ASSERT((functionBody->hasCapturedVariables() && functionBody->captures(parameters.at(i))) || shouldCaptureAllTheThings);
  335. index = capturedArguments[i]->index();
  336. RegisterID original(nextParameterIndex);
  337. emitMove(capturedArguments[i], &original);
  338. }
  339. addParameter(parameters.at(i), index);
  340. }
  341. preserveLastVar();
  342. // We declare the callee's name last because it should lose to a var, function, and/or parameter declaration.
  343. addCallee(functionBody, calleeRegister);
  344. if (isConstructor()) {
  345. emitCreateThis(&m_thisRegister);
  346. } else if (!codeBlock->isStrictMode() && (functionBody->usesThis() || codeBlock->usesEval() || m_shouldEmitDebugHooks)) {
  347. UnlinkedValueProfile profile = emitProfiledOpcode(op_convert_this);
  348. instructions().append(kill(&m_thisRegister));
  349. instructions().append(profile);
  350. }
  351. }
  352. BytecodeGenerator::BytecodeGenerator(VM& vm, JSScope* scope, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, ProfilerMode profilerMode)
  353. : m_shouldEmitDebugHooks(debuggerMode == DebuggerOn)
  354. , m_shouldEmitProfileHooks(profilerMode == ProfilerOn)
  355. , m_symbolTable(codeBlock->symbolTable())
  356. , m_scopeNode(evalNode)
  357. , m_scope(vm, scope)
  358. , m_codeBlock(vm, codeBlock)
  359. , m_thisRegister(CallFrame::thisArgumentOffset())
  360. , m_emptyValueRegister(0)
  361. , m_globalObjectRegister(0)
  362. , m_finallyDepth(0)
  363. , m_dynamicScopeDepth(0)
  364. , m_codeType(EvalCode)
  365. , m_nextConstantOffset(0)
  366. , m_globalConstantIndex(0)
  367. , m_hasCreatedActivation(true)
  368. , m_firstLazyFunction(0)
  369. , m_lastLazyFunction(0)
  370. , m_staticPropertyAnalyzer(&m_instructions)
  371. , m_vm(&vm)
  372. , m_lastOpcodeID(op_end)
  373. #ifndef NDEBUG
  374. , m_lastOpcodePosition(0)
  375. #endif
  376. , m_stack(wtfThreadData().stack())
  377. , m_usesExceptions(false)
  378. , m_expressionTooDeep(false)
  379. {
  380. m_codeBlock->setNeedsFullScopeChain(true);
  381. m_symbolTable->setUsesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode());
  382. m_codeBlock->setNumParameters(1);
  383. emitOpcode(op_enter);
  384. const DeclarationStacks::FunctionStack& functionStack = evalNode->functionStack();
  385. for (size_t i = 0; i < functionStack.size(); ++i)
  386. m_codeBlock->addFunctionDecl(makeFunction(functionStack[i]));
  387. const DeclarationStacks::VarStack& varStack = evalNode->varStack();
  388. unsigned numVariables = varStack.size();
  389. Vector<Identifier, 0, UnsafeVectorOverflow> variables;
  390. variables.reserveCapacity(numVariables);
  391. for (size_t i = 0; i < numVariables; ++i)
  392. variables.append(*varStack[i].first);
  393. codeBlock->adoptVariables(variables);
  394. preserveLastVar();
  395. }
  396. BytecodeGenerator::~BytecodeGenerator()
  397. {
  398. }
  399. RegisterID* BytecodeGenerator::emitInitLazyRegister(RegisterID* reg)
  400. {
  401. emitOpcode(op_init_lazy_reg);
  402. instructions().append(reg->index());
  403. return reg;
  404. }
  405. RegisterID* BytecodeGenerator::resolveCallee(FunctionBodyNode* functionBodyNode)
  406. {
  407. if (functionBodyNode->ident().isNull() || !functionBodyNode->functionNameIsInScope())
  408. return 0;
  409. m_calleeRegister.setIndex(JSStack::Callee);
  410. // If non-strict eval is in play, we use a separate object in the scope chain for the callee's name.
  411. if ((m_codeBlock->usesEval() && !m_codeBlock->isStrictMode()) || m_shouldEmitDebugHooks) {
  412. emitOpcode(op_push_name_scope);
  413. instructions().append(addConstant(functionBodyNode->ident()));
  414. instructions().append(m_calleeRegister.index());
  415. instructions().append(ReadOnly | DontDelete);
  416. return 0;
  417. }
  418. if (!functionBodyNode->captures(functionBodyNode->ident()))
  419. return &m_calleeRegister;
  420. // Move the callee into the captured section of the stack.
  421. return emitMove(addVar(), &m_calleeRegister);
  422. }
  423. void BytecodeGenerator::addCallee(FunctionBodyNode* functionBodyNode, RegisterID* calleeRegister)
  424. {
  425. if (functionBodyNode->ident().isNull() || !functionBodyNode->functionNameIsInScope())
  426. return;
  427. // If non-strict eval is in play, we use a separate object in the scope chain for the callee's name.
  428. if ((m_codeBlock->usesEval() && !m_codeBlock->isStrictMode()) || m_shouldEmitDebugHooks)
  429. return;
  430. ASSERT(calleeRegister);
  431. symbolTable().add(functionBodyNode->ident().impl(), SymbolTableEntry(calleeRegister->index(), ReadOnly));
  432. }
  433. void BytecodeGenerator::addParameter(const Identifier& ident, int parameterIndex)
  434. {
  435. // Parameters overwrite var declarations, but not function declarations.
  436. StringImpl* rep = ident.impl();
  437. if (!m_functions.contains(rep)) {
  438. symbolTable().set(rep, parameterIndex);
  439. RegisterID& parameter = registerFor(parameterIndex);
  440. parameter.setIndex(parameterIndex);
  441. }
  442. // To maintain the calling convention, we have to allocate unique space for
  443. // each parameter, even if the parameter doesn't make it into the symbol table.
  444. m_codeBlock->addParameter();
  445. }
  446. bool BytecodeGenerator::willResolveToArguments(const Identifier& ident)
  447. {
  448. if (ident != propertyNames().arguments)
  449. return false;
  450. if (!shouldOptimizeLocals())
  451. return false;
  452. SymbolTableEntry entry = symbolTable().get(ident.impl());
  453. if (entry.isNull())
  454. return false;
  455. if (m_codeBlock->usesArguments() && m_codeType == FunctionCode)
  456. return true;
  457. return false;
  458. }
  459. RegisterID* BytecodeGenerator::uncheckedRegisterForArguments()
  460. {
  461. ASSERT(willResolveToArguments(propertyNames().arguments));
  462. SymbolTableEntry entry = symbolTable().get(propertyNames().arguments.impl());
  463. ASSERT(!entry.isNull());
  464. return &registerFor(entry.getIndex());
  465. }
  466. RegisterID* BytecodeGenerator::createLazyRegisterIfNecessary(RegisterID* reg)
  467. {
  468. if (m_lastLazyFunction <= reg->index() || reg->index() < m_firstLazyFunction)
  469. return reg;
  470. emitLazyNewFunction(reg, m_lazyFunctions.get(reg->index()));
  471. return reg;
  472. }
  473. RegisterID* BytecodeGenerator::newRegister()
  474. {
  475. m_calleeRegisters.append(m_calleeRegisters.size());
  476. m_codeBlock->m_numCalleeRegisters = max<int>(m_codeBlock->m_numCalleeRegisters, m_calleeRegisters.size());
  477. return &m_calleeRegisters.last();
  478. }
  479. RegisterID* BytecodeGenerator::newTemporary()
  480. {
  481. // Reclaim free register IDs.
  482. while (m_calleeRegisters.size() && !m_calleeRegisters.last().refCount())
  483. m_calleeRegisters.removeLast();
  484. RegisterID* result = newRegister();
  485. result->setTemporary();
  486. return result;
  487. }
  488. LabelScopePtr BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
  489. {
  490. // Reclaim free label scopes.
  491. while (m_labelScopes.size() && !m_labelScopes.last().refCount())
  492. m_labelScopes.removeLast();
  493. // Allocate new label scope.
  494. LabelScope scope(type, name, scopeDepth(), newLabel(), type == LabelScope::Loop ? newLabel() : PassRefPtr<Label>()); // Only loops have continue targets.
  495. m_labelScopes.append(scope);
  496. return LabelScopePtr(&m_labelScopes, m_labelScopes.size() - 1);
  497. }
  498. PassRefPtr<Label> BytecodeGenerator::newLabel()
  499. {
  500. // Reclaim free label IDs.
  501. while (m_labels.size() && !m_labels.last().refCount())
  502. m_labels.removeLast();
  503. // Allocate new label ID.
  504. m_labels.append(this);
  505. return &m_labels.last();
  506. }
  507. PassRefPtr<Label> BytecodeGenerator::emitLabel(Label* l0)
  508. {
  509. unsigned newLabelIndex = instructions().size();
  510. l0->setLocation(newLabelIndex);
  511. if (m_codeBlock->numberOfJumpTargets()) {
  512. unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
  513. ASSERT(lastLabelIndex <= newLabelIndex);
  514. if (newLabelIndex == lastLabelIndex) {
  515. // Peephole optimizations have already been disabled by emitting the last label
  516. return l0;
  517. }
  518. }
  519. m_codeBlock->addJumpTarget(newLabelIndex);
  520. // This disables peephole optimizations when an instruction is a jump target
  521. m_lastOpcodeID = op_end;
  522. return l0;
  523. }
  524. void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
  525. {
  526. #ifndef NDEBUG
  527. size_t opcodePosition = instructions().size();
  528. ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
  529. m_lastOpcodePosition = opcodePosition;
  530. #endif
  531. instructions().append(opcodeID);
  532. m_lastOpcodeID = opcodeID;
  533. }
  534. UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
  535. {
  536. #if ENABLE(VALUE_PROFILER)
  537. return m_codeBlock->addArrayProfile();
  538. #else
  539. return 0;
  540. #endif
  541. }
  542. UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
  543. {
  544. #if ENABLE(VALUE_PROFILER)
  545. return m_codeBlock->addArrayAllocationProfile();
  546. #else
  547. return 0;
  548. #endif
  549. }
  550. UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
  551. {
  552. return m_codeBlock->addObjectAllocationProfile();
  553. }
  554. UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
  555. {
  556. #if ENABLE(VALUE_PROFILER)
  557. UnlinkedValueProfile result = m_codeBlock->addValueProfile();
  558. #else
  559. UnlinkedValueProfile result = 0;
  560. #endif
  561. emitOpcode(opcodeID);
  562. return result;
  563. }
  564. void BytecodeGenerator::emitLoopHint()
  565. {
  566. emitOpcode(op_loop_hint);
  567. }
  568. void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
  569. {
  570. ASSERT(instructions().size() >= 4);
  571. size_t size = instructions().size();
  572. dstIndex = instructions().at(size - 3).u.operand;
  573. src1Index = instructions().at(size - 2).u.operand;
  574. src2Index = instructions().at(size - 1).u.operand;
  575. }
  576. void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
  577. {
  578. ASSERT(instructions().size() >= 3);
  579. size_t size = instructions().size();
  580. dstIndex = instructions().at(size - 2).u.operand;
  581. srcIndex = instructions().at(size - 1).u.operand;
  582. }
  583. void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
  584. {
  585. ASSERT(instructions().size() >= 4);
  586. instructions().shrink(instructions().size() - 4);
  587. m_lastOpcodeID = op_end;
  588. }
  589. void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
  590. {
  591. ASSERT(instructions().size() >= 3);
  592. instructions().shrink(instructions().size() - 3);
  593. m_lastOpcodeID = op_end;
  594. }
  595. PassRefPtr<Label> BytecodeGenerator::emitJump(Label* target)
  596. {
  597. size_t begin = instructions().size();
  598. emitOpcode(op_jmp);
  599. instructions().append(target->bind(begin, instructions().size()));
  600. return target;
  601. }
  602. PassRefPtr<Label> BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label* target)
  603. {
  604. if (m_lastOpcodeID == op_less) {
  605. int dstIndex;
  606. int src1Index;
  607. int src2Index;
  608. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  609. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  610. rewindBinaryOp();
  611. size_t begin = instructions().size();
  612. emitOpcode(op_jless);
  613. instructions().append(src1Index);
  614. instructions().append(src2Index);
  615. instructions().append(target->bind(begin, instructions().size()));
  616. return target;
  617. }
  618. } else if (m_lastOpcodeID == op_lesseq) {
  619. int dstIndex;
  620. int src1Index;
  621. int src2Index;
  622. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  623. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  624. rewindBinaryOp();
  625. size_t begin = instructions().size();
  626. emitOpcode(op_jlesseq);
  627. instructions().append(src1Index);
  628. instructions().append(src2Index);
  629. instructions().append(target->bind(begin, instructions().size()));
  630. return target;
  631. }
  632. } else if (m_lastOpcodeID == op_greater) {
  633. int dstIndex;
  634. int src1Index;
  635. int src2Index;
  636. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  637. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  638. rewindBinaryOp();
  639. size_t begin = instructions().size();
  640. emitOpcode(op_jgreater);
  641. instructions().append(src1Index);
  642. instructions().append(src2Index);
  643. instructions().append(target->bind(begin, instructions().size()));
  644. return target;
  645. }
  646. } else if (m_lastOpcodeID == op_greatereq) {
  647. int dstIndex;
  648. int src1Index;
  649. int src2Index;
  650. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  651. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  652. rewindBinaryOp();
  653. size_t begin = instructions().size();
  654. emitOpcode(op_jgreatereq);
  655. instructions().append(src1Index);
  656. instructions().append(src2Index);
  657. instructions().append(target->bind(begin, instructions().size()));
  658. return target;
  659. }
  660. } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
  661. int dstIndex;
  662. int srcIndex;
  663. retrieveLastUnaryOp(dstIndex, srcIndex);
  664. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  665. rewindUnaryOp();
  666. size_t begin = instructions().size();
  667. emitOpcode(op_jeq_null);
  668. instructions().append(srcIndex);
  669. instructions().append(target->bind(begin, instructions().size()));
  670. return target;
  671. }
  672. } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
  673. int dstIndex;
  674. int srcIndex;
  675. retrieveLastUnaryOp(dstIndex, srcIndex);
  676. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  677. rewindUnaryOp();
  678. size_t begin = instructions().size();
  679. emitOpcode(op_jneq_null);
  680. instructions().append(srcIndex);
  681. instructions().append(target->bind(begin, instructions().size()));
  682. return target;
  683. }
  684. }
  685. size_t begin = instructions().size();
  686. emitOpcode(op_jtrue);
  687. instructions().append(cond->index());
  688. instructions().append(target->bind(begin, instructions().size()));
  689. return target;
  690. }
  691. PassRefPtr<Label> BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label* target)
  692. {
  693. if (m_lastOpcodeID == op_less && target->isForward()) {
  694. int dstIndex;
  695. int src1Index;
  696. int src2Index;
  697. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  698. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  699. rewindBinaryOp();
  700. size_t begin = instructions().size();
  701. emitOpcode(op_jnless);
  702. instructions().append(src1Index);
  703. instructions().append(src2Index);
  704. instructions().append(target->bind(begin, instructions().size()));
  705. return target;
  706. }
  707. } else if (m_lastOpcodeID == op_lesseq && target->isForward()) {
  708. int dstIndex;
  709. int src1Index;
  710. int src2Index;
  711. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  712. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  713. rewindBinaryOp();
  714. size_t begin = instructions().size();
  715. emitOpcode(op_jnlesseq);
  716. instructions().append(src1Index);
  717. instructions().append(src2Index);
  718. instructions().append(target->bind(begin, instructions().size()));
  719. return target;
  720. }
  721. } else if (m_lastOpcodeID == op_greater && target->isForward()) {
  722. int dstIndex;
  723. int src1Index;
  724. int src2Index;
  725. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  726. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  727. rewindBinaryOp();
  728. size_t begin = instructions().size();
  729. emitOpcode(op_jngreater);
  730. instructions().append(src1Index);
  731. instructions().append(src2Index);
  732. instructions().append(target->bind(begin, instructions().size()));
  733. return target;
  734. }
  735. } else if (m_lastOpcodeID == op_greatereq && target->isForward()) {
  736. int dstIndex;
  737. int src1Index;
  738. int src2Index;
  739. retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
  740. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  741. rewindBinaryOp();
  742. size_t begin = instructions().size();
  743. emitOpcode(op_jngreatereq);
  744. instructions().append(src1Index);
  745. instructions().append(src2Index);
  746. instructions().append(target->bind(begin, instructions().size()));
  747. return target;
  748. }
  749. } else if (m_lastOpcodeID == op_not) {
  750. int dstIndex;
  751. int srcIndex;
  752. retrieveLastUnaryOp(dstIndex, srcIndex);
  753. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  754. rewindUnaryOp();
  755. size_t begin = instructions().size();
  756. emitOpcode(op_jtrue);
  757. instructions().append(srcIndex);
  758. instructions().append(target->bind(begin, instructions().size()));
  759. return target;
  760. }
  761. } else if (m_lastOpcodeID == op_eq_null && target->isForward()) {
  762. int dstIndex;
  763. int srcIndex;
  764. retrieveLastUnaryOp(dstIndex, srcIndex);
  765. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  766. rewindUnaryOp();
  767. size_t begin = instructions().size();
  768. emitOpcode(op_jneq_null);
  769. instructions().append(srcIndex);
  770. instructions().append(target->bind(begin, instructions().size()));
  771. return target;
  772. }
  773. } else if (m_lastOpcodeID == op_neq_null && target->isForward()) {
  774. int dstIndex;
  775. int srcIndex;
  776. retrieveLastUnaryOp(dstIndex, srcIndex);
  777. if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
  778. rewindUnaryOp();
  779. size_t begin = instructions().size();
  780. emitOpcode(op_jeq_null);
  781. instructions().append(srcIndex);
  782. instructions().append(target->bind(begin, instructions().size()));
  783. return target;
  784. }
  785. }
  786. size_t begin = instructions().size();
  787. emitOpcode(op_jfalse);
  788. instructions().append(cond->index());
  789. instructions().append(target->bind(begin, instructions().size()));
  790. return target;
  791. }
  792. PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label* target)
  793. {
  794. size_t begin = instructions().size();
  795. emitOpcode(op_jneq_ptr);
  796. instructions().append(cond->index());
  797. instructions().append(Special::CallFunction);
  798. instructions().append(target->bind(begin, instructions().size()));
  799. return target;
  800. }
  801. PassRefPtr<Label> BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label* target)
  802. {
  803. size_t begin = instructions().size();
  804. emitOpcode(op_jneq_ptr);
  805. instructions().append(cond->index());
  806. instructions().append(Special::ApplyFunction);
  807. instructions().append(target->bind(begin, instructions().size()));
  808. return target;
  809. }
  810. unsigned BytecodeGenerator::addConstant(const Identifier& ident)
  811. {
  812. StringImpl* rep = ident.impl();
  813. IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
  814. if (result.isNewEntry)
  815. m_codeBlock->addIdentifier(Identifier(m_vm, rep));
  816. return result.iterator->value;
  817. }
  818. // We can't hash JSValue(), so we use a dedicated data member to cache it.
  819. RegisterID* BytecodeGenerator::addConstantEmptyValue()
  820. {
  821. if (!m_emptyValueRegister) {
  822. int index = m_nextConstantOffset;
  823. m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
  824. ++m_nextConstantOffset;
  825. m_codeBlock->addConstant(JSValue());
  826. m_emptyValueRegister = &m_constantPoolRegisters[index];
  827. }
  828. return m_emptyValueRegister;
  829. }
  830. RegisterID* BytecodeGenerator::addConstantValue(JSValue v)
  831. {
  832. if (!v)
  833. return addConstantEmptyValue();
  834. int index = m_nextConstantOffset;
  835. JSValueMap::AddResult result = m_jsValueMap.add(JSValue::encode(v), m_nextConstantOffset);
  836. if (result.isNewEntry) {
  837. m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
  838. ++m_nextConstantOffset;
  839. m_codeBlock->addConstant(v);
  840. } else
  841. index = result.iterator->value;
  842. return &m_constantPoolRegisters[index];
  843. }
  844. unsigned BytecodeGenerator::addRegExp(RegExp* r)
  845. {
  846. return m_codeBlock->addRegExp(r);
  847. }
  848. RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
  849. {
  850. m_staticPropertyAnalyzer.mov(dst->index(), src->index());
  851. emitOpcode(op_mov);
  852. instructions().append(dst->index());
  853. instructions().append(src->index());
  854. return dst;
  855. }
  856. RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
  857. {
  858. emitOpcode(opcodeID);
  859. instructions().append(dst->index());
  860. instructions().append(src->index());
  861. return dst;
  862. }
  863. RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
  864. {
  865. emitOpcode(op_inc);
  866. instructions().append(srcDst->index());
  867. return srcDst;
  868. }
  869. RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
  870. {
  871. emitOpcode(op_dec);
  872. instructions().append(srcDst->index());
  873. return srcDst;
  874. }
  875. RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
  876. {
  877. emitOpcode(opcodeID);
  878. instructions().append(dst->index());
  879. instructions().append(src1->index());
  880. instructions().append(src2->index());
  881. if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
  882. opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
  883. instructions().append(types.toInt());
  884. return dst;
  885. }
  886. RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
  887. {
  888. if (m_lastOpcodeID == op_typeof) {
  889. int dstIndex;
  890. int srcIndex;
  891. retrieveLastUnaryOp(dstIndex, srcIndex);
  892. if (src1->index() == dstIndex
  893. && src1->isTemporary()
  894. && m_codeBlock->isConstantRegisterIndex(src2->index())
  895. && m_codeBlock->constantRegister(src2->index()).get().isString()) {
  896. const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
  897. if (value == "undefined") {
  898. rewindUnaryOp();
  899. emitOpcode(op_is_undefined);
  900. instructions().append(dst->index());
  901. instructions().append(srcIndex);
  902. return dst;
  903. }
  904. if (value == "boolean") {
  905. rewindUnaryOp();
  906. emitOpcode(op_is_boolean);
  907. instructions().append(dst->index());
  908. instructions().append(srcIndex);
  909. return dst;
  910. }
  911. if (value == "number") {
  912. rewindUnaryOp();
  913. emitOpcode(op_is_number);
  914. instructions().append(dst->index());
  915. instructions().append(srcIndex);
  916. return dst;
  917. }
  918. if (value == "string") {
  919. rewindUnaryOp();
  920. emitOpcode(op_is_string);
  921. instructions().append(dst->index());
  922. instructions().append(srcIndex);
  923. return dst;
  924. }
  925. if (value == "object") {
  926. rewindUnaryOp();
  927. emitOpcode(op_is_object);
  928. instructions().append(dst->index());
  929. instructions().append(srcIndex);
  930. return dst;
  931. }
  932. if (value == "function") {
  933. rewindUnaryOp();
  934. emitOpcode(op_is_function);
  935. instructions().append(dst->index());
  936. instructions().append(srcIndex);
  937. return dst;
  938. }
  939. }
  940. }
  941. emitOpcode(opcodeID);
  942. instructions().append(dst->index());
  943. instructions().append(src1->index());
  944. instructions().append(src2->index());
  945. return dst;
  946. }
  947. RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
  948. {
  949. return emitLoad(dst, jsBoolean(b));
  950. }
  951. RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, double number)
  952. {
  953. // FIXME: Our hash tables won't hold infinity, so we make a new JSValue each time.
  954. // Later we can do the extra work to handle that like the other cases. They also don't
  955. // work correctly with NaN as a key.
  956. if (std::isnan(number) || number == HashTraits<double>::emptyValue() || HashTraits<double>::isDeletedValue(number))
  957. return emitLoad(dst, jsNumber(number));
  958. JSValue& valueInMap = m_numberMap.add(number, JSValue()).iterator->value;
  959. if (!valueInMap)
  960. valueInMap = jsNumber(number);
  961. return emitLoad(dst, valueInMap);
  962. }
  963. RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
  964. {
  965. JSString*& stringInMap = m_stringMap.add(identifier.impl(), 0).iterator->value;
  966. if (!stringInMap)
  967. stringInMap = jsOwnedString(vm(), identifier.string());
  968. return emitLoad(dst, JSValue(stringInMap));
  969. }
  970. RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v)
  971. {
  972. RegisterID* constantID = addConstantValue(v);
  973. if (dst)
  974. return emitMove(dst, constantID);
  975. return constantID;
  976. }
  977. RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
  978. {
  979. if (!m_globalObjectRegister) {
  980. int index = m_nextConstantOffset;
  981. m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
  982. ++m_nextConstantOffset;
  983. m_codeBlock->addConstant(JSValue());
  984. m_globalObjectRegister = &m_constantPoolRegisters[index];
  985. m_codeBlock->setGlobalObjectRegister(index);
  986. }
  987. if (dst)
  988. emitMove(dst, m_globalObjectRegister);
  989. return m_globalObjectRegister;
  990. }
  991. ResolveResult BytecodeGenerator::resolve(const Identifier& property)
  992. {
  993. if (property == propertyNames().thisIdentifier)
  994. return ResolveResult::registerResolve(thisRegister(), ResolveResult::ReadOnlyFlag);
  995. // Check if the property should be allocated in a register.
  996. if (m_codeType != GlobalCode && shouldOptimizeLocals() && m_symbolTable) {
  997. SymbolTableEntry entry = symbolTable().get(property.impl());
  998. if (!entry.isNull()) {
  999. if (property == propertyNames().arguments)
  1000. createArgumentsIfNecessary();
  1001. unsigned flags = entry.isReadOnly() ? ResolveResult::ReadOnlyFlag : 0;
  1002. RegisterID* local = createLazyRegisterIfNecessary(&registerFor(entry.getIndex()));
  1003. return ResolveResult::registerResolve(local, flags);
  1004. }
  1005. }
  1006. // Cases where we cannot statically optimize the lookup.
  1007. if (property == propertyNames().arguments || !canOptimizeNonLocals())
  1008. return ResolveResult::dynamicResolve();
  1009. if (!m_scope || m_codeType != FunctionCode || m_shouldEmitDebugHooks)
  1010. return ResolveResult::dynamicResolve();
  1011. ScopeChainIterator iter = m_scope->begin();
  1012. ScopeChainIterator end = m_scope->end();
  1013. size_t depth = m_codeBlock->needsFullScopeChain();
  1014. unsigned flags = 0;
  1015. for (; iter != end; ++iter, ++depth) {
  1016. JSObject* currentScope = iter.get();
  1017. if (!currentScope->isStaticScopeObject())
  1018. return ResolveResult::dynamicResolve();
  1019. JSSymbolTableObject* currentVariableObject = jsCast<JSSymbolTableObject*>(currentScope);
  1020. SymbolTableEntry entry = currentVariableObject->symbolTable()->get(property.impl());
  1021. // Found the property
  1022. if (!entry.isNull()) {
  1023. if (entry.isReadOnly())
  1024. flags |= ResolveResult::ReadOnlyFlag;
  1025. if (++iter == end)
  1026. return ResolveResult::dynamicResolve();
  1027. #if !ASSERT_DISABLED
  1028. if (JSActivation* activation = jsDynamicCast<JSActivation*>(currentVariableObject))
  1029. ASSERT(activation->isValid(entry));
  1030. #endif
  1031. return ResolveResult::lexicalResolve(entry.getIndex(), depth, flags);
  1032. }
  1033. bool scopeRequiresDynamicChecks = false;
  1034. if (currentVariableObject->isDynamicScope(scopeRequiresDynamicChecks))
  1035. break;
  1036. if (scopeRequiresDynamicChecks)
  1037. flags |= ResolveResult::DynamicFlag;
  1038. }
  1039. return ResolveResult::dynamicResolve();
  1040. }
  1041. ResolveResult BytecodeGenerator::resolveConstDecl(const Identifier& property)
  1042. {
  1043. // Register-allocated const declarations.
  1044. if (m_codeType == FunctionCode && m_symbolTable) {
  1045. SymbolTableEntry entry = symbolTable().get(property.impl());
  1046. if (!entry.isNull()) {
  1047. unsigned flags = entry.isReadOnly() ? ResolveResult::ReadOnlyFlag : 0;
  1048. RegisterID* local = createLazyRegisterIfNecessary(&registerFor(entry.getIndex()));
  1049. return ResolveResult::registerResolve(local, flags);
  1050. }
  1051. }
  1052. return ResolveResult::dynamicResolve();
  1053. }
  1054. void BytecodeGenerator::emitCheckHasInstance(RegisterID* dst, RegisterID* value, RegisterID* base, Label* target)
  1055. {
  1056. size_t begin = instructions().size();
  1057. emitOpcode(op_check_has_instance);
  1058. instructions().append(dst->index());
  1059. instructions().append(value->index());
  1060. instructions().append(base->index());
  1061. instructions().append(target->bind(begin, instructions().size()));
  1062. }
  1063. RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
  1064. {
  1065. emitOpcode(op_instanceof);
  1066. instructions().append(dst->index());
  1067. instructions().append(value->index());
  1068. instructions().append(basePrototype->index());
  1069. return dst;
  1070. }
  1071. bool BytecodeGenerator::shouldAvoidResolveGlobal()
  1072. {
  1073. return !m_labelScopes.size();
  1074. }
  1075. RegisterID* BytecodeGenerator::emitResolve(RegisterID* dst, const ResolveResult& resolveResult, const Identifier& property)
  1076. {
  1077. if (resolveResult.isStatic())
  1078. return emitGetStaticVar(dst, resolveResult, property);
  1079. UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve);
  1080. instructions().append(kill(dst));
  1081. instructions().append(addConstant(property));
  1082. instructions().append(getResolveOperations(property));
  1083. instructions().append(profile);
  1084. return dst;
  1085. }
  1086. RegisterID* BytecodeGenerator::emitResolveBase(RegisterID* dst, const ResolveResult& resolveResult, const Identifier& property)
  1087. {
  1088. if (!resolveResult.isDynamic()) {
  1089. // Global object is the base
  1090. return emitLoadGlobalObject(dst);
  1091. }
  1092. // We can't optimise at all :-(
  1093. UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_base);
  1094. instructions().append(kill(dst));
  1095. instructions().append(addConstant(property));
  1096. instructions().append(false);
  1097. instructions().append(getResolveBaseOperations(property));
  1098. instructions().append(0);
  1099. instructions().append(profile);
  1100. return dst;
  1101. }
  1102. RegisterID* BytecodeGenerator::emitResolveBaseForPut(RegisterID* dst, const ResolveResult&, const Identifier& property, NonlocalResolveInfo& verifier)
  1103. {
  1104. // We can't optimise at all :-(
  1105. UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_base);
  1106. instructions().append(kill(dst));
  1107. instructions().append(addConstant(property));
  1108. instructions().append(m_codeBlock->isStrictMode());
  1109. uint32_t putToBaseIndex = 0;
  1110. instructions().append(getResolveBaseForPutOperations(property, putToBaseIndex));
  1111. verifier.resolved(putToBaseIndex);
  1112. instructions().append(putToBaseIndex);
  1113. instructions().append(profile);
  1114. return dst;
  1115. }
  1116. RegisterID* BytecodeGenerator::emitResolveWithBaseForPut(RegisterID* baseDst, RegisterID* propDst, const ResolveResult& resolveResult, const Identifier& property, NonlocalResolveInfo& verifier)
  1117. {
  1118. ASSERT_UNUSED(resolveResult, !resolveResult.isStatic());
  1119. UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_with_base);
  1120. instructions().append(kill(baseDst));
  1121. instructions().append(propDst->index());
  1122. instructions().append(addConstant(property));
  1123. uint32_t putToBaseIndex = 0;
  1124. instructions().append(getResolveWithBaseForPutOperations(property, putToBaseIndex));
  1125. verifier.resolved(putToBaseIndex);
  1126. instructions().append(putToBaseIndex);
  1127. instructions().append(profile);
  1128. return baseDst;
  1129. }
  1130. RegisterID* BytecodeGenerator::emitResolveWithThis(RegisterID* baseDst, RegisterID* propDst, const ResolveResult& resolveResult, const Identifier& property)
  1131. {
  1132. if (resolveResult.isStatic()) {
  1133. emitLoad(baseDst, jsUndefined());
  1134. emitGetStaticVar(propDst, resolveResult, property);
  1135. return baseDst;
  1136. }
  1137. UnlinkedValueProfile profile = emitProfiledOpcode(op_resolve_with_this);
  1138. instructions().append(kill(baseDst));
  1139. instructions().append(propDst->index());
  1140. instructions().append(addConstant(property));
  1141. instructions().append(getResolveWithThisOperations(property));
  1142. instructions().append(profile);
  1143. return baseDst;
  1144. }
  1145. RegisterID* BytecodeGenerator::emitGetStaticVar(RegisterID* dst, const ResolveResult& resolveResult, const Identifier&)
  1146. {
  1147. ASSERT(m_codeType == FunctionCode);
  1148. switch (resolveResult.type()) {
  1149. case ResolveResult::Register:
  1150. case ResolveResult::ReadOnlyRegister:
  1151. if (dst == ignoredResult())
  1152. return 0;
  1153. return moveToDestinationIfNeeded(dst, resolveResult.local());
  1154. case ResolveResult::Lexical:
  1155. case ResolveResult::ReadOnlyLexical: {
  1156. UnlinkedValueProfile profile = emitProfiledOpcode(op_get_scoped_var);
  1157. instructions().append(dst->index());
  1158. instructions().append(resolveResult.index());
  1159. instructions().append(resolveResult.depth());
  1160. instructions().append(profile);
  1161. return dst;
  1162. }
  1163. default:
  1164. RELEASE_ASSERT_NOT_REACHED();
  1165. return 0;
  1166. }
  1167. }
  1168. RegisterID* BytecodeGenerator::emitInitGlobalConst(const Identifier& identifier, RegisterID* value)
  1169. {
  1170. ASSERT(m_codeType == GlobalCode);
  1171. emitOpcode(op_init_global_const_nop);
  1172. instructions().append(0);
  1173. instructions().append(value->index());
  1174. instructions().append(0);
  1175. instructions().append(addConstant(identifier));
  1176. return value;
  1177. }
  1178. RegisterID* BytecodeGenerator::emitPutStaticVar(const ResolveResult& resolveResult, const Identifier&, RegisterID* value)
  1179. {
  1180. ASSERT(m_codeType == FunctionCode);
  1181. switch (resolveResult.type()) {
  1182. case ResolveResult::Register:
  1183. case ResolveResult::ReadOnlyRegister:
  1184. return moveToDestinationIfNeeded(resolveResult.local(), value);
  1185. case ResolveResult::Lexical:
  1186. case ResolveResult::ReadOnlyLexical:
  1187. emitOpcode(op_put_scoped_var);
  1188. instructions().append(resolveResult.index());
  1189. instructions().append(resolveResult.depth());
  1190. instructions().append(value->index());
  1191. return value;
  1192. default:
  1193. RELEASE_ASSERT_NOT_REACHED();
  1194. return 0;
  1195. }
  1196. }
  1197. RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
  1198. {
  1199. m_codeBlock->addPropertyAccessInstruction(instructions().size());
  1200. UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
  1201. instructions().append(kill(dst));
  1202. instructions().append(base->index());
  1203. instructions().append(addConstant(property));
  1204. instructions().append(0);
  1205. instructions().append(0);
  1206. instructions().append(0);
  1207. instructions().append(0);
  1208. instructions().append(profile);
  1209. return dst;
  1210. }
  1211. RegisterID* BytecodeGenerator::emitGetArgumentsLength(RegisterID* dst, RegisterID* base)
  1212. {
  1213. emitOpcode(op_get_arguments_length);
  1214. instructions().append(dst->index());
  1215. ASSERT(base->index() == m_codeBlock->argumentsRegister());
  1216. instructions().append(base->index());
  1217. instructions().append(addConstant(propertyNames().length));
  1218. return dst;
  1219. }
  1220. RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
  1221. {
  1222. unsigned propertyIndex = addConstant(property);
  1223. m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
  1224. m_codeBlock->addPropertyAccessInstruction(instructions().size());
  1225. emitOpcode(op_put_by_id);
  1226. instructions().append(base->index());
  1227. instructions().append(propertyIndex);
  1228. instructions().append(value->index());
  1229. instructions().append(0);
  1230. instructions().append(0);
  1231. instructions().append(0);
  1232. instructions().append(0);
  1233. instructions().append(0);
  1234. return value;
  1235. }
  1236. RegisterID* BytecodeGenerator::emitPutToBase(RegisterID* base, const Identifier& property, RegisterID* value, NonlocalResolveInfo& resolveInfo)
  1237. {
  1238. emitOpcode(op_put_to_base);
  1239. instructions().append(base->index());
  1240. instructions().append(addConstant(property));
  1241. instructions().append(value->index());
  1242. instructions().append(resolveInfo.put());
  1243. return value;
  1244. }
  1245. RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value)
  1246. {
  1247. unsigned propertyIndex = addConstant(property);
  1248. m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
  1249. m_codeBlock->addPropertyAccessInstruction(instructions().size());
  1250. emitOpcode(op_put_by_id);
  1251. instructions().append(base->index());
  1252. instructions().append(propertyIndex);
  1253. instructions().append(value->index());
  1254. instructions().append(0);
  1255. instructions().append(0);
  1256. instructions().append(0);
  1257. instructions().append(0);
  1258. instructions().append(
  1259. property != m_vm->propertyNames->underscoreProto
  1260. && PropertyName(property).asIndex() == PropertyName::NotAnIndex);
  1261. return value;
  1262. }
  1263. void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, RegisterID* getter, RegisterID* setter)
  1264. {
  1265. unsigned propertyIndex = addConstant(property);
  1266. m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
  1267. emitOpcode(op_put_getter_setter);
  1268. instructions().append(base->index());
  1269. instructions().append(propertyIndex);
  1270. instructions().append(getter->index());
  1271. instructions().append(setter->index());
  1272. }
  1273. RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
  1274. {
  1275. emitOpcode(op_del_by_id);
  1276. instructions().append(dst->index());
  1277. instructions().append(base->index());
  1278. instructions().append(addConstant(property));
  1279. return dst;
  1280. }
  1281. RegisterID* BytecodeGenerator::emitGetArgumentByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
  1282. {
  1283. UnlinkedArrayProfile arrayProfile = newArrayProfile();
  1284. UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument_by_val);
  1285. instructions().append(kill(dst));
  1286. ASSERT(base->index() == m_codeBlock->argumentsRegister());
  1287. instructions().append(base->index());
  1288. instructions().append(property->index());
  1289. instructions().append(arrayProfile);
  1290. instructions().append(profile);
  1291. return dst;
  1292. }
  1293. RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
  1294. {
  1295. for (size_t i = m_forInContextStack.size(); i > 0; i--) {
  1296. ForInContext& context = m_forInContextStack[i - 1];
  1297. if (context.propertyRegister == property) {
  1298. emitOpcode(op_get_by_pname);
  1299. instructions().append(dst->index());
  1300. instructions().append(base->index());
  1301. instructions().append(property->index());
  1302. instructions().append(context.expectedSubscriptRegister->index());
  1303. instructions().append(context.iterRegister->index());
  1304. instructions().append(context.indexRegister->index());
  1305. return dst;
  1306. }
  1307. }
  1308. UnlinkedArrayProfile arrayProfile = newArrayProfile();
  1309. UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
  1310. instructions().append(kill(dst));
  1311. instructions().append(base->index());
  1312. instructions().append(property->index());
  1313. instructions().append(arrayProfile);
  1314. instructions().append(profile);
  1315. return dst;
  1316. }
  1317. RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
  1318. {
  1319. UnlinkedArrayProfile arrayProfile = newArrayProfile();
  1320. emitOpcode(op_put_by_val);
  1321. instructions().append(base->index());
  1322. instructions().append(property->index());
  1323. instructions().append(value->index());
  1324. instructions().append(arrayProfile);
  1325. return value;
  1326. }
  1327. RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
  1328. {
  1329. emitOpcode(op_del_by_val);
  1330. instructions().append(dst->index());
  1331. instructions().append(base->index());
  1332. instructions().append(property->index());
  1333. return dst;
  1334. }
  1335. RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
  1336. {
  1337. emitOpcode(op_put_by_index);
  1338. instructions().append(base->index());
  1339. instructions().append(index);
  1340. instructions().append(value->index());
  1341. return value;
  1342. }
  1343. RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
  1344. {
  1345. RefPtr<RegisterID> func = newTemporary();
  1346. UnlinkedValueProfile profile = emitProfiledOpcode(op_get_callee);
  1347. instructions().append(func->index());
  1348. instructions().append(profile);
  1349. size_t begin = instructions().size();
  1350. m_staticPropertyAnalyzer.createThis(m_thisRegister.index(), begin + 3);
  1351. emitOpcode(op_create_this);
  1352. instructions().append(m_thisRegister.index());
  1353. instructions().append(func->index());
  1354. instructions().append(0);
  1355. return dst;
  1356. }
  1357. RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
  1358. {
  1359. size_t begin = instructions().size();
  1360. m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
  1361. emitOpcode(op_new_object);
  1362. instructions().append(dst->index());
  1363. instructions().append(0);
  1364. instructions().append(newObjectAllocationProfile());
  1365. return dst;
  1366. }
  1367. unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
  1368. {
  1369. return m_codeBlock->addConstantBuffer(length);
  1370. }
  1371. JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
  1372. {
  1373. JSString*& stringInMap = m_stringMap.add(identifier.impl(), 0).iterator->value;
  1374. if (!stringInMap) {
  1375. stringInMap = jsString(vm(), identifier.string());
  1376. addConstantValue(stringInMap);
  1377. }
  1378. return stringInMap;
  1379. }
  1380. RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
  1381. {
  1382. #if !ASSERT_DISABLED
  1383. unsigned checkLength = 0;
  1384. #endif
  1385. bool hadVariableExpression = false;
  1386. if (length) {
  1387. for (ElementNode* n = elements; n; n = n->next()) {
  1388. if (!n->value()->isConstant()) {
  1389. hadVariableExpression = true;
  1390. break;
  1391. }
  1392. if (n->elision())
  1393. break;
  1394. #if !ASSERT_DISABLED
  1395. checkLength++;
  1396. #endif
  1397. }
  1398. if (!hadVariableExpression) {
  1399. ASSERT(length == checkLength);
  1400. unsigned constantBufferIndex = addConstantBuffer(length);
  1401. JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
  1402. unsigned index = 0;
  1403. for (ElementNode* n = elements; index < length; n = n->next()) {
  1404. ASSERT(n->value()->isConstant());
  1405. constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
  1406. }
  1407. emitOpcode(op_new_array_buffer);
  1408. instructions().append(dst->index());
  1409. instructions().append(constantBufferIndex);
  1410. instructions().append(length);
  1411. instructions().append(newArrayAllocationProfile());
  1412. return dst;
  1413. }
  1414. }
  1415. Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
  1416. for (ElementNode* n = elements; n; n = n->next()) {
  1417. if (n->elision())
  1418. break;
  1419. argv.append(newTemporary());
  1420. // op_new_array requires the initial values to be a sequential range of registers
  1421. ASSERT(argv.size() == 1 || argv[argv.size() - 1]->index() == argv[argv.size() - 2]->index() + 1);
  1422. emitNode(argv.last().get(), n->value());
  1423. }
  1424. emitOpcode(op_new_array);
  1425. instructions().append(dst->index());
  1426. instructions().append(argv.size() ? argv[0]->index() : 0); // argv
  1427. instructions().append(argv.size()); // argc
  1428. instructions().append(newArrayAllocationProfile());
  1429. return dst;
  1430. }
  1431. RegisterID* BytecodeGenerator::emitNewFunction(RegisterID* dst, FunctionBodyNode* function)
  1432. {
  1433. return emitNewFunctionInternal(dst, m_codeBlock->addFunctionDecl(makeFunction(function)), false);
  1434. }
  1435. RegisterID* BytecodeGenerator::emitLazyNewFunction(RegisterID* dst, FunctionBodyNode* function)
  1436. {
  1437. FunctionOffsetMap::AddResult ptr = m_functionOffsets.add(function, 0);
  1438. if (ptr.isNewEntry)
  1439. ptr.iterator->value = m_codeBlock->addFunctionDecl(makeFunction(function));
  1440. return emitNewFunctionInternal(dst, ptr.iterator->value, true);
  1441. }
  1442. RegisterID* BytecodeGenerator::emitNewFunctionInternal(RegisterID* dst, unsigned index, bool doNullCheck)
  1443. {
  1444. createActivationIfNecessary();
  1445. emitOpcode(op_new_func);
  1446. instructions().append(dst->index());
  1447. instructions().append(index);
  1448. instructions().append(doNullCheck);
  1449. return dst;
  1450. }
  1451. RegisterID* BytecodeGenerator::emitNewRegExp(RegisterID* dst, RegExp* regExp)
  1452. {
  1453. emitOpcode(op_new_regexp);
  1454. instructions().append(dst->index());
  1455. instructions().append(addRegExp(regExp));
  1456. return dst;
  1457. }
  1458. RegisterID* BytecodeGenerator::emitNewFunctionExpression(RegisterID* r0, FuncExprNode* n)
  1459. {
  1460. FunctionBodyNode* function = n->body();
  1461. unsigned index = m_codeBlock->addFunctionExpr(makeFunction(function));
  1462. createActivationIfNecessary();
  1463. emitOpcode(op_new_func_exp);
  1464. instructions().append(r0->index());
  1465. instructions().append(index);
  1466. return r0;
  1467. }
  1468. RegisterID* BytecodeGenerator::emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
  1469. {
  1470. return emitCall(op_call, dst, func, expectedFunction, callArguments, divot, startOffset, endOffset, line, lineStart);
  1471. }
  1472. void BytecodeGenerator::createArgumentsIfNecessary()
  1473. {
  1474. if (m_codeType != FunctionCode)
  1475. return;
  1476. if (!m_codeBlock->usesArguments())
  1477. return;
  1478. // If we're in strict mode we tear off the arguments on function
  1479. // entry, so there's no need to check if we need to create them
  1480. // now
  1481. if (m_codeBlock->isStrictMode())
  1482. return;
  1483. emitOpcode(op_create_arguments);
  1484. instructions().append(m_codeBlock->argumentsRegister());
  1485. }
  1486. void BytecodeGenerator::createActivationIfNecessary()
  1487. {
  1488. if (m_hasCreatedActivation)
  1489. return;
  1490. if (!m_codeBlock->needsFullScopeChain())
  1491. return;
  1492. emitOpcode(op_create_activation);
  1493. instructions().append(m_activationRegister->index());
  1494. }
  1495. RegisterID* BytecodeGenerator::emitCallEval(RegisterID* dst, RegisterID* func, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
  1496. {
  1497. return emitCall(op_call_eval, dst, func, NoExpectedFunction, callArguments, divot, startOffset, endOffset, line, lineStart);
  1498. }
  1499. ExpectedFunction BytecodeGenerator::expectedFunctionForIdentifier(const Identifier& identifier)
  1500. {
  1501. if (identifier == m_vm->propertyNames->Object)
  1502. return ExpectObjectConstructor;
  1503. if (identifier == m_vm->propertyNames->Array)
  1504. return ExpectArrayConstructor;
  1505. return NoExpectedFunction;
  1506. }
  1507. ExpectedFunction BytecodeGenerator::emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, Label* done)
  1508. {
  1509. RefPtr<Label> realCall = newLabel();
  1510. switch (expectedFunction) {
  1511. case ExpectObjectConstructor: {
  1512. // If the number of arguments is non-zero, then we can't do anything interesting.
  1513. if (callArguments.argumentCountIncludingThis() >= 2)
  1514. return NoExpectedFunction;
  1515. size_t begin = instructions().size();
  1516. emitOpcode(op_jneq_ptr);
  1517. instructions().append(func->index());
  1518. instructions().append(Special::ObjectConstructor);
  1519. instructions().append(realCall->bind(begin, instructions().size()));
  1520. if (dst != ignoredResult())
  1521. emitNewObject(dst);
  1522. break;
  1523. }
  1524. case ExpectArrayConstructor: {
  1525. // If you're doing anything other than "new Array()" or "new Array(foo)" then we
  1526. // don't do inline it, for now. The only reason is that call arguments are in
  1527. // the opposite order of what op_new_array expects, so we'd either need to change
  1528. // how op_new_array works or we'd need an op_new_array_reverse. Neither of these
  1529. // things sounds like it's worth it.
  1530. if (callArguments.argumentCountIncludingThis() > 2)
  1531. return NoExpectedFunction;
  1532. size_t begin = instructions().size();
  1533. emitOpcode(op_jneq_ptr);
  1534. instructions().append(func->index());
  1535. instructions().append(Special::ArrayConstructor);
  1536. instructions().append(realCall->bind(begin, instructions().size()));
  1537. if (dst != ignoredResult()) {
  1538. if (callArguments.argumentCountIncludingThis() == 2) {
  1539. emitOpcode(op_new_array_with_size);
  1540. instructions().append(dst->index());
  1541. instructions().append(callArguments.argumentRegister(0)->index());
  1542. instructions().append(newArrayAllocationProfile());
  1543. } else {
  1544. ASSERT(callArguments.argumentCountIncludingThis() == 1);
  1545. emitOpcode(op_new_array);
  1546. instructions().append(dst->index());
  1547. instructions().append(0);
  1548. instructions().append(0);
  1549. instructions().append(newArrayAllocationProfile());
  1550. }
  1551. }
  1552. break;
  1553. }
  1554. default:
  1555. ASSERT(expectedFunction == NoExpectedFunction);
  1556. return NoExpectedFunction;
  1557. }
  1558. size_t begin = instructions().size();
  1559. emitOpcode(op_jmp);
  1560. instructions().append(done->bind(begin, instructions().size()));
  1561. emitLabel(realCall.get());
  1562. return expectedFunction;
  1563. }
  1564. RegisterID* BytecodeGenerator::emitCall(OpcodeID opcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
  1565. {
  1566. ASSERT(opcodeID == op_call || opcodeID == op_call_eval);
  1567. ASSERT(func->refCount());
  1568. if (m_shouldEmitProfileHooks)
  1569. emitMove(callArguments.profileHookRegister(), func);
  1570. // Generate code for arguments.
  1571. unsigned argument = 0;
  1572. for (ArgumentListNode* n = callArguments.argumentsNode()->m_listNode; n; n = n->m_next)
  1573. emitNode(callArguments.argumentRegister(argument++), n);
  1574. // Reserve space for call frame.
  1575. Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
  1576. for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
  1577. callFrame.append(newTemporary());
  1578. if (m_shouldEmitProfileHooks) {
  1579. emitOpcode(op_profile_will_call);
  1580. instructions().append(callArguments.profileHookRegister()->index());
  1581. }
  1582. emitExpressionInfo(divot, startOffset, endOffset, line, lineStart);
  1583. RefPtr<Label> done = newLabel();
  1584. expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
  1585. // Emit call.
  1586. UnlinkedArrayProfile arrayProfile = newArrayProfile();
  1587. emitOpcode(opcodeID);
  1588. instructions().append(func->index()); // func
  1589. instructions().append(callArguments.argumentCountIncludingThis()); // argCount
  1590. instructions().append(callArguments.registerOffset()); // registerOffset
  1591. #if ENABLE(LLINT)
  1592. instructions().append(m_codeBlock->addLLIntCallLinkInfo());
  1593. #else
  1594. instructions().append(0);
  1595. #endif
  1596. instructions().append(arrayProfile);
  1597. if (dst != ignoredResult()) {
  1598. UnlinkedValueProfile profile = emitProfiledOpcode(op_call_put_result);
  1599. instructions().append(kill(dst));
  1600. instructions().append(profile);
  1601. }
  1602. if (expectedFunction != NoExpectedFunction)
  1603. emitLabel(done.get());
  1604. if (m_shouldEmitProfileHooks) {
  1605. emitOpcode(op_profile_did_call);
  1606. instructions().append(callArguments.profileHookRegister()->index());
  1607. }
  1608. return dst;
  1609. }
  1610. RegisterID* BytecodeGenerator::emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, RegisterID* profileHookRegister, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
  1611. {
  1612. if (m_shouldEmitProfileHooks) {
  1613. emitMove(profileHookRegister, func);
  1614. emitOpcode(op_profile_will_call);
  1615. instructions().append(profileHookRegister->index());
  1616. }
  1617. emitExpressionInfo(divot, startOffset, endOffset, line, lineStart);
  1618. // Emit call.
  1619. emitOpcode(op_call_varargs);
  1620. instructions().append(func->index());
  1621. instructions().append(thisRegister->index());
  1622. instructions().append(arguments->index());
  1623. instructions().append(firstFreeRegister->index());
  1624. if (dst != ignoredResult()) {
  1625. UnlinkedValueProfile profile = emitProfiledOpcode(op_call_put_result);
  1626. instructions().append(kill(dst));
  1627. instructions().append(profile);
  1628. }
  1629. if (m_shouldEmitProfileHooks) {
  1630. emitOpcode(op_profile_did_call);
  1631. instructions().append(profileHookRegister->index());
  1632. }
  1633. return dst;
  1634. }
  1635. RegisterID* BytecodeGenerator::emitReturn(RegisterID* src)
  1636. {
  1637. if (m_codeBlock->needsFullScopeChain()) {
  1638. emitOpcode(op_tear_off_activation);
  1639. instructions().append(m_activationRegister->index());
  1640. }
  1641. if (m_codeBlock->usesArguments() && m_codeBlock->numParameters() != 1 && !m_codeBlock->isStrictMode()) {
  1642. emitOpcode(op_tear_off_arguments);
  1643. instructions().append(m_codeBlock->argumentsRegister());
  1644. instructions().append(m_activationRegister ? m_activationRegister->index() : emitLoad(0, JSValue())->index());
  1645. }
  1646. // Constructors use op_ret_object_or_this to check the result is an
  1647. // object, unless we can trivially determine the check is not
  1648. // necessary (currently, if the return value is 'this').
  1649. if (isConstructor() && (src->index() != m_thisRegister.index())) {
  1650. emitOpcode(op_ret_object_or_this);
  1651. instructions().append(src->index());
  1652. instructions().append(m_thisRegister.index());
  1653. return src;
  1654. }
  1655. return emitUnaryNoDstOp(op_ret, src);
  1656. }
  1657. RegisterID* BytecodeGenerator::emitUnaryNoDstOp(OpcodeID opcodeID, RegisterID* src)
  1658. {
  1659. emitOpcode(opcodeID);
  1660. instructions().append(src->index());
  1661. return src;
  1662. }
  1663. RegisterID* BytecodeGenerator::emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction expectedFunction, CallArguments& callArguments, unsigned divot, unsigned startOffset, unsigned endOffset, unsigned line, unsigned lineStart)
  1664. {
  1665. ASSERT(func->refCount());
  1666. if (m_shouldEmitProfileHooks)
  1667. emitMove(callArguments.profileHookRegister(), func);
  1668. // Generate code for arguments.
  1669. unsigned argument = 0;
  1670. if (ArgumentsNode* argumentsNode = callArguments.argumentsNode()) {
  1671. for (ArgumentListNode* n = argumentsNode->m_listNode; n; n = n->m_next)
  1672. emitNode(callArguments.argumentRegister(argument++), n);
  1673. }
  1674. if (m_shouldEmitProfileHooks) {
  1675. emitOpcode(op_profile_will_call);
  1676. instructions().append(callArguments.profileHookRegister()->index());
  1677. }
  1678. // Reserve space for call frame.
  1679. Vector<RefPtr<RegisterID>, JSStack::CallFrameHeaderSize, UnsafeVectorOverflow> callFrame;
  1680. for (int i = 0; i < JSStack::CallFrameHeaderSize; ++i)
  1681. callFrame.append(newTemporary());
  1682. emitExpressionInfo(divot, startOffset, endOffset, line, lineStart);
  1683. RefPtr<Label> done = newLabel();
  1684. expectedFunction = emitExpectedFunctionSnippet(dst, func, expectedFunction, callArguments, done.get());
  1685. emitOpcode(op_construct);
  1686. instructions().append(func->index()); // func
  1687. instructions().append(callArguments.argumentCountIncludingThis()); // argCount
  1688. instructions().append(callArguments.registerOffset()); // registerOffset
  1689. #if ENABLE(LLINT)
  1690. instructions().append(m_codeBlock->addLLIntCallLinkInfo());
  1691. #else
  1692. instructions().append(0);
  1693. #endif
  1694. instructions().append(0);
  1695. if (dst != ignoredResult()) {
  1696. UnlinkedValueProfile profile = emitProfiledOpcode(op_call_put_result);
  1697. instructions().append(kill(dst));
  1698. instructions().append(profile);
  1699. }
  1700. if (expectedFunction != NoExpectedFunction)
  1701. emitLabel(done.get());
  1702. if (m_shouldEmitProfileHooks) {
  1703. emitOpcode(op_profile_did_call);
  1704. instructions().append(callArguments.profileHookRegister()->index());
  1705. }
  1706. return dst;
  1707. }
  1708. RegisterID* BytecodeGenerator::emitStrcat(RegisterID* dst, RegisterID* src, int count)
  1709. {
  1710. emitOpcode(op_strcat);
  1711. instructions().append(dst->index());
  1712. instructions().append(src->index());
  1713. instructions().append(count);
  1714. return dst;
  1715. }
  1716. void BytecodeGenerator::emitToPrimitive(RegisterID* dst, RegisterID* src)
  1717. {
  1718. emitOpcode(op_to_primitive);
  1719. instructions().append(dst->index());
  1720. instructions().append(src->index());
  1721. }
  1722. RegisterID* BytecodeGenerator::emitPushWithScope(RegisterID* scope)
  1723. {
  1724. ControlFlowContext context;
  1725. context.isFinallyBlock = false;
  1726. m_scopeContextStack.append(context);
  1727. m_dynamicScopeDepth++;
  1728. return emitUnaryNoDstOp(op_push_with_scope, scope);
  1729. }
  1730. void BytecodeGenerator::emitPopScope()
  1731. {
  1732. ASSERT(m_scopeContextStack.size());
  1733. ASSERT(!m_scopeContextStack.last().isFinallyBlock);
  1734. emitOpcode(op_pop_scope);
  1735. m_scopeContextStack.removeLast();
  1736. m_dynamicScopeDepth--;
  1737. }
  1738. void BytecodeGenerator::emitDebugHook(DebugHookID debugHookID, unsigned firstLine, unsigned lastLine, unsigned charOffset, unsigned lineStart)
  1739. {
  1740. #if ENABLE(DEBUG_WITH_BREAKPOINT)
  1741. if (debugHookID != DidReachBreakpoint)
  1742. return;
  1743. #else
  1744. if (!m_shouldEmitDebugHooks)
  1745. return;
  1746. #endif
  1747. emitExpressionInfo(charOffset, 0, 0, firstLine, lineStart);
  1748. unsigned charPosition = charOffset - m_scopeNode->source().startOffset();
  1749. emitOpcode(op_debug);
  1750. instructions().append(debugHookID);
  1751. instructions().append(firstLine);
  1752. instructions().append(lastLine);
  1753. instructions().append(charPosition);
  1754. }
  1755. void BytecodeGenerator::pushFinallyContext(StatementNode* finallyBlock)
  1756. {
  1757. ControlFlowContext scope;
  1758. scope.isFinallyBlock = true;
  1759. FinallyContext context = {
  1760. finallyBlock,
  1761. static_cast<unsigned>(m_scopeContextStack.size()),
  1762. static_cast<unsigned>(m_switchContextStack.size()),
  1763. static_cast<unsigned>(m_forInContextStack.size()),
  1764. static_cast<unsigned>(m_tryContextStack.size()),
  1765. static_cast<unsigned>(m_labelScopes.size()),
  1766. m_finallyDepth,
  1767. m_dynamicScopeDepth
  1768. };
  1769. scope.finallyContext = context;
  1770. m_scopeContextStack.append(scope);
  1771. m_finallyDepth++;
  1772. }
  1773. void BytecodeGenerator::popFinallyContext()
  1774. {
  1775. ASSERT(m_scopeContextStack.size());
  1776. ASSERT(m_scopeContextStack.last().isFinallyBlock);
  1777. ASSERT(m_finallyDepth > 0);
  1778. m_scopeContextStack.removeLast();
  1779. m_finallyDepth--;
  1780. }
  1781. LabelScope* BytecodeGenerator::breakTarget(const Identifier& name)
  1782. {
  1783. // Reclaim free label scopes.
  1784. //
  1785. // The condition was previously coded as 'm_labelScopes.size() && !m_labelScopes.last().refCount()',
  1786. // however sometimes this appears to lead to GCC going a little haywire and entering the loop with
  1787. // size 0, leading to segfaulty badness. We are yet to identify a valid cause within our code to
  1788. // cause the GCC codegen to misbehave in this fashion, and as such the following refactoring of the
  1789. // loop condition is a workaround.
  1790. while (m_labelScopes.size()) {
  1791. if (m_labelScopes.last().refCount())
  1792. break;
  1793. m_labelScopes.removeLast();
  1794. }
  1795. if (!m_labelScopes.size())
  1796. return 0;
  1797. // We special-case the following, which is a syntax error in Firefox:
  1798. // label:
  1799. // break;
  1800. if (name.isEmpty()) {
  1801. for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
  1802. LabelScope* scope = &m_labelScopes[i];
  1803. if (scope->type() != LabelScope::NamedLabel) {
  1804. ASSERT(scope->breakTarget());
  1805. return scope;
  1806. }
  1807. }
  1808. return 0;
  1809. }
  1810. for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
  1811. LabelScope* scope = &m_labelScopes[i];
  1812. if (scope->name() && *scope->name() == name) {
  1813. ASSERT(scope->breakTarget());
  1814. return scope;
  1815. }
  1816. }
  1817. return 0;
  1818. }
  1819. LabelScope* BytecodeGenerator::continueTarget(const Identifier& name)
  1820. {
  1821. // Reclaim free label scopes.
  1822. while (m_labelScopes.size() && !m_labelScopes.last().refCount())
  1823. m_labelScopes.removeLast();
  1824. if (!m_labelScopes.size())
  1825. return 0;
  1826. if (name.isEmpty()) {
  1827. for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
  1828. LabelScope* scope = &m_labelScopes[i];
  1829. if (scope->type() == LabelScope::Loop) {
  1830. ASSERT(scope->continueTarget());
  1831. return scope;
  1832. }
  1833. }
  1834. return 0;
  1835. }
  1836. // Continue to the loop nested nearest to the label scope that matches
  1837. // 'name'.
  1838. LabelScope* result = 0;
  1839. for (int i = m_labelScopes.size() - 1; i >= 0; --i) {
  1840. LabelScope* scope = &m_labelScopes[i];
  1841. if (scope->type() == LabelScope::Loop) {
  1842. ASSERT(scope->continueTarget());
  1843. result = scope;
  1844. }
  1845. if (scope->name() && *scope->name() == name)
  1846. return result; // may be 0
  1847. }
  1848. return 0;
  1849. }
  1850. void BytecodeGenerator::emitComplexPopScopes(ControlFlowContext* topScope, ControlFlowContext* bottomScope)
  1851. {
  1852. while (topScope > bottomScope) {
  1853. // First we count the number of dynamic scopes we need to remove to get
  1854. // to a finally block.
  1855. int nNormalScopes = 0;
  1856. while (topScope > bottomScope) {
  1857. if (topScope->isFinallyBlock)
  1858. break;
  1859. ++nNormalScopes;
  1860. --topScope;
  1861. }
  1862. if (nNormalScopes) {
  1863. // We need to remove a number of dynamic scopes to get to the next
  1864. // finally block
  1865. while (nNormalScopes--)
  1866. emitOpcode(op_pop_scope);
  1867. // If topScope == bottomScope then there isn't a finally block left to emit.
  1868. if (topScope == bottomScope)
  1869. return;
  1870. }
  1871. Vector<ControlFlowContext> savedScopeContextStack;
  1872. Vector<SwitchInfo> savedSwitchContextStack;
  1873. Vector<ForInContext> savedForInContextStack;
  1874. Vector<TryContext> poppedTryContexts;
  1875. LabelScopeStore savedLabelScopes;
  1876. while (topScope > bottomScope && topScope->isFinallyBlock) {
  1877. RefPtr<Label> beforeFinally = emitLabel(newLabel().get());
  1878. // Save the current state of the world while instating the state of the world
  1879. // for the finally block.
  1880. FinallyContext finallyContext = topScope->finallyContext;
  1881. bool flipScopes = finallyContext.scopeContextStackSize != m_scopeContextStack.size();
  1882. bool flipSwitches = finallyContext.switchContextStackSize != m_switchContextStack.size();
  1883. bool flipForIns = finallyContext.forInContextStackSize != m_forInContextStack.size();
  1884. bool flipTries = finallyContext.tryContextStackSize != m_tryContextStack.size();
  1885. bool flipLabelScopes = finallyContext.labelScopesSize != m_labelScopes.size();
  1886. int topScopeIndex = -1;
  1887. int bottomScopeIndex = -1;
  1888. if (flipScopes) {
  1889. topScopeIndex = topScope - m_scopeContextStack.begin();
  1890. bottomScopeIndex = bottomScope - m_scopeContextStack.begin();
  1891. savedScopeContextStack = m_scopeContextStack;
  1892. m_scopeContextStack.shrink(finallyContext.scopeContextStackSize);
  1893. }
  1894. if (flipSwitches) {
  1895. savedSwitchContextStack = m_switchContextStack;
  1896. m_switchContextStack.shrink(finallyContext.switchContextStackSize);
  1897. }
  1898. if (flipForIns) {
  1899. savedForInContextStack = m_forInContextStack;
  1900. m_forInContextStack.shrink(finallyContext.forInContextStackSize);
  1901. }
  1902. if (flipTries) {
  1903. while (m_tryContextStack.size() != finallyContext.tryContextStackSize) {
  1904. ASSERT(m_tryContextStack.size() > finallyContext.tryContextStackSize);
  1905. TryContext context = m_tryContextStack.last();
  1906. m_tryContextStack.removeLast();
  1907. TryRange range;
  1908. range.start = context.start;
  1909. range.end = beforeFinally;
  1910. range.tryData = context.tryData;
  1911. m_tryRanges.append(range);
  1912. poppedTryContexts.append(context);
  1913. }
  1914. }
  1915. if (flipLabelScopes) {
  1916. savedLabelScopes = m_labelScopes;
  1917. while (m_labelScopes.size() > finallyContext.labelScopesSize)
  1918. m_labelScopes.removeLast();
  1919. }
  1920. int savedFinallyDepth = m_finallyDepth;
  1921. m_finallyDepth = finallyContext.finallyDepth;
  1922. int savedDynamicScopeDepth = m_dynamicScopeDepth;
  1923. m_dynamicScopeDepth = finallyContext.dynamicScopeDepth;
  1924. // Emit the finally block.
  1925. emitNode(finallyContext.finallyBlock);
  1926. RefPtr<Label> afterFinally = emitLabel(newLabel().get());
  1927. // Restore the state of the world.
  1928. if (flipScopes) {
  1929. m_scopeContextStack = savedScopeContextStack;
  1930. topScope = &m_scopeContextStack[topScopeIndex]; // assert it's within bounds
  1931. bottomScope = m_scopeContextStack.begin() + bottomScopeIndex; // don't assert, since it the index might be -1.
  1932. }
  1933. if (flipSwitches)
  1934. m_switchContextStack = savedSwitchContextStack;
  1935. if (flipForIns)
  1936. m_forInContextStack = savedForInContextStack;
  1937. if (flipTries) {
  1938. ASSERT(m_tryContextStack.size() == finallyContext.tryContextStackSize);
  1939. for (unsigned i = poppedTryContexts.size(); i--;) {
  1940. TryContext context = poppedTryContexts[i];
  1941. context.start = afterFinally;
  1942. m_tryContextStack.append(context);
  1943. }
  1944. poppedTryContexts.clear();
  1945. }
  1946. if (flipLabelScopes)
  1947. m_labelScopes = savedLabelScopes;
  1948. m_finallyDepth = savedFinallyDepth;
  1949. m_dynamicScopeDepth = savedDynamicScopeDepth;
  1950. --topScope;
  1951. }
  1952. }
  1953. }
  1954. void BytecodeGenerator::emitPopScopes(int targetScopeDepth)
  1955. {
  1956. ASSERT(scopeDepth() - targetScopeDepth >= 0);
  1957. size_t scopeDelta = scopeDepth() - targetScopeDepth;
  1958. ASSERT(scopeDelta <= m_scopeContextStack.size());
  1959. if (!scopeDelta)
  1960. return;
  1961. if (!m_finallyDepth) {
  1962. while (scopeDelta--)
  1963. emitOpcode(op_pop_scope);
  1964. return;
  1965. }
  1966. emitComplexPopScopes(&m_scopeContextStack.last(), &m_scopeContextStack.last() - scopeDelta);
  1967. }
  1968. RegisterID* BytecodeGenerator::emitGetPropertyNames(RegisterID* dst, RegisterID* base, RegisterID* i, RegisterID* size, Label* breakTarget)
  1969. {
  1970. size_t begin = instructions().size();
  1971. emitOpcode(op_get_pnames);
  1972. instructions().append(dst->index());
  1973. instructions().append(base->index());
  1974. instructions().append(i->index());
  1975. instructions().append(size->index());
  1976. instructions().append(breakTarget->bind(begin, instructions().size()));
  1977. return dst;
  1978. }
  1979. RegisterID* BytecodeGenerator::emitNextPropertyName(RegisterID* dst, RegisterID* base, RegisterID* i, RegisterID* size, RegisterID* iter, Label* target)
  1980. {
  1981. size_t begin = instructions().size();
  1982. emitOpcode(op_next_pname);
  1983. instructions().append(dst->index());
  1984. instructions().append(base->index());
  1985. instructions().append(i->index());
  1986. instructions().append(size->index());
  1987. instructions().append(iter->index());
  1988. instructions().append(target->bind(begin, instructions().size()));
  1989. return dst;
  1990. }
  1991. TryData* BytecodeGenerator::pushTry(Label* start)
  1992. {
  1993. TryData tryData;
  1994. tryData.target = newLabel();
  1995. tryData.targetScopeDepth = UINT_MAX;
  1996. m_tryData.append(tryData);
  1997. TryData* result = &m_tryData.last();
  1998. TryContext tryContext;
  1999. tryContext.start = start;
  2000. tryContext.tryData = result;
  2001. m_tryContextStack.append(tryContext);
  2002. return result;
  2003. }
  2004. RegisterID* BytecodeGenerator::popTryAndEmitCatch(TryData* tryData, RegisterID* targetRegister, Label* end)
  2005. {
  2006. m_usesExceptions = true;
  2007. ASSERT_UNUSED(tryData, m_tryContextStack.last().tryData == tryData);
  2008. TryRange tryRange;
  2009. tryRange.start = m_tryContextStack.last().start;
  2010. tryRange.end = end;
  2011. tryRange.tryData = m_tryContextStack.last().tryData;
  2012. m_tryRanges.append(tryRange);
  2013. m_tryContextStack.removeLast();
  2014. emitLabel(tryRange.tryData->target.get());
  2015. tryRange.tryData->targetScopeDepth = m_dynamicScopeDepth;
  2016. emitOpcode(op_catch);
  2017. instructions().append(targetRegister->index());
  2018. return targetRegister;
  2019. }
  2020. void BytecodeGenerator::emitThrowReferenceError(const String& message)
  2021. {
  2022. emitOpcode(op_throw_static_error);
  2023. instructions().append(addConstantValue(addStringConstant(Identifier(m_vm, message)))->index());
  2024. instructions().append(true);
  2025. }
  2026. void BytecodeGenerator::emitPushNameScope(const Identifier& property, RegisterID* value, unsigned attributes)
  2027. {
  2028. ControlFlowContext context;
  2029. context.isFinallyBlock = false;
  2030. m_scopeContextStack.append(context);
  2031. m_dynamicScopeDepth++;
  2032. emitOpcode(op_push_name_scope);
  2033. instructions().append(addConstant(property));
  2034. instructions().append(value->index());
  2035. instructions().append(attributes);
  2036. }
  2037. void BytecodeGenerator::beginSwitch(RegisterID* scrutineeRegister, SwitchInfo::SwitchType type)
  2038. {
  2039. SwitchInfo info = { static_cast<uint32_t>(instructions().size()), type };
  2040. switch (type) {
  2041. case SwitchInfo::SwitchImmediate:
  2042. emitOpcode(op_switch_imm);
  2043. break;
  2044. case SwitchInfo::SwitchCharacter:
  2045. emitOpcode(op_switch_char);
  2046. break;
  2047. case SwitchInfo::SwitchString:
  2048. emitOpcode(op_switch_string);
  2049. break;
  2050. default:
  2051. RELEASE_ASSERT_NOT_REACHED();
  2052. }
  2053. instructions().append(0); // place holder for table index
  2054. instructions().append(0); // place holder for default target
  2055. instructions().append(scrutineeRegister->index());
  2056. m_switchContextStack.append(info);
  2057. }
  2058. static int32_t keyForImmediateSwitch(ExpressionNode* node, int32_t min, int32_t max)
  2059. {
  2060. UNUSED_PARAM(max);
  2061. ASSERT(node->isNumber());
  2062. double value = static_cast<NumberNode*>(node)->value();
  2063. int32_t key = static_cast<int32_t>(value);
  2064. ASSERT(key == value);
  2065. ASSERT(key >= min);
  2066. ASSERT(key <= max);
  2067. return key - min;
  2068. }
  2069. static void prepareJumpTableForImmediateSwitch(UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max)
  2070. {
  2071. jumpTable.min = min;
  2072. jumpTable.branchOffsets.resize(max - min + 1);
  2073. jumpTable.branchOffsets.fill(0);
  2074. for (uint32_t i = 0; i < clauseCount; ++i) {
  2075. // We're emitting this after the clause labels should have been fixed, so
  2076. // the labels should not be "forward" references
  2077. ASSERT(!labels[i]->isForward());
  2078. jumpTable.add(keyForImmediateSwitch(nodes[i], min, max), labels[i]->bind(switchAddress, switchAddress + 3));
  2079. }
  2080. }
  2081. static int32_t keyForCharacterSwitch(ExpressionNode* node, int32_t min, int32_t max)
  2082. {
  2083. UNUSED_PARAM(max);
  2084. ASSERT(node->isString());
  2085. StringImpl* clause = static_cast<StringNode*>(node)->value().impl();
  2086. ASSERT(clause->length() == 1);
  2087. int32_t key = (*clause)[0];
  2088. ASSERT(key >= min);
  2089. ASSERT(key <= max);
  2090. return key - min;
  2091. }
  2092. static void prepareJumpTableForCharacterSwitch(UnlinkedSimpleJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, int32_t min, int32_t max)
  2093. {
  2094. jumpTable.min = min;
  2095. jumpTable.branchOffsets.resize(max - min + 1);
  2096. jumpTable.branchOffsets.fill(0);
  2097. for (uint32_t i = 0; i < clauseCount; ++i) {
  2098. // We're emitting this after the clause labels should have been fixed, so
  2099. // the labels should not be "forward" references
  2100. ASSERT(!labels[i]->isForward());
  2101. jumpTable.add(keyForCharacterSwitch(nodes[i], min, max), labels[i]->bind(switchAddress, switchAddress + 3));
  2102. }
  2103. }
  2104. static void prepareJumpTableForStringSwitch(UnlinkedStringJumpTable& jumpTable, int32_t switchAddress, uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes)
  2105. {
  2106. for (uint32_t i = 0; i < clauseCount; ++i) {
  2107. // We're emitting this after the clause labels should have been fixed, so
  2108. // the labels should not be "forward" references
  2109. ASSERT(!labels[i]->isForward());
  2110. ASSERT(nodes[i]->isString());
  2111. StringImpl* clause = static_cast<StringNode*>(nodes[i])->value().impl();
  2112. jumpTable.offsetTable.add(clause, labels[i]->bind(switchAddress, switchAddress + 3));
  2113. }
  2114. }
  2115. void BytecodeGenerator::endSwitch(uint32_t clauseCount, RefPtr<Label>* labels, ExpressionNode** nodes, Label* defaultLabel, int32_t min, int32_t max)
  2116. {
  2117. SwitchInfo switchInfo = m_switchContextStack.last();
  2118. m_switchContextStack.removeLast();
  2119. if (switchInfo.switchType == SwitchInfo::SwitchImmediate) {
  2120. instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfImmediateSwitchJumpTables();
  2121. instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
  2122. UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addImmediateSwitchJumpTable();
  2123. prepareJumpTableForImmediateSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max);
  2124. } else if (switchInfo.switchType == SwitchInfo::SwitchCharacter) {
  2125. instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfCharacterSwitchJumpTables();
  2126. instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
  2127. UnlinkedSimpleJumpTable& jumpTable = m_codeBlock->addCharacterSwitchJumpTable();
  2128. prepareJumpTableForCharacterSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes, min, max);
  2129. } else {
  2130. ASSERT(switchInfo.switchType == SwitchInfo::SwitchString);
  2131. instructions()[switchInfo.bytecodeOffset + 1] = m_codeBlock->numberOfStringSwitchJumpTables();
  2132. instructions()[switchInfo.bytecodeOffset + 2] = defaultLabel->bind(switchInfo.bytecodeOffset, switchInfo.bytecodeOffset + 3);
  2133. UnlinkedStringJumpTable& jumpTable = m_codeBlock->addStringSwitchJumpTable();
  2134. prepareJumpTableForStringSwitch(jumpTable, switchInfo.bytecodeOffset, clauseCount, labels, nodes);
  2135. }
  2136. }
  2137. RegisterID* BytecodeGenerator::emitThrowExpressionTooDeepException()
  2138. {
  2139. // It would be nice to do an even better job of identifying exactly where the expression is.
  2140. // And we could make the caller pass the node pointer in, if there was some way of getting
  2141. // that from an arbitrary node. However, calling emitExpressionInfo without any useful data
  2142. // is still good enough to get us an accurate line number.
  2143. m_expressionTooDeep = true;
  2144. return newTemporary();
  2145. }
  2146. void BytecodeGenerator::setIsNumericCompareFunction(bool isNumericCompareFunction)
  2147. {
  2148. m_codeBlock->setIsNumericCompareFunction(isNumericCompareFunction);
  2149. }
  2150. bool BytecodeGenerator::isArgumentNumber(const Identifier& ident, int argumentNumber)
  2151. {
  2152. RegisterID* registerID = resolve(ident).local();
  2153. if (!registerID || registerID->index() >= 0)
  2154. return 0;
  2155. return registerID->index() == CallFrame::argumentOffset(argumentNumber);
  2156. }
  2157. void BytecodeGenerator::emitReadOnlyExceptionIfNeeded()
  2158. {
  2159. if (!isStrictMode())
  2160. return;
  2161. emitOpcode(op_throw_static_error);
  2162. instructions().append(addConstantValue(addStringConstant(Identifier(m_vm, StrictModeReadonlyPropertyWriteError)))->index());
  2163. instructions().append(false);
  2164. }
  2165. } // namespace JSC