ByteCodeGenerator.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #if defined(_M_ARM32_OR_ARM64) || defined(_M_X64)
  6. const long AstBytecodeRatioEstimate = 4;
  7. #else
  8. const long AstBytecodeRatioEstimate = 5;
  9. #endif
  10. class ByteCodeGenerator
  11. {
  12. private:
  13. Js::ScriptContext* scriptContext;
  14. ArenaAllocator *alloc;
  15. ulong flags;
  16. Js::PropertyRecordList* propertyRecords;
  17. SList<FuncInfo*> *funcInfoStack;
  18. ParseNode *currentBlock;
  19. ParseNode *currentTopStatement;
  20. Scope *currentScope;
  21. Scope *globalScope; // the global members will be in this scope
  22. Js::ScopeInfo* parentScopeInfo;
  23. Js::ByteCodeWriter m_writer;
  24. // pointer to the root function wrapper that will be invoked by the caller
  25. Js::ParseableFunctionInfo * pRootFunc;
  26. long maxAstSize;
  27. uint16 envDepth;
  28. uint sourceIndex;
  29. uint dynamicScopeCount;
  30. uint loopDepth;
  31. uint16 m_callSiteId;
  32. bool isBinding;
  33. bool trackEnvDepth;
  34. bool funcEscapes;
  35. bool inPrologue;
  36. bool inDestructuredPattern;
  37. Parser* parser; // currently active parser (used for AST transformation)
  38. Js::Utf8SourceInfo *m_utf8SourceInfo;
  39. // The stack walker won't be able to find the current function being defer parse, pass in
  40. // The address so we can patch it up if it is a stack function and we need to box it.
  41. Js::ScriptFunction ** functionRef;
  42. public:
  43. // This points to the current function body which can be reused when parsing a subtree (called due to deferred parsing logic).
  44. Js::FunctionBody * pCurrentFunction;
  45. bool InDestructuredPattern() const { return inDestructuredPattern; }
  46. void SetInDestructuredPattern(bool in) { inDestructuredPattern = in; }
  47. bool InPrologue() const { return inPrologue; }
  48. void SetInPrologue(bool val) { inPrologue = val; }
  49. Parser* GetParser() { return parser; }
  50. Js::ParseableFunctionInfo * GetRootFunc(){return pRootFunc;}
  51. void SetRootFuncInfo(FuncInfo* funcInfo);
  52. // Treat the return value register like a constant register so that the byte code writer maps it to the bottom
  53. // of the register range.
  54. static const Js::RegSlot ReturnRegister = REGSLOT_TO_CONSTREG(Js::FunctionBody::ReturnValueRegSlot);
  55. static const Js::RegSlot RootObjectRegister = REGSLOT_TO_CONSTREG(Js::FunctionBody::RootObjectRegSlot);
  56. static const unsigned int DefaultArraySize = 0; // This __must__ be '0' so that "(new Array()).length == 0"
  57. static const unsigned int MinArgumentsForCallOptimization = 16;
  58. bool forceNoNative;
  59. ByteCodeGenerator(Js::ScriptContext* scriptContext, Js::ScopeInfo* parentScopeInfo);
  60. #if DBG_DUMP
  61. bool Trace() const
  62. {
  63. return Js::Configuration::Global.flags.Trace.IsEnabled(Js::ByteCodePhase);
  64. }
  65. #else
  66. bool Trace() const
  67. {
  68. return false;
  69. }
  70. #endif
  71. Js::ScriptContext* GetScriptContext() { return scriptContext; }
  72. Scope *GetCurrentScope() const { return currentScope; }
  73. void SetCurrentBlock(ParseNode *pnode) { currentBlock = pnode; }
  74. ParseNode *GetCurrentBlock() const { return currentBlock; }
  75. void SetCurrentTopStatement(ParseNode *pnode) { currentTopStatement = pnode; }
  76. ParseNode *GetCurrentTopStatement() const { return currentTopStatement; }
  77. Js::ModuleID GetModuleID() const
  78. {
  79. return m_utf8SourceInfo->GetSrcInfo()->moduleID;
  80. }
  81. void SetFlags(ulong grfscr)
  82. {
  83. flags = grfscr;
  84. }
  85. ulong GetFlags(void)
  86. {
  87. return flags;
  88. }
  89. bool IsConsoleScopeEval(void)
  90. {
  91. return (flags & fscrConsoleScopeEval) == fscrConsoleScopeEval;
  92. }
  93. bool IsBinding() const {
  94. return isBinding;
  95. }
  96. Js::ByteCodeWriter *Writer() {
  97. return &m_writer;
  98. }
  99. ArenaAllocator *GetAllocator() {
  100. return alloc;
  101. }
  102. Js::PropertyRecordList* EnsurePropertyRecordList()
  103. {
  104. if (this->propertyRecords == nullptr)
  105. {
  106. Recycler* recycler = this->scriptContext->GetRecycler();
  107. this->propertyRecords = RecyclerNew(recycler, Js::PropertyRecordList, recycler);
  108. }
  109. return this->propertyRecords;
  110. }
  111. bool IsEvalWithBlockScopingNoParentScopeInfo()
  112. {
  113. return (flags & fscrEvalCode) && !HasParentScopeInfo() && scriptContext->GetConfig()->IsBlockScopeEnabled();
  114. }
  115. Js::ProfileId GetNextCallSiteId(Js::OpCode op)
  116. {
  117. if (m_writer.ShouldIncrementCallSiteId(op))
  118. {
  119. if (m_callSiteId != Js::Constants::NoProfileId)
  120. {
  121. return m_callSiteId++;
  122. }
  123. }
  124. return m_callSiteId;
  125. }
  126. Js::RegSlot NextVarRegister();
  127. Js::RegSlot NextConstRegister();
  128. FuncInfo *TopFuncInfo() const;
  129. void EnterLoop();
  130. void ExitLoop() { loopDepth--; }
  131. BOOL IsInLoop() const { return loopDepth > 0; }
  132. // TODO: per-function register assignment for env and global symbols
  133. void AssignRegister(Symbol *sym);
  134. void AddTargetStmt(ParseNode *pnodeStmt);
  135. Js::RegSlot AssignNullConstRegister();
  136. Js::RegSlot AssignUndefinedConstRegister();
  137. Js::RegSlot AssignTrueConstRegister();
  138. Js::RegSlot AssignFalseConstRegister();
  139. Js::RegSlot AssignThisRegister();
  140. Js::RegSlot AssignNewTargetRegister();
  141. void SetNeedEnvRegister();
  142. void AssignFrameObjRegister();
  143. void AssignFrameSlotsRegister();
  144. void AssignFrameDisplayRegister();
  145. void InitScopeSlotArray(FuncInfo * funcInfo);
  146. void FinalizeRegisters(FuncInfo * funcInfo, Js::FunctionBody * byteCodeFunction);
  147. void SetHasTry(bool has);
  148. void SetHasFinally(bool has);
  149. void SetNumberOfInArgs(Js::ArgSlot argCount);
  150. Js::RegSlot EnregisterConstant(unsigned int constant);
  151. Js::RegSlot EnregisterStringConstant(IdentPtr pid);
  152. Js::RegSlot EnregisterDoubleConstant(double d);
  153. Js::RegSlot EnregisterStringTemplateCallsiteConstant(ParseNode* pnode);
  154. static Js::JavascriptArray* BuildArrayFromStringList(ParseNode* stringNodeList, uint arrayLength, Js::ScriptContext* scriptContext);
  155. bool HasParentScopeInfo() const
  156. {
  157. return this->parentScopeInfo != nullptr;
  158. }
  159. void RestoreScopeInfo(Js::FunctionBody* funcInfo);
  160. FuncInfo *StartBindGlobalStatements(ParseNode *pnode);
  161. void AssignPropertyId(Symbol *sym, Js::ParseableFunctionInfo* functionInfo);
  162. void AssignPropertyId(IdentPtr pid);
  163. void ProcessCapturedSyms(ParseNode *pnodeFnc);
  164. void RecordAllIntConstants(FuncInfo * funcInfo);
  165. void RecordAllStrConstants(FuncInfo * funcInfo);
  166. void RecordAllStringTemplateCallsiteConstants(FuncInfo* funcInfo);
  167. // For now, this just assigns field ids for the current script.
  168. // Later, we will combine this information with the global field ID map.
  169. // This temporary code will not work if a global member is accessed both with and without a LHS.
  170. void AssignPropertyIds(Js::ParseableFunctionInfo* functionInfo);
  171. void MapCacheIdsToPropertyIds(FuncInfo *funcInfo);
  172. void MapReferencedPropertyIds(FuncInfo *funcInfo);
  173. FuncInfo *StartBindFunction(const wchar_t *name, uint nameLength, uint shortNameOffset, bool* pfuncExprWithName, ParseNode *pnode);
  174. void EndBindFunction(bool funcExprWithName);
  175. void StartBindCatch(ParseNode *pnode);
  176. // Block scopes related functions
  177. template<class Fn> void IterateBlockScopedVariables(ParseNode *pnodeBlock, Fn fn);
  178. void InitBlockScopedContent(ParseNode *pnodeBlock, Js::DebuggerScope *debuggerScope, FuncInfo *funcInfo);
  179. Js::DebuggerScope* RecordStartScopeObject(ParseNode *pnodeBlock, Js::DiagExtraScopesType scopeType, Js::RegSlot scopeLocation = Js::Constants::NoRegister, int* index = nullptr);
  180. void RecordEndScopeObject(ParseNode *pnodeBlock);
  181. void EndBindCatch();
  182. void StartEmitFunction(ParseNode *pnodeFnc);
  183. void EndEmitFunction(ParseNode *pnodeFnc);
  184. void StartEmitBlock(ParseNode *pnodeBlock);
  185. void EndEmitBlock(ParseNode *pnodeBlock);
  186. void StartEmitCatch(ParseNode *pnodeCatch);
  187. void EndEmitCatch(ParseNode *pnodeCatch);
  188. void StartEmitWith(ParseNode *pnodeWith);
  189. void EndEmitWith(ParseNode *pnodeWith);
  190. void EnsureFncScopeSlots(ParseNode *pnode, FuncInfo *funcInfo);
  191. void EnsureLetConstScopeSlots(ParseNode *pnodeBlock, FuncInfo *funcInfo);
  192. void PushScope(Scope *innerScope);
  193. void PopScope();
  194. void PushBlock(ParseNode *pnode);
  195. void PopBlock();
  196. void PushFuncInfo(wchar_t const * location, FuncInfo* funcInfo);
  197. void PopFuncInfo(wchar_t const * location);
  198. Js::RegSlot PrependLocalScopes(Js::RegSlot evalEnv, Js::RegSlot tempLoc, FuncInfo *funcInfo);
  199. Symbol *FindSymbol(Symbol **symRef, IdentPtr pid, bool forReference = false);
  200. Symbol *AddSymbolToScope(Scope *scope, const wchar_t *key, int keyLength, ParseNode *varDecl, SymbolType symbolType);
  201. Symbol *AddSymbolToFunctionScope(const wchar_t *key, int keyLength, ParseNode *varDecl, SymbolType symbolType);
  202. void FuncEscapes(Scope *scope);
  203. void EmitTopLevelStatement(ParseNode *stmt, FuncInfo *funcInfo, BOOL fReturnValue);
  204. void EmitInvertedLoop(ParseNode* outerLoop,ParseNode* invertedLoop,FuncInfo* funcInfo);
  205. void DefineFunctions(FuncInfo *funcInfoParent);
  206. Js::RegSlot DefineOneFunction(ParseNode *pnodeFnc, FuncInfo *funcInfoParent, bool generateAssignment=true, Js::RegSlot regEnv = Js::Constants::NoRegister, Js::RegSlot frameDisplayTemp = Js::Constants::NoRegister);
  207. void DefineCachedFunctions(FuncInfo *funcInfoParent);
  208. void DefineUncachedFunctions(FuncInfo *funcInfoParent);
  209. void DefineUserVars(FuncInfo *funcInfo);
  210. void InitBlockScopedNonTemps(ParseNode *pnode, FuncInfo *funcInfo);
  211. // temporarily load all constants and special registers in a single block
  212. void LoadAllConstants(FuncInfo *funcInfo);
  213. void LoadHeapArguments(FuncInfo *funcInfo);
  214. void LoadUncachedHeapArguments(FuncInfo *funcInfo);
  215. void LoadCachedHeapArguments(FuncInfo *funcInfo);
  216. void LoadThisObject(FuncInfo *funcInfo, bool thisLoadedFromParams = false);
  217. void EmitThis(FuncInfo *funcInfo, Js::RegSlot fromRegister);
  218. void LoadNewTargetObject(FuncInfo *funcInfo);
  219. void GetEnclosingNonLambdaScope(FuncInfo *funcInfo, Scope * &scope, Js::PropertyId &envIndex);
  220. void EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl = false);
  221. void EmitInternalScopedSlotLoad(FuncInfo *funcInfo, Scope *scope, Js::PropertyId envIndex, Js::RegSlot slot, Js::RegSlot symbolRegister, bool chkUndecl = false);
  222. void EmitInternalScopedSlotStore(FuncInfo *funcInfo, Js::RegSlot slot, Js::RegSlot symbolRegister);
  223. void EmitInternalScopeObjInit(FuncInfo *funcInfo, Scope *scope, Js::RegSlot valueLocation, Js::PropertyId propertyId);
  224. void EmitSuperCall(FuncInfo* funcInfo, ParseNode* pnode, BOOL fReturnValue);
  225. void EmitScopeSlotLoadThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl = true);
  226. void EmitScopeSlotStoreThis(FuncInfo *funcInfo, Js::RegSlot regLoc, bool chkUndecl = false);
  227. void EmitClassConstructorEndCode(FuncInfo *funcInfo);
  228. void EmitBaseClassConstructorThisObject(FuncInfo *funcInfo);
  229. // TODO: home the 'this' argument
  230. void EmitLoadFormalIntoRegister(ParseNode *pnodeFormal, Js::RegSlot pos, FuncInfo *funcInfo);
  231. void HomeArguments(FuncInfo *funcInfo);
  232. void EnsureNoRedeclarations(ParseNode *pnodeBlock, FuncInfo *funcInfo);
  233. void DefineLabels(FuncInfo *funcInfo);
  234. void EmitProgram(ParseNode *pnodeProg);
  235. void EmitScopeList(ParseNode *pnode);
  236. void EmitDefaultArgs(FuncInfo *funcInfo, ParseNode *pnode);
  237. void EmitOneFunction(ParseNode *pnode);
  238. void EmitGlobalFncDeclInit(Js::RegSlot rhsLocation, Js::PropertyId propertyId, FuncInfo * funcInfo);
  239. void EmitLocalPropInit(Js::RegSlot rhsLocation, Symbol *sym, FuncInfo *funcInfo);
  240. void EmitPropStore(Js::RegSlot rhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo, bool isLet = false, bool isConst = false, bool isFncDeclVar = false);
  241. void EmitPropLoad(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo);
  242. void EmitPropDelete(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo);
  243. void EmitPropTypeof(Js::RegSlot lhsLocation, Symbol *sym, IdentPtr pid, FuncInfo *funcInfo);
  244. void EmitTypeOfFld(FuncInfo * funcInfo, Js::PropertyId propertyId, Js::RegSlot value, Js::RegSlot instance, Js::OpCode op1);
  245. void EmitLoadInstance(Symbol *sym, IdentPtr pid, Js::RegSlot *pThisLocation, Js::RegSlot *pTargetLocation, FuncInfo *funcInfo);
  246. void EmitGlobalBody(FuncInfo *funcInfo);
  247. void EmitFunctionBody(FuncInfo *funcInfo);
  248. void EmitAsmFunctionBody(FuncInfo *funcInfo);
  249. void EmitScopeObjectInit(FuncInfo *funcInfo);
  250. void EmitPatchableRootProperty(Js::OpCode opcode, Js::RegSlot regSlot, Js::PropertyId propertyId, bool isLoadMethod, bool isStore, FuncInfo *funcInfo);
  251. struct TryScopeRecord;
  252. JsUtil::DoublyLinkedList<TryScopeRecord> tryScopeRecordsList;
  253. void EmitLeaveOpCodesBeforeYield();
  254. void EmitTryBlockHeadersAfterYield();
  255. void InvalidateCachedOuterScopes(FuncInfo *funcInfo);
  256. bool InDynamicScope() const { return dynamicScopeCount != 0; }
  257. Scope * FindScopeForSym(Scope *symScope, Scope *scope, Js::PropertyId *envIndex, FuncInfo *funcInfo) const;
  258. static Js::OpCode GetStFldOpCode(bool isStrictMode, bool isRoot, bool isLetDecl, bool isConstDecl, bool isClassMemberInit)
  259. {
  260. return isClassMemberInit ? Js::OpCode::InitClassMember :
  261. isConstDecl ? (isRoot ? Js::OpCode::InitRootConstFld : Js::OpCode::InitConstFld) :
  262. isLetDecl ? (isRoot ? Js::OpCode::InitRootLetFld : Js::OpCode::InitLetFld) :
  263. isStrictMode ? (isRoot ? Js::OpCode::StRootFldStrict : Js::OpCode::StFldStrict) :
  264. isRoot ? Js::OpCode::StRootFld : Js::OpCode::StFld;
  265. }
  266. static Js::OpCode GetStFldOpCode(FuncInfo* funcInfo, bool isRoot, bool isLetDecl, bool isConstDecl, bool isClassMemberInit);
  267. static Js::OpCode GetScopedStFldOpCode(bool isStrictMode)
  268. {
  269. return isStrictMode ? Js::OpCode::ScopedStFldStrict : Js::OpCode::ScopedStFld;
  270. }
  271. static Js::OpCode GetScopedStFldOpCode(FuncInfo* funcInfo, bool isConsoleScopeLetConst = false);
  272. static Js::OpCode GetStElemIOpCode(bool isStrictMode)
  273. {
  274. return isStrictMode ? Js::OpCode::StElemI_A_Strict : Js::OpCode::StElemI_A;
  275. }
  276. static Js::OpCode GetStElemIOpCode(FuncInfo* funcInfo);
  277. bool DoJitLoopBodies(FuncInfo *funcInfo) const;
  278. static void Generate(__in ParseNode *pnode, ulong grfscr, __in ByteCodeGenerator* byteCodeGenerator, __inout Js::ParseableFunctionInfo ** ppRootFunc, __in uint sourceIndex, __in bool forceNoNative, __in Parser* parser, Js::ScriptFunction ** functionRef);
  279. void Begin(
  280. __in ArenaAllocator *alloc,
  281. __in ulong grfscr,
  282. __in Js::ParseableFunctionInfo* pRootFunc);
  283. void SetCurrentSourceIndex(uint sourceIndex) { this->sourceIndex = sourceIndex; }
  284. uint GetCurrentSourceIndex() { return sourceIndex; }
  285. static bool IsFalse(ParseNode* node);
  286. void StartStatement(ParseNode* node);
  287. void EndStatement(ParseNode* node);
  288. void StartSubexpression(ParseNode* node);
  289. void EndSubexpression(ParseNode* node);
  290. bool UseParserBindings() const;
  291. bool IsES6DestructuringEnabled() const;
  292. bool IsES6ForLoopSemanticsEnabled() const;
  293. // Debugger methods.
  294. bool IsInDebugMode() const;
  295. bool IsInNonDebugMode() const;
  296. bool ShouldTrackDebuggerMetadata() const;
  297. void TrackRegisterPropertyForDebugger(Js::DebuggerScope *debuggerScope, Symbol *symbol, FuncInfo *funcInfo, Js::DebuggerScopePropertyFlags flags = Js::DebuggerScopePropertyFlags_None, bool isFunctionDeclaration = false);
  298. void TrackActivationObjectPropertyForDebugger(Js::DebuggerScope *debuggerScope, Symbol *symbol, Js::DebuggerScopePropertyFlags flags = Js::DebuggerScopePropertyFlags_None, bool isFunctionDeclaration = false);
  299. void TrackSlotArrayPropertyForDebugger(Js::DebuggerScope *debuggerScope, Symbol* symbol, Js::PropertyId propertyId, Js::DebuggerScopePropertyFlags flags = Js::DebuggerScopePropertyFlags_None, bool isFunctionDeclaration = false);
  300. void TrackFunctionDeclarationPropertyForDebugger(Symbol *functionDeclarationSymbol, FuncInfo *funcInfoParent);
  301. void UpdateDebuggerPropertyInitializationOffset(Js::RegSlot location, Js::PropertyId propertyId, bool shouldConsumeRegister = true);
  302. FuncInfo *FindEnclosingNonLambda();
  303. bool CanStackNestedFunc(FuncInfo * funcInfo, bool trace = false);
  304. void CheckDeferParseHasMaybeEscapedNestedFunc();
  305. bool NeedObjectAsFunctionScope(FuncInfo * funcInfo, ParseNode * pnodeFnc) const;
  306. bool HasInterleavingDynamicScope(Symbol * sym) const;
  307. void MarkThisUsedInLambda();
  308. void EmitInitCapturedThis(FuncInfo* funcInfo, Scope* scope);
  309. void EmitInitCapturedNewTarget(FuncInfo* funcInfo, Scope* scope);
  310. Js::FunctionBody *EnsureFakeGlobalFuncForUndefer(ParseNode *pnode);
  311. Js::FunctionBody *MakeGlobalFunctionBody(ParseNode *pnode);
  312. static bool NeedScopeObjectForArguments(FuncInfo *funcInfo, ParseNode *pnodeFnc);
  313. Js::OpCode GetStSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, bool chkBlockVar, FuncInfo *funcInfo);
  314. Js::OpCode GetLdSlotOp(Scope *scope, int envIndex, Js::RegSlot scopeLocation, FuncInfo *funcInfo);
  315. Js::OpCode GetInitFldOp(Scope *scope, Js::RegSlot scopeLocation, FuncInfo *funcInfo, bool letDecl = false);
  316. private:
  317. bool NeedCheckBlockVar(Symbol* sym, Scope* scope, FuncInfo* funcInfo) const;
  318. Js::OpCode ToChkUndeclOp(Js::OpCode op) const;
  319. };
  320. template<class Fn> void ByteCodeGenerator::IterateBlockScopedVariables(ParseNode *pnodeBlock, Fn fn)
  321. {
  322. Assert(pnodeBlock->nop == knopBlock);
  323. for (auto lexvar = pnodeBlock->sxBlock.pnodeLexVars; lexvar; lexvar = lexvar->sxVar.pnodeNext)
  324. {
  325. fn(lexvar);
  326. }
  327. }
  328. struct ApplyCheck {
  329. bool matches;
  330. bool insideApplyCall;
  331. bool sawApply;
  332. };