Debian Codegraph @

js/src/frontend/CompilationStencil.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef frontend_CompilationStencil_h
8 #define frontend_CompilationStencil_h
9
10 #include "mozilla/AlreadyAddRefed.h" // already_AddRefed
11 #include "mozilla/Assertions.h" // MOZ_ASSERT, MOZ_RELEASE_ASSERT, MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE
12 #include "mozilla/Atomics.h" // mozilla::Atomic
13 #include "mozilla/Attributes.h" // MOZ_RAII, MOZ_STACK_CLASS
14 #include "mozilla/HashTable.h" // mozilla::HashMap, mozilla::DefaultHasher
15 #include "mozilla/Maybe.h" // mozilla::Maybe
16 #include "mozilla/MemoryReporting.h" // mozilla::MallocSizeOf
17 #include "mozilla/RefPtr.h" // RefPtr
18 #include "mozilla/Span.h" // mozilla::Span
19 #include "mozilla/Variant.h" // mozilla::Variant
20
21 #include <algorithm> // std::swap
22 #include <stddef.h> // size_t
23 #include <stdint.h> // uint32_t, uintptr_t
24 #include <type_traits> // std::is_pointer_v
25 #include <utility> // std::forward, std::move
26
27 #include "ds/LifoAlloc.h" // LifoAlloc, LifoAllocScope
28 #include "frontend/FrontendContext.h" // FrontendContext
29 #include "frontend/FunctionSyntaxKind.h" // FunctionSyntaxKind
30 #include "frontend/NameAnalysisTypes.h" // NameLocation
31 #include "frontend/ParserAtom.h" // ParserAtomsTable, ParserAtomIndex, TaggedParserAtomIndex, ParserAtomSpan
32 #include "frontend/ScopeIndex.h" // ScopeIndex
33 #include "frontend/ScriptIndex.h" // ScriptIndex
34 #include "frontend/SharedContext.h" // ThisBinding, InheritThis, Directives
35 #include "frontend/Stencil.h" // ScriptStencil, ScriptStencilExtra, ScopeStencil, RegExpStencil, BigIntStencil, ObjLiteralStencil, BaseParserScopeData, StencilModuleMetadata
36 #include "frontend/TaggedParserAtomIndexHasher.h" // TaggedParserAtomIndexHasher
37 #include "frontend/UsedNameTracker.h" // UsedNameTracker
38 #include "js/AllocPolicy.h" // SystemAllocPolicy, ReportOutOfMemory
39 #include "js/GCVector.h" // JS::GCVector
40 #include "js/RefCounted.h" // AtomicRefCounted
41 #include "js/RootingAPI.h" // JS::Handle
42 #include "js/Transcoding.h" // JS::TranscodeBuffer, JS::TranscodeRange
43 #include "js/UniquePtr.h" // js::UniquePtr
44 #include "js/Vector.h" // Vector
45 #include "js/WasmModule.h" // JS::WasmModule
46 #include "vm/FunctionFlags.h" // FunctionFlags
47 #include "vm/GlobalObject.h" // GlobalObject
48 #include "vm/JSContext.h" // JSContext
49 #include "vm/JSFunction.h" // JSFunction
50 #include "vm/JSScript.h" // BaseScript, ScriptSource, SourceExtent
51 #include "vm/Realm.h" // JSContext::global
52 #include "vm/Scope.h" // Scope, ModuleScope
53 #include "vm/ScopeKind.h" // ScopeKind
54 #include "vm/SharedStencil.h" // ImmutableScriptFlags, MemberInitializers, SharedImmutableScriptData, RO_IMMUTABLE_SCRIPT_FLAGS
55
56 class JSAtom;
57 class JSFunction;
58 class JSObject;
59 class JSString;
60 class JSTracer;
61
62 namespace JS {
63 class JS_PUBLIC_API ReadOnlyCompileOptions;
64 }
65
66 namespace js {
67
68 class AtomSet;
69 class JSONPrinter;
70 class ModuleObject;
71
72 namespace frontend {
73
74 struct CompilationInput;
75 struct CompilationStencil;
76 struct CompilationGCOutput;
77 struct PreallocatedCompilationGCOutput;
78 class ScriptStencilIterable;
79 struct InputName;
80 class ScopeBindingCache;
81
82 // When delazifying modules' inner functions, the actual global scope is used.
83 // However, when doing a delazification the global scope is not available. We
84 // use this dummy type to be a placeholder to be used as part of the InputScope
85 // variants to mimic what the Global scope would be used for.
86 struct FakeStencilGlobalScope {};
87
88 // Reference to a Scope within a CompilationStencil.
89 struct ScopeStencilRef {
90 const CompilationStencil& context_;
91 const ScopeIndex scopeIndex_;
92
93 // Lookup the ScopeStencil referenced by this ScopeStencilRef.
94 inline const ScopeStencil& scope() const;
95 };
96
97 // Wraps a scope for a CompilationInput. The scope is either as a GC pointer to
98 // an instantiated scope, or as a reference to a CompilationStencil.
99 //
100 // Note: A scope reference may be nullptr/InvalidIndex if there is no such
101 // scope, such as the enclosingScope at the end of a scope chain. See `isNull`
102 // helper.
103 class InputScope {
104 using InputScopeStorage =
105 mozilla::Variant<Scope*, ScopeStencilRef, FakeStencilGlobalScope>;
106 InputScopeStorage scope_;
107
108 public:
109 // Create an InputScope given an instantiated scope.
110 explicit InputScope(Scope* ptr) : scope_(ptr) {}
111
112 // Create an InputScope for a global.
113 explicit InputScope(FakeStencilGlobalScope global) : scope_(global) {}
114
115 // Create an InputScope given a CompilationStencil and the ScopeIndex which is
116 // an offset within the same CompilationStencil given as argument.
117 InputScope(const CompilationStencil& context, ScopeIndex scopeIndex)
118 : scope_(ScopeStencilRef{context, scopeIndex}) {}
119
120 // Returns the variant used by the InputScope. This can be useful for complex
121 // cases where the following accessors are not enough.
122 const InputScopeStorage& variant() const { return scope_; }
123 InputScopeStorage& variant() { return scope_; }
124
125 // This match function will unwrap the variant for each type, and will
126 // specialize and call the Matcher given as argument with the type and value
127 // of the stored pointer / reference.
128 //
129 // This is useful for cases where the code is literally identical despite
130 // having different specializations. This is achiveable by relying on
131 // function overloading when the usage differ between the 2 types.
132 //
133 // Example:
134 // inputScope.match([](auto& scope) {
135 // // scope is either a `Scope*` or a `ScopeStencilRef`.
136 // for (auto bi = InputBindingIter(scope); bi; bi++) {
137 // InputName name(scope, bi.name());
138 // // ...
139 // }
140 // });
141 template <typename Matcher>
142 decltype(auto) match(Matcher&& matcher) const& {
143 return scope_.match(std::forward<Matcher>(matcher));
144 }
145 template <typename Matcher>
146 decltype(auto) match(Matcher&& matcher) & {
147 return scope_.match(std::forward<Matcher>(matcher));
148 }
149
150 bool isNull() const {
151 return scope_.match(
152 [](const Scope* ptr) { return !ptr; },
153 [](const ScopeStencilRef& ref) { return !ref.scopeIndex_.isValid(); },
154 [](const FakeStencilGlobalScope&) { return false; });
155 }
156
157 ScopeKind kind() const {
158 return scope_.match(
159 [](const Scope* ptr) { return ptr->kind(); },
160 [](const ScopeStencilRef& ref) { return ref.scope().kind(); },
161 [](const FakeStencilGlobalScope&) { return ScopeKind::Global; });
162 };
163 bool hasEnvironment() const {
164 return scope_.match(
165 [](const Scope* ptr) { return ptr->hasEnvironment(); },
166 [](const ScopeStencilRef& ref) { return ref.scope().hasEnvironment(); },
167 [](const FakeStencilGlobalScope&) {
168 // See Scope::hasEnvironment
169 return true;
170 });
171 };
172 inline InputScope enclosing() const;
173 bool hasOnChain(ScopeKind kind) const {
174 return scope_.match([=](const Scope* ptr) { return ptr->hasOnChain(kind); },
175 [=](const ScopeStencilRef& ref) {
176 ScopeStencilRef it = ref;
177 while (true) {
178 const ScopeStencil& scope = it.scope();
179 if (scope.kind() == kind) {
180 return true;
181 }
182 if (scope.kind() == ScopeKind::Module &&
183 kind == ScopeKind::Global) {
184 return true;
185 }
186 if (!scope.hasEnclosing()) {
187 break;
188 }
189 new (&it) ScopeStencilRef{ref.context_,
190 scope.enclosing()};
191 }
192 return false;
193 },
194 [=](const FakeStencilGlobalScope&) {
195 return kind == ScopeKind::Global;
196 });
197 }
198 uint32_t environmentChainLength() const {
199 return scope_.match(
200 [](const Scope* ptr) { return ptr->environmentChainLength(); },
201 [](const ScopeStencilRef& ref) {
202 uint32_t length = 0;
203 ScopeStencilRef it = ref;
204 while (true) {
205 const ScopeStencil& scope = it.scope();
206 if (scope.hasEnvironment() &&
207 scope.kind() != ScopeKind::NonSyntactic) {
208 length++;
209 }
210 if (scope.kind() == ScopeKind::Module) {
211 // Stencil do not encode the Global scope, as it used to be
212 // assumed to already exists. As moving delazification off-thread,
213 // we need to materialize a fake-stencil version of the Global
214 // Scope.
215 MOZ_ASSERT(!scope.hasEnclosing());
216 length += js::ModuleScope::EnclosingEnvironmentChainLength;
217 }
218 if (!scope.hasEnclosing()) {
219 break;
220 }
221 new (&it) ScopeStencilRef{ref.context_, scope.enclosing()};
222 }
223 return length;
224 },
225 [=](const FakeStencilGlobalScope&) {
226 // Stencil-based delazification needs to calculate
227 // environmentChainLength where the global is not available.
228 //
229 // The FakeStencilGlobalScope is used to represent what the global
230 // would be if we had access to it while delazifying.
231 return uint32_t(js::ModuleScope::EnclosingEnvironmentChainLength);
232 });
233 }
234 void trace(JSTracer* trc);
235 bool isStencil() const { return !scope_.is<Scope*>(); };
236
237 // Various accessors which are valid only when the InputScope is a
238 // FunctionScope. Some of these accessors are returning values associated with
239 // the canonical function.
240 private:
241 inline FunctionFlags functionFlags() const;
242 inline ImmutableScriptFlags immutableFlags() const;
243
244 public:
245 inline MemberInitializers getMemberInitializers() const;
246 RO_IMMUTABLE_SCRIPT_FLAGS(immutableFlags())
247 bool isArrow() const { return functionFlags().isArrow(); }
248 bool allowSuperProperty() const {
249 return functionFlags().allowSuperProperty();
250 }
251 bool isClassConstructor() const {
252 return functionFlags().isClassConstructor();
253 }
254 };
255
256 // Reference to a Script within a CompilationStencil.
257 struct ScriptStencilRef {
258 const CompilationStencil& context_;
259 const ScriptIndex scriptIndex_;
260
261 inline const ScriptStencil& scriptData() const;
262 inline const ScriptStencilExtra& scriptExtra() const;
263 };
264
265 // Wraps a script for a CompilationInput. The script is either as a BaseScript
266 // pointer to an instantiated script, or as a reference to a CompilationStencil.
267 class InputScript {
268 using InputScriptStorage = mozilla::Variant<BaseScript*, ScriptStencilRef>;
269 InputScriptStorage script_;
270
271 public:
272 // Create an InputScript given an instantiated BaseScript pointer.
273 explicit InputScript(BaseScript* ptr) : script_(ptr) {}
274
275 // Create an InputScript given a CompilationStencil and the ScriptIndex which
276 // is an offset within the same CompilationStencil given as argument.
277 InputScript(const CompilationStencil& context, ScriptIndex scriptIndex)
278 : script_(ScriptStencilRef{context, scriptIndex}) {}
279
280 const InputScriptStorage& raw() const { return script_; }
281 InputScriptStorage& raw() { return script_; }
282
283 SourceExtent extent() const {
284 return script_.match(
285 [](const BaseScript* ptr) { return ptr->extent(); },
286 [](const ScriptStencilRef& ref) { return ref.scriptExtra().extent; });
287 }
288 ImmutableScriptFlags immutableFlags() const {
289 return script_.match(
290 [](const BaseScript* ptr) { return ptr->immutableFlags(); },
291 [](const ScriptStencilRef& ref) {
292 return ref.scriptExtra().immutableFlags;
293 });
294 }
295 RO_IMMUTABLE_SCRIPT_FLAGS(immutableFlags())
296 FunctionFlags functionFlags() const {
297 return script_.match(
298 [](const BaseScript* ptr) { return ptr->function()->flags(); },
299 [](const ScriptStencilRef& ref) {
300 return ref.scriptData().functionFlags;
301 });
302 }
303 bool hasPrivateScriptData() const {
304 return script_.match(
305 [](const BaseScript* ptr) { return ptr->hasPrivateScriptData(); },
306 [](const ScriptStencilRef& ref) {
307 // See BaseScript::CreateRawLazy.
308 return ref.scriptData().hasGCThings() ||
309 ref.scriptExtra().useMemberInitializers();
310 });
311 }
312 InputScope enclosingScope() const {
313 return script_.match(
314 [](const BaseScript* ptr) {
315 return InputScope(ptr->function()->enclosingScope());
316 },
317 [](const ScriptStencilRef& ref) {
318 // The ScriptStencilRef only reference lazy Script, otherwise we
319 // should fetch the enclosing scope using the bodyScope field of the
320 // immutable data which is a reference to the vector of gc-things.
321 MOZ_RELEASE_ASSERT(!ref.scriptData().hasSharedData());
322 MOZ_ASSERT(ref.scriptData().hasLazyFunctionEnclosingScopeIndex());
323 auto scopeIndex = ref.scriptData().lazyFunctionEnclosingScopeIndex();
324 return InputScope(ref.context_, scopeIndex);
325 });
326 }
327 MemberInitializers getMemberInitializers() const {
328 return script_.match(
329 [](const BaseScript* ptr) { return ptr->getMemberInitializers(); },
330 [](const ScriptStencilRef& ref) {
331 return ref.scriptExtra().memberInitializers();
332 });
333 }
334
335 InputName displayAtom() const;
336 void trace(JSTracer* trc);
337 bool isNull() const {
338 return script_.match([](const BaseScript* ptr) { return !ptr; },
339 [](const ScriptStencilRef& ref) { return false; });
340 }
341 bool isStencil() const {
342 return script_.match([](const BaseScript* ptr) { return false; },
343 [](const ScriptStencilRef&) { return true; });
344 }
345
346 ScriptSourceObject* sourceObject() const {
347 return script_.match(
348 [](const BaseScript* ptr) { return ptr->sourceObject(); },
349 [](const ScriptStencilRef&) {
350 return static_cast<ScriptSourceObject*>(nullptr);
351 });
352 }
353 };
354
355 // Iterator for walking the scope chain, this is identical to ScopeIter but
356 // accept an InputScope instead of a Scope pointer.
357 //
358 // It may be placed in GC containers; for example:
359 //
360 // for (Rooted<InputScopeIter> si(cx, InputScopeIter(scope)); si; si++) {
361 // use(si);
362 // SomeMayGCOperation();
363 // use(si);
364 // }
365 //
366 class MOZ_STACK_CLASS InputScopeIter {
367 InputScope scope_;
368
369 public:
370 explicit InputScopeIter(const InputScope& scope) : scope_(scope) {}
371
372 InputScope& scope() {
373 MOZ_ASSERT(!done());
374 return scope_;
375 }
376
377 const InputScope& scope() const {
378 MOZ_ASSERT(!done());
379 return scope_;
380 }
381
382 bool done() const { return scope_.isNull(); }
383 explicit operator bool() const { return !done(); }
384 void operator++(int) { scope_ = scope_.enclosing(); }
385 ScopeKind kind() const { return scope_.kind(); }
386
387 // Returns whether this scope has a syntactic environment (i.e., an
388 // Environment that isn't a non-syntactic With or NonSyntacticVariables)
389 // on the environment chain.
390 bool hasSyntacticEnvironment() const {
391 return scope_.hasEnvironment() && scope_.kind() != ScopeKind::NonSyntactic;
392 }
393
394 void trace(JSTracer* trc) { scope_.trace(trc); }
395 };
396
397 // Reference to a Binding Name within an existing CompilationStencil.
398 // TaggedParserAtomIndex are in some cases indexes in the parserAtomData of the
399 // CompilationStencil.
400 struct NameStencilRef {
401 const CompilationStencil& context_;
402 const TaggedParserAtomIndex atomIndex_;
403 };
404
405 // Wraps a name for a CompilationInput. The name is either as a GC pointer to
406 // a JSAtom, or a TaggedParserAtomIndex which might reference to a non-included.
407 //
408 // The constructor for this class are using an InputScope as argument. This
409 // InputScope is made to fetch back the CompilationStencil associated with the
410 // TaggedParserAtomIndex when using a Stencil as input.
411 struct InputName {
412 using InputNameStorage = mozilla::Variant<JSAtom*, NameStencilRef>;
413 InputNameStorage variant_;
414
415 InputName(Scope*, JSAtom* ptr) : variant_(ptr) {}
416 InputName(const ScopeStencilRef& scope, TaggedParserAtomIndex index)
417 : variant_(NameStencilRef{scope.context_, index}) {}
418 InputName(BaseScript*, JSAtom* ptr) : variant_(ptr) {}
419 InputName(const ScriptStencilRef& script, TaggedParserAtomIndex index)
420 : variant_(NameStencilRef{script.context_, index}) {}
421
422 // Dummy for empty global.
423 InputName(const FakeStencilGlobalScope&, TaggedParserAtomIndex)
424 : variant_(static_cast<JSAtom*>(nullptr)) {}
425
426 // The InputName is either from an instantiated name, or from another
427 // CompilationStencil. This method interns the current name in the parser atom
428 // table of a CompilationState, which has a corresponding CompilationInput.
429 TaggedParserAtomIndex internInto(FrontendContext* fc,
430 ParserAtomsTable& parserAtoms,
431 CompilationAtomCache& atomCache);
432
433 // Compare an InputName, which is not yet interned, with `other` is either an
434 // interned name or a well-known or static string.
435 //
436 // The `otherCached` argument should be a reference to a JSAtom*, initialized
437 // to nullptr, which is used to cache the JSAtom representation of the `other`
438 // argument if needed. If a different `other` parameter is provided, the
439 // `otherCached` argument should be reset to nullptr.
440 bool isEqualTo(FrontendContext* fc, ParserAtomsTable& parserAtoms,
441 CompilationAtomCache& atomCache, TaggedParserAtomIndex other,
442 JSAtom** otherCached) const;
443
444 bool isNull() const {
445 return variant_.match(
446 [](JSAtom* ptr) { return !ptr; },
447 [](const NameStencilRef& ref) { return !ref.atomIndex_; });
448 }
449 };
450
451 // ScopeContext holds information derived from the scope and environment chains
452 // to try to avoid the parser needing to traverse VM structures directly.
453 struct ScopeContext {
454 // Cache: Scope -> (JSAtom/TaggedParserAtomIndex -> NameLocation)
455 //
456 // This cache maps the scope to a hash table which can lookup a name of the
457 // scope to the equivalent NameLocation.
458 ScopeBindingCache* scopeCache = nullptr;
459
460 // Generation number of the `scopeCache` collected before filling the cache
461 // with enclosing scope information.
462 //
463 // The generation number, obtained from `scopeCache->getCurrentGeneration()`
464 // is incremented each time the GC invalidate the content of the cache. The
465 // `scopeCache` can only be used when the generation number collected before
466 // filling the cache is identical to the generation number seen when querying
467 // the cached content.
468 size_t scopeCacheGen = 0;
469
470 // Class field initializer info if we are nested within a class constructor.
471 // We may be an combination of arrow and eval context within the constructor.
472 mozilla::Maybe<MemberInitializers> memberInitializers = {};
473
474 enum class EnclosingLexicalBindingKind {
475 Let,
476 Const,
477 CatchParameter,
478 Synthetic,
479 PrivateMethod,
480 };
481
482 using EnclosingLexicalBindingCache =
483 mozilla::HashMap<TaggedParserAtomIndex, EnclosingLexicalBindingKind,
484 TaggedParserAtomIndexHasher>;
485
486 // Cache of enclosing lexical bindings.
487 // Used only for eval.
488 mozilla::Maybe<EnclosingLexicalBindingCache> enclosingLexicalBindingCache_;
489
490 // A map of private names to NameLocations used to allow evals to
491 // provide correct private name semantics (particularly around early
492 // errors and private brand lookup).
493 using EffectiveScopePrivateFieldCache =
494 mozilla::HashMap<TaggedParserAtomIndex, NameLocation,
495 TaggedParserAtomIndexHasher>;
496
497 // Cache of enclosing class's private fields.
498 // Used only for eval.
499 mozilla::Maybe<EffectiveScopePrivateFieldCache>
500 effectiveScopePrivateFieldCache_;
501
502 #ifdef DEBUG
503 bool enclosingEnvironmentIsDebugProxy_ = false;
504 #endif
505
506 // How many hops required to navigate from 'enclosingScope' to effective
507 // scope.
508 uint32_t effectiveScopeHops = 0;
509
510 uint32_t enclosingScopeEnvironmentChainLength = 0;
511
512 // Eval and arrow scripts also inherit the "this" environment -- used by
513 // `super` expressions -- from their enclosing script. We count the number of
514 // environment hops needed to get from enclosing scope to the nearest
515 // appropriate environment. This value is undefined if the script we are
516 // compiling is not an eval or arrow-function.
517 uint32_t enclosingThisEnvironmentHops = 0;
518
519 // The kind of enclosing scope.
520 ScopeKind enclosingScopeKind = ScopeKind::Global;
521
522 // The type of binding required for `this` of the top level context, as
523 // indicated by the enclosing scopes of this parse.
524 //
525 // NOTE: This is computed based on the effective scope (defined above).
526 ThisBinding thisBinding = ThisBinding::Global;
527
528 // Eval and arrow scripts inherit certain syntax allowances from their
529 // enclosing scripts.
530 bool allowNewTarget = false;
531 bool allowSuperProperty = false;
532 bool allowSuperCall = false;
533 bool allowArguments = true;
534
535 // Indicates there is a 'class' or 'with' scope on enclosing scope chain.
536 bool inClass = false;
537 bool inWith = false;
538
539 // True if the enclosing scope is for FunctionScope of arrow function.
540 bool enclosingScopeIsArrow = false;
541
542 // True if the enclosing scope has environment.
543 bool enclosingScopeHasEnvironment = false;
544
545 #ifdef DEBUG
546 // True if the enclosing scope has non-syntactic scope on chain.
547 bool hasNonSyntacticScopeOnChain = false;
548
549 // True if the enclosing scope has function scope where the function needs
550 // home object.
551 bool hasFunctionNeedsHomeObjectOnChain = false;
552 #endif
553
554 bool init(FrontendContext* fc, CompilationInput& input,
555 ParserAtomsTable& parserAtoms, ScopeBindingCache* scopeCache,
556 InheritThis inheritThis, JSObject* enclosingEnv);
557
558 mozilla::Maybe<EnclosingLexicalBindingKind>
559 lookupLexicalBindingInEnclosingScope(TaggedParserAtomIndex name);
560
561 NameLocation searchInEnclosingScope(FrontendContext* fc,
562 CompilationInput& input,
563 ParserAtomsTable& parserAtoms,
564 TaggedParserAtomIndex name);
565
566 bool effectiveScopePrivateFieldCacheHas(TaggedParserAtomIndex name);
567 mozilla::Maybe<NameLocation> getPrivateFieldLocation(
568 TaggedParserAtomIndex name);
569
570 private:
571 void computeThisBinding(const InputScope& scope);
572 void computeThisEnvironment(const InputScope& enclosingScope);
573 void computeInScope(const InputScope& enclosingScope);
574 void cacheEnclosingScope(const InputScope& enclosingScope);
575 NameLocation searchInEnclosingScopeWithCache(FrontendContext* fc,
576 CompilationInput& input,
577 ParserAtomsTable& parserAtoms,
578 TaggedParserAtomIndex name);
579 NameLocation searchInEnclosingScopeNoCache(FrontendContext* fc,
580 CompilationInput& input,
581 ParserAtomsTable& parserAtoms,
582 TaggedParserAtomIndex name);
583
584 InputScope determineEffectiveScope(InputScope& scope, JSObject* environment);
585
586 bool cachePrivateFieldsForEval(FrontendContext* fc, CompilationInput& input,
587 JSObject* enclosingEnvironment,
588 const InputScope& effectiveScope,
589 ParserAtomsTable& parserAtoms);
590
591 bool cacheEnclosingScopeBindingForEval(FrontendContext* fc,
592 CompilationInput& input,
593 ParserAtomsTable& parserAtoms);
594
595 bool addToEnclosingLexicalBindingCache(FrontendContext* fc,
596 ParserAtomsTable& parserAtoms,
597 CompilationAtomCache& atomCache,
598 InputName& name,
599 EnclosingLexicalBindingKind kind);
600 };
601
602 struct CompilationAtomCache {
603 public:
604 using AtomCacheVector = JS::GCVector<JSString*, 0, js::SystemAllocPolicy>;
605
606 private:
607 // Atoms lowered into or converted from CompilationStencil.parserAtomData.
608 //
609 // This field is here instead of in CompilationGCOutput because atoms lowered
610 // from JSAtom is part of input (enclosing scope bindings, lazy function name,
611 // etc), and having 2 vectors in both input/output is error prone.
612 AtomCacheVector atoms_;
613
614 public:
615 JSString* getExistingStringAt(ParserAtomIndex index) const;
616 JSString* getExistingStringAt(JSContext* cx,
617 TaggedParserAtomIndex taggedIndex) const;
618 JSString* getStringAt(ParserAtomIndex index) const;
619
620 JSAtom* getExistingAtomAt(ParserAtomIndex index) const;
621 JSAtom* getExistingAtomAt(JSContext* cx,
622 TaggedParserAtomIndex taggedIndex) const;
623 JSAtom* getAtomAt(ParserAtomIndex index) const;
624
625 bool hasAtomAt(ParserAtomIndex index) const;
626 bool setAtomAt(FrontendContext* fc, ParserAtomIndex index, JSString* atom);
627 bool allocate(FrontendContext* fc, size_t length);
628
629 bool empty() const { return atoms_.empty(); }
630 size_t size() const { return atoms_.length(); }
631
632 void stealBuffer(AtomCacheVector& atoms);
633 void releaseBuffer(AtomCacheVector& atoms);
634
635 void trace(JSTracer* trc);
636
637 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
638 return atoms_.sizeOfExcludingThis(mallocSizeOf);
639 }
640 };
641
642 // Information associated with an extra binding provided to a global script.
643 // See frontend::CompileGlobalScriptWithExtraBindings.
644 struct ExtraBindingInfo {
645 // UTF-8 encoded name of the binding.
646 UniqueChars nameChars;
647
648 TaggedParserAtomIndex nameIndex;
649
650 // If the binding conflicts with global variable or global lexical variable,
651 // the binding is shadowed.
652 bool isShadowed = false;
653
654 ExtraBindingInfo(UniqueChars&& nameChars, bool isShadowed)
655 : nameChars(std::move(nameChars)), isShadowed(isShadowed) {}
656 };
657
658 using ExtraBindingInfoVector =
659 js::Vector<ExtraBindingInfo, 0, js::SystemAllocPolicy>;
660
661 // Input of the compilation, including source and enclosing context.
662 struct CompilationInput {
663 enum class CompilationTarget {
664 Global,
665 SelfHosting,
666 StandaloneFunction,
667 StandaloneFunctionInNonSyntacticScope,
668 Eval,
669 Module,
670 Delazification,
671 };
672 CompilationTarget target = CompilationTarget::Global;
673
674 const JS::ReadOnlyCompileOptions& options;
675
676 CompilationAtomCache atomCache;
677
678 private:
679 InputScript lazy_ = InputScript(nullptr);
680
681 // Extra bindings for the global script.
682 ExtraBindingInfoVector* maybeExtraBindings_ = nullptr;
683
684 public:
685 RefPtr<ScriptSource> source;
686
687 // * If the target is Global, null.
688 // * If the target is SelfHosting, null. Instantiation code for self-hosting
689 // will ignore this and use the appropriate empty global scope instead.
690 // * If the target is StandaloneFunction, an empty global scope.
691 // * If the target is StandaloneFunctionInNonSyntacticScope, the non-null
692 // enclosing scope of the function
693 // * If the target is Eval, the non-null enclosing scope of the `eval`.
694 // * If the target is Module, null that means empty global scope
695 // (See EmitterScope::checkEnvironmentChainLength)
696 // * If the target is Delazification, the non-null enclosing scope of
697 // the function
698 InputScope enclosingScope = InputScope(nullptr);
699
700 explicit CompilationInput(const JS::ReadOnlyCompileOptions& options)
701 : options(options) {}
702
703 private:
704 bool initScriptSource(FrontendContext* fc);
705
706 public:
707 bool initForGlobal(FrontendContext* fc) {
708 target = CompilationTarget::Global;
709 return initScriptSource(fc);
710 }
711
712 bool initForGlobalWithExtraBindings(
713 FrontendContext* fc, ExtraBindingInfoVector* maybeExtraBindings) {
714 MOZ_ASSERT(maybeExtraBindings);
715 target = CompilationTarget::Global;
716 maybeExtraBindings_ = maybeExtraBindings;
717 return initScriptSource(fc);
718 }
719
720 bool initForSelfHostingGlobal(FrontendContext* fc) {
721 target = CompilationTarget::SelfHosting;
722 return initScriptSource(fc);
723 }
724
725 bool initForStandaloneFunction(JSContext* cx, FrontendContext* fc) {
726 target = CompilationTarget::StandaloneFunction;
727 if (!initScriptSource(fc)) {
728 return false;
729 }
730 enclosingScope = InputScope(&cx->global()->emptyGlobalScope());
731 return true;
732 }
733
734 bool initForStandaloneFunctionInNonSyntacticScope(
735 FrontendContext* fc, JS::Handle<Scope*> functionEnclosingScope);
736
737 bool initForEval(FrontendContext* fc, JS::Handle<Scope*> evalEnclosingScope) {
738 target = CompilationTarget::Eval;
739 if (!initScriptSource(fc)) {
740 return false;
741 }
742 enclosingScope = InputScope(evalEnclosingScope);
743 return true;
744 }
745
746 bool initForModule(FrontendContext* fc) {
747 target = CompilationTarget::Module;
748 if (!initScriptSource(fc)) {
749 return false;
750 }
751 // The `enclosingScope` is the emptyGlobalScope.
752 return true;
753 }
754
755 void initFromLazy(JSContext* cx, BaseScript* lazyScript, ScriptSource* ss) {
756 MOZ_ASSERT(cx->compartment() == lazyScript->compartment());
757
758 // We can only compile functions whose parents have previously been
759 // compiled, because compilation requires full information about the
760 // function's immediately enclosing scope.
761 MOZ_ASSERT(lazyScript->isReadyForDelazification());
762 target = CompilationTarget::Delazification;
763 lazy_ = InputScript(lazyScript);
764 source = ss;
765 enclosingScope = lazy_.enclosingScope();
766 }
767
768 void initFromStencil(CompilationStencil& context, ScriptIndex scriptIndex,
769 ScriptSource* ss) {
770 target = CompilationTarget::Delazification;
771 lazy_ = InputScript(context, scriptIndex);
772 source = ss;
773 enclosingScope = lazy_.enclosingScope();
774 }
775
776 // Returns true if enclosingScope field is provided to init* function,
777 // instead of setting to empty global internally.
778 bool hasNonDefaultEnclosingScope() const {
779 return target == CompilationTarget::StandaloneFunctionInNonSyntacticScope ||
780 target == CompilationTarget::Eval ||
781 target == CompilationTarget::Delazification;
782 }
783
784 // Returns the enclosing scope provided to init* function.
785 // nullptr otherwise.
786 InputScope maybeNonDefaultEnclosingScope() const {
787 if (hasNonDefaultEnclosingScope()) {
788 return enclosingScope;
789 }
790 return InputScope(nullptr);
791 }
792
793 // The BaseScript* is needed when instantiating a lazy function.
794 // See InstantiateTopLevel and FunctionsFromExistingLazy.
795 InputScript lazyOuterScript() { return lazy_; }
796 BaseScript* lazyOuterBaseScript() { return lazy_.raw().as<BaseScript*>(); }
797
798 // The JSFunction* is needed when instantiating a lazy function.
799 // See FunctionsFromExistingLazy.
800 JSFunction* function() const {
801 return lazy_.raw().as<BaseScript*>()->function();
802 }
803
804 // When compiling an inner function, we want to know the unique identifier
805 // which identify a function. This is computed from the source extend.
806 SourceExtent extent() const { return lazy_.extent(); }
807
808 // See `BaseScript::immutableFlags_`.
809 ImmutableScriptFlags immutableFlags() const { return lazy_.immutableFlags(); }
810
811 RO_IMMUTABLE_SCRIPT_FLAGS(immutableFlags())
812
813 FunctionFlags functionFlags() const { return lazy_.functionFlags(); }
814
815 // When delazifying, return the kind of function which is defined.
816 FunctionSyntaxKind functionSyntaxKind() const;
817
818 bool hasPrivateScriptData() const {
819 // This is equivalent to: ngcthings != 0 || useMemberInitializers()
820 // See BaseScript::CreateRawLazy.
821 return lazy_.hasPrivateScriptData();
822 }
823
824 // Whether this CompilationInput is parsing the top-level of a script, or
825 // false if we are parsing an inner function.
826 bool isInitialStencil() { return lazy_.isNull(); }
827
828 // Whether this CompilationInput is parsing a specific function with already
829 // pre-parsed contextual information.
830 bool isDelazifying() { return target == CompilationTarget::Delazification; }
831
832 bool hasExtraBindings() const { return !!maybeExtraBindings_; }
833 ExtraBindingInfoVector& extraBindings() { return *maybeExtraBindings_; }
834 const ExtraBindingInfoVector& extraBindings() const {
835 return *maybeExtraBindings_;
836 }
837 bool internExtraBindings(FrontendContext* fc, ParserAtomsTable& parserAtoms);
838
839 void trace(JSTracer* trc);
840
841 // Size of dynamic data. Note that GC data is counted by GC and not here. We
842 // also ignore ScriptSource which is a shared RefPtr.
843 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
844 return atomCache.sizeOfExcludingThis(mallocSizeOf);
845 }
846 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
847 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
848 }
849
850 #if defined(DEBUG) || defined(JS_JITSPEW)
851 void dump() const;
852 void dump(js::JSONPrinter& json) const;
853 void dumpFields(js::JSONPrinter& json) const;
854 #endif
855 };
856
857 // When compiling a function which was previously Syntaxly Parsed, we generated
858 // some information which made it possible to skip over some parsing phases,
859 // such as computing closed over bindings as well as parsing inner functions.
860 // This class contains all information which is generated by the SyntaxParse and
861 // reused in the FullParse.
862 class CompilationSyntaxParseCache {
863 // When delazifying, we should prepare an array which contains all
864 // stencil-like gc-things such that it can be used by the parser.
865 //
866 // When compiling from a Stencil, this will alias the existing Stencil.
867 mozilla::Span<TaggedScriptThingIndex> cachedGCThings_;
868
869 // When delazifying, we should perpare an array which contains all
870 // stencil-like information about scripts, such that it can be used by the
871 // parser.
872 //
873 // When compiling from a Stencil, these will alias the existing Stencil.
874 mozilla::Span<ScriptStencil> cachedScriptData_;
875 mozilla::Span<ScriptStencilExtra> cachedScriptExtra_;
876
877 // When delazifying, we copy the atom, either from JSAtom, or from another
878 // Stencil into TaggedParserAtomIndex which are valid in this current
879 // CompilationState.
880 mozilla::Span<TaggedParserAtomIndex> closedOverBindings_;
881
882 // Atom of the function being compiled. This atom index is valid in the
883 // current CompilationState.
884 TaggedParserAtomIndex displayAtom_;
885
886 // Stencil-like data about the function which is being compiled.
887 ScriptStencilExtra funExtra_;
888
889 #ifdef DEBUG
890 // Whether any of these data should be considered or not.
891 bool isInitialized = false;
892 #endif
893
894 public:
895 // When doing a full-parse of an incomplete BaseScript*, we have to iterate
896 // over functions and closed-over bindings, to avoid costly recursive decent
897 // in inner functions. This function will clone the BaseScript* information to
898 // make it available as a stencil-like data to the full-parser.
899 mozilla::Span<TaggedParserAtomIndex> closedOverBindings() const {
900 MOZ_ASSERT(isInitialized);
901 return closedOverBindings_;
902 }
903 const ScriptStencil& scriptData(size_t functionIndex) const {
904 return cachedScriptData_[scriptIndex(functionIndex)];
905 }
906 const ScriptStencilExtra& scriptExtra(size_t functionIndex) const {
907 return cachedScriptExtra_[scriptIndex(functionIndex)];
908 }
909
910 // Return the name of the function being delazified, if any.
911 TaggedParserAtomIndex displayAtom() const {
912 MOZ_ASSERT(isInitialized);
913 return displayAtom_;
914 }
915
916 // Return the extra information about the function being delazified, if any.
917 const ScriptStencilExtra& funExtra() const {
918 MOZ_ASSERT(isInitialized);
919 return funExtra_;
920 }
921
922 // Initialize the SynaxParse cache given a LifoAlloc. The JSContext is only
923 // used for reporting allocation errors.
924 [[nodiscard]] bool init(FrontendContext* fc, LifoAlloc& alloc,
925 ParserAtomsTable& parseAtoms,
926 CompilationAtomCache& atomCache,
927 const InputScript& lazy);
928
929 private:
930 // Return the script index of a given inner function.
931 //
932 // WARNING: The ScriptIndex returned by this function corresponds to the index
933 // in the cachedScriptExtra_ and cachedScriptData_ spans. With the
934 // cachedGCThings_ span, these might be reference to an actual Stencil from
935 // another compilation. Thus, the ScriptIndex returned by this function should
936 // not be confused with any ScriptIndex from the CompilationState.
937 ScriptIndex scriptIndex(size_t functionIndex) const {
938 MOZ_ASSERT(isInitialized);
939 auto taggedScriptIndex = cachedGCThings_[functionIndex];
940 MOZ_ASSERT(taggedScriptIndex.isFunction());
941 return taggedScriptIndex.toFunction();
942 }
943
944 [[nodiscard]] bool copyFunctionInfo(FrontendContext* fc,
945 ParserAtomsTable& parseAtoms,
946 CompilationAtomCache& atomCache,
947 const InputScript& lazy);
948 [[nodiscard]] bool copyScriptInfo(FrontendContext* fc, LifoAlloc& alloc,
949 ParserAtomsTable& parseAtoms,
950 CompilationAtomCache& atomCache,
951 BaseScript* lazy);
952 [[nodiscard]] bool copyScriptInfo(FrontendContext* fc, LifoAlloc& alloc,
953 ParserAtomsTable& parseAtoms,
954 CompilationAtomCache& atomCache,
955 const ScriptStencilRef& lazy);
956 [[nodiscard]] bool copyClosedOverBindings(FrontendContext* fc,
957 LifoAlloc& alloc,
958 ParserAtomsTable& parseAtoms,
959 CompilationAtomCache& atomCache,
960 BaseScript* lazy);
961 [[nodiscard]] bool copyClosedOverBindings(FrontendContext* fc,
962 LifoAlloc& alloc,
963 ParserAtomsTable& parseAtoms,
964 CompilationAtomCache& atomCache,
965 const ScriptStencilRef& lazy);
966 };
967
968 // AsmJS scripts are very rare on-average, so we use a HashMap to associate
969 // data with a ScriptStencil. The ScriptStencil has a flag to indicate if we
970 // need to even do this lookup.
971 using StencilAsmJSMap =
972 mozilla::HashMap<ScriptIndex, RefPtr<const JS::WasmModule>,
973 mozilla::DefaultHasher<ScriptIndex>,
974 js::SystemAllocPolicy>;
975
976 struct StencilAsmJSContainer
977 : public js::AtomicRefCounted<StencilAsmJSContainer> {
978 StencilAsmJSMap moduleMap;
979
980 StencilAsmJSContainer() = default;
981
982 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
983 return moduleMap.shallowSizeOfExcludingThis(mallocSizeOf);
984 }
985 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
986 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
987 }
988 };
989
990 // Store shared data for non-lazy script.
991 struct SharedDataContainer {
992 // NOTE: While stored, we must hold a ref-count and care must be taken when
993 // updating or clearing the pointer.
994 using SingleSharedDataPtr = SharedImmutableScriptData*;
995
996 using SharedDataVector =
997 Vector<RefPtr<js::SharedImmutableScriptData>, 0, js::SystemAllocPolicy>;
998 using SharedDataVectorPtr = SharedDataVector*;
999
1000 using SharedDataMap =
1001 mozilla::HashMap<ScriptIndex, RefPtr<js::SharedImmutableScriptData>,
1002 mozilla::DefaultHasher<ScriptIndex>,
1003 js::SystemAllocPolicy>;
1004 using SharedDataMapPtr = SharedDataMap*;
1005
1006 private:
1007 enum {
1008 SingleTag = 0,
1009 VectorTag = 1,
1010 MapTag = 2,
1011 BorrowTag = 3,
1012
1013 TagMask = 3,
1014 };
1015
1016 uintptr_t data_ = 0;
1017
1018 public:
1019 // Defaults to SingleSharedData.
1020 SharedDataContainer() = default;
1021
1022 SharedDataContainer(const SharedDataContainer&) = delete;
1023 SharedDataContainer(SharedDataContainer&& other) noexcept {
1024 std::swap(data_, other.data_);
1025 MOZ_ASSERT(other.isEmpty());
1026 }
1027
1028 SharedDataContainer& operator=(const SharedDataContainer&) = delete;
1029 SharedDataContainer& operator=(SharedDataContainer&& other) noexcept {
1030 std::swap(data_, other.data_);
1031 MOZ_ASSERT(other.isEmpty());
1032 return *this;
1033 }
1034
1035 ~SharedDataContainer();
1036
1037 [[nodiscard]] bool initVector(FrontendContext* fc);
1038 [[nodiscard]] bool initMap(FrontendContext* fc);
1039
1040 private:
1041 [[nodiscard]] bool convertFromSingleToMap(FrontendContext* fc);
1042
1043 public:
1044 bool isEmpty() const { return (data_) == SingleTag; }
1045 bool isSingle() const { return (data_ & TagMask) == SingleTag; }
1046 bool isVector() const { return (data_ & TagMask) == VectorTag; }
1047 bool isMap() const { return (data_ & TagMask) == MapTag; }
1048 bool isBorrow() const { return (data_ & TagMask) == BorrowTag; }
1049
1050 void setSingle(already_AddRefed<SharedImmutableScriptData>&& data) {
1051 MOZ_ASSERT(isEmpty());
1052 data_ = reinterpret_cast<uintptr_t>(data.take());
1053 MOZ_ASSERT(isSingle());
1054 MOZ_ASSERT(!isEmpty());
1055 }
1056
1057 void setBorrow(SharedDataContainer* sharedData) {
1058 MOZ_ASSERT(isEmpty());
1059 data_ = reinterpret_cast<uintptr_t>(sharedData) | BorrowTag;
1060 MOZ_ASSERT(isBorrow());
1061 }
1062
1063 SingleSharedDataPtr asSingle() const {
1064 MOZ_ASSERT(isSingle());
1065 MOZ_ASSERT(!isEmpty());
1066 static_assert(SingleTag == 0);
1067 return reinterpret_cast<SingleSharedDataPtr>(data_);
1068 }
1069 SharedDataVectorPtr asVector() const {
1070 MOZ_ASSERT(isVector());
1071 return reinterpret_cast<SharedDataVectorPtr>(data_ & ~TagMask);
1072 }
1073 SharedDataMapPtr asMap() const {
1074 MOZ_ASSERT(isMap());
1075 return reinterpret_cast<SharedDataMapPtr>(data_ & ~TagMask);
1076 }
1077 SharedDataContainer* asBorrow() const {
1078 MOZ_ASSERT(isBorrow());
1079 return reinterpret_cast<SharedDataContainer*>(data_ & ~TagMask);
1080 }
1081
1082 [[nodiscard]] bool prepareStorageFor(FrontendContext* fc,
1083 size_t nonLazyScriptCount,
1084 size_t allScriptCount);
1085 [[nodiscard]] bool cloneFrom(FrontendContext* fc,
1086 const SharedDataContainer& other);
1087
1088 // Returns index-th script's shared data, or nullptr if it doesn't have.
1089 js::SharedImmutableScriptData* get(ScriptIndex index) const;
1090
1091 // Add data for index-th script and share it with VM.
1092 [[nodiscard]] bool addAndShare(FrontendContext* fc, ScriptIndex index,
1093 js::SharedImmutableScriptData* data);
1094
1095 // Add data for index-th script without sharing it with VM.
1096 // The data should already be shared with VM.
1097 //
1098 // The data is supposed to be added from delazification.
1099 [[nodiscard]] bool addExtraWithoutShare(FrontendContext* fc,
1100 ScriptIndex index,
1101 js::SharedImmutableScriptData* data);
1102
1103 // Dynamic memory associated with this container. Does not include the
1104 // SharedImmutableScriptData since we are not the unique owner of it.
1105 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1106 if (isVector()) {
1107 return asVector()->sizeOfIncludingThis(mallocSizeOf);
1108 }
1109 if (isMap()) {
1110 return asMap()->shallowSizeOfIncludingThis(mallocSizeOf);
1111 }
1112 MOZ_ASSERT(isSingle() || isBorrow());
1113 return 0;
1114 }
1115
1116 #if defined(DEBUG) || defined(JS_JITSPEW)
1117 void dump() const;
1118 void dump(js::JSONPrinter& json) const;
1119 void dumpFields(js::JSONPrinter& json) const;
1120 #endif
1121 };
1122
1123 struct ExtensibleCompilationStencil;
1124
1125 // The top level struct of stencil specialized for non-extensible case.
1126 // Used as the compilation output, and also XDR decode output.
1127 //
1128 // In XDR decode output case, the span and not-owning pointer fields point
1129 // the internal LifoAlloc and the external XDR buffer.
1130 //
1131 // In BorrowingCompilationStencil usage, span and not-owning pointer fields
1132 // point the ExtensibleCompilationStencil and its LifoAlloc.
1133 //
1134 // The dependent XDR buffer or ExtensibleCompilationStencil must be kept
1135 // alive manually.
1136 //
1137 // See SMDOC in Stencil.h for more info.
1138 struct CompilationStencil {
1139 friend struct ExtensibleCompilationStencil;
1140
1141 static constexpr ScriptIndex TopLevelIndex = ScriptIndex(0);
1142
1143 static constexpr size_t LifoAllocChunkSize = 512;
1144
1145 // The lifetime of this CompilationStencil may be managed by stack allocation,
1146 // UniquePtr<T>, or RefPtr<T>. If a RefPtr is used, this ref-count will track
1147 // the lifetime, otherwise it is ignored.
1148 //
1149 // NOTE: Internal code and public APIs use a mix of these different allocation
1150 // modes.
1151 //
1152 // See: JS::StencilAddRef/Release
1153 mutable mozilla::Atomic<uintptr_t> refCount_{0};
1154
1155 private:
1156 // On-heap ExtensibleCompilationStencil that this CompilationStencil owns,
1157 // and this CompilationStencil borrows each data from.
1158 UniquePtr<ExtensibleCompilationStencil> ownedBorrowStencil;
1159
1160 public:
1161 enum class StorageType {
1162 // Pointers and spans point LifoAlloc or owned buffer.
1163 Owned,
1164
1165 // Pointers and spans point external data, such as XDR buffer, or not-owned
1166 // ExtensibleCompilationStencil (see BorrowingCompilationStencil).
1167 Borrowed,
1168
1169 // Pointers and spans point data owned by ownedBorrowStencil.
1170 OwnedExtensible,
1171 };
1172 StorageType storageType = StorageType::Owned;
1173
1174 // Value of CanLazilyParse(CompilationInput) on compilation.
1175 // Used during instantiation, and also queried by
1176 // InitialStencilAndDelazifications.
1177 bool canLazilyParse = false;
1178
1179 // If this stencil is a delazification, this identifies location of the
1180 // function in the source text.
1181 using FunctionKey = SourceExtent::FunctionKey;
1182 FunctionKey functionKey = SourceExtent::NullFunctionKey;
1183
1184 // This holds allocations that do not require destructors to be run but are
1185 // live until the stencil is released.
1186 LifoAlloc alloc;
1187
1188 // The source text holder for the script. This may be an empty placeholder if
1189 // the code will fully parsed and options indicate the source will never be
1190 // needed again.
1191 RefPtr<ScriptSource> source;
1192
1193 // Stencil for all function and non-function scripts. The TopLevelIndex is
1194 // reserved for the top-level script. This top-level may or may not be a
1195 // function.
1196 mozilla::Span<ScriptStencil> scriptData;
1197
1198 // Immutable data computed during initial compilation and never updated during
1199 // delazification.
1200 mozilla::Span<ScriptStencilExtra> scriptExtra;
1201
1202 mozilla::Span<TaggedScriptThingIndex> gcThingData;
1203
1204 // scopeData and scopeNames have the same size, and i-th scopeNames contains
1205 // the names for the bindings contained in the slot defined by i-th scopeData.
1206 mozilla::Span<ScopeStencil> scopeData;
1207 mozilla::Span<BaseParserScopeData*> scopeNames;
1208
1209 // Hold onto the RegExpStencil, BigIntStencil, and ObjLiteralStencil that are
1210 // allocated during parse to ensure correct destruction.
1211 mozilla::Span<RegExpStencil> regExpData;
1212 mozilla::Span<BigIntStencil> bigIntData;
1213 mozilla::Span<ObjLiteralStencil> objLiteralData;
1214
1215 // List of parser atoms for this compilation. This may contain nullptr entries
1216 // when round-tripping with XDR if the atom was generated in original parse
1217 // but not used by stencil.
1218 ParserAtomSpan parserAtomData;
1219
1220 // Variable sized container for bytecode and other immutable data. A valid
1221 // stencil always contains at least an entry for `TopLevelIndex` script.
1222 SharedDataContainer sharedData;
1223
1224 // Module metadata if this is a module compile.
1225 RefPtr<StencilModuleMetadata> moduleMetadata;
1226
1227 // AsmJS modules generated by parsing. These scripts are never lazy and
1228 // therefore only generated during initial parse.
1229 RefPtr<StencilAsmJSContainer> asmJS;
1230
1231 // End of fields.
1232
1233 // Construct a CompilationStencil
1234 explicit CompilationStencil(ScriptSource* source)
1235 : alloc(LifoAllocChunkSize, js::BackgroundMallocArena), source(source) {}
1236
1237 // Take the ownership of on-heap ExtensibleCompilationStencil and
1238 // borrow from it.
1239 explicit CompilationStencil(
1240 UniquePtr<ExtensibleCompilationStencil>&& extensibleStencil);
1241
1242 void AddRef();
1243 void Release();
1244
1245 protected:
1246 void borrowFromExtensibleCompilationStencil(
1247 ExtensibleCompilationStencil& extensibleStencil);
1248
1249 #ifdef DEBUG
1250 void assertBorrowingFromExtensibleCompilationStencil(
1251 const ExtensibleCompilationStencil& extensibleStencil) const;
1252 #endif
1253
1254 public:
1255 bool isInitialStencil() const {
1256 return functionKey == SourceExtent::NullFunctionKey;
1257 }
1258
1259 [[nodiscard]] static bool instantiateStencilAfterPreparation(
1260 JSContext* cx, CompilationInput& input, const CompilationStencil& stencil,
1261 CompilationGCOutput& gcOutput);
1262
1263 [[nodiscard]] static bool prepareForInstantiate(
1264 FrontendContext* fc, CompilationAtomCache& atomCache,
1265 const CompilationStencil& stencil, CompilationGCOutput& gcOutput);
1266 [[nodiscard]] static bool prepareForInstantiate(
1267 FrontendContext* fc, const CompilationStencil& stencil,
1268 PreallocatedCompilationGCOutput& gcOutput);
1269
1270 [[nodiscard]] static bool instantiateStencils(
1271 JSContext* cx, CompilationInput& input, const CompilationStencil& stencil,
1272 CompilationGCOutput& gcOutput);
1273
1274 // Decode the special self-hosted stencil
1275 [[nodiscard]] bool instantiateSelfHostedAtoms(
1276 JSContext* cx, AtomSet& atomSet, CompilationAtomCache& atomCache) const;
1277 [[nodiscard]] JSScript* instantiateSelfHostedTopLevelForRealm(
1278 JSContext* cx, CompilationInput& input);
1279 [[nodiscard]] JSFunction* instantiateSelfHostedLazyFunction(
1280 JSContext* cx, CompilationAtomCache& atomCache, ScriptIndex index,
1281 JS::Handle<JSAtom*> name);
1282 [[nodiscard]] bool delazifySelfHostedFunction(JSContext* cx,
1283 CompilationAtomCache& atomCache,
1284 ScriptIndexRange range,
1285 Handle<JSAtom*> name,
1286 JS::Handle<JSFunction*> fun);
1287
1288 // To avoid any misuses, make sure this is neither copyable or assignable.
1289 CompilationStencil(const CompilationStencil&) = delete;
1290 CompilationStencil(CompilationStencil&&) = delete;
1291 CompilationStencil& operator=(const CompilationStencil&) = delete;
1292 CompilationStencil& operator=(CompilationStencil&&) = delete;
1293 #ifdef DEBUG
1294 ~CompilationStencil() {
1295 // We can mix UniquePtr<..> and RefPtr<..>. This asserts that a UniquePtr
1296 // does not delete a reference-counted stencil.
1297 MOZ_ASSERT(!refCount_);
1298 }
1299 #endif
1300
1301 static inline ScriptStencilIterable functionScriptStencils(
1302 const CompilationStencil& stencil, CompilationGCOutput& gcOutput);
1303
1304 void setFunctionKey(BaseScript* lazy) {
1305 functionKey = lazy->extent().toFunctionKey();
1306 }
1307
1308 inline size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
1309 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1310 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
1311 }
1312
1313 const ParserAtomSpan& parserAtomsSpan() const { return parserAtomData; }
1314
1315 bool isModule() const;
1316
1317 bool hasAsmJS() const;
1318
1319 bool hasMultipleReference() const { return refCount_ > 1; }
1320
1321 bool hasOwnedBorrow() const {
1322 return storageType == StorageType::OwnedExtensible;
1323 }
1324
1325 ExtensibleCompilationStencil* takeOwnedBorrow() {
1326 MOZ_ASSERT(!hasMultipleReference());
1327 MOZ_ASSERT(hasOwnedBorrow());
1328 return ownedBorrowStencil.release();
1329 }
1330
1331 #ifdef DEBUG
1332 void assertNoExternalDependency() const;
1333 #endif
1334
1335 #if defined(DEBUG) || defined(JS_JITSPEW)
1336 void dump() const;
1337 void dump(js::JSONPrinter& json) const;
1338 void dumpFields(js::JSONPrinter& json) const;
1339
1340 void dumpAtom(TaggedParserAtomIndex index) const;
1341 #endif
1342 };
1343
1344 // A Map from a function key to the ScriptIndex in the initial stencil.
1345 class FunctionKeyToScriptIndexMap {
1346 using FunctionKey = SourceExtent::FunctionKey;
1347 mozilla::HashMap<FunctionKey, ScriptIndex,
1348 mozilla::DefaultHasher<FunctionKey>, js::SystemAllocPolicy>
1349 map_;
1350
1351 template <typename T>
1352 [[nodiscard]] bool init(FrontendContext* fc, const T& scriptExtra,
1353 size_t scriptExtraSize);
1354
1355 public:
1356 FunctionKeyToScriptIndexMap() = default;
1357
1358 [[nodiscard]] bool init(FrontendContext* fc,
1359 const CompilationStencil* initial);
1360 [[nodiscard]] bool init(FrontendContext* fc,
1361 const ExtensibleCompilationStencil* initial);
1362
1363 mozilla::Maybe<ScriptIndex> get(FunctionKey key) const;
1364
1365 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
1366 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1367 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
1368 }
1369 };
1370
1371 // A class to Associate the initial stencil and the delazifications.
1372 //
1373 // This struct is initialized with the initial stencil, with an empty set of
1374 // delazifications.
1375 // The delazifications_ vector is fixed-size, pre-allocated for each script
1376 // stencil, excluding the top-level script.
1377 //
1378 // The delazifications_ vector elements are initialized with nullptr, and
1379 // monotonically populated with each delazification result.
1380 // Only the first delazification for the given function is used.
1381 //
1382 // This struct is supposed to be read/write from multiple threads, and all
1383 // operations, except init, are thread-safe.
1384 struct InitialStencilAndDelazifications {
1385 private:
1386 using FunctionKey = SourceExtent::FunctionKey;
1387
1388 // Shared reference to the initial stencil.
1389 RefPtr<const CompilationStencil> initial_;
1390
1391 // Exclusively owning pointers for delazifications.
1392 //
1393 // The i-th element is for ScriptIndex(i-1).
1394 //
1395 // If the initial stencil is known to be fully-parsed, this vector is
1396 // 0-sized and unused.
1397 Vector<mozilla::Atomic<CompilationStencil*>, 0, js::SystemAllocPolicy>
1398 delazifications_;
1399
1400 // A Map from a function key to the ScriptIndex in the initial stencil.
1401 //
1402 // If the initial stencil is known to be fully-parsed, this map is
1403 // uninitialized and unused
1404 FunctionKeyToScriptIndexMap functionKeyToInitialScriptIndex_;
1405
1406 mutable mozilla::Atomic<uintptr_t> refCount_{0};
1407
1408 public:
1409 InitialStencilAndDelazifications() = default;
1410 ~InitialStencilAndDelazifications();
1411
1412 void AddRef();
1413 void Release();
1414
1415 [[nodiscard]] bool init(FrontendContext* fc,
1416 const CompilationStencil* initial);
1417
1418 // Get the initial stencil.
1419 // As long as this instance is initialized, this returns non-null pointer.
1420 const CompilationStencil* getInitial() const;
1421
1422 // Returns true if the initial stencil is compiled with
1423 // CanLazilyParse(CompilationInput).
1424 //
1425 // If this returns false:
1426 // * the delazifications_ vector is not allocated
1427 // * the functionKeyToInitialScriptIndex_ is not initialized
1428 // * getDelazificationAt and storeDelazification shouldn't be called
1429 // * getMerged shouldn't be called, and getInitial should be used instead
1430 bool canLazilyParse() const { return initial_->canLazilyParse; }
1431
1432 // Return the delazification stencil if it's already populated.
1433 // Returns nullptr otherwise.
1434 //
1435 // The functionIndex parameter is the index of the corresponding script
1436 // stencil (0-indexed, with the index 0 being the top-level script).
1437 //
1438 // if the extent is used instead, it calculates functionIndex and returns
1439 // the delazification stencil if the functionIndex is found and it's already
1440 // populated.
1441 // Returns nullptr otherwise.
1442 const CompilationStencil* getDelazificationAt(size_t functionIndex) const;
1443 const CompilationStencil* getDelazificationFor(
1444 const SourceExtent& extent) const;
1445
1446 // Try storing the delazification stencil.
1447 //
1448 // The `delazification` stencil should have only one ref count.
1449 //
1450 // If the function was not yet delazified and populated, the `delazification`
1451 // is stored into the vector and the ownership is transferred to the vector,
1452 // and the same `delazification`'s pointer is returned.
1453 //
1454 // If the function was already delazified and stored, the passed
1455 // `delazification` is discared, and the already delazified stencil's pointer
1456 // is returned.
1457 //
1458 // This function is infallible and never returns nullptr.
1459 const CompilationStencil* storeDelazification(
1460 RefPtr<CompilationStencil>&& delazification);
1461
1462 // Create single CompilationStencil that reflects the initial stencil
1463 // and the all delazifications.
1464 //
1465 // Returns nullptr if any error happens, and sets exception on the
1466 // FrontendContext.
1467 CompilationStencil* getMerged(FrontendContext* fc) const;
1468
1469 bool hasAsmJS() const;
1470
1471 // Instantiate the initial stencil and all delazifications populated so far.
1472 [[nodiscard]] static bool instantiateStencils(
1473 JSContext* cx, CompilationInput& input,
1474 InitialStencilAndDelazifications& stencils,
1475 CompilationGCOutput& gcOutput);
1476
1477 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
1478 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1479 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
1480 }
1481
1482 #if defined(DEBUG) || defined(JS_JITSPEW)
1483 void dump() const;
1484 void dump(js::JSONPrinter& json) const;
1485 void dumpFields(js::JSONPrinter& json) const;
1486 #endif
1487 };
1488
1489 // The top level struct of stencil specialized for extensible case.
1490 // Used as the temporary storage during compilation, an the compilation output.
1491 //
1492 // All not-owning pointer fields point the internal LifoAlloc.
1493 //
1494 // See CompilationStencil for each field's description.
1495 //
1496 // Also see SMDOC in Stencil.h for more info.
1497 struct ExtensibleCompilationStencil {
1498 bool canLazilyParse = false;
1499
1500 using FunctionKey = SourceExtent::FunctionKey;
1501
1502 FunctionKey functionKey = SourceExtent::NullFunctionKey;
1503
1504 // Data pointed by other fields are allocated in this LifoAlloc,
1505 // and moved to `CompilationStencil.alloc`.
1506 LifoAlloc alloc;
1507
1508 RefPtr<ScriptSource> source;
1509
1510 // NOTE: We reserve a modest amount of inline storage in order to reduce
1511 // allocations in the most common delazification cases. These common
1512 // cases have one script and scope, as well as a handful of gcthings.
1513 // For complex pages this covers about 75% of delazifications.
1514
1515 Vector<ScriptStencil, 1, js::SystemAllocPolicy> scriptData;
1516 Vector<ScriptStencilExtra, 0, js::SystemAllocPolicy> scriptExtra;
1517
1518 Vector<TaggedScriptThingIndex, 8, js::SystemAllocPolicy> gcThingData;
1519
1520 Vector<ScopeStencil, 1, js::SystemAllocPolicy> scopeData;
1521 Vector<BaseParserScopeData*, 1, js::SystemAllocPolicy> scopeNames;
1522
1523 Vector<RegExpStencil, 0, js::SystemAllocPolicy> regExpData;
1524 BigIntStencilVector bigIntData;
1525 Vector<ObjLiteralStencil, 0, js::SystemAllocPolicy> objLiteralData;
1526
1527 // Table of parser atoms for this compilation.
1528 ParserAtomsTable parserAtoms;
1529
1530 SharedDataContainer sharedData;
1531
1532 RefPtr<StencilModuleMetadata> moduleMetadata;
1533
1534 RefPtr<StencilAsmJSContainer> asmJS;
1535
1536 explicit ExtensibleCompilationStencil(ScriptSource* source);
1537
1538 explicit ExtensibleCompilationStencil(CompilationInput& input);
1539 ExtensibleCompilationStencil(const JS::ReadOnlyCompileOptions& options,
1540 RefPtr<ScriptSource> source);
1541
1542 ExtensibleCompilationStencil(ExtensibleCompilationStencil&& other) noexcept
1543 : canLazilyParse(other.canLazilyParse),
1544 functionKey(other.functionKey),
1545 alloc(CompilationStencil::LifoAllocChunkSize,
1546 js::BackgroundMallocArena),
1547 source(std::move(other.source)),
1548 scriptData(std::move(other.scriptData)),
1549 scriptExtra(std::move(other.scriptExtra)),
1550 gcThingData(std::move(other.gcThingData)),
1551 scopeData(std::move(other.scopeData)),
1552 scopeNames(std::move(other.scopeNames)),
1553 regExpData(std::move(other.regExpData)),
1554 bigIntData(std::move(other.bigIntData)),
1555 objLiteralData(std::move(other.objLiteralData)),
1556 parserAtoms(std::move(other.parserAtoms)),
1557 sharedData(std::move(other.sharedData)),
1558 moduleMetadata(std::move(other.moduleMetadata)),
1559 asmJS(std::move(other.asmJS)) {
1560 alloc.steal(&other.alloc);
1561 parserAtoms.fixupAlloc(alloc);
1562 }
1563
1564 ExtensibleCompilationStencil& operator=(
1565 ExtensibleCompilationStencil&& other) noexcept {
1566 MOZ_ASSERT(alloc.isEmpty());
1567
1568 canLazilyParse = other.canLazilyParse;
1569 functionKey = other.functionKey;
1570 source = std::move(other.source);
1571 scriptData = std::move(other.scriptData);
1572 scriptExtra = std::move(other.scriptExtra);
1573 gcThingData = std::move(other.gcThingData);
1574 scopeData = std::move(other.scopeData);
1575 scopeNames = std::move(other.scopeNames);
1576 regExpData = std::move(other.regExpData);
1577 bigIntData = std::move(other.bigIntData);
1578 objLiteralData = std::move(other.objLiteralData);
1579 parserAtoms = std::move(other.parserAtoms);
1580 sharedData = std::move(other.sharedData);
1581 moduleMetadata = std::move(other.moduleMetadata);
1582 asmJS = std::move(other.asmJS);
1583
1584 alloc.steal(&other.alloc);
1585 parserAtoms.fixupAlloc(alloc);
1586
1587 return *this;
1588 }
1589
1590 void setFunctionKey(const SourceExtent& extent) {
1591 functionKey = extent.toFunctionKey();
1592 }
1593
1594 bool isInitialStencil() const {
1595 return functionKey == SourceExtent::NullFunctionKey;
1596 }
1597
1598 // Steal CompilationStencil content.
1599 [[nodiscard]] bool steal(FrontendContext* fc,
1600 RefPtr<CompilationStencil>&& other);
1601
1602 // Clone ExtensibleCompilationStencil content.
1603 [[nodiscard]] bool cloneFrom(FrontendContext* fc,
1604 const CompilationStencil& other);
1605 [[nodiscard]] bool cloneFrom(FrontendContext* fc,
1606 const ExtensibleCompilationStencil& other);
1607
1608 private:
1609 template <typename Stencil>
1610 [[nodiscard]] bool cloneFromImpl(FrontendContext* fc, const Stencil& other);
1611
1612 public:
1613 const ParserAtomVector& parserAtomsSpan() const {
1614 return parserAtoms.entries();
1615 }
1616
1617 bool isModule() const;
1618
1619 bool hasAsmJS() const;
1620
1621 inline size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
1622 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1623 return mallocSizeOf(this) + sizeOfExcludingThis(mallocSizeOf);
1624 }
1625
1626 #ifdef DEBUG
1627 void assertNoExternalDependency() const;
1628 #endif
1629
1630 #if defined(DEBUG) || defined(JS_JITSPEW)
1631 void dump();
1632 void dump(js::JSONPrinter& json);
1633 void dumpFields(js::JSONPrinter& json);
1634
1635 void dumpAtom(TaggedParserAtomIndex index);
1636 #endif
1637 };
1638
1639 // The internal state of the compilation.
1640 struct MOZ_RAII CompilationState : public ExtensibleCompilationStencil {
1641 Directives directives;
1642
1643 ScopeContext scopeContext;
1644
1645 UsedNameTracker usedNames;
1646
1647 // LifoAlloc scope used by Parser for allocating AST etc.
1648 //
1649 // NOTE: This is not used for ExtensibleCompilationStencil.alloc.
1650 LifoAllocScope& parserAllocScope;
1651
1652 CompilationInput& input;
1653 CompilationSyntaxParseCache previousParseCache;
1654
1655 // The number of functions that *will* have bytecode.
1656 // This doesn't count top-level non-function script.
1657 //
1658 // This should be counted while parsing, and should be passed to
1659 // SharedDataContainer.prepareStorageFor *before* start emitting bytecode.
1660 size_t nonLazyFunctionCount = 0;
1661
1662 // End of fields.
1663
1664 CompilationState(FrontendContext* fc, LifoAllocScope& parserAllocScope,
1665 CompilationInput& input);
1666
1667 bool init(FrontendContext* fc, ScopeBindingCache* scopeCache,
1668 InheritThis inheritThis = InheritThis::No,
1669 JSObject* enclosingEnv = nullptr) {
1670 if (!scopeContext.init(fc, input, parserAtoms, scopeCache, inheritThis,
1671 enclosingEnv)) {
1672 return false;
1673 }
1674
1675 // gcThings is later used by the full parser initialization.
1676 if (input.isDelazifying()) {
1677 InputScript lazy = input.lazyOuterScript();
1678 auto& atomCache = input.atomCache;
1679 if (!previousParseCache.init(fc, alloc, parserAtoms, atomCache, lazy)) {
1680 return false;
1681 }
1682 }
1683
1684 return true;
1685 }
1686
1687 // Track the state of key allocations and roll them back as parts of parsing
1688 // get retried. This ensures iteration during stencil instantiation does not
1689 // encounter discarded frontend state.
1690 struct CompilationStatePosition {
1691 // Temporarily share this token struct with CompilationState.
1692 size_t scriptDataLength = 0;
1693
1694 size_t asmJSCount = 0;
1695 };
1696
1697 bool prepareSharedDataStorage(FrontendContext* fc);
1698
1699 CompilationStatePosition getPosition();
1700 void rewind(const CompilationStatePosition& pos);
1701
1702 // When parsing arrow function, parameter is parsed twice, and if there are
1703 // functions inside parameter expression, stencils will be created for them.
1704 //
1705 // Those functions exist only for lazy parsing.
1706 // Mark them "ghost", so that they don't affect other parts.
1707 //
1708 // See GHOST_FUNCTION in FunctionFlags.h for more details.
1709 void markGhost(const CompilationStatePosition& pos);
1710
1711 // Allocate space for `length` gcthings, and return the address of the
1712 // first element to `cursor` to initialize on the caller.
1713 bool allocateGCThingsUninitialized(FrontendContext* fc,
1714 ScriptIndex scriptIndex, size_t length,
1715 TaggedScriptThingIndex** cursor);
1716
1717 bool appendScriptStencilAndData(FrontendContext* fc);
1718
1719 bool appendGCThings(FrontendContext* fc, ScriptIndex scriptIndex,
1720 mozilla::Span<const TaggedScriptThingIndex> things);
1721 };
1722
1723 // A temporary CompilationStencil instance that borrows
1724 // ExtensibleCompilationStencil data.
1725 // Ensure that this instance does not outlive the ExtensibleCompilationStencil.
1726 class MOZ_STACK_CLASS BorrowingCompilationStencil : public CompilationStencil {
1727 public:
1728 explicit BorrowingCompilationStencil(
1729 ExtensibleCompilationStencil& extensibleStencil);
1730 };
1731
1732 // Size of dynamic data. Ignores Spans (unless their contents are in the
1733 // LifoAlloc) and RefPtrs since we are not the unique owner.
1734 inline size_t CompilationStencil::sizeOfExcludingThis(
1735 mozilla::MallocSizeOf mallocSizeOf) const {
1736 if (ownedBorrowStencil) {
1737 return ownedBorrowStencil->sizeOfIncludingThis(mallocSizeOf);
1738 }
1739
1740 size_t moduleMetadataSize =
1741 moduleMetadata ? moduleMetadata->sizeOfIncludingThis(mallocSizeOf) : 0;
1742 size_t asmJSSize = asmJS ? asmJS->sizeOfIncludingThis(mallocSizeOf) : 0;
1743
1744 return alloc.sizeOfExcludingThis(mallocSizeOf) +
1745 sharedData.sizeOfExcludingThis(mallocSizeOf) + moduleMetadataSize +
1746 asmJSSize;
1747 }
1748
1749 inline size_t ExtensibleCompilationStencil::sizeOfExcludingThis(
1750 mozilla::MallocSizeOf mallocSizeOf) const {
1751 size_t moduleMetadataSize =
1752 moduleMetadata ? moduleMetadata->sizeOfIncludingThis(mallocSizeOf) : 0;
1753 size_t asmJSSize = asmJS ? asmJS->sizeOfIncludingThis(mallocSizeOf) : 0;
1754
1755 return alloc.sizeOfExcludingThis(mallocSizeOf) +
1756 scriptData.sizeOfExcludingThis(mallocSizeOf) +
1757 scriptExtra.sizeOfExcludingThis(mallocSizeOf) +
1758 gcThingData.sizeOfExcludingThis(mallocSizeOf) +
1759 scopeData.sizeOfExcludingThis(mallocSizeOf) +
1760 scopeNames.sizeOfExcludingThis(mallocSizeOf) +
1761 regExpData.sizeOfExcludingThis(mallocSizeOf) +
1762 bigIntData.sizeOfExcludingThis(mallocSizeOf) +
1763 objLiteralData.sizeOfExcludingThis(mallocSizeOf) +
1764 parserAtoms.sizeOfExcludingThis(mallocSizeOf) +
1765 sharedData.sizeOfExcludingThis(mallocSizeOf) + moduleMetadataSize +
1766 asmJSSize;
1767 }
1768
1769 // A PreAllocateableGCArray is an array of GC thing pointers.
1770 //
1771 // The array's internal buffer can be allocated ahead of time, possibly off
1772 // main thread.
1773 template <typename T>
1774 struct PreAllocateableGCArray {
1775 private:
1776 size_t length_ = 0;
1777
1778 // Inline element for the case when length_ == 1.
1779 T inlineElem_;
1780
1781 // Heap-allocated elements for the case when length_ > 1;
1782 T* elems_ = nullptr;
1783
1784 public:
1785 struct Preallocated {
1786 private:
1787 size_t length_ = 0;
1788 uintptr_t* elems_ = nullptr;
1789
1790 friend struct PreAllocateableGCArray<T>;
1791
1792 public:
1793 Preallocated() = default;
1794 ~Preallocated();
1795
1796 bool empty() const { return length_ == 0; }
1797
1798 size_t length() const { return length_; }
1799
1800 private:
1801 bool isInline() const { return length_ == 1; }
1802
1803 public:
1804 bool allocate(size_t length);
1805
1806 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1807 return sizeof(uintptr_t) * length_;
1808 }
1809 };
1810
1811 PreAllocateableGCArray() {
1812 static_assert(std::is_pointer_v<T>,
1813 "PreAllocateableGCArray element must be a pointer");
1814 }
1815 ~PreAllocateableGCArray();
1816
1817 bool empty() const { return length_ == 0; }
1818
1819 size_t length() const { return length_; }
1820
1821 private:
1822 bool isInline() const { return length_ == 1; }
1823
1824 public:
1825 bool allocate(size_t length);
1826 bool allocateWith(T init, size_t length);
1827
1828 // Steal pre-allocated buffer.
1829 void steal(Preallocated&& buffer);
1830
1831 T& operator[](size_t index) {
1832 MOZ_ASSERT(index < length_);
1833
1834 if (isInline()) {
1835 return inlineElem_;
1836 }
1837
1838 return elems_[index];
1839 }
1840 const T& operator[](size_t index) const {
1841 MOZ_ASSERT(index < length_);
1842
1843 if (isInline()) {
1844 return inlineElem_;
1845 }
1846
1847 return elems_[index];
1848 }
1849
1850 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1851 if (!elems_) {
1852 return 0;
1853 }
1854
1855 return sizeof(T) * length_;
1856 }
1857
1858 void trace(JSTracer* trc);
1859 };
1860
1861 struct CompilationGCOutput;
1862
1863 // Pre-allocated storage for CompilationGCOutput.
1864 struct PreallocatedCompilationGCOutput {
1865 private:
1866 PreAllocateableGCArray<JSFunction*>::Preallocated functions;
1867 PreAllocateableGCArray<js::Scope*>::Preallocated scopes;
1868
1869 friend struct CompilationGCOutput;
1870
1871 public:
1872 PreallocatedCompilationGCOutput() = default;
1873
1874 [[nodiscard]] bool allocate(FrontendContext* fc, size_t scriptDataLength,
1875 size_t scopeDataLength) {
1876 if (!functions.allocate(scriptDataLength)) {
1877 ReportOutOfMemory(fc);
1878 return false;
1879 }
1880 if (!scopes.allocate(scopeDataLength)) {
1881 ReportOutOfMemory(fc);
1882 return false;
1883 }
1884 return true;
1885 }
1886
1887 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1888 return functions.sizeOfExcludingThis(mallocSizeOf) +
1889 scopes.sizeOfExcludingThis(mallocSizeOf);
1890 }
1891 };
1892
1893 // The output of GC allocation from stencil.
1894 struct CompilationGCOutput {
1895 // The resulting outermost script for the compilation powered
1896 // by this CompilationStencil.
1897 JSScript* script = nullptr;
1898
1899 // The resulting module object if there is one.
1900 ModuleObject* module = nullptr;
1901
1902 // An array to handle tracing of JSFunction* and Atoms within.
1903 //
1904 // If the top level script isn't a function, the item at TopLevelIndex is
1905 // nullptr.
1906 PreAllocateableGCArray<JSFunction*> functions;
1907
1908 // References to scopes are controlled via AbstractScopePtr, which holds onto
1909 // an index (and CompilationStencil reference).
1910 PreAllocateableGCArray<js::Scope*> scopes;
1911
1912 // The result ScriptSourceObject. This is unused in delazifying parses.
1913 ScriptSourceObject* sourceObject = nullptr;
1914
1915 private:
1916 // If we are only instantiating part of a stencil, we can reduce allocations
1917 // by setting a base index and allocating only the array elements we need.
1918 // This applies to both the `functions` and `scopes` arrays. These fields are
1919 // initialized by `ensureAllocatedWithBaseIndex` which also allocates the
1920 // array appropriately.
1921 //
1922 // Note: These are only used for self-hosted delazification currently.
1923 ScriptIndex functionsBaseIndex{};
1924 ScopeIndex scopesBaseIndex{};
1925
1926 // End of fields.
1927
1928 public:
1929 CompilationGCOutput() = default;
1930
1931 // Helper to access the `functions` array. The NoBaseIndex version is used if
1932 // the caller never uses a base index.
1933 JSFunction*& getFunction(ScriptIndex index) {
1934 return functions[index - functionsBaseIndex];
1935 }
1936 JSFunction*& getFunctionNoBaseIndex(ScriptIndex index) {
1937 MOZ_ASSERT(!functionsBaseIndex);
1938 return functions[index];
1939 }
1940
1941 // Helper accessors for the `scopes` array.
1942 js::Scope*& getScope(ScopeIndex index) {
1943 return scopes[index - scopesBaseIndex];
1944 }
1945 js::Scope*& getScopeNoBaseIndex(ScopeIndex index) {
1946 MOZ_ASSERT(!scopesBaseIndex);
1947 return scopes[index];
1948 }
1949 js::Scope* getScopeNoBaseIndex(ScopeIndex index) const {
1950 MOZ_ASSERT(!scopesBaseIndex);
1951 return scopes[index];
1952 }
1953
1954 // Allocate output arrays.
1955 [[nodiscard]] bool ensureAllocated(FrontendContext* fc,
1956 size_t scriptDataLength,
1957 size_t scopeDataLength) {
1958 if (functions.empty()) {
1959 if (!functions.allocate(scriptDataLength)) {
1960 ReportOutOfMemory(fc);
1961 return false;
1962 }
1963 }
1964 if (scopes.empty()) {
1965 if (!scopes.allocate(scopeDataLength)) {
1966 ReportOutOfMemory(fc);
1967 return false;
1968 }
1969 }
1970 return true;
1971 }
1972
1973 // Steal output arrays' buffer.
1974 void steal(PreallocatedCompilationGCOutput&& pre) {
1975 functions.steal(std::move(pre.functions));
1976 scopes.steal(std::move(pre.scopes));
1977 }
1978
1979 // A variant of `ensureAllocated` that sets a base index for the function and
1980 // scope arrays. This is used when instantiating only a subset of the stencil.
1981 // Currently this only applies to self-hosted delazification. The ranges
1982 // include the start index and exclude the limit index.
1983 [[nodiscard]] bool ensureAllocatedWithBaseIndex(FrontendContext* fc,
1984 ScriptIndex scriptStart,
1985 ScriptIndex scriptLimit,
1986 ScopeIndex scopeStart,
1987 ScopeIndex scopeLimit) {
1988 this->functionsBaseIndex = scriptStart;
1989 this->scopesBaseIndex = scopeStart;
1990
1991 return ensureAllocated(fc, scriptLimit - scriptStart,
1992 scopeLimit - scopeStart);
1993 }
1994
1995 // Size of dynamic data. Note that GC data is counted by GC and not here.
1996 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
1997 return functions.sizeOfExcludingThis(mallocSizeOf) +
1998 scopes.sizeOfExcludingThis(mallocSizeOf);
1999 }
2000
2001 void trace(JSTracer* trc);
2002 };
2003
2004 // Iterator over functions that make up a CompilationStencil. This abstracts
2005 // over the parallel arrays in stencil and gc-output that use the same index
2006 // system.
2007 class ScriptStencilIterable {
2008 public:
2009 class ScriptAndFunction {
2010 public:
2011 const ScriptStencil& script;
2012 const ScriptStencilExtra* scriptExtra;
2013 JSFunction* function;
2014 ScriptIndex index;
2015
2016 ScriptAndFunction() = delete;
2017 ScriptAndFunction(const ScriptStencil& script,
2018 const ScriptStencilExtra* scriptExtra,
2019 JSFunction* function, ScriptIndex index)
2020 : script(script),
2021 scriptExtra(scriptExtra),
2022 function(function),
2023 index(index) {}
2024 };
2025
2026 class Iterator {
2027 size_t index_ = 0;
2028 const CompilationStencil& stencil_;
2029 CompilationGCOutput& gcOutput_;
2030
2031 Iterator(const CompilationStencil& stencil, CompilationGCOutput& gcOutput,
2032 size_t index)
2033 : index_(index), stencil_(stencil), gcOutput_(gcOutput) {
2034 MOZ_ASSERT(index == stencil.scriptData.size());
2035 }
2036
2037 public:
2038 explicit Iterator(const CompilationStencil& stencil,
2039 CompilationGCOutput& gcOutput)
2040 : stencil_(stencil), gcOutput_(gcOutput) {
2041 skipTopLevelNonFunction();
2042 }
2043
2044 Iterator operator++() {
2045 next();
2046 assertFunction();
2047 return *this;
2048 }
2049
2050 void next() {
2051 MOZ_ASSERT(index_ < stencil_.scriptData.size());
2052 index_++;
2053 }
2054
2055 void assertFunction() {
2056 if (index_ < stencil_.scriptData.size()) {
2057 MOZ_ASSERT(stencil_.scriptData[index_].isFunction());
2058 }
2059 }
2060
2061 void skipTopLevelNonFunction() {
2062 MOZ_ASSERT(index_ == 0);
2063 if (stencil_.scriptData.size()) {
2064 if (!stencil_.scriptData[0].isFunction()) {
2065 next();
2066 assertFunction();
2067 }
2068 }
2069 }
2070
2071 bool operator!=(const Iterator& other) const {
2072 return index_ != other.index_;
2073 }
2074
2075 ScriptAndFunction operator*() {
2076 ScriptIndex index = ScriptIndex(index_);
2077 const ScriptStencil& script = stencil_.scriptData[index];
2078 const ScriptStencilExtra* scriptExtra = nullptr;
2079 if (stencil_.isInitialStencil()) {
2080 scriptExtra = &stencil_.scriptExtra[index];
2081 }
2082 return ScriptAndFunction(script, scriptExtra,
2083 gcOutput_.getFunctionNoBaseIndex(index), index);
2084 }
2085
2086 static Iterator end(const CompilationStencil& stencil,
2087 CompilationGCOutput& gcOutput) {
2088 return Iterator(stencil, gcOutput, stencil.scriptData.size());
2089 }
2090 };
2091
2092 const CompilationStencil& stencil_;
2093 CompilationGCOutput& gcOutput_;
2094
2095 explicit ScriptStencilIterable(const CompilationStencil& stencil,
2096 CompilationGCOutput& gcOutput)
2097 : stencil_(stencil), gcOutput_(gcOutput) {}
2098
2099 Iterator begin() const { return Iterator(stencil_, gcOutput_); }
2100
2101 Iterator end() const { return Iterator::end(stencil_, gcOutput_); }
2102 };
2103
2104 inline ScriptStencilIterable CompilationStencil::functionScriptStencils(
2105 const CompilationStencil& stencil, CompilationGCOutput& gcOutput) {
2106 return ScriptStencilIterable(stencil, gcOutput);
2107 }
2108
2109 // Merge CompilationStencil for delazification into initial
2110 // ExtensibleCompilationStencil.
2111 struct CompilationStencilMerger {
2112 private:
2113 using FunctionKey = SourceExtent::FunctionKey;
2114
2115 // The stencil for the initial compilation.
2116 // Delazifications are merged into this.
2117 //
2118 // If any failure happens during merge operation, this field is reset to
2119 // nullptr.
2120 UniquePtr<ExtensibleCompilationStencil> initial_;
2121
2122 FunctionKeyToScriptIndexMap functionKeyToInitialScriptIndex_;
2123
2124 ScriptIndex getInitialScriptIndexFor(
2125 const CompilationStencil& delazification) const;
2126
2127 // A map from delazification's ParserAtomIndex to
2128 // initial's TaggedParserAtomIndex
2129 using AtomIndexMap = Vector<TaggedParserAtomIndex, 0, js::SystemAllocPolicy>;
2130
2131 [[nodiscard]] bool buildAtomIndexMap(FrontendContext* fc,
2132 const CompilationStencil& delazification,
2133 AtomIndexMap& atomIndexMap);
2134
2135 public:
2136 CompilationStencilMerger() = default;
2137
2138 // Set the initial stencil and prepare for merging.
2139 [[nodiscard]] bool setInitial(
2140 FrontendContext* fc, UniquePtr<ExtensibleCompilationStencil>&& initial);
2141
2142 // Merge the delazification stencil into the initial stencil.
2143 [[nodiscard]] bool addDelazification(
2144 FrontendContext* fc, const CompilationStencil& delazification);
2145
2146 // Merge the delazification stencil into the initial stencil if the
2147 // delazification stencil can be merged.
2148 //
2149 // If the delazification's enclosing function is not yet merged, this does
2150 // do nothing.
2151 [[nodiscard]] bool maybeAddDelazification(
2152 FrontendContext* fc, const CompilationStencil& delazification);
2153
2154 ExtensibleCompilationStencil& getResult() const { return *initial_; }
2155 UniquePtr<ExtensibleCompilationStencil> takeResult() {
2156 return std::move(initial_);
2157 }
2158 };
2159
2160 const ScopeStencil& ScopeStencilRef::scope() const {
2161 return context_.scopeData[scopeIndex_];
2162 }
2163
2164 InputScope InputScope::enclosing() const {
2165 return scope_.match(
2166 [](const Scope* ptr) {
2167 // This may return a nullptr Scope pointer.
2168 return InputScope(ptr->enclosing());
2169 },
2170 [](const ScopeStencilRef& ref) {
2171 if (ref.scope().hasEnclosing()) {
2172 return InputScope(ref.context_, ref.scope().enclosing());
2173 }
2174 // The global scope is not known by the Stencil, while parsing inner
2175 // functions from Stencils where they are known at the execution using
2176 // the GlobalScope.
2177 if (ref.scope().kind() == ScopeKind::Module) {
2178 return InputScope(FakeStencilGlobalScope{});
2179 }
2180 return InputScope(nullptr);
2181 },
2182 [](const FakeStencilGlobalScope&) { return InputScope(nullptr); });
2183 }
2184
2185 FunctionFlags InputScope::functionFlags() const {
2186 return scope_.match(
2187 [](const Scope* ptr) {
2188 JSFunction* fun = ptr->as<FunctionScope>().canonicalFunction();
2189 return fun->flags();
2190 },
2191 [](const ScopeStencilRef& ref) {
2192 MOZ_ASSERT(ref.scope().isFunction());
2193 ScriptIndex scriptIndex = ref.scope().functionIndex();
2194 ScriptStencil& data = ref.context_.scriptData[scriptIndex];
2195 return data.functionFlags;
2196 },
2197 [](const FakeStencilGlobalScope&) -> FunctionFlags {
2198 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("No functionFlags on global.");
2199 });
2200 }
2201
2202 ImmutableScriptFlags InputScope::immutableFlags() const {
2203 return scope_.match(
2204 [](const Scope* ptr) {
2205 JSFunction* fun = ptr->as<FunctionScope>().canonicalFunction();
2206 return fun->baseScript()->immutableFlags();
2207 },
2208 [](const ScopeStencilRef& ref) {
2209 MOZ_ASSERT(ref.scope().isFunction());
2210 ScriptIndex scriptIndex = ref.scope().functionIndex();
2211 ScriptStencilExtra& extra = ref.context_.scriptExtra[scriptIndex];
2212 return extra.immutableFlags;
2213 },
2214 [](const FakeStencilGlobalScope&) -> ImmutableScriptFlags {
2215 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("No immutableFlags on global.");
2216 });
2217 }
2218
2219 MemberInitializers InputScope::getMemberInitializers() const {
2220 return scope_.match(
2221 [](const Scope* ptr) {
2222 JSFunction* fun = ptr->as<FunctionScope>().canonicalFunction();
2223 return fun->baseScript()->getMemberInitializers();
2224 },
2225 [](const ScopeStencilRef& ref) {
2226 MOZ_ASSERT(ref.scope().isFunction());
2227 ScriptIndex scriptIndex = ref.scope().functionIndex();
2228 ScriptStencilExtra& extra = ref.context_.scriptExtra[scriptIndex];
2229 return extra.memberInitializers();
2230 },
2231 [](const FakeStencilGlobalScope&) -> MemberInitializers {
2232 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE(
2233 "No getMemberInitializers on global.");
2234 });
2235 }
2236
2237 const ScriptStencil& ScriptStencilRef::scriptData() const {
2238 return context_.scriptData[scriptIndex_];
2239 }
2240
2241 const ScriptStencilExtra& ScriptStencilRef::scriptExtra() const {
2242 return context_.scriptExtra[scriptIndex_];
2243 }
2244
2245 } // namespace frontend
2246 } // namespace js
2247
2248 namespace mozilla {
2249 template <>
2250 struct RefPtrTraits<js::frontend::CompilationStencil> {
2251 static void AddRef(js::frontend::CompilationStencil* stencil) {
2252 stencil->AddRef();
2253 }
2254 static void Release(js::frontend::CompilationStencil* stencil) {
2255 stencil->Release();
2256 }
2257 };
2258 } // namespace mozilla
2259
2260 #endif // frontend_CompilationStencil_h