forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHelperThreads.cpp
2745 lines (2294 loc) · 85.6 KB
/
HelperThreads.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/HelperThreads.h"
#include "mozilla/ReverseIterator.h" // mozilla::Reversed(...)
#include "mozilla/ScopeExit.h"
#include "mozilla/Span.h" // mozilla::Span<TaggedScriptThingIndex>
#include "mozilla/Utf8.h" // mozilla::Utf8Unit
#include <algorithm>
#include "frontend/BytecodeCompilation.h" // frontend::{CompileGlobalScriptToExtensibleStencil, FireOnNewScript}
#include "frontend/BytecodeCompiler.h" // frontend::ParseModuleToExtensibleStencil
#include "frontend/CompilationStencil.h" // frontend::{CompilationStencil, ExtensibleCompilationStencil, CompilationInput, BorrowingCompilationStencil, ScriptStencilRef}
#include "frontend/FrontendContext.h"
#include "frontend/ScopeBindingCache.h" // frontend::ScopeBindingCache
#include "gc/GC.h"
#include "jit/IonCompileTask.h"
#include "jit/JitRuntime.h"
#include "jit/JitScript.h"
#include "js/CompileOptions.h" // JS::CompileOptions, JS::DecodeOptions, JS::ReadOnlyCompileOptions
#include "js/ContextOptions.h" // JS::ContextOptions
#include "js/experimental/CompileScript.h"
#include "js/experimental/JSStencil.h"
#include "js/friend/StackLimits.h" // js::ReportOverRecursed
#include "js/HelperThreadAPI.h"
#include "js/OffThreadScriptCompilation.h" // JS::OffThreadToken, JS::OffThreadCompileCallback
#include "js/SourceText.h"
#include "js/Stack.h"
#include "js/Transcoding.h"
#include "js/UniquePtr.h"
#include "js/Utility.h"
#include "threading/CpuCount.h"
#include "vm/ErrorReporting.h"
#include "vm/HelperThreadState.h"
#include "vm/InternalThreadPool.h"
#include "vm/MutexIDs.h"
#include "wasm/WasmGenerator.h"
using namespace js;
using mozilla::TimeDuration;
using mozilla::TimeStamp;
using mozilla::Utf8Unit;
using JS::CompileOptions;
using JS::DispatchReason;
using JS::ReadOnlyCompileOptions;
namespace js {
Mutex gHelperThreadLock(mutexid::GlobalHelperThreadState);
GlobalHelperThreadState* gHelperThreadState = nullptr;
} // namespace js
bool js::CreateHelperThreadsState() {
MOZ_ASSERT(!gHelperThreadState);
gHelperThreadState = js_new<GlobalHelperThreadState>();
return gHelperThreadState;
}
void js::DestroyHelperThreadsState() {
AutoLockHelperThreadState lock;
if (!gHelperThreadState) {
return;
}
gHelperThreadState->finish(lock);
js_delete(gHelperThreadState);
gHelperThreadState = nullptr;
}
bool js::EnsureHelperThreadsInitialized() {
MOZ_ASSERT(gHelperThreadState);
return gHelperThreadState->ensureInitialized();
}
static size_t ClampDefaultCPUCount(size_t cpuCount) {
// It's extremely rare for SpiderMonkey to have more than a few cores worth
// of work. At higher core counts, performance can even decrease due to NUMA
// (and SpiderMonkey's lack of NUMA-awareness), contention, and general lack
// of optimization for high core counts. So to avoid wasting thread stack
// resources (and cluttering gdb and core dumps), clamp to 8 cores for now.
return std::min<size_t>(cpuCount, 8);
}
static size_t ThreadCountForCPUCount(size_t cpuCount) {
// We need at least two threads for tier-2 wasm compilations, because
// there's a master task that holds a thread while other threads do the
// compilation.
return std::max<size_t>(cpuCount, 2);
}
bool js::SetFakeCPUCount(size_t count) {
HelperThreadState().setCpuCount(count);
return true;
}
void GlobalHelperThreadState::setCpuCount(size_t count) {
// This must be called before any threads have been initialized.
AutoLockHelperThreadState lock;
MOZ_ASSERT(!isInitialized(lock));
// We can't do this if an external thread pool is in use.
MOZ_ASSERT(!dispatchTaskCallback);
cpuCount = count;
threadCount = ThreadCountForCPUCount(count);
}
size_t js::GetHelperThreadCount() { return HelperThreadState().threadCount; }
size_t js::GetHelperThreadCPUCount() { return HelperThreadState().cpuCount; }
size_t js::GetMaxWasmCompilationThreads() {
return HelperThreadState().maxWasmCompilationThreads();
}
void JS::SetProfilingThreadCallbacks(
JS::RegisterThreadCallback registerThread,
JS::UnregisterThreadCallback unregisterThread) {
HelperThreadState().registerThread = registerThread;
HelperThreadState().unregisterThread = unregisterThread;
}
static size_t ThreadStackQuotaForSize(size_t size) {
// Set the stack quota to 10% less that the actual size.
return size_t(double(size) * 0.9);
}
// Bug 1630189: Without MOZ_NEVER_INLINE, Windows PGO builds have a linking
// error for HelperThreadTaskCallback.
JS_PUBLIC_API MOZ_NEVER_INLINE void JS::SetHelperThreadTaskCallback(
HelperThreadTaskCallback callback, size_t threadCount, size_t stackSize) {
AutoLockHelperThreadState lock;
HelperThreadState().setDispatchTaskCallback(callback, threadCount, stackSize,
lock);
}
void GlobalHelperThreadState::setDispatchTaskCallback(
JS::HelperThreadTaskCallback callback, size_t threadCount, size_t stackSize,
const AutoLockHelperThreadState& lock) {
MOZ_ASSERT(!isInitialized(lock));
MOZ_ASSERT(!dispatchTaskCallback);
MOZ_ASSERT(threadCount != 0);
MOZ_ASSERT(stackSize >= 16 * 1024);
dispatchTaskCallback = callback;
this->threadCount = threadCount;
this->stackQuota = ThreadStackQuotaForSize(stackSize);
}
bool js::StartOffThreadWasmCompile(wasm::CompileTask* task,
wasm::CompileMode mode) {
return HelperThreadState().submitTask(task, mode);
}
bool GlobalHelperThreadState::submitTask(wasm::CompileTask* task,
wasm::CompileMode mode) {
AutoLockHelperThreadState lock;
if (!wasmWorklist(lock, mode).pushBack(task)) {
return false;
}
dispatch(DispatchReason::NewTask, lock);
return true;
}
size_t js::RemovePendingWasmCompileTasks(
const wasm::CompileTaskState& taskState, wasm::CompileMode mode,
const AutoLockHelperThreadState& lock) {
wasm::CompileTaskPtrFifo& worklist =
HelperThreadState().wasmWorklist(lock, mode);
return worklist.eraseIf([&taskState](wasm::CompileTask* task) {
return &task->state == &taskState;
});
}
void js::StartOffThreadWasmTier2Generator(wasm::UniqueTier2GeneratorTask task) {
(void)HelperThreadState().submitTask(std::move(task));
}
bool GlobalHelperThreadState::submitTask(wasm::UniqueTier2GeneratorTask task) {
AutoLockHelperThreadState lock;
MOZ_ASSERT(isInitialized(lock));
if (!wasmTier2GeneratorWorklist(lock).append(task.get())) {
return false;
}
(void)task.release();
dispatch(DispatchReason::NewTask, lock);
return true;
}
static void CancelOffThreadWasmTier2GeneratorLocked(
AutoLockHelperThreadState& lock) {
if (!HelperThreadState().isInitialized(lock)) {
return;
}
// Remove pending tasks from the tier2 generator worklist and cancel and
// delete them.
{
wasm::Tier2GeneratorTaskPtrVector& worklist =
HelperThreadState().wasmTier2GeneratorWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
wasm::Tier2GeneratorTask* task = worklist[i];
HelperThreadState().remove(worklist, &i);
js_delete(task);
}
}
// There is at most one running Tier2Generator task and we assume that
// below.
static_assert(GlobalHelperThreadState::MaxTier2GeneratorTasks == 1,
"code must be generalized");
// If there is a running Tier2 generator task, shut it down in a predictable
// way. The task will be deleted by the normal deletion logic.
for (auto* helper : HelperThreadState().helperTasks(lock)) {
if (helper->is<wasm::Tier2GeneratorTask>()) {
// Set a flag that causes compilation to shortcut itself.
helper->as<wasm::Tier2GeneratorTask>()->cancel();
// Wait for the generator task to finish. This avoids a shutdown race
// where the shutdown code is trying to shut down helper threads and the
// ongoing tier2 compilation is trying to finish, which requires it to
// have access to helper threads.
uint32_t oldFinishedCount =
HelperThreadState().wasmTier2GeneratorsFinished(lock);
while (HelperThreadState().wasmTier2GeneratorsFinished(lock) ==
oldFinishedCount) {
HelperThreadState().wait(lock);
}
// At most one of these tasks.
break;
}
}
}
void js::CancelOffThreadWasmTier2Generator() {
AutoLockHelperThreadState lock;
CancelOffThreadWasmTier2GeneratorLocked(lock);
}
bool js::StartOffThreadIonCompile(jit::IonCompileTask* task,
const AutoLockHelperThreadState& lock) {
return HelperThreadState().submitTask(task, lock);
}
bool GlobalHelperThreadState::submitTask(
jit::IonCompileTask* task, const AutoLockHelperThreadState& locked) {
MOZ_ASSERT(isInitialized(locked));
if (!ionWorklist(locked).append(task)) {
return false;
}
// The build is moving off-thread. Freeze the LifoAlloc to prevent any
// unwanted mutations.
task->alloc().lifoAlloc()->setReadOnly();
dispatch(DispatchReason::NewTask, locked);
return true;
}
bool js::StartOffThreadIonFree(jit::IonCompileTask* task,
const AutoLockHelperThreadState& lock) {
js::UniquePtr<jit::IonFreeTask> freeTask =
js::MakeUnique<jit::IonFreeTask>(task);
if (!freeTask) {
return false;
}
return HelperThreadState().submitTask(std::move(freeTask), lock);
}
bool GlobalHelperThreadState::submitTask(
UniquePtr<jit::IonFreeTask> task, const AutoLockHelperThreadState& locked) {
MOZ_ASSERT(isInitialized(locked));
if (!ionFreeList(locked).append(std::move(task))) {
return false;
}
dispatch(DispatchReason::NewTask, locked);
return true;
}
/*
* Move an IonCompilationTask for which compilation has either finished, failed,
* or been cancelled into the global finished compilation list. All off thread
* compilations which are started must eventually be finished.
*/
void js::FinishOffThreadIonCompile(jit::IonCompileTask* task,
const AutoLockHelperThreadState& lock) {
AutoEnterOOMUnsafeRegion oomUnsafe;
if (!HelperThreadState().ionFinishedList(lock).append(task)) {
oomUnsafe.crash("FinishOffThreadIonCompile");
}
task->script()
->runtimeFromAnyThread()
->jitRuntime()
->numFinishedOffThreadTasksRef(lock)++;
}
static JSRuntime* GetSelectorRuntime(const CompilationSelector& selector) {
struct Matcher {
JSRuntime* operator()(JSScript* script) {
return script->runtimeFromMainThread();
}
JSRuntime* operator()(Realm* realm) {
return realm->runtimeFromMainThread();
}
JSRuntime* operator()(Zone* zone) { return zone->runtimeFromMainThread(); }
JSRuntime* operator()(ZonesInState zbs) { return zbs.runtime; }
JSRuntime* operator()(JSRuntime* runtime) { return runtime; }
};
return selector.match(Matcher());
}
static bool JitDataStructuresExist(const CompilationSelector& selector) {
struct Matcher {
bool operator()(JSScript* script) { return !!script->realm()->jitRealm(); }
bool operator()(Realm* realm) { return !!realm->jitRealm(); }
bool operator()(Zone* zone) { return !!zone->jitZone(); }
bool operator()(ZonesInState zbs) { return zbs.runtime->hasJitRuntime(); }
bool operator()(JSRuntime* runtime) { return runtime->hasJitRuntime(); }
};
return selector.match(Matcher());
}
static bool IonCompileTaskMatches(const CompilationSelector& selector,
jit::IonCompileTask* task) {
struct TaskMatches {
jit::IonCompileTask* task_;
bool operator()(JSScript* script) { return script == task_->script(); }
bool operator()(Realm* realm) { return realm == task_->script()->realm(); }
bool operator()(Zone* zone) {
return zone == task_->script()->zoneFromAnyThread();
}
bool operator()(JSRuntime* runtime) {
return runtime == task_->script()->runtimeFromAnyThread();
}
bool operator()(ZonesInState zbs) {
return zbs.runtime == task_->script()->runtimeFromAnyThread() &&
zbs.state == task_->script()->zoneFromAnyThread()->gcState();
}
};
return selector.match(TaskMatches{task});
}
static void CancelOffThreadIonCompileLocked(const CompilationSelector& selector,
AutoLockHelperThreadState& lock) {
if (!HelperThreadState().isInitialized(lock)) {
return;
}
MOZ_ASSERT(GetSelectorRuntime(selector)->jitRuntime() != nullptr);
/* Cancel any pending entries for which processing hasn't started. */
GlobalHelperThreadState::IonCompileTaskVector& worklist =
HelperThreadState().ionWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
jit::IonCompileTask* task = worklist[i];
if (IonCompileTaskMatches(selector, task)) {
// Once finished, tasks are added to a Linked list which is
// allocated with the IonCompileTask class. The IonCompileTask is
// allocated in the LifoAlloc so we need the LifoAlloc to be mutable.
worklist[i]->alloc().lifoAlloc()->setReadWrite();
FinishOffThreadIonCompile(task, lock);
HelperThreadState().remove(worklist, &i);
}
}
/* Wait for in progress entries to finish up. */
bool cancelled;
do {
cancelled = false;
for (auto* helper : HelperThreadState().helperTasks(lock)) {
if (!helper->is<jit::IonCompileTask>()) {
continue;
}
jit::IonCompileTask* ionCompileTask = helper->as<jit::IonCompileTask>();
if (IonCompileTaskMatches(selector, ionCompileTask)) {
ionCompileTask->mirGen().cancel();
cancelled = true;
}
}
if (cancelled) {
HelperThreadState().wait(lock);
}
} while (cancelled);
/* Cancel code generation for any completed entries. */
GlobalHelperThreadState::IonCompileTaskVector& finished =
HelperThreadState().ionFinishedList(lock);
for (size_t i = 0; i < finished.length(); i++) {
jit::IonCompileTask* task = finished[i];
if (IonCompileTaskMatches(selector, task)) {
JSRuntime* rt = task->script()->runtimeFromAnyThread();
rt->jitRuntime()->numFinishedOffThreadTasksRef(lock)--;
jit::FinishOffThreadTask(rt, task, lock);
HelperThreadState().remove(finished, &i);
}
}
/* Cancel lazy linking for pending tasks (attached to the ionScript). */
JSRuntime* runtime = GetSelectorRuntime(selector);
jit::IonCompileTask* task =
runtime->jitRuntime()->ionLazyLinkList(runtime).getFirst();
while (task) {
jit::IonCompileTask* next = task->getNext();
if (IonCompileTaskMatches(selector, task)) {
jit::FinishOffThreadTask(runtime, task, lock);
}
task = next;
}
}
void js::CancelOffThreadIonCompile(const CompilationSelector& selector) {
if (!JitDataStructuresExist(selector)) {
return;
}
AutoLockHelperThreadState lock;
CancelOffThreadIonCompileLocked(selector, lock);
}
#ifdef DEBUG
bool js::HasOffThreadIonCompile(Realm* realm) {
AutoLockHelperThreadState lock;
if (!HelperThreadState().isInitialized(lock)) {
return false;
}
GlobalHelperThreadState::IonCompileTaskVector& worklist =
HelperThreadState().ionWorklist(lock);
for (size_t i = 0; i < worklist.length(); i++) {
jit::IonCompileTask* task = worklist[i];
if (task->script()->realm() == realm) {
return true;
}
}
for (auto* helper : HelperThreadState().helperTasks(lock)) {
if (helper->is<jit::IonCompileTask>() &&
helper->as<jit::IonCompileTask>()->script()->realm() == realm) {
return true;
}
}
GlobalHelperThreadState::IonCompileTaskVector& finished =
HelperThreadState().ionFinishedList(lock);
for (size_t i = 0; i < finished.length(); i++) {
jit::IonCompileTask* task = finished[i];
if (task->script()->realm() == realm) {
return true;
}
}
JSRuntime* rt = realm->runtimeFromMainThread();
jit::IonCompileTask* task = rt->jitRuntime()->ionLazyLinkList(rt).getFirst();
while (task) {
if (task->script()->realm() == realm) {
return true;
}
task = task->getNext();
}
return false;
}
#endif
struct MOZ_RAII AutoSetContextFrontendErrors {
explicit AutoSetContextFrontendErrors(FrontendContext* fc) {
fc->linkWithJSContext(TlsContext.get());
}
~AutoSetContextFrontendErrors() {
TlsContext.get()->setFrontendErrors(nullptr);
}
};
AutoSetHelperThreadContext::AutoSetHelperThreadContext(
const JS::ContextOptions& options, AutoLockHelperThreadState& lock)
: lock(lock) {
cx = HelperThreadState().getFirstUnusedContext(lock);
MOZ_ASSERT(cx);
cx->setHelperThread(options, lock);
}
AutoSetHelperThreadContext::~AutoSetHelperThreadContext() {
cx->tempLifoAlloc().releaseAll();
if (cx->shouldFreeUnusedMemory()) {
cx->tempLifoAlloc().freeAll();
cx->setFreeUnusedMemory(false);
}
cx->clearHelperThread(lock);
cx = nullptr;
}
ParseTask::ParseTask(ParseTaskKind kind, JSContext* cx,
JS::OffThreadCompileCallback callback, void* callbackData)
: kind(kind),
options(cx),
contextOptions(cx->options()),
callback(callback),
callbackData(callbackData) {
// Note that |cx| is the main thread context here but the parse task will
// run with a different, helper thread, context.
MOZ_ASSERT(!cx->isHelperThreadContext());
}
bool ParseTask::init(JSContext* cx, const ReadOnlyCompileOptions& options) {
MOZ_ASSERT(!cx->isHelperThreadContext());
if (!this->options.copy(cx, options)) {
return false;
}
runtime = cx->runtime();
if (!fc_.allocateOwnedPool()) {
ReportOutOfMemory(cx);
return false;
}
// MultiStencilsDecode doesn't support JS::InstantiationStorage.
MOZ_ASSERT_IF(this->options.allocateInstantiationStorage,
kind != ParseTaskKind::MultiStencilsDecode);
return true;
}
void ParseTask::moveInstantiationStorageInto(
JS::InstantiationStorage& storage) {
storage.gcOutput_ = instantiationStorage_.gcOutput_;
instantiationStorage_.gcOutput_ = nullptr;
}
ParseTask::~ParseTask() {
// The LinkedListElement destructor will remove us from any list we are part
// of without synchronization, so ensure that doesn't happen.
MOZ_DIAGNOSTIC_ASSERT(!isInList());
}
void ParseTask::trace(JSTracer* trc) {
if (runtime != trc->runtime()) {
return;
}
compileStorage_.trace(trc);
instantiationStorage_.trace(trc);
}
size_t ParseTask::sizeOfExcludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
size_t compileStorageSize = compileStorage_.sizeOfIncludingThis(mallocSizeOf);
size_t stencilSize =
stencil_ ? stencil_->sizeOfIncludingThis(mallocSizeOf) : 0;
size_t gcOutputSize =
instantiationStorage_.gcOutput_
? instantiationStorage_.gcOutput_->sizeOfExcludingThis(mallocSizeOf)
: 0;
// TODO: 'errors' requires adding support to `CompileError`. They are not
// common though.
return options.sizeOfExcludingThis(mallocSizeOf) + compileStorageSize +
stencilSize + gcOutputSize;
}
void ParseTask::runHelperThreadTask(AutoLockHelperThreadState& locked) {
runTask(locked);
// Schedule DelazifyTask if needed. NOTE: This should be done before adding
// this task to the finished list, as we temporarily release the lock to make
// a few large allocations.
scheduleDelazifyTask(locked);
// The callback is invoked while we are still off thread.
callback(this, callbackData);
// FinishOffThreadScript will need to be called on the script to
// migrate it into the correct compartment.
HelperThreadState().parseFinishedList(locked).insertBack(this);
}
void ParseTask::runTask(AutoLockHelperThreadState& lock) {
fc_.setStackQuota(HelperThreadState().stackQuota);
AutoUnlockHelperThreadState unlock(lock);
parse(&fc_);
fc_.nameCollectionPool().purge();
}
void ParseTask::scheduleDelazifyTask(AutoLockHelperThreadState& lock) {
if (!stencil_) {
return;
}
// Skip delazify tasks if we parese everything on-demand or ahead.
auto strategy = options.eagerDelazificationStrategy();
if (strategy == JS::DelazificationOption::OnDemandOnly ||
strategy == JS::DelazificationOption::ParseEverythingEagerly) {
return;
}
UniquePtr<DelazifyTask> task;
{
AutoSetHelperThreadContext usesContext(contextOptions, lock);
AutoUnlockHelperThreadState unlock(lock);
AutoSetContextRuntime ascr(runtime);
task = DelazifyTask::Create(runtime, contextOptions, options, *stencil_);
if (!task) {
return;
}
}
// Schedule delazification task if there is any function to delazify.
if (!task->strategy->done()) {
HelperThreadState().submitTask(task.release(), lock);
}
}
template <typename Unit>
struct CompileToStencilTask : public ParseTask {
JS::SourceText<Unit> data;
CompileToStencilTask(JSContext* cx, JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback,
void* callbackData);
void parse(FrontendContext* fc) override;
};
template <typename Unit>
struct CompileModuleToStencilTask : public ParseTask {
JS::SourceText<Unit> data;
CompileModuleToStencilTask(JSContext* cx, JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback,
void* callbackData);
void parse(FrontendContext* fc) override;
};
struct DecodeStencilTask : public ParseTask {
const JS::TranscodeRange range;
DecodeStencilTask(JSContext* cx, const JS::TranscodeRange& range,
JS::OffThreadCompileCallback callback, void* callbackData);
void parse(FrontendContext* fc) override;
};
struct MultiStencilsDecodeTask : public ParseTask {
JS::TranscodeSources* sources;
MultiStencilsDecodeTask(JSContext* cx, JS::TranscodeSources& sources,
JS::OffThreadCompileCallback callback,
void* callbackData);
void parse(FrontendContext* fc) override;
};
template <typename Unit>
CompileToStencilTask<Unit>::CompileToStencilTask(
JSContext* cx, JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback, void* callbackData)
: ParseTask(ParseTaskKind::ScriptStencil, cx, callback, callbackData),
data(std::move(srcBuf)) {}
template <typename Unit>
void CompileToStencilTask<Unit>::parse(FrontendContext* fc) {
stencil_ =
JS::CompileGlobalScriptToStencil(fc, options, data, compileStorage_);
if (!stencil_) {
return;
}
if (options.allocateInstantiationStorage) {
if (!JS::PrepareForInstantiate(fc, compileStorage_, *stencil_,
instantiationStorage_)) {
stencil_ = nullptr;
}
}
}
template <typename Unit>
CompileModuleToStencilTask<Unit>::CompileModuleToStencilTask(
JSContext* cx, JS::SourceText<Unit>& srcBuf,
JS::OffThreadCompileCallback callback, void* callbackData)
: ParseTask(ParseTaskKind::ModuleStencil, cx, callback, callbackData),
data(std::move(srcBuf)) {}
template <typename Unit>
void CompileModuleToStencilTask<Unit>::parse(FrontendContext* fc) {
stencil_ =
JS::CompileModuleScriptToStencil(fc, options, data, compileStorage_);
if (!stencil_) {
return;
}
if (options.allocateInstantiationStorage) {
if (!JS::PrepareForInstantiate(fc, compileStorage_, *stencil_,
instantiationStorage_)) {
stencil_ = nullptr;
}
}
}
DecodeStencilTask::DecodeStencilTask(JSContext* cx,
const JS::TranscodeRange& range,
JS::OffThreadCompileCallback callback,
void* callbackData)
: ParseTask(ParseTaskKind::StencilDecode, cx, callback, callbackData),
range(range) {
MOZ_ASSERT(JS::IsTranscodingBytecodeAligned(range.begin().get()));
}
static void ReportDecodeFailure(JS::FrontendContext* fc, ...) {
va_list ap;
va_start(ap, fc);
js::ErrorMetadata metadata;
metadata.filename = "<unknown>";
metadata.lineNumber = 0;
metadata.columnNumber = 0;
metadata.lineLength = 0;
metadata.tokenOffset = 0;
metadata.isMuted = false;
js::ReportCompileErrorLatin1(fc, std::move(metadata), nullptr,
JSMSG_DECODE_FAILURE, &ap);
va_end(ap);
}
void DecodeStencilTask::parse(FrontendContext* fc) {
if (!compileStorage_.allocateInput(fc, options)) {
return;
}
if (!compileStorage_.getInput().initForGlobal(fc)) {
return;
}
stencil_ = fc->getAllocator()->new_<frontend::CompilationStencil>(
compileStorage_.getInput().source);
if (!stencil_) {
return;
}
bool succeeded = false;
(void)stencil_->deserializeStencils(fc, options, range, &succeeded);
if (!succeeded) {
if (!fc->hadErrors()) {
ReportDecodeFailure(fc);
}
stencil_ = nullptr;
return;
}
if (options.allocateInstantiationStorage) {
if (!JS::PrepareForInstantiate(fc, compileStorage_, *stencil_,
instantiationStorage_)) {
stencil_ = nullptr;
}
}
}
MultiStencilsDecodeTask::MultiStencilsDecodeTask(
JSContext* cx, JS::TranscodeSources& sources,
JS::OffThreadCompileCallback callback, void* callbackData)
: ParseTask(ParseTaskKind::MultiStencilsDecode, cx, callback, callbackData),
sources(&sources) {}
void MultiStencilsDecodeTask::parse(FrontendContext* fc) {
if (!stencils.reserve(sources->length())) {
ReportOutOfMemory(fc); // This sets |outOfMemory|.
return;
}
for (auto& source : *sources) {
frontend::CompilationInput stencilInput(options);
if (!stencilInput.initForGlobal(fc)) {
break;
}
RefPtr<frontend::CompilationStencil> stencil =
fc->getAllocator()->new_<frontend::CompilationStencil>(
stencilInput.source);
if (!stencil) {
break;
}
bool succeeded = false;
(void)stencil->deserializeStencils(fc, options, source.range, &succeeded);
if (!succeeded) {
// If any decodes fail, don't process the rest. We likely are hitting OOM.
break;
}
stencils.infallibleEmplaceBack(stencil.forget());
}
}
void js::StartOffThreadDelazification(
JSContext* cx, const ReadOnlyCompileOptions& options,
const frontend::CompilationStencil& stencil) {
// Skip delazify tasks if we parse everything on-demand or ahead.
auto strategy = options.eagerDelazificationStrategy();
if (strategy == JS::DelazificationOption::OnDemandOnly ||
strategy == JS::DelazificationOption::ParseEverythingEagerly) {
return;
}
// Skip delazify task if code coverage is enabled.
if (cx->realm()->collectCoverageForDebug()) {
return;
}
if (!CanUseExtraThreads()) {
return;
}
AutoAssertNoPendingException aanpe(cx);
JSRuntime* runtime = cx->runtime();
UniquePtr<DelazifyTask> task;
task = DelazifyTask::Create(runtime, cx->options(), options, stencil);
if (!task) {
return;
}
// Schedule delazification task if there is any function to delazify.
if (!task->strategy->done()) {
AutoLockHelperThreadState lock;
HelperThreadState().submitTask(task.release(), lock);
}
}
bool DelazifyStrategy::add(FrontendContext* fc,
const frontend::CompilationStencil& stencil,
ScriptIndex index) {
using namespace js::frontend;
ScriptStencilRef scriptRef{stencil, index};
// Only functions with bytecode are allowed to be added.
MOZ_ASSERT(!scriptRef.scriptData().isGhost());
MOZ_ASSERT(scriptRef.scriptData().hasSharedData());
// Lookup the gc-things range which are referenced by this script.
size_t offset = scriptRef.scriptData().gcThingsOffset.index;
size_t length = scriptRef.scriptData().gcThingsLength;
auto gcThingData = stencil.gcThingData.Subspan(offset, length);
// Iterate over gc-things of the script and queue inner functions.
for (TaggedScriptThingIndex index : mozilla::Reversed(gcThingData)) {
if (!index.isFunction()) {
continue;
}
ScriptIndex innerScriptIndex = index.toFunction();
ScriptStencilRef innerScriptRef{stencil, innerScriptIndex};
if (innerScriptRef.scriptData().isGhost() ||
!innerScriptRef.scriptData().functionFlags.isInterpreted()) {
continue;
}
if (innerScriptRef.scriptData().hasSharedData()) {
// The top-level parse decided to eagerly parse this function, thus we
// should visit its inner function the same way.
if (!add(fc, stencil, innerScriptIndex)) {
return false;
}
continue;
}
// Maybe insert the new script index in the queue of functions to delazify.
if (!insert(innerScriptIndex, innerScriptRef)) {
ReportOutOfMemory(fc);
return false;
}
}
return true;
}
DelazifyStrategy::ScriptIndex LargeFirstDelazification::next() {
std::swap(heap.back(), heap[0]);
ScriptIndex result = heap.popCopy().second;
// NOTE: These are a heap indexes offseted by 1, such that we can manipulate
// the tree of heap-sorted values which bubble up the largest values towards
// the root of the tree.
size_t len = heap.length();
size_t i = 1;
while (true) {
// NOTE: We write (n + 1) - 1, instead of n, to explicit that the
// manipualted indexes are all offseted by 1.
size_t n = 2 * i;
size_t largest;
if (n + 1 <= len && heap[(n + 1) - 1].first > heap[n - 1].first) {
largest = n + 1;
} else if (n <= len) {
// The condition is n <= len in case n + 1 is out of the heap vector, but
// not n, in which case we still want to check if the last element of the
// heap vector should be swapped. Otherwise heap[n - 1] represents a
// larger function than heap[(n + 1) - 1].
largest = n;
} else {
// n is out-side the heap vector, thus our element is already in a leaf
// position and would not be moved any more.
break;
}
if (heap[i - 1].first < heap[largest - 1].first) {
// We found a function which has a larger body as a child of the current
// element. we swap it with the current element, such that the largest
// element is closer to the root of the tree.
std::swap(heap[i - 1], heap[largest - 1]);
i = largest;
} else {
// The largest function found as a child of the current node is smaller
// than the current node's function size. The heap tree is now organized
// as expected.
break;
}
}
return result;
}
bool LargeFirstDelazification::insert(ScriptIndex index,
frontend::ScriptStencilRef& ref) {
const frontend::ScriptStencilExtra& extra = ref.scriptExtra();
SourceSize size = extra.extent.sourceEnd - extra.extent.sourceStart;
if (!heap.append(std::pair(size, index))) {
return false;
}
// NOTE: These are a heap indexes offseted by 1, such that we can manipulate
// the tree of heap-sorted values which bubble up the largest values towards
// the root of the tree.
size_t i = heap.length();
while (i > 1) {
if (heap[i - 1].first <= heap[(i / 2) - 1].first) {
return true;
}
std::swap(heap[i - 1], heap[(i / 2) - 1]);
i /= 2;
}
return true;
}
UniquePtr<DelazifyTask> DelazifyTask::Create(
JSRuntime* runtime, const JS::ContextOptions& contextOptions,
const JS::ReadOnlyCompileOptions& options,
const frontend::CompilationStencil& stencil) {
UniquePtr<DelazifyTask> task;
task.reset(js_new<DelazifyTask>(runtime, contextOptions));
if (!task) {
return nullptr;
}
AutoSetContextFrontendErrors recordErrors(&task->fc_);
RefPtr<ScriptSource> source(stencil.source);
StencilCache& cache = runtime->caches().delazificationCache;
if (!cache.startCaching(std::move(source))) {
return nullptr;
}
// Clone the extensible stencil to be used for eager delazification.
auto initial = task->fc_.getAllocator()
->make_unique<frontend::ExtensibleCompilationStencil>(
options, stencil.source);
if (!initial || !initial->cloneFrom(&task->fc_, stencil)) {
// In case of errors, skip this and delazify on-demand.
return nullptr;
}
if (!task->init(options, std::move(initial))) {
// In case of errors, skip this and delazify on-demand.
return nullptr;
}