Debian Codegraph @

js/src/vm/ConcurrentDelazification.cpp

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 #include "vm/ConcurrentDelazification.h"
8
9 #include "mozilla/Assertions.h" // MOZ_ASSERT, MOZ_CRASH
10 #include "mozilla/RefPtr.h" // RefPtr
11 #include "mozilla/ReverseIterator.h" // mozilla::Reversed
12 #include "mozilla/ScopeExit.h" // mozilla::MakeScopeExit
13
14 #include <stddef.h> // size_t
15 #include <utility> // std::swap, std::move, std::pair
16
17 #include "ds/LifoAlloc.h" // LifoAlloc
18 #include "frontend/BytecodeCompiler.h" // DelazifyCanonicalScriptedFunction, DelazifyFailureReason
19 #include "frontend/CompilationStencil.h" // CompilationStencil, ExtensibleCompilationStencil, BorrowingCompilationStencil, ScriptStencilRef
20 #include "frontend/FrontendContext.h" // JS::FrontendContext
21 #include "frontend/ScopeBindingCache.h" // StencilScopeBindingCache
22 #include "frontend/Stencil.h" // TaggedScriptThingIndex, ScriptStencilExtra
23 #include "js/AllocPolicy.h" // ReportOutOfMemory
24 #include "js/experimental/JSStencil.h" // RefPtrTraits<JS::Stencil>
25 #include "vm/JSContext.h" // JSContext
26
27 using namespace js;
28
29 bool DelazifyStrategy::add(FrontendContext* fc,
30 const frontend::CompilationStencil& stencil,
31 ScriptIndex index) {
32 using namespace js::frontend;
33 ScriptStencilRef scriptRef{stencil, index};
34
35 // Only functions with bytecode are allowed to be added.
36 MOZ_ASSERT(!scriptRef.scriptData().isGhost());
37 MOZ_ASSERT(scriptRef.scriptData().hasSharedData());
38
39 // Lookup the gc-things range which are referenced by this script.
40 size_t offset = scriptRef.scriptData().gcThingsOffset.index;
41 size_t length = scriptRef.scriptData().gcThingsLength;
42 auto gcThingData = stencil.gcThingData.Subspan(offset, length);
43
44 // Iterate over gc-things of the script and queue inner functions.
45 for (TaggedScriptThingIndex index : mozilla::Reversed(gcThingData)) {
46 if (!index.isFunction()) {
47 continue;
48 }
49
50 ScriptIndex innerScriptIndex = index.toFunction();
51 ScriptStencilRef innerScriptRef{stencil, innerScriptIndex};
52 if (innerScriptRef.scriptData().isGhost() ||
53 !innerScriptRef.scriptData().functionFlags.isInterpreted()) {
54 continue;
55 }
56 if (innerScriptRef.scriptData().hasSharedData()) {
57 // The top-level parse decided to eagerly parse this function, thus we
58 // should visit its inner function the same way.
59 if (!add(fc, stencil, innerScriptIndex)) {
60 return false;
61 }
62 continue;
63 }
64
65 // Maybe insert the new script index in the queue of functions to delazify.
66 if (!insert(innerScriptIndex, innerScriptRef)) {
67 ReportOutOfMemory(fc);
68 return false;
69 }
70 }
71
72 return true;
73 }
74
75 DelazifyStrategy::ScriptIndex LargeFirstDelazification::next() {
76 std::swap(heap.back(), heap[0]);
77 ScriptIndex result = heap.popCopy().second;
78
79 // NOTE: These are a heap indexes offseted by 1, such that we can manipulate
80 // the tree of heap-sorted values which bubble up the largest values towards
81 // the root of the tree.
82 size_t len = heap.length();
83 size_t i = 1;
84 while (true) {
85 // NOTE: We write (n + 1) - 1, instead of n, to explicit that the
86 // manipualted indexes are all offseted by 1.
87 size_t n = 2 * i;
88 size_t largest;
89 if (n + 1 <= len && heap[(n + 1) - 1].first > heap[n - 1].first) {
90 largest = n + 1;
91 } else if (n <= len) {
92 // The condition is n <= len in case n + 1 is out of the heap vector, but
93 // not n, in which case we still want to check if the last element of the
94 // heap vector should be swapped. Otherwise heap[n - 1] represents a
95 // larger function than heap[(n + 1) - 1].
96 largest = n;
97 } else {
98 // n is out-side the heap vector, thus our element is already in a leaf
99 // position and would not be moved any more.
100 break;
101 }
102
103 if (heap[i - 1].first < heap[largest - 1].first) {
104 // We found a function which has a larger body as a child of the current
105 // element. we swap it with the current element, such that the largest
106 // element is closer to the root of the tree.
107 std::swap(heap[i - 1], heap[largest - 1]);
108 i = largest;
109 } else {
110 // The largest function found as a child of the current node is smaller
111 // than the current node's function size. The heap tree is now organized
112 // as expected.
113 break;
114 }
115 }
116
117 return result;
118 }
119
120 bool LargeFirstDelazification::insert(ScriptIndex index,
121 frontend::ScriptStencilRef& ref) {
122 const frontend::ScriptStencilExtra& extra = ref.scriptExtra();
123 SourceSize size = extra.extent.sourceEnd - extra.extent.sourceStart;
124 if (!heap.append(std::pair(size, index))) {
125 return false;
126 }
127
128 // NOTE: These are a heap indexes offseted by 1, such that we can manipulate
129 // the tree of heap-sorted values which bubble up the largest values towards
130 // the root of the tree.
131 size_t i = heap.length();
132 while (i > 1) {
133 if (heap[i - 1].first <= heap[(i / 2) - 1].first) {
134 return true;
135 }
136
137 std::swap(heap[i - 1], heap[(i / 2) - 1]);
138 i /= 2;
139 }
140
141 return true;
142 }
143
144 bool DelazificationContext::init(
145 const JS::ReadOnlyCompileOptions& options,
146 frontend::InitialStencilAndDelazifications* stencils) {
147 using namespace js::frontend;
148
149 stencils_ = stencils;
150
151 const CompilationStencil& stencil = *stencils->getInitial();
152 auto initial = fc_.getAllocator()->make_unique<ExtensibleCompilationStencil>(
153 options, stencil.source);
154 if (!initial || !initial->cloneFrom(&fc_, stencil)) {
155 return false;
156 }
157
158 if (!fc_.allocateOwnedPool()) {
159 return false;
160 }
161
162 if (!merger_.setInitial(&fc_, std::move(initial))) {
163 return false;
164 }
165
166 switch (options.eagerDelazificationStrategy()) {
167 case JS::DelazificationOption::OnDemandOnly:
168 // OnDemandOnly will parse function as they are require to continue the
169 // execution on the main thread.
170 MOZ_CRASH("OnDemandOnly should not create a DelazificationContext.");
171 break;
172 case JS::DelazificationOption::CheckConcurrentWithOnDemand:
173 case JS::DelazificationOption::ConcurrentDepthFirst:
174 // ConcurrentDepthFirst visit all functions to be delazified, visiting the
175 // inner functions before the siblings functions.
176 strategy_ = fc_.getAllocator()->make_unique<DepthFirstDelazification>();
177 break;
178 case JS::DelazificationOption::ConcurrentLargeFirst:
179 // ConcurrentLargeFirst visit all functions to be delazified, visiting the
180 // largest function first.
181 strategy_ = fc_.getAllocator()->make_unique<LargeFirstDelazification>();
182 break;
183 case JS::DelazificationOption::ParseEverythingEagerly:
184 // ParseEverythingEagerly parse all functions eagerly, thus leaving no
185 // functions to be parsed on demand.
186 MOZ_CRASH(
187 "ParseEverythingEagerly should not create a DelazificationContext");
188 break;
189 }
190
191 if (!strategy_) {
192 return false;
193 }
194
195 // Queue functions from the top-level to be delazify.
196 BorrowingCompilationStencil borrow(merger_.getResult());
197 ScriptIndex topLevel{0};
198 return strategy_->add(&fc_, borrow, topLevel);
199 }
200
201 bool DelazificationContext::delazify() {
202 fc_.setStackQuota(stackQuota_);
203 auto purgePool =
204 mozilla::MakeScopeExit([&] { fc_.nameCollectionPool().purge(); });
205
206 using namespace js::frontend;
207
208 // Create a scope-binding cache dedicated to this delazification. The memory
209 // would be reclaimed when interrupted or if all delazification are completed.
210 //
211 // We do not use the one from the JSContext/Runtime, as it is not thread safe
212 // to use it, as it could be purged by a GC in the mean time.
213 StencilScopeBindingCache scopeCache(merger_);
214
215 LifoAlloc tempLifoAlloc(JSContext::TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE,
216 js::BackgroundMallocArena);
217
218 while (!strategy_->done()) {
219 if (isInterrupted_) {
220 isInterrupted_ = false;
221 break;
222 }
223 const CompilationStencil* innerStencil;
224 ScriptIndex scriptIndex = strategy_->next();
225 {
226 BorrowingCompilationStencil borrow(merger_.getResult());
227
228 // Parse and generate bytecode for the inner function.
229 DelazifyFailureReason failureReason;
230 innerStencil = DelazifyCanonicalScriptedFunction(
231 &fc_, tempLifoAlloc, initialPrefableOptions_, &scopeCache, borrow,
232 scriptIndex, stencils_.get(), &failureReason);
233 if (!innerStencil) {
234 if (failureReason == DelazifyFailureReason::Compressed) {
235 // The script source is already compressed, and delazification cannot
236 // be performed without decompressing.
237 // There is no reason to keep our eager delazification going.
238 strategy_->clear();
239 return true;
240 }
241
242 strategy_->clear();
243 return false;
244 }
245 }
246
247 // We are merging the delazification now, while this could be post-poned
248 // until we have to look at inner functions, this is simpler to do it now
249 // than querying the cache for every enclosing script.
250 if (!merger_.addDelazification(&fc_, *innerStencil)) {
251 strategy_->clear();
252 return false;
253 }
254
255 {
256 BorrowingCompilationStencil borrow(merger_.getResult());
257 if (!strategy_->add(&fc_, borrow, scriptIndex)) {
258 strategy_->clear();
259 return false;
260 }
261 }
262 }
263
264 return true;
265 }
266
267 bool DelazificationContext::done() const {
268 if (!strategy_) {
269 return true;
270 }
271
272 return strategy_->done();
273 }
274
275 size_t DelazificationContext::sizeOfExcludingThis(
276 mozilla::MallocSizeOf mallocSizeOf) const {
277 size_t mergerSize = merger_.getResult().sizeOfIncludingThis(mallocSizeOf);
278 return mergerSize;
279 }