[JSC] Introduce LinkTimeConstant mechanism
[WebKit-https.git] / Source / JavaScriptCore / runtime / JSGlobalObject.cpp
1 /*
2  * Copyright (C) 2007-2019 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich (cwzwarich@uwaterloo.ca)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "JSGlobalObject.h"
32
33 #include "ArrayConstructor.h"
34 #include "ArrayIteratorPrototype.h"
35 #include "ArrayPrototype.h"
36 #include "AsyncFromSyncIteratorPrototype.h"
37 #include "AtomicsObject.h"
38 #include "AsyncFunctionConstructor.h"
39 #include "AsyncFunctionPrototype.h"
40 #include "AsyncGeneratorFunctionConstructor.h"
41 #include "AsyncGeneratorFunctionPrototype.h"
42 #include "AsyncGeneratorPrototype.h"
43 #include "AsyncIteratorPrototype.h"
44 #include "BigIntConstructor.h"
45 #include "BigIntObject.h"
46 #include "BigIntPrototype.h"
47 #include "BooleanConstructor.h"
48 #include "BooleanPrototype.h"
49 #include "BuiltinNames.h"
50 #include "CatchScope.h"
51 #include "ClonedArguments.h"
52 #include "CodeBlock.h"
53 #include "CodeBlockSetInlines.h"
54 #include "CodeCache.h"
55 #include "ConsoleObject.h"
56 #include "DateConstructor.h"
57 #include "DatePrototype.h"
58 #include "Debugger.h"
59 #include "DebuggerScope.h"
60 #include "DirectArguments.h"
61 #include "DirectEvalExecutable.h"
62 #include "ECMAScriptSpecInternalFunctions.h"
63 #include "Error.h"
64 #include "ErrorConstructor.h"
65 #include "ErrorPrototype.h"
66 #include "Exception.h"
67 #include "FunctionConstructor.h"
68 #include "FunctionPrototype.h"
69 #include "GeneratorFunctionConstructor.h"
70 #include "GeneratorFunctionPrototype.h"
71 #include "GeneratorPrototype.h"
72 #include "GetterSetter.h"
73 #include "HeapIterationScope.h"
74 #include "IndirectEvalExecutable.h"
75 #include "InspectorInstrumentationObject.h"
76 #include "Interpreter.h"
77 #include "IteratorPrototype.h"
78 #include "JSAPIWrapperObject.h"
79 #include "JSArrayBuffer.h"
80 #include "JSArrayBufferConstructor.h"
81 #include "JSArrayBufferPrototype.h"
82 #include "JSAsyncFunction.h"
83 #include "JSAsyncGeneratorFunction.h"
84 #include "JSBigInt.h"
85 #include "JSBoundFunction.h"
86 #include "JSCInlines.h"
87 #include "JSCallbackConstructor.h"
88 #include "JSCallbackFunction.h"
89 #include "JSCallbackObject.h"
90 #include "JSCustomGetterSetterFunction.h"
91 #include "JSDataView.h"
92 #include "JSDataViewPrototype.h"
93 #include "JSDollarVM.h"
94 #include "JSFunction.h"
95 #include "JSGeneratorFunction.h"
96 #include "JSGenericTypedArrayViewConstructorInlines.h"
97 #include "JSGenericTypedArrayViewInlines.h"
98 #include "JSGenericTypedArrayViewPrototypeInlines.h"
99 #include "JSGlobalObjectFunctions.h"
100 #include "JSInternalPromise.h"
101 #include "JSInternalPromiseConstructor.h"
102 #include "JSInternalPromisePrototype.h"
103 #include "JSLexicalEnvironment.h"
104 #include "JSLock.h"
105 #include "JSMap.h"
106 #include "JSMicrotask.h"
107 #include "JSModuleEnvironment.h"
108 #include "JSModuleLoader.h"
109 #include "JSModuleNamespaceObject.h"
110 #include "JSModuleRecord.h"
111 #include "JSNativeStdFunction.h"
112 #include "JSNonDestructibleProxy.h"
113 #include "JSONObject.h"
114 #include "JSPromise.h"
115 #include "JSPromiseConstructor.h"
116 #include "JSPromisePrototype.h"
117 #include "JSSet.h"
118 #include "JSStringIterator.h"
119 #include "JSTypedArrayConstructors.h"
120 #include "JSTypedArrayPrototypes.h"
121 #include "JSTypedArrayViewConstructor.h"
122 #include "JSTypedArrayViewPrototype.h"
123 #include "JSTypedArrays.h"
124 #include "JSWeakMap.h"
125 #include "JSWeakObjectRef.h"
126 #include "JSWeakSet.h"
127 #include "JSWebAssembly.h"
128 #include "JSWebAssemblyCompileError.h"
129 #include "JSWebAssemblyInstance.h"
130 #include "JSWebAssemblyLinkError.h"
131 #include "JSWebAssemblyMemory.h"
132 #include "JSWebAssemblyModule.h"
133 #include "JSWebAssemblyRuntimeError.h"
134 #include "JSWebAssemblyTable.h"
135 #include "JSWithScope.h"
136 #include "LazyClassStructureInlines.h"
137 #include "LazyPropertyInlines.h"
138 #include "LinkTimeConstant.h"
139 #include "Lookup.h"
140 #include "MapConstructor.h"
141 #include "MapIteratorPrototype.h"
142 #include "MapPrototype.h"
143 #include "MarkedSpaceInlines.h"
144 #include "MathObject.h"
145 #include "Microtask.h"
146 #include "NativeErrorConstructor.h"
147 #include "NativeErrorPrototype.h"
148 #include "NullGetterFunction.h"
149 #include "NullSetterFunction.h"
150 #include "NumberConstructor.h"
151 #include "NumberPrototype.h"
152 #include "ObjCCallbackFunction.h"
153 #include "ObjectConstructor.h"
154 #include "ObjectPropertyChangeAdaptiveWatchpoint.h"
155 #include "ObjectPropertyConditionSet.h"
156 #include "ObjectPrototype.h"
157 #include "ParserError.h"
158 #include "ProxyConstructor.h"
159 #include "ProxyObject.h"
160 #include "ProxyRevoke.h"
161 #include "ReflectObject.h"
162 #include "RegExpCache.h"
163 #include "RegExpConstructor.h"
164 #include "RegExpMatchesArray.h"
165 #include "RegExpObject.h"
166 #include "RegExpPrototype.h"
167 #include "RegExpStringIteratorPrototype.h"
168 #include "ScopedArguments.h"
169 #include "SetConstructor.h"
170 #include "SetIteratorPrototype.h"
171 #include "SetPrototype.h"
172 #include "StrictEvalActivation.h"
173 #include "StringConstructor.h"
174 #include "StringIteratorPrototype.h"
175 #include "StringPrototype.h"
176 #include "Symbol.h"
177 #include "SymbolConstructor.h"
178 #include "SymbolObject.h"
179 #include "SymbolPrototype.h"
180 #include "VariableWriteFireDetail.h"
181 #include "WasmCapabilities.h"
182 #include "WeakGCMapInlines.h"
183 #include "WeakMapConstructor.h"
184 #include "WeakMapPrototype.h"
185 #include "WeakObjectRefConstructor.h"
186 #include "WeakObjectRefPrototype.h"
187 #include "WeakSetConstructor.h"
188 #include "WeakSetPrototype.h"
189 #include "WebAssemblyCompileErrorConstructor.h"
190 #include "WebAssemblyCompileErrorPrototype.h"
191 #include "WebAssemblyFunction.h"
192 #include "WebAssemblyInstanceConstructor.h"
193 #include "WebAssemblyInstancePrototype.h"
194 #include "WebAssemblyLinkErrorConstructor.h"
195 #include "WebAssemblyLinkErrorPrototype.h"
196 #include "WebAssemblyMemoryConstructor.h"
197 #include "WebAssemblyMemoryPrototype.h"
198 #include "WebAssemblyModuleConstructor.h"
199 #include "WebAssemblyModulePrototype.h"
200 #include "WebAssemblyModuleRecord.h"
201 #include "WebAssemblyRuntimeErrorConstructor.h"
202 #include "WebAssemblyRuntimeErrorPrototype.h"
203 #include "WebAssemblyTableConstructor.h"
204 #include "WebAssemblyTablePrototype.h"
205 #include "WebAssemblyToJSCallee.h"
206 #include <wtf/RandomNumber.h>
207
208 #if ENABLE(INTL)
209 #include "IntlCollator.h"
210 #include "IntlCollatorPrototype.h"
211 #include "IntlDateTimeFormat.h"
212 #include "IntlDateTimeFormatPrototype.h"
213 #include "IntlNumberFormat.h"
214 #include "IntlNumberFormatPrototype.h"
215 #include "IntlObject.h"
216 #include "IntlPluralRules.h"
217 #include "IntlPluralRulesPrototype.h"
218 #include <unicode/ucol.h>
219 #include <unicode/udat.h>
220 #include <unicode/unum.h>
221 #endif // ENABLE(INTL)
222
223 #if ENABLE(REMOTE_INSPECTOR)
224 #include "JSGlobalObjectDebuggable.h"
225 #include "JSGlobalObjectInspectorController.h"
226 #endif
227
228 #ifdef JSC_GLIB_API_ENABLED
229 #include "JSCCallbackFunction.h"
230 #include "JSCWrapperMap.h"
231 #endif
232
233 namespace JSC {
234
235 #define CHECK_FEATURE_FLAG_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
236 static_assert(std::is_same_v<std::remove_cv_t<decltype(featureFlag)>, bool> || std::is_same_v<std::remove_cv_t<decltype(featureFlag)>, bool&>);
237
238 FOR_EACH_SIMPLE_BUILTIN_TYPE(CHECK_FEATURE_FLAG_TYPE)
239 FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(CHECK_FEATURE_FLAG_TYPE)
240 FOR_EACH_LAZY_BUILTIN_TYPE(CHECK_FEATURE_FLAG_TYPE)
241
242 static JSValue createProxyProperty(VM& vm, JSObject* object)
243 {
244     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
245     return ProxyConstructor::create(vm, ProxyConstructor::createStructure(vm, global, global->functionPrototype()));
246 }
247
248 static JSValue createJSONProperty(VM& vm, JSObject* object)
249 {
250     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
251     return JSONObject::create(vm, JSONObject::createStructure(vm, global, global->objectPrototype()));
252 }
253
254 static JSValue createMathProperty(VM& vm, JSObject* object)
255 {
256     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
257     return MathObject::create(vm, global, MathObject::createStructure(vm, global, global->objectPrototype()));
258 }
259
260 static JSValue createReflectProperty(VM& vm, JSObject* object)
261 {
262     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
263     return ReflectObject::create(vm, global, ReflectObject::createStructure(vm, global, global->objectPrototype()));
264 }
265
266 static JSValue createConsoleProperty(VM& vm, JSObject* object)
267 {
268     JSGlobalObject* global = jsCast<JSGlobalObject*>(object);
269     return ConsoleObject::create(vm, global, ConsoleObject::createStructure(vm, global, constructEmptyObject(global)));
270 }
271
272 static EncodedJSValue JSC_HOST_CALL makeBoundFunction(JSGlobalObject* globalObject, CallFrame* callFrame)
273 {
274     VM& vm = globalObject->vm();
275     auto scope = DECLARE_THROW_SCOPE(vm);
276
277     JSObject* target = asObject(callFrame->uncheckedArgument(0));
278     JSValue boundThis = callFrame->uncheckedArgument(1);
279     JSValue boundArgs = callFrame->uncheckedArgument(2);
280     JSValue lengthValue = callFrame->uncheckedArgument(3);
281     JSString* nameString = asString(callFrame->uncheckedArgument(4));
282
283     ASSERT(lengthValue.isInt32AsAnyInt());
284     int32_t length = lengthValue.asInt32AsAnyInt();
285
286     String name = nameString->value(globalObject);
287     RETURN_IF_EXCEPTION(scope, { });
288
289     RELEASE_AND_RETURN(scope, JSValue::encode(JSBoundFunction::create(vm, globalObject, target, boundThis, boundArgs.isCell() ? jsCast<JSArray*>(boundArgs) : nullptr, length, WTFMove(name))));
290 }
291
292 static EncodedJSValue JSC_HOST_CALL hasOwnLengthProperty(JSGlobalObject* globalObject, CallFrame* callFrame)
293 {
294     VM& vm = globalObject->vm();
295     JSObject* target = asObject(callFrame->uncheckedArgument(0));
296     return JSValue::encode(jsBoolean(target->hasOwnProperty(globalObject, vm.propertyNames->length)));
297 }
298
299 #if !ASSERT_DISABLED
300 static EncodedJSValue JSC_HOST_CALL assertCall(JSGlobalObject* globalObject, CallFrame* callFrame)
301 {
302     RELEASE_ASSERT(callFrame->argument(0).isBoolean());
303     if (callFrame->argument(0).asBoolean())
304         return JSValue::encode(jsUndefined());
305
306     bool iteratedOnce = false;
307     CodeBlock* codeBlock = nullptr;
308     unsigned line;
309     callFrame->iterate(globalObject->vm(), [&] (StackVisitor& visitor) {
310         if (!iteratedOnce) {
311             iteratedOnce = true;
312             return StackVisitor::Continue;
313         }
314
315         RELEASE_ASSERT(visitor->hasLineAndColumnInfo());
316         unsigned column;
317         visitor->computeLineAndColumn(line, column);
318         codeBlock = visitor->codeBlock();
319         return StackVisitor::Done;
320     });
321     RELEASE_ASSERT(!!codeBlock);
322     RELEASE_ASSERT_WITH_MESSAGE(false, "JS assertion failed at line %u in:\n%s\n", line, codeBlock->sourceCodeForTools().data());
323     return JSValue::encode(jsUndefined());
324 }
325 #endif
326
327 } // namespace JSC
328
329 #include "JSGlobalObject.lut.h"
330
331 namespace JSC {
332
333 const ClassInfo JSGlobalObject::s_info = { "GlobalObject", &Base::s_info, &globalObjectTable, nullptr, CREATE_METHOD_TABLE(JSGlobalObject) };
334
335 const GlobalObjectMethodTable JSGlobalObject::s_globalObjectMethodTable = {
336     &supportsRichSourceInfo,
337     &shouldInterruptScript,
338     &javaScriptRuntimeFlags,
339     nullptr, // queueTaskToEventLoop
340     &shouldInterruptScriptBeforeTimeout,
341     nullptr, // moduleLoaderImportModule
342     nullptr, // moduleLoaderResolve
343     nullptr, // moduleLoaderFetch
344     nullptr, // moduleLoaderCreateImportMetaProperties
345     nullptr, // moduleLoaderEvaluate
346     nullptr, // promiseRejectionTracker
347     nullptr, // defaultLanguage
348     nullptr, // compileStreaming
349     nullptr, // instantiateStreaming
350 };
351
352 /* Source for JSGlobalObject.lut.h
353 @begin globalObjectTable
354   isNaN                 JSBuiltin                                    DontEnum|Function 1
355   isFinite              JSBuiltin                                    DontEnum|Function 1
356   escape                globalFuncEscape                             DontEnum|Function 1
357   unescape              globalFuncUnescape                           DontEnum|Function 1
358   decodeURI             globalFuncDecodeURI                          DontEnum|Function 1
359   decodeURIComponent    globalFuncDecodeURIComponent                 DontEnum|Function 1
360   encodeURI             globalFuncEncodeURI                          DontEnum|Function 1
361   encodeURIComponent    globalFuncEncodeURIComponent                 DontEnum|Function 1
362   eval                  JSGlobalObject::m_evalFunction               DontEnum|CellProperty
363   globalThis            JSGlobalObject::m_globalThis                 DontEnum|CellProperty
364   parseInt              JSGlobalObject::m_parseIntFunction           DontEnum|CellProperty
365   parseFloat            JSGlobalObject::m_parseFloatFunction         DontEnum|CellProperty
366   ArrayBuffer           JSGlobalObject::m_arrayBufferStructure       DontEnum|ClassStructure
367   EvalError             JSGlobalObject::m_evalErrorStructure         DontEnum|ClassStructure
368   RangeError            JSGlobalObject::m_rangeErrorStructure        DontEnum|ClassStructure
369   ReferenceError        JSGlobalObject::m_referenceErrorStructure    DontEnum|ClassStructure
370   SyntaxError           JSGlobalObject::m_syntaxErrorStructure       DontEnum|ClassStructure
371   TypeError             JSGlobalObject::m_typeErrorStructure         DontEnum|ClassStructure
372   URIError              JSGlobalObject::m_URIErrorStructure          DontEnum|ClassStructure
373   Proxy                 createProxyProperty                          DontEnum|PropertyCallback
374   Reflect               createReflectProperty                        DontEnum|PropertyCallback
375   JSON                  createJSONProperty                           DontEnum|PropertyCallback
376   Math                  createMathProperty                           DontEnum|PropertyCallback
377   console               createConsoleProperty                        DontEnum|PropertyCallback
378   Int8Array             JSGlobalObject::m_typedArrayInt8             DontEnum|ClassStructure
379   Int16Array            JSGlobalObject::m_typedArrayInt16            DontEnum|ClassStructure
380   Int32Array            JSGlobalObject::m_typedArrayInt32            DontEnum|ClassStructure
381   Uint8Array            JSGlobalObject::m_typedArrayUint8            DontEnum|ClassStructure
382   Uint8ClampedArray     JSGlobalObject::m_typedArrayUint8Clamped     DontEnum|ClassStructure
383   Uint16Array           JSGlobalObject::m_typedArrayUint16           DontEnum|ClassStructure
384   Uint32Array           JSGlobalObject::m_typedArrayUint32           DontEnum|ClassStructure
385   Float32Array          JSGlobalObject::m_typedArrayFloat32          DontEnum|ClassStructure
386   Float64Array          JSGlobalObject::m_typedArrayFloat64          DontEnum|ClassStructure
387   DataView              JSGlobalObject::m_typedArrayDataView         DontEnum|ClassStructure
388   Date                  JSGlobalObject::m_dateStructure              DontEnum|ClassStructure
389   Error                 JSGlobalObject::m_errorStructure             DontEnum|ClassStructure
390   Boolean               JSGlobalObject::m_booleanObjectStructure     DontEnum|ClassStructure
391   Number                JSGlobalObject::m_numberObjectStructure      DontEnum|ClassStructure
392   Symbol                JSGlobalObject::m_symbolObjectStructure      DontEnum|ClassStructure
393   WeakMap               JSGlobalObject::m_weakMapStructure           DontEnum|ClassStructure
394   WeakSet               JSGlobalObject::m_weakSetStructure           DontEnum|ClassStructure
395 @end
396 */
397
398 static EncodedJSValue JSC_HOST_CALL enqueueJob(JSGlobalObject* globalObject, CallFrame* callFrame)
399 {
400     VM& vm = globalObject->vm();
401
402     JSValue job = callFrame->argument(0);
403     JSValue argument0 = callFrame->argument(1);
404     JSValue argument1 = callFrame->argument(2);
405     JSValue argument2 = callFrame->argument(3);
406
407     globalObject->queueMicrotask(createJSMicrotask(vm, job, argument0, argument1, argument2));
408
409     return JSValue::encode(jsUndefined());
410 }
411
412 JSGlobalObject::JSGlobalObject(VM& vm, Structure* structure, const GlobalObjectMethodTable* globalObjectMethodTable)
413     : Base(vm, structure, 0)
414     , m_vm(&vm)
415     , m_linkTimeConstants(numberOfLinkTimeConstants)
416     , m_masqueradesAsUndefinedWatchpoint(adoptRef(new WatchpointSet(IsWatched)))
417     , m_havingABadTimeWatchpoint(adoptRef(new WatchpointSet(IsWatched)))
418     , m_varInjectionWatchpoint(adoptRef(new WatchpointSet(IsWatched)))
419     , m_weakRandom(Options::forceWeakRandomSeed() ? Options::forcedWeakRandomSeed() : static_cast<unsigned>(randomNumber() * (std::numeric_limits<unsigned>::max() + 1.0)))
420     , m_arrayIteratorProtocolWatchpointSet(IsWatched)
421     , m_mapIteratorProtocolWatchpointSet(IsWatched)
422     , m_setIteratorProtocolWatchpointSet(IsWatched)
423     , m_stringIteratorProtocolWatchpointSet(IsWatched)
424     , m_mapSetWatchpointSet(IsWatched)
425     , m_setAddWatchpointSet(IsWatched)
426     , m_arraySpeciesWatchpointSet(ClearWatchpoint)
427     , m_arrayJoinWatchpointSet(IsWatched)
428     , m_numberToStringWatchpointSet(IsWatched)
429     , m_runtimeFlags()
430     , m_stackTraceLimit(Options::defaultErrorStackTraceLimit())
431     , m_globalObjectMethodTable(globalObjectMethodTable ? globalObjectMethodTable : &s_globalObjectMethodTable)
432 {
433 }
434
435 JSGlobalObject::~JSGlobalObject()
436 {
437 #if ENABLE(REMOTE_INSPECTOR)
438     m_inspectorController->globalObjectDestroyed();
439 #endif
440
441     if (m_debugger)
442         m_debugger->detach(this, Debugger::GlobalObjectIsDestructing);
443 }
444
445 void JSGlobalObject::destroy(JSCell* cell)
446 {
447     static_cast<JSGlobalObject*>(cell)->JSGlobalObject::~JSGlobalObject();
448 }
449
450 void JSGlobalObject::setGlobalThis(VM& vm, JSObject* globalThis)
451 {
452     m_globalThis.set(vm, this, globalThis);
453 }
454
455 static GetterSetter* getGetterById(JSGlobalObject* globalObject, JSObject* base, const Identifier& ident)
456 {
457     JSValue baseValue = JSValue(base);
458     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::VMInquiry);
459     baseValue.getPropertySlot(globalObject, ident, slot);
460     return jsCast<GetterSetter*>(slot.getPureResult());
461 }
462
463 template<ErrorType errorType>
464 void JSGlobalObject::initializeErrorConstructor(LazyClassStructure::Initializer& init)
465 {
466     init.setPrototype(NativeErrorPrototype::create(init.vm, NativeErrorPrototype::createStructure(init.vm, this, m_errorStructure.prototype(this)), errorTypeName(errorType)));
467     init.setStructure(ErrorInstance::createStructure(init.vm, this, init.prototype));
468     init.setConstructor(NativeErrorConstructor<errorType>::create(init.vm, NativeErrorConstructor<errorType>::createStructure(init.vm, this, m_errorStructure.constructor(this)), jsCast<NativeErrorPrototype*>(init.prototype)));
469 }
470
471 void JSGlobalObject::init(VM& vm)
472 {
473     ASSERT(vm.currentThreadIsHoldingAPILock());
474     auto catchScope = DECLARE_CATCH_SCOPE(vm);
475
476     Base::setStructure(vm, Structure::toCacheableDictionaryTransition(vm, structure(vm)));
477
478     m_debugger = 0;
479
480 #if ENABLE(REMOTE_INSPECTOR)
481     m_inspectorController = makeUnique<Inspector::JSGlobalObjectInspectorController>(*this);
482     m_inspectorDebuggable = makeUnique<JSGlobalObjectDebuggable>(*this);
483     m_inspectorDebuggable->init();
484     m_consoleClient = m_inspectorController->consoleClient();
485 #endif
486
487     m_functionPrototype.set(vm, this, FunctionPrototype::create(vm, FunctionPrototype::createStructure(vm, this, jsNull()))); // The real prototype will be set once ObjectPrototype is created.
488     m_calleeStructure.set(vm, this, JSCallee::createStructure(vm, this, jsNull()));
489
490     m_globalLexicalEnvironment.set(vm, this, JSGlobalLexicalEnvironment::create(vm, JSGlobalLexicalEnvironment::createStructure(vm, this), this));
491
492     // Need to create the callee structure (above) before creating the callee.
493     JSCallee* globalCallee = JSCallee::create(vm, this, globalScope());
494     m_globalCallee.set(vm, this, globalCallee);
495
496     CallFrame::initDeprecatedCallFrameForDebugger(JSGlobalObject::deprecatedCallFrameForDebugger(), globalCallee);
497
498     JSCallee* stackOverflowFrameCallee = JSCallee::create(vm, this, globalScope());
499     m_stackOverflowFrameCallee.set(vm, this, stackOverflowFrameCallee);
500
501     m_hostFunctionStructure.set(vm, this, JSFunction::createStructure(vm, this, m_functionPrototype.get()));
502
503     auto initFunctionStructures = [&] (FunctionStructures& structures) {
504         structures.strictFunctionStructure.set(vm, this, JSStrictFunction::createStructure(vm, this, m_functionPrototype.get()));
505         structures.sloppyFunctionStructure.set(vm, this, JSSloppyFunction::createStructure(vm, this, m_functionPrototype.get()));
506         structures.arrowFunctionStructure.set(vm, this, JSArrowFunction::createStructure(vm, this, m_functionPrototype.get()));
507     };
508     initFunctionStructures(m_builtinFunctions);
509     initFunctionStructures(m_ordinaryFunctions);
510
511     m_customGetterSetterFunctionStructure.initLater(
512         [] (const Initializer<Structure>& init) {
513             init.set(JSCustomGetterSetterFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
514         });
515     m_boundFunctionStructure.initLater(
516         [] (const Initializer<Structure>& init) {
517             init.set(JSBoundFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
518         });
519     m_nativeStdFunctionStructure.initLater(
520         [] (const Initializer<Structure>& init) {
521             init.set(JSNativeStdFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
522         });
523     JSFunction* callFunction = nullptr;
524     JSFunction* applyFunction = nullptr;
525     JSFunction* hasInstanceSymbolFunction = nullptr;
526     m_functionPrototype->addFunctionProperties(vm, this, &callFunction, &applyFunction, &hasInstanceSymbolFunction);
527     m_arrayProtoToStringFunction.initLater(
528         [] (const Initializer<JSFunction>& init) {
529             init.set(JSFunction::create(init.vm, init.owner, 0, init.vm.propertyNames->toString.string(), arrayProtoFuncToString, NoIntrinsic));
530         });
531     m_arrayProtoValuesFunction.initLater(
532         [] (const Initializer<JSFunction>& init) {
533             init.set(JSFunction::create(init.vm, arrayPrototypeValuesCodeGenerator(init.vm), init.owner));
534         });
535
536     m_iteratorProtocolFunction.initLater(
537         [] (const Initializer<JSFunction>& init) {
538             init.set(JSFunction::create(init.vm, iteratorHelpersPerformIterationCodeGenerator(init.vm), init.owner));
539         });
540
541     m_promiseResolveFunction.initLater(
542         [] (const Initializer<JSFunction>& init) {
543             init.set(JSFunction::create(init.vm, promiseConstructorResolveCodeGenerator(init.vm), init.owner));
544         });
545
546     m_functionProtoHasInstanceSymbolFunction.set(vm, this, hasInstanceSymbolFunction);
547     m_throwTypeErrorGetterSetter.initLater(
548         [] (const Initializer<GetterSetter>& init) {
549             JSFunction* thrower = init.owner->throwTypeErrorFunction();
550             GetterSetter* getterSetter = GetterSetter::create(init.vm, init.owner, thrower, thrower);
551             init.set(getterSetter);
552         });
553
554     m_nullGetterFunction.set(vm, this, NullGetterFunction::create(vm, NullGetterFunction::createStructure(vm, this, m_functionPrototype.get())));
555     m_nullSetterFunction.set(vm, this, NullSetterFunction::create(vm, NullSetterFunction::createStructure(vm, this, m_functionPrototype.get())));
556     m_objectPrototype.set(vm, this, ObjectPrototype::create(vm, this, ObjectPrototype::createStructure(vm, this, jsNull())));
557     // We have to manually set this here because we make it a prototype without transition below.
558     m_objectPrototype.get()->didBecomePrototype();
559     GetterSetter* protoAccessor = GetterSetter::create(vm, this,
560         JSFunction::create(vm, this, 0, makeString("get ", vm.propertyNames->underscoreProto.string()), globalFuncProtoGetter, UnderscoreProtoIntrinsic),
561         JSFunction::create(vm, this, 0, makeString("set ", vm.propertyNames->underscoreProto.string()), globalFuncProtoSetter));
562     m_objectPrototype->putDirectNonIndexAccessorWithoutTransition(vm, vm.propertyNames->underscoreProto, protoAccessor, PropertyAttribute::Accessor | PropertyAttribute::DontEnum);
563     m_functionPrototype->structure(vm)->setPrototypeWithoutTransition(vm, m_objectPrototype.get());
564     m_objectStructureForObjectConstructor.set(vm, this, vm.structureCache.emptyObjectStructureForPrototype(this, m_objectPrototype.get(), JSFinalObject::defaultInlineCapacity()));
565     m_objectProtoValueOfFunction.set(vm, this, jsCast<JSFunction*>(objectPrototype()->getDirect(vm, vm.propertyNames->valueOf)));
566     
567     JSFunction* thrower = JSFunction::create(vm, this, 0, String(), globalFuncThrowTypeErrorArgumentsCalleeAndCaller);
568     GetterSetter* getterSetter = GetterSetter::create(vm, this, thrower, thrower);
569     m_throwTypeErrorArgumentsCalleeAndCallerGetterSetter.set(vm, this, getterSetter);
570     
571     m_functionPrototype->initRestrictedProperties(vm, this);
572
573     m_speciesGetterSetter.set(vm, this, GetterSetter::create(vm, this, JSFunction::create(vm, globalOperationsSpeciesGetterCodeGenerator(vm), this), nullptr));
574
575     m_typedArrayProto.initLater(
576         [] (const Initializer<JSTypedArrayViewPrototype>& init) {
577             init.set(JSTypedArrayViewPrototype::create(init.vm, init.owner, JSTypedArrayViewPrototype::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get())));
578             
579             // Make sure that the constructor gets initialized, too.
580             init.owner->m_typedArraySuperConstructor.get(init.owner);
581         });
582     m_typedArraySuperConstructor.initLater(
583         [] (const Initializer<JSTypedArrayViewConstructor>& init) {
584             JSTypedArrayViewPrototype* prototype = init.owner->m_typedArrayProto.get(init.owner);
585             JSTypedArrayViewConstructor* constructor = JSTypedArrayViewConstructor::create(init.vm, init.owner, JSTypedArrayViewConstructor::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()), prototype, init.owner->m_speciesGetterSetter.get());
586             prototype->putDirectWithoutTransition(init.vm, init.vm.propertyNames->constructor, constructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
587             init.set(constructor);
588         });
589     
590 #define INIT_TYPED_ARRAY_LATER(type) \
591     m_typedArray ## type.initLater( \
592         [] (LazyClassStructure::Initializer& init) { \
593             init.setPrototype(JS ## type ## ArrayPrototype::create(init.vm, init.global, JS ## type ## ArrayPrototype::createStructure(init.vm, init.global, init.global->m_typedArrayProto.get(init.global)))); \
594             init.setStructure(JS ## type ## Array::createStructure(init.vm, init.global, init.prototype)); \
595             init.setConstructor(JS ## type ## ArrayConstructor::create(init.vm, init.global, JS ## type ## ArrayConstructor::createStructure(init.vm, init.global, init.global->m_typedArraySuperConstructor.get(init.global)), init.prototype, #type "Array"_s, typedArrayConstructorAllocate ## type ## ArrayCodeGenerator(init.vm))); \
596             init.global->putDirect(init.vm, init.vm.propertyNames->builtinNames().type ## ArrayPrivateName(), init.constructor, static_cast<unsigned>(PropertyAttribute::DontEnum)); \
597         });
598     FOR_EACH_TYPED_ARRAY_TYPE_EXCLUDING_DATA_VIEW(INIT_TYPED_ARRAY_LATER)
599 #undef INIT_TYPED_ARRAY_LATER
600     
601     m_typedArrayDataView.initLater(
602         [] (LazyClassStructure::Initializer& init) {
603             init.setPrototype(JSDataViewPrototype::create(init.vm, JSDataViewPrototype::createStructure(init.vm, init.global, init.global->m_objectPrototype.get())));
604             init.setStructure(JSDataView::createStructure(init.vm, init.global, init.prototype));
605             init.setConstructor(JSDataViewConstructor::create(init.vm, init.global, JSDataViewConstructor::createStructure(init.vm, init.global, init.global->m_functionPrototype.get()), init.prototype, "DataView"_s, nullptr));
606         });
607     
608     m_lexicalEnvironmentStructure.set(vm, this, JSLexicalEnvironment::createStructure(vm, this));
609     m_moduleEnvironmentStructure.initLater(
610         [] (const Initializer<Structure>& init) {
611             init.set(JSModuleEnvironment::createStructure(init.vm, init.owner));
612         });
613     m_strictEvalActivationStructure.initLater(
614         [] (const Initializer<Structure>& init) {
615             init.set(StrictEvalActivation::createStructure(init.vm, init.owner, jsNull()));
616         });
617     m_debuggerScopeStructure.initLater(
618         [] (const Initializer<Structure>& init) {
619             init.set(DebuggerScope::createStructure(init.vm, init.owner));
620         });
621     m_withScopeStructure.initLater(
622         [] (const Initializer<Structure>& init) {
623             init.set(JSWithScope::createStructure(init.vm, init.owner, jsNull()));
624         });
625     
626     m_nullPrototypeObjectStructure.set(vm, this, JSFinalObject::createStructure(vm, this, jsNull(), JSFinalObject::defaultInlineCapacity()));
627     
628     m_callbackFunctionStructure.initLater(
629         [] (const Initializer<Structure>& init) {
630             init.set(JSCallbackFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
631         });
632     m_directArgumentsStructure.set(vm, this, DirectArguments::createStructure(vm, this, m_objectPrototype.get()));
633     m_scopedArgumentsStructure.set(vm, this, ScopedArguments::createStructure(vm, this, m_objectPrototype.get()));
634     m_clonedArgumentsStructure.set(vm, this, ClonedArguments::createStructure(vm, this, m_objectPrototype.get()));
635     m_callbackConstructorStructure.initLater(
636         [] (const Initializer<Structure>& init) {
637             init.set(JSCallbackConstructor::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
638         });
639     m_callbackObjectStructure.initLater(
640         [] (const Initializer<Structure>& init) {
641             init.set(JSCallbackObject<JSDestructibleObject>::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
642         });
643
644 #if JSC_OBJC_API_ENABLED
645     m_objcCallbackFunctionStructure.initLater(
646         [] (const Initializer<Structure>& init) {
647             init.set(ObjCCallbackFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
648         });
649     m_objcWrapperObjectStructure.initLater(
650         [] (const Initializer<Structure>& init) {
651             init.set(JSCallbackObject<JSAPIWrapperObject>::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
652         });
653 #endif
654 #ifdef JSC_GLIB_API_ENABLED
655     m_glibCallbackFunctionStructure.initLater(
656         [] (const Initializer<Structure>& init) {
657             init.set(JSCCallbackFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
658         });
659     m_glibWrapperObjectStructure.initLater(
660         [] (const Initializer<Structure>& init) {
661             init.set(JSCallbackObject<JSAPIWrapperObject>::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
662         });
663 #endif
664     m_arrayPrototype.set(vm, this, ArrayPrototype::create(vm, this, ArrayPrototype::createStructure(vm, this, m_objectPrototype.get())));
665     
666     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(UndecidedShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithUndecided));
667     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(Int32Shape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithInt32));
668     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(DoubleShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithDouble));
669     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(ContiguousShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithContiguous));
670     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(ArrayStorageShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithArrayStorage));
671     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(SlowPutArrayStorageShape)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), ArrayWithSlowPutArrayStorage));
672     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(CopyOnWriteArrayWithInt32)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), CopyOnWriteArrayWithInt32));
673     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(CopyOnWriteArrayWithDouble)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), CopyOnWriteArrayWithDouble));
674     m_originalArrayStructureForIndexingShape[arrayIndexFromIndexingType(CopyOnWriteArrayWithContiguous)].set(vm, this, JSArray::createStructure(vm, this, m_arrayPrototype.get(), CopyOnWriteArrayWithContiguous));
675     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
676         m_arrayStructureForIndexingShapeDuringAllocation[i] = m_originalArrayStructureForIndexingShape[i];
677
678     m_regExpPrototype.set(vm, this, RegExpPrototype::create(vm, this, RegExpPrototype::createStructure(vm, this, m_objectPrototype.get())));
679     m_regExpStructure.set(vm, this, RegExpObject::createStructure(vm, this, m_regExpPrototype.get()));
680     m_regExpMatchesArrayStructure.set(vm, this, createRegExpMatchesArrayStructure(vm, this));
681     m_regExpMatchesArrayWithGroupsStructure.set(vm, this, createRegExpMatchesArrayWithGroupsStructure(vm, this));
682
683     m_moduleRecordStructure.initLater(
684         [] (const Initializer<Structure>& init) {
685             init.set(JSModuleRecord::createStructure(init.vm, init.owner, jsNull()));
686         });
687     m_moduleNamespaceObjectStructure.initLater(
688         [] (const Initializer<Structure>& init) {
689             init.set(JSModuleNamespaceObject::createStructure(init.vm, init.owner, jsNull()));
690         });
691     m_proxyObjectStructure.initLater(
692         [] (const Initializer<Structure>& init) {
693             bool isCallable = false;
694             init.set(ProxyObject::createStructure(init.vm, init.owner, jsNull(), isCallable));
695         });
696     m_callableProxyObjectStructure.initLater(
697         [] (const Initializer<Structure>& init) {
698             bool isCallable = true;
699             init.set(ProxyObject::createStructure(init.vm, init.owner, jsNull(), isCallable));
700         });
701     m_proxyRevokeStructure.initLater(
702         [] (const Initializer<Structure>& init) {
703             init.set(ProxyRevoke::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
704         });
705
706     m_parseIntFunction.initLater(
707         [] (const Initializer<JSFunction>& init) {
708             init.set(JSFunction::create(init.vm, init.owner, 2, init.vm.propertyNames->parseInt.string(), globalFuncParseInt, ParseIntIntrinsic));
709         });
710     m_parseFloatFunction.initLater(
711         [] (const Initializer<JSFunction>& init) {
712             init.set(JSFunction::create(init.vm, init.owner, 1, init.vm.propertyNames->parseFloat.string(), globalFuncParseFloat, NoIntrinsic));
713         });
714     
715 #if ENABLE(SHARED_ARRAY_BUFFER)
716     m_sharedArrayBufferPrototype.set(vm, this, JSArrayBufferPrototype::create(vm, this, JSArrayBufferPrototype::createStructure(vm, this, m_objectPrototype.get()), ArrayBufferSharingMode::Shared));
717     m_sharedArrayBufferStructure.set(vm, this, JSArrayBuffer::createStructure(vm, this, m_sharedArrayBufferPrototype.get()));
718 #endif
719
720     m_iteratorPrototype.set(vm, this, IteratorPrototype::create(vm, this, IteratorPrototype::createStructure(vm, this, m_objectPrototype.get())));
721     m_asyncIteratorPrototype.set(vm, this, AsyncIteratorPrototype::create(vm, this, AsyncIteratorPrototype::createStructure(vm, this, m_objectPrototype.get())));
722
723     m_generatorPrototype.set(vm, this, GeneratorPrototype::create(vm, this, GeneratorPrototype::createStructure(vm, this, m_iteratorPrototype.get())));
724     m_asyncGeneratorPrototype.set(vm, this, AsyncGeneratorPrototype::create(vm, this, AsyncGeneratorPrototype::createStructure(vm, this, m_asyncIteratorPrototype.get())));
725
726     JSFunction* defaultPromiseThen = JSFunction::create(vm, promisePrototypeThenCodeGenerator(vm), this);
727     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::defaultPromiseThen)].set(vm, this, defaultPromiseThen);
728
729 #define CREATE_PROTOTYPE_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) { \
730         m_ ## lowerName ## Prototype.set(vm, this, capitalName##Prototype::create(vm, this, capitalName##Prototype::createStructure(vm, this, m_ ## prototypeBase ## Prototype.get()))); \
731         m_ ## properName ## Structure.set(vm, this, instanceType::createStructure(vm, this, m_ ## lowerName ## Prototype.get())); \
732     }
733     
734     FOR_EACH_SIMPLE_BUILTIN_TYPE(CREATE_PROTOTYPE_FOR_SIMPLE_TYPE)
735     FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(CREATE_PROTOTYPE_FOR_SIMPLE_TYPE)
736     
737 #undef CREATE_PROTOTYPE_FOR_SIMPLE_TYPE
738
739 #define CREATE_PROTOTYPE_FOR_LAZY_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) {  \
740     m_ ## properName ## Structure.initLater(\
741         [] (LazyClassStructure::Initializer& init) { \
742             init.setPrototype(capitalName##Prototype::create(init.vm, init.global, capitalName##Prototype::createStructure(init.vm, init.global, init.global->m_ ## prototypeBase ## Prototype.get()))); \
743             init.setStructure(instanceType::createStructure(init.vm, init.global, init.prototype)); \
744             init.setConstructor(capitalName ## Constructor::create(init.vm, capitalName ## Constructor::createStructure(init.vm, init.global, init.global->m_functionPrototype.get()), jsCast<capitalName ## Prototype*>(init.prototype), init.global->m_speciesGetterSetter.get())); \
745         }); \
746     }
747     
748     FOR_EACH_LAZY_BUILTIN_TYPE(CREATE_PROTOTYPE_FOR_LAZY_TYPE)
749     
750     // Constructors
751
752     ObjectConstructor* objectConstructor = ObjectConstructor::create(vm, this, ObjectConstructor::createStructure(vm, this, m_functionPrototype.get()), m_objectPrototype.get());
753     m_objectConstructor.set(vm, this, objectConstructor);
754     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Object)].set(vm, this, objectConstructor);
755
756     JSFunction* throwTypeErrorFunction = JSFunction::create(vm, this, 0, String(), globalFuncThrowTypeError);
757     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::throwTypeErrorFunction)].set(vm, this, throwTypeErrorFunction);
758
759     FunctionConstructor* functionConstructor = FunctionConstructor::create(vm, FunctionConstructor::createStructure(vm, this, m_functionPrototype.get()), m_functionPrototype.get());
760     m_functionConstructor.set(vm, this, functionConstructor);
761
762     ArrayConstructor* arrayConstructor = ArrayConstructor::create(vm, this, ArrayConstructor::createStructure(vm, this, m_functionPrototype.get()), m_arrayPrototype.get(), m_speciesGetterSetter.get());
763     m_arrayConstructor.set(vm, this, arrayConstructor);
764     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Array)].set(vm, this, arrayConstructor);
765     
766     RegExpConstructor* regExpConstructor = RegExpConstructor::create(vm, RegExpConstructor::createStructure(vm, this, m_functionPrototype.get()), m_regExpPrototype.get(), m_speciesGetterSetter.get());
767     m_regExpConstructor.set(vm, this, regExpConstructor);
768     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::RegExp)].set(vm, this, regExpConstructor);
769     m_regExpGlobalData.cachedResult().record(vm, this, nullptr, jsEmptyString(vm), MatchResult(0, 0));
770     
771 #if ENABLE(SHARED_ARRAY_BUFFER)
772     JSSharedArrayBufferConstructor* sharedArrayBufferConstructor = nullptr;
773     sharedArrayBufferConstructor = JSSharedArrayBufferConstructor::create(vm, JSSharedArrayBufferConstructor::createStructure(vm, this, m_functionPrototype.get()), m_sharedArrayBufferPrototype.get(), m_speciesGetterSetter.get());
774     m_sharedArrayBufferPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, sharedArrayBufferConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
775
776     AtomicsObject* atomicsObject = AtomicsObject::create(vm, this, AtomicsObject::createStructure(vm, this, m_objectPrototype.get()));
777 #endif
778
779 #define CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
780 capitalName ## Constructor* lowerName ## Constructor = featureFlag ? capitalName ## Constructor::create(vm, capitalName ## Constructor::createStructure(vm, this, m_functionPrototype.get()), m_ ## lowerName ## Prototype.get(), m_speciesGetterSetter.get()) : nullptr; \
781     if (featureFlag) \
782         m_ ## lowerName ## Prototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, lowerName ## Constructor, static_cast<unsigned>(PropertyAttribute::DontEnum)); \
783
784     FOR_EACH_SIMPLE_BUILTIN_TYPE(CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE)
785     
786 #undef CREATE_CONSTRUCTOR_FOR_SIMPLE_TYPE
787
788     m_promiseConstructor.set(vm, this, promiseConstructor);
789     m_internalPromiseConstructor.set(vm, this, internalPromiseConstructor);
790     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Promise)].set(vm, this, promiseConstructor);
791     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::InternalPromise)].set(vm, this, internalPromiseConstructor);
792     
793     m_evalErrorStructure.initLater(
794         [] (LazyClassStructure::Initializer& init) {
795             init.global->initializeErrorConstructor<ErrorType::EvalError>(init);
796         });
797     m_rangeErrorStructure.initLater(
798         [] (LazyClassStructure::Initializer& init) {
799             init.global->initializeErrorConstructor<ErrorType::RangeError>(init);
800         });
801     m_referenceErrorStructure.initLater(
802         [] (LazyClassStructure::Initializer& init) {
803             init.global->initializeErrorConstructor<ErrorType::ReferenceError>(init);
804         });
805     m_syntaxErrorStructure.initLater(
806         [] (LazyClassStructure::Initializer& init) {
807             init.global->initializeErrorConstructor<ErrorType::SyntaxError>(init);
808         });
809     m_typeErrorStructure.initLater(
810         [] (LazyClassStructure::Initializer& init) {
811             init.global->initializeErrorConstructor<ErrorType::TypeError>(init);
812         });
813     m_URIErrorStructure.initLater(
814         [] (LazyClassStructure::Initializer& init) {
815             init.global->initializeErrorConstructor<ErrorType::URIError>(init);
816         });
817
818     m_generatorFunctionPrototype.set(vm, this, GeneratorFunctionPrototype::create(vm, GeneratorFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
819     GeneratorFunctionConstructor* generatorFunctionConstructor = GeneratorFunctionConstructor::create(vm, GeneratorFunctionConstructor::createStructure(vm, this, functionConstructor), m_generatorFunctionPrototype.get());
820     m_generatorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, generatorFunctionConstructor, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
821     m_generatorFunctionStructure.set(vm, this, JSGeneratorFunction::createStructure(vm, this, m_generatorFunctionPrototype.get()));
822
823     m_generatorPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, m_generatorFunctionPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
824     m_generatorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->prototype, m_generatorPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
825     m_generatorStructure.set(vm, this, JSGenerator::createStructure(vm, this, m_generatorPrototype.get()));
826
827     m_asyncFunctionPrototype.set(vm, this, AsyncFunctionPrototype::create(vm, AsyncFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
828     AsyncFunctionConstructor* asyncFunctionConstructor = AsyncFunctionConstructor::create(vm, AsyncFunctionConstructor::createStructure(vm, this, functionConstructor), m_asyncFunctionPrototype.get());
829     m_asyncFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, asyncFunctionConstructor, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
830     m_asyncFunctionStructure.set(vm, this, JSAsyncFunction::createStructure(vm, this, m_asyncFunctionPrototype.get()));
831
832     m_asyncGeneratorFunctionPrototype.set(vm, this, AsyncGeneratorFunctionPrototype::create(vm, AsyncGeneratorFunctionPrototype::createStructure(vm, this, m_functionPrototype.get())));
833     AsyncGeneratorFunctionConstructor* asyncGeneratorFunctionConstructor = AsyncGeneratorFunctionConstructor::create(vm, AsyncGeneratorFunctionConstructor::createStructure(vm, this, functionConstructor), m_asyncGeneratorFunctionPrototype.get());
834     m_asyncGeneratorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, asyncGeneratorFunctionConstructor, PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
835     m_asyncGeneratorFunctionStructure.set(vm, this, JSAsyncGeneratorFunction::createStructure(vm, this, m_asyncGeneratorFunctionPrototype.get()));
836
837     m_asyncGeneratorPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, m_asyncGeneratorFunctionPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
838     m_asyncGeneratorFunctionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->prototype, m_asyncGeneratorPrototype.get(), PropertyAttribute::DontEnum | PropertyAttribute::ReadOnly);
839     m_asyncGeneratorStructure.set(vm, this, JSAsyncGenerator::createStructure(vm, this, m_asyncGeneratorPrototype.get()));
840     
841     m_objectPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, objectConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
842     m_functionPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, functionConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
843     m_arrayPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, arrayConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
844     m_regExpPrototype->putDirectWithoutTransition(vm, vm.propertyNames->constructor, regExpConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
845     
846     putDirectWithoutTransition(vm, vm.propertyNames->Object, objectConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
847     putDirectWithoutTransition(vm, vm.propertyNames->Function, functionConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
848     putDirectWithoutTransition(vm, vm.propertyNames->Array, arrayConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
849     putDirectWithoutTransition(vm, vm.propertyNames->RegExp, regExpConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
850
851 #if ENABLE(SHARED_ARRAY_BUFFER)
852     putDirectWithoutTransition(vm, vm.propertyNames->SharedArrayBuffer, sharedArrayBufferConstructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
853     putDirectWithoutTransition(vm, Identifier::fromString(vm, "Atomics"), atomicsObject, static_cast<unsigned>(PropertyAttribute::DontEnum));
854 #endif
855
856 #define PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
857     if (featureFlag) \
858         putDirectWithoutTransition(vm, vm.propertyNames-> jsName, lowerName ## Constructor, static_cast<unsigned>(PropertyAttribute::DontEnum));
859
860
861     FOR_EACH_SIMPLE_BUILTIN_TYPE_WITH_CONSTRUCTOR(PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE)
862
863 #undef PUT_CONSTRUCTOR_FOR_SIMPLE_TYPE
864     m_iteratorResultObjectStructure.initLater(
865         [] (const Initializer<Structure>& init) {
866             init.set(createIteratorResultObjectStructure(init.vm, *init.owner));
867         });
868     
869     m_evalFunction.initLater(
870         [] (const Initializer<JSFunction>& init) {
871             init.set(JSFunction::create(init.vm, init.owner, 1, init.vm.propertyNames->eval.string(), globalFuncEval, NoIntrinsic));
872         });
873     
874 #if ENABLE(INTL)
875     m_collatorStructure.initLater(
876         [] (const Initializer<Structure>& init) {
877             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
878             IntlCollatorPrototype* collatorPrototype = IntlCollatorPrototype::create(init.vm, globalObject, IntlCollatorPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
879             init.set(IntlCollator::createStructure(init.vm, globalObject, collatorPrototype));
880         });
881     m_numberFormatStructure.initLater(
882         [] (const Initializer<Structure>& init) {
883             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
884             IntlNumberFormatPrototype* numberFormatPrototype = IntlNumberFormatPrototype::create(init.vm, globalObject, IntlNumberFormatPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
885             init.set(IntlNumberFormat::createStructure(init.vm, globalObject, numberFormatPrototype));
886         });
887     m_dateTimeFormatStructure.initLater(
888         [] (const Initializer<Structure>& init) {
889             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
890             IntlDateTimeFormatPrototype* dateTimeFormatPrototype = IntlDateTimeFormatPrototype::create(init.vm, globalObject, IntlDateTimeFormatPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
891             init.set(IntlDateTimeFormat::createStructure(init.vm, globalObject, dateTimeFormatPrototype));
892         });
893     m_pluralRulesStructure.initLater(
894         [] (const Initializer<Structure>& init) {
895             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
896             IntlPluralRulesPrototype* pluralRulesPrototype = IntlPluralRulesPrototype::create(init.vm, globalObject, IntlPluralRulesPrototype::createStructure(init.vm, globalObject, globalObject->objectPrototype()));
897             init.set(IntlPluralRules::createStructure(init.vm, globalObject, pluralRulesPrototype));
898         });
899     m_defaultCollator.initLater(
900         [] (const Initializer<IntlCollator>& init) {
901             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
902             VM& vm = init.vm;
903             auto scope = DECLARE_CATCH_SCOPE(vm);
904             IntlCollator* collator = IntlCollator::create(vm, globalObject->collatorStructure());
905             collator->initializeCollator(globalObject, jsUndefined(), jsUndefined());
906             scope.releaseAssertNoException();
907             init.set(collator);
908         });
909
910     IntlObject* intl = IntlObject::create(vm, IntlObject::createStructure(vm, this, m_objectPrototype.get()));
911     putDirectWithoutTransition(vm, vm.propertyNames->Intl, intl, static_cast<unsigned>(PropertyAttribute::DontEnum));
912 #endif // ENABLE(INTL)
913
914     m_moduleLoader.initLater(
915         [] (const Initializer<JSModuleLoader>& init) {
916             auto catchScope = DECLARE_CATCH_SCOPE(init.vm);
917             init.set(JSModuleLoader::create(init.owner, init.vm, JSModuleLoader::createStructure(init.vm, init.owner, jsNull())));
918             catchScope.releaseAssertNoException();
919         });
920     if (Options::exposeInternalModuleLoader())
921         putDirectWithoutTransition(vm, vm.propertyNames->Loader, moduleLoader(), static_cast<unsigned>(PropertyAttribute::DontEnum));
922
923     GetterSetter* regExpProtoFlagsGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->flags);
924     catchScope.assertNoException();
925     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoFlagsGetter)].set(vm, this, regExpProtoFlagsGetter);
926     GetterSetter* regExpProtoGlobalGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->global);
927     catchScope.assertNoException();
928     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoGlobalGetter)].set(vm, this, regExpProtoGlobalGetter);
929     GetterSetter* regExpProtoIgnoreCaseGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->ignoreCase);
930     catchScope.assertNoException();
931     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoIgnoreCaseGetter)].set(vm, this, regExpProtoIgnoreCaseGetter);
932     GetterSetter* regExpProtoMultilineGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->multiline);
933     catchScope.assertNoException();
934     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoMultilineGetter)].set(vm, this, regExpProtoMultilineGetter);
935     GetterSetter* regExpProtoSourceGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->source);
936     catchScope.assertNoException();
937     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoSourceGetter)].set(vm, this, regExpProtoSourceGetter);
938     GetterSetter* regExpProtoStickyGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->sticky);
939     catchScope.assertNoException();
940     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoStickyGetter)].set(vm, this, regExpProtoStickyGetter);
941     GetterSetter* regExpProtoUnicodeGetter = getGetterById(this, m_regExpPrototype.get(), vm.propertyNames->unicode);
942     catchScope.assertNoException();
943     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpProtoUnicodeGetter)].set(vm, this, regExpProtoUnicodeGetter);
944     JSFunction* regExpSymbolReplace = jsCast<JSFunction*>(m_regExpPrototype->getDirect(vm, vm.propertyNames->replaceSymbol));
945     m_regExpProtoSymbolReplace.set(vm, this, regExpSymbolReplace);
946     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpBuiltinExec)].set(vm, this, jsCast<JSFunction*>(m_regExpPrototype->getDirect(vm, vm.propertyNames->exec)));
947     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpPrototypeSymbolReplace)].set(vm, this, m_regExpPrototype->getDirect(vm, vm.propertyNames->replaceSymbol).asCell());
948
949     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::Set)].set(vm, this, setConstructor);
950     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isArray)].set(vm, this, arrayConstructor->getDirect(vm, vm.propertyNames->isArray).asCell());
951     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::callFunction)].set(vm, this, callFunction);
952     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::applyFunction)].set(vm, this, applyFunction);
953
954 #define INIT_PRIVATE_GLOBAL(funcName, code) \
955     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::funcName)].initLater([] (const Initializer<JSCell>& init) { \
956             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner); \
957             init.set(JSFunction::create(init.vm, code ## CodeGenerator(init.vm), globalObject)); \
958         });
959     JSC_FOREACH_BUILTIN_FUNCTION_PRIVATE_GLOBAL_NAME(INIT_PRIVATE_GLOBAL)
960 #undef INIT_PRIVATE_GLOBAL
961
962     // FIXME: Initializing them lazily.
963     // https://bugs.webkit.org/show_bug.cgi?id=203795
964     JSObject* arrayIteratorPrototype = ArrayIteratorPrototype::create(vm, this, ArrayIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
965     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::ArrayIterator))->putDirect(vm, vm.propertyNames->prototype, arrayIteratorPrototype);
966
967     JSObject* asyncFromSyncIteratorPrototype = AsyncFromSyncIteratorPrototype::create(vm, this, AsyncFromSyncIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
968     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::AsyncFromSyncIterator))->putDirect(vm, vm.propertyNames->prototype, asyncFromSyncIteratorPrototype);
969
970     JSObject* mapIteratorPrototype = MapIteratorPrototype::create(vm, this, MapIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
971     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::MapIterator))->putDirect(vm, vm.propertyNames->prototype, mapIteratorPrototype);
972
973     JSObject* regExpStringIteratorPrototype = RegExpStringIteratorPrototype::create(vm, this, RegExpStringIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
974     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::RegExpStringIterator))->putDirect(vm, vm.propertyNames->prototype, regExpStringIteratorPrototype);
975
976     JSObject* setIteratorPrototype = SetIteratorPrototype::create(vm, this, SetIteratorPrototype::createStructure(vm, this, m_iteratorPrototype.get()));
977     jsCast<JSObject*>(linkTimeConstant(LinkTimeConstant::SetIterator))->putDirect(vm, vm.propertyNames->prototype, setIteratorPrototype);
978
979     // Map and Set helpers.
980     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketHead)].initLater([] (const Initializer<JSCell>& init) {
981             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketHead, JSMapBucketHeadIntrinsic));
982         });
983     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketNext)].initLater([] (const Initializer<JSCell>& init) {
984             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketNext, JSMapBucketNextIntrinsic));
985         });
986     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketKey)].initLater([] (const Initializer<JSCell>& init) {
987             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketKey, JSMapBucketKeyIntrinsic));
988         });
989     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::mapBucketValue)].initLater([] (const Initializer<JSCell>& init) {
990             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mapPrivateFuncMapBucketValue, JSMapBucketValueIntrinsic));
991         });
992     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::setBucketHead)].initLater([] (const Initializer<JSCell>& init) {
993             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), setPrivateFuncSetBucketHead, JSSetBucketHeadIntrinsic));
994         });
995     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::setBucketNext)].initLater([] (const Initializer<JSCell>& init) {
996             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), setPrivateFuncSetBucketNext, JSSetBucketNextIntrinsic));
997         });
998     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::setBucketKey)].initLater([] (const Initializer<JSCell>& init) {
999             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), setPrivateFuncSetBucketKey, JSSetBucketKeyIntrinsic));
1000         });
1001
1002     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::importModule)].initLater([] (const Initializer<JSCell>& init) {
1003             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncImportModule));
1004         });
1005     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::propertyIsEnumerable)].initLater([] (const Initializer<JSCell>& init) {
1006             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncPropertyIsEnumerable));
1007         });
1008     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::ownKeys)].initLater([] (const Initializer<JSCell>& init) {
1009             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncOwnKeys));
1010         });
1011     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::enqueueJob)].initLater([] (const Initializer<JSCell>& init) {
1012             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, "enqueueJob"_s, enqueueJob));
1013         });
1014     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::makeTypeError)].initLater([] (const Initializer<JSCell>& init) {
1015             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncMakeTypeError));
1016         });
1017     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArrayLength)].initLater([] (const Initializer<JSCell>& init) {
1018             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncLength));
1019         });
1020     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArrayGetOriginalConstructor)].initLater([] (const Initializer<JSCell>& init) {
1021             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncGetOriginalConstructor));
1022         });
1023     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArraySort)].initLater([] (const Initializer<JSCell>& init) {
1024             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncSort));
1025         });
1026     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isTypedArrayView)].initLater([] (const Initializer<JSCell>& init) {
1027             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncIsTypedArrayView, IsTypedArrayViewIntrinsic));
1028         });
1029     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::typedArraySubarrayCreate)].initLater([] (const Initializer<JSCell>& init) {
1030             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), typedArrayViewPrivateFuncSubarrayCreate));
1031         });
1032     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isBoundFunction)].initLater([] (const Initializer<JSCell>& init) {
1033             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), isBoundFunction));
1034         });
1035     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::hasInstanceBoundFunction)].initLater([] (const Initializer<JSCell>& init) {
1036             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), hasInstanceBoundFunction));
1037         });
1038     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::instanceOf)].initLater([] (const Initializer<JSCell>& init) {
1039             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), objectPrivateFuncInstanceOf));
1040         });
1041     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::BuiltinLog)].initLater([] (const Initializer<JSCell>& init) {
1042             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), globalFuncBuiltinLog));
1043         });
1044     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::BuiltinDescribe)].initLater([] (const Initializer<JSCell>& init) {
1045             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), globalFuncBuiltinDescribe));
1046         });
1047     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::trunc)].initLater([] (const Initializer<JSCell>& init) {
1048             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), mathProtoFuncTrunc, TruncIntrinsic));
1049         });
1050     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::repeatCharacter)].initLater([] (const Initializer<JSCell>& init) {
1051             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), stringProtoFuncRepeatCharacter));
1052         });
1053     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::arraySpeciesCreate)].initLater([] (const Initializer<JSCell>& init) {
1054             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), arrayProtoFuncSpeciesCreate));
1055         });
1056     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isArraySlow)].initLater([] (const Initializer<JSCell>& init) {
1057             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), arrayConstructorPrivateFuncIsArraySlow));
1058         });
1059     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::concatMemcpy)].initLater([] (const Initializer<JSCell>& init) {
1060             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), arrayProtoPrivateFuncConcatMemcpy));
1061         });
1062     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::appendMemcpy)].initLater([] (const Initializer<JSCell>& init) {
1063             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), arrayProtoPrivateFuncAppendMemcpy));
1064         });
1065     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::hostPromiseRejectionTracker)].initLater([] (const Initializer<JSCell>& init) {
1066             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), globalFuncHostPromiseRejectionTracker));
1067         });
1068     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::InspectorInstrumentation)].initLater([] (const Initializer<JSCell>& init) {
1069             JSGlobalObject* globalObject = jsCast<JSGlobalObject*>(init.owner);
1070             init.set(InspectorInstrumentationObject::create(init.vm, globalObject, InspectorInstrumentationObject::createStructure(init.vm, globalObject, globalObject->m_objectPrototype.get())));
1071         });
1072     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::thisTimeValue)].initLater([] (const Initializer<JSCell>& init) {
1073             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), dateProtoFuncGetTime, DatePrototypeGetTimeIntrinsic));
1074         });
1075     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isConstructor)].initLater([] (const Initializer<JSCell>& init) {
1076             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), esSpecIsConstructor, NoIntrinsic));
1077         });
1078
1079     // RegExp.prototype helpers.
1080     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpCreate)].initLater([] (const Initializer<JSCell>& init) {
1081             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), esSpecRegExpCreate, NoIntrinsic));
1082         });
1083     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::isRegExp)].initLater([] (const Initializer<JSCell>& init) {
1084             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), esSpecIsRegExp, NoIntrinsic));
1085         });
1086     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpMatchFast)].initLater([] (const Initializer<JSCell>& init) {
1087             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), regExpProtoFuncMatchFast, RegExpMatchFastIntrinsic));
1088         });
1089     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpSearchFast)].initLater([] (const Initializer<JSCell>& init) {
1090             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), regExpProtoFuncSearchFast));
1091         });
1092     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpSplitFast)].initLater([] (const Initializer<JSCell>& init) {
1093             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), regExpProtoFuncSplitFast));
1094         });
1095     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::regExpTestFast)].initLater([] (const Initializer<JSCell>& init) {
1096             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), regExpProtoFuncTestFast, RegExpTestFastIntrinsic));
1097         });
1098
1099     // String.prototype helpers.
1100     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringIncludesInternal)].initLater([] (const Initializer<JSCell>& init) {
1101             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), builtinStringIncludesInternal));
1102         });
1103     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringSplitFast)].initLater([] (const Initializer<JSCell>& init) {
1104             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), stringProtoFuncSplitFast));
1105         });
1106     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::stringSubstrInternal)].initLater([] (const Initializer<JSCell>& init) {
1107             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 2, String(), builtinStringSubstrInternal));
1108         });
1109
1110     // Function prototype helpers.
1111     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::makeBoundFunction)].initLater([] (const Initializer<JSCell>& init) {
1112             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 5, String(), makeBoundFunction));
1113         });
1114     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::hasOwnLengthProperty)].initLater([] (const Initializer<JSCell>& init) {
1115             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), hasOwnLengthProperty));
1116         });
1117
1118 #if ENABLE(INTL)
1119     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::dateTimeFormat)].initLater([] (const Initializer<JSCell>& init) {
1120             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 0, String(), globalFuncDateTimeFormat));
1121         });
1122 #endif // ENABLE(INTL)
1123 #if ENABLE(WEBASSEMBLY) && ENABLE(WEBASSEMBLY_STREAMING_API)
1124     // WebAssembly Streaming API
1125     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::webAssemblyCompileStreamingInternal)].initLater([] (const Initializer<JSCell>& init) {
1126             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), webAssemblyCompileStreamingInternal));
1127         });
1128     m_linkTimeConstants[static_cast<unsigned>(LinkTimeConstant::webAssemblyInstantiateStreamingInternal)].initLater([] (const Initializer<JSCell>& init) {
1129             init.set(JSFunction::create(init.vm, jsCast<JSGlobalObject*>(init.owner), 1, String(), webAssemblyInstantiateStreamingInternal));
1130         });
1131 #endif
1132
1133     GlobalPropertyInfo staticGlobals[] = {
1134         GlobalPropertyInfo(vm.propertyNames->NaN, jsNaN(), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1135         GlobalPropertyInfo(vm.propertyNames->Infinity, jsNumber(std::numeric_limits<double>::infinity()), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1136         GlobalPropertyInfo(vm.propertyNames->undefinedKeyword, jsUndefined(), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1137 #if !ASSERT_DISABLED
1138         GlobalPropertyInfo(vm.propertyNames->builtinNames().assertPrivateName(), JSFunction::create(vm, this, 1, String(), assertCall), PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1139 #endif
1140     };
1141     addStaticGlobals(staticGlobals, WTF_ARRAY_LENGTH(staticGlobals));
1142     
1143     if (UNLIKELY(Options::useDollarVM()))
1144         exposeDollarVM(vm);
1145
1146 #if ENABLE(WEBASSEMBLY)
1147     if (Wasm::isSupported()) {
1148         m_webAssemblyModuleRecordStructure.initLater(
1149             [] (const Initializer<Structure>& init) {
1150                 init.set(WebAssemblyModuleRecord::createStructure(init.vm, init.owner, init.owner->m_objectPrototype.get()));
1151             });
1152         m_webAssemblyFunctionStructure.initLater(
1153             [] (const Initializer<Structure>& init) {
1154                 init.set(WebAssemblyFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
1155             });
1156         m_jsToWasmICCalleeStructure.initLater(
1157             [] (const Initializer<Structure>& init) {
1158                 init.set(JSToWasmICCallee::createStructure(init.vm, init.owner, jsNull()));
1159             });
1160         m_webAssemblyWrapperFunctionStructure.initLater(
1161             [] (const Initializer<Structure>& init) {
1162                 init.set(WebAssemblyWrapperFunction::createStructure(init.vm, init.owner, init.owner->m_functionPrototype.get()));
1163             });
1164         m_webAssemblyToJSCalleeStructure.initLater(
1165             [] (const Initializer<Structure>& init) {
1166                 init.set(WebAssemblyToJSCallee::createStructure(init.vm, init.owner, jsNull()));
1167             });
1168         auto* webAssembly = JSWebAssembly::create(vm, this, JSWebAssembly::createStructure(vm, this, m_objectPrototype.get()));
1169         putDirectWithoutTransition(vm, Identifier::fromString(vm, "WebAssembly"), webAssembly, static_cast<unsigned>(PropertyAttribute::DontEnum));
1170
1171 #define CREATE_WEBASSEMBLY_PROTOTYPE(capitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) \
1172     if (featureFlag) {\
1173         m_ ## properName ## Structure.initLater(\
1174             [] (LazyClassStructure::Initializer& init) { \
1175                 init.setPrototype(capitalName##Prototype::create(init.vm, init.global, capitalName##Prototype::createStructure(init.vm, init.global, init.global->prototypeBase ## Prototype()))); \
1176                 init.setStructure(instanceType::createStructure(init.vm, init.global, init.prototype)); \
1177                 init.setConstructor(capitalName ## Constructor::create(init.vm, capitalName ## Constructor::createStructure(init.vm, init.global, init.global->functionPrototype()), jsCast<capitalName ## Prototype*>(init.prototype))); \
1178             }); \
1179     }
1180
1181         FOR_EACH_WEBASSEMBLY_CONSTRUCTOR_TYPE(CREATE_WEBASSEMBLY_PROTOTYPE)
1182
1183 #undef CREATE_WEBASSEMBLY_CONSTRUCTOR
1184     }
1185 #endif // ENABLE(WEBASSEMBLY)
1186
1187 #undef CREATE_PROTOTYPE_FOR_LAZY_TYPE
1188
1189     auto setupAdaptiveWatchpoint = [&] (JSObject* base, const Identifier& ident) -> ObjectPropertyCondition {
1190         // Performing these gets should not throw.
1191         PropertySlot slot(base, PropertySlot::InternalMethodType::Get);
1192         bool result = base->getOwnPropertySlot(base, this, ident, slot);
1193         ASSERT_UNUSED(result, result);
1194         catchScope.assertNoException();
1195         RELEASE_ASSERT(slot.isCacheableValue());
1196         JSValue functionValue = slot.getValue(this, ident);
1197         catchScope.assertNoException();
1198         ASSERT(jsDynamicCast<JSFunction*>(vm, functionValue));
1199
1200         ObjectPropertyCondition condition = generateConditionForSelfEquivalence(vm, nullptr, base, ident.impl());
1201         RELEASE_ASSERT(condition.requiredValue() == functionValue);
1202
1203         bool isWatchable = condition.isWatchable(PropertyCondition::EnsureWatchability);
1204         RELEASE_ASSERT(isWatchable); // We allow this to install the necessary watchpoints.
1205
1206         return condition;
1207     };
1208
1209     {
1210         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(arrayIteratorPrototype, vm.propertyNames->next);
1211         m_arrayIteratorPrototypeNext = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_arrayIteratorProtocolWatchpointSet);
1212         m_arrayIteratorPrototypeNext->install(vm);
1213     }
1214     {
1215         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this->arrayPrototype(), vm.propertyNames->iteratorSymbol);
1216         m_arrayPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_arrayIteratorProtocolWatchpointSet);
1217         m_arrayPrototypeSymbolIteratorWatchpoint->install(vm);
1218     }
1219     {
1220         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(this->arrayPrototype(), vm.propertyNames->join);
1221         m_arrayPrototypeJoinWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_arrayJoinWatchpointSet);
1222         m_arrayPrototypeJoinWatchpoint->install(vm);
1223     }
1224
1225     {
1226         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(mapIteratorPrototype, vm.propertyNames->next);
1227         m_mapIteratorPrototypeNextWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_mapIteratorProtocolWatchpointSet);
1228         m_mapIteratorPrototypeNextWatchpoint->install(vm);
1229     }
1230     {
1231         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(m_mapPrototype.get(), vm.propertyNames->iteratorSymbol);
1232         m_mapPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_mapIteratorProtocolWatchpointSet);
1233         m_mapPrototypeSymbolIteratorWatchpoint->install(vm);
1234     }
1235
1236     {
1237         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(setIteratorPrototype, vm.propertyNames->next);
1238         m_setIteratorPrototypeNextWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_setIteratorProtocolWatchpointSet);
1239         m_setIteratorPrototypeNextWatchpoint->install(vm);
1240     }
1241     {
1242         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(m_setPrototype.get(), vm.propertyNames->iteratorSymbol);
1243         m_setPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_setIteratorProtocolWatchpointSet);
1244         m_setPrototypeSymbolIteratorWatchpoint->install(vm);
1245     }
1246
1247     {
1248         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(m_stringIteratorPrototype.get(), vm.propertyNames->next);
1249         m_stringIteratorPrototypeNextWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_stringIteratorProtocolWatchpointSet);
1250         m_stringIteratorPrototypeNextWatchpoint->install(vm);
1251     }
1252     {
1253         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(m_stringPrototype.get(), vm.propertyNames->iteratorSymbol);
1254         m_stringPrototypeSymbolIteratorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_stringIteratorProtocolWatchpointSet);
1255         m_stringPrototypeSymbolIteratorWatchpoint->install(vm);
1256     }
1257
1258     {
1259         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(m_mapPrototype.get(), vm.propertyNames->set);
1260         m_mapPrototypeSetWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_mapSetWatchpointSet);
1261         m_mapPrototypeSetWatchpoint->install(vm);
1262     }
1263
1264     {
1265         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(m_setPrototype.get(), vm.propertyNames->add);
1266         m_setPrototypeAddWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_setAddWatchpointSet);
1267         m_setPrototypeAddWatchpoint->install(vm);
1268     }
1269
1270     // Unfortunately, the prototype objects of the builtin objects can be touched from concurrent compilers. So eagerly initialize them only if we use JIT.
1271     if (VM::canUseJIT()) {
1272         this->booleanPrototype();
1273         auto* numberPrototype = this->numberPrototype();
1274         this->symbolPrototype();
1275
1276         ObjectPropertyCondition condition = setupAdaptiveWatchpoint(numberPrototype, vm.propertyNames->toString);
1277         m_numberPrototypeToStringWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, condition, m_numberToStringWatchpointSet);
1278         m_numberPrototypeToStringWatchpoint->install(vm);
1279         m_numberProtoToStringFunction.set(vm, this, jsCast<JSFunction*>(numberPrototype->getDirect(vm, vm.propertyNames->toString)));
1280     }
1281
1282     fixupPrototypeChainWithObjectPrototype(vm);
1283 }
1284
1285 bool JSGlobalObject::put(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
1286 {
1287     VM& vm = globalObject->vm();
1288     auto scope = DECLARE_THROW_SCOPE(vm);
1289     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(cell);
1290     ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(thisObject));
1291
1292     if (UNLIKELY(isThisValueAltered(slot, thisObject)))
1293         RELEASE_AND_RETURN(scope, ordinarySetSlow(globalObject, thisObject, propertyName, value, slot.thisValue(), slot.isStrictMode()));
1294
1295     bool shouldThrowReadOnlyError = slot.isStrictMode();
1296     bool ignoreReadOnlyErrors = false;
1297     bool putResult = false;
1298     bool done = symbolTablePutTouchWatchpointSet(thisObject, globalObject, propertyName, value, shouldThrowReadOnlyError, ignoreReadOnlyErrors, putResult);
1299     EXCEPTION_ASSERT((!!scope.exception() == (done && !putResult)) || !shouldThrowReadOnlyError);
1300     if (done)
1301         return putResult;
1302     RELEASE_AND_RETURN(scope, Base::put(thisObject, globalObject, propertyName, value, slot));
1303 }
1304
1305 bool JSGlobalObject::defineOwnProperty(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, const PropertyDescriptor& descriptor, bool shouldThrow)
1306 {
1307     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(object);
1308     PropertySlot slot(thisObject, PropertySlot::InternalMethodType::VMInquiry);
1309     // silently ignore attempts to add accessors aliasing vars.
1310     if (descriptor.isAccessorDescriptor() && symbolTableGet(thisObject, propertyName, slot))
1311         return false;
1312     return Base::defineOwnProperty(thisObject, globalObject, propertyName, descriptor, shouldThrow);
1313 }
1314
1315 void JSGlobalObject::addGlobalVar(const Identifier& ident)
1316 {
1317     ConcurrentJSLocker locker(symbolTable()->m_lock);
1318     SymbolTableEntry entry = symbolTable()->get(locker, ident.impl());
1319     if (!entry.isNull())
1320         return;
1321     
1322     ScopeOffset offset = symbolTable()->takeNextScopeOffset(locker);
1323     SymbolTableEntry newEntry(VarOffset(offset), 0);
1324     newEntry.prepareToWatch();
1325     symbolTable()->add(locker, ident.impl(), WTFMove(newEntry));
1326     
1327     ScopeOffset offsetForAssert = addVariables(1, jsUndefined());
1328     RELEASE_ASSERT(offsetForAssert == offset);
1329 }
1330
1331 void JSGlobalObject::addFunction(JSGlobalObject* globalObject, const Identifier& propertyName)
1332 {
1333     VM& vm = globalObject->vm();
1334     VM::DeletePropertyModeScope scope(vm, VM::DeletePropertyMode::IgnoreConfigurable);
1335     methodTable(vm)->deleteProperty(this, globalObject, propertyName);
1336     addGlobalVar(propertyName);
1337 }
1338
1339 void JSGlobalObject::setGlobalScopeExtension(JSScope* scope)
1340 {
1341     m_globalScopeExtension.set(vm(), this, scope);
1342 }
1343
1344 void JSGlobalObject::clearGlobalScopeExtension()
1345 {
1346     m_globalScopeExtension.clear();
1347 }
1348
1349 static inline JSObject* lastInPrototypeChain(VM& vm, JSObject* object)
1350 {
1351     JSObject* o = object;
1352     while (o->getPrototypeDirect(vm).isObject())
1353         o = asObject(o->getPrototypeDirect(vm));
1354     return o;
1355 }
1356
1357 // Private namespace for helpers for JSGlobalObject::haveABadTime()
1358 namespace {
1359
1360 class GlobalObjectDependencyFinder : public MarkedBlock::VoidFunctor {
1361 public:
1362     GlobalObjectDependencyFinder(VM& vm)
1363         : m_vm(vm)
1364     { }
1365
1366     IterationStatus operator()(HeapCell*, HeapCell::Kind) const;
1367
1368     void addDependency(JSGlobalObject* key, JSGlobalObject* dependent);
1369     HashSet<JSGlobalObject*>* dependentsFor(JSGlobalObject* key);
1370
1371 private:
1372     void visit(JSObject*);
1373
1374     VM& m_vm;
1375     HashMap<JSGlobalObject*, HashSet<JSGlobalObject*>> m_dependencies;
1376 };
1377
1378 inline void GlobalObjectDependencyFinder::addDependency(JSGlobalObject* key, JSGlobalObject* dependent)
1379 {
1380     auto keyResult = m_dependencies.add(key, HashSet<JSGlobalObject*>());
1381     keyResult.iterator->value.add(dependent);
1382 }
1383
1384 inline HashSet<JSGlobalObject*>* GlobalObjectDependencyFinder::dependentsFor(JSGlobalObject* key)
1385 {
1386     auto iterator = m_dependencies.find(key);
1387     if (iterator == m_dependencies.end())
1388         return nullptr;
1389     return &iterator->value;
1390 }
1391
1392 inline void GlobalObjectDependencyFinder::visit(JSObject* object)
1393 {
1394     VM& vm = m_vm;
1395
1396     if (!object->mayBePrototype())
1397         return;
1398
1399     JSObject* current = object;
1400     JSGlobalObject* objectGlobalObject = object->globalObject(vm);
1401     do {
1402         JSValue prototypeValue = current->getPrototypeDirect(vm);
1403         if (prototypeValue.isNull())
1404             return;
1405         current = asObject(prototypeValue);
1406
1407         JSGlobalObject* protoGlobalObject = current->globalObject(vm);
1408         if (protoGlobalObject != objectGlobalObject)
1409             addDependency(protoGlobalObject, objectGlobalObject);
1410     } while (true);
1411 }
1412
1413 IterationStatus GlobalObjectDependencyFinder::operator()(HeapCell* cell, HeapCell::Kind kind) const
1414 {
1415     if (isJSCellKind(kind) && static_cast<JSCell*>(cell)->isObject()) {
1416         // FIXME: This const_cast exists because this isn't a C++ lambda.
1417         // https://bugs.webkit.org/show_bug.cgi?id=159644
1418         const_cast<GlobalObjectDependencyFinder*>(this)->visit(jsCast<JSObject*>(static_cast<JSCell*>(cell)));
1419     }
1420     return IterationStatus::Continue;
1421 }
1422
1423 enum class BadTimeFinderMode {
1424     SingleGlobal,
1425     MultipleGlobals
1426 };
1427
1428 template<BadTimeFinderMode mode>
1429 class ObjectsWithBrokenIndexingFinder : public MarkedBlock::VoidFunctor {
1430 public:
1431     ObjectsWithBrokenIndexingFinder(VM&, Vector<JSObject*>&, JSGlobalObject*);
1432     ObjectsWithBrokenIndexingFinder(VM&, Vector<JSObject*>&, HashSet<JSGlobalObject*>&);
1433
1434     bool needsMultiGlobalsScan() const { return m_needsMultiGlobalsScan; }
1435     IterationStatus operator()(HeapCell*, HeapCell::Kind) const;
1436
1437 private:
1438     IterationStatus visit(JSObject*);
1439
1440     VM& m_vm;
1441     Vector<JSObject*>& m_foundObjects;
1442     JSGlobalObject* m_globalObject { nullptr }; // Only used for SingleBadTimeGlobal mode.
1443     HashSet<JSGlobalObject*>* m_globalObjects { nullptr }; // Only used for BadTimeGlobalGraph mode;
1444     bool m_needsMultiGlobalsScan { false };
1445 };
1446
1447 template<>
1448 ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::SingleGlobal>::ObjectsWithBrokenIndexingFinder(
1449     VM& vm, Vector<JSObject*>& foundObjects, JSGlobalObject* globalObject)
1450     : m_vm(vm)
1451     , m_foundObjects(foundObjects)
1452     , m_globalObject(globalObject)
1453 {
1454 }
1455
1456 template<>
1457 ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::MultipleGlobals>::ObjectsWithBrokenIndexingFinder(
1458     VM& vm, Vector<JSObject*>& foundObjects, HashSet<JSGlobalObject*>& globalObjects)
1459     : m_vm(vm)
1460     , m_foundObjects(foundObjects)
1461     , m_globalObjects(&globalObjects)
1462 {
1463 }
1464
1465 inline bool hasBrokenIndexing(IndexingType type)
1466 {
1467     return type && !hasSlowPutArrayStorage(type);
1468 }
1469
1470 inline bool hasBrokenIndexing(JSObject* object)
1471 {
1472     IndexingType type = object->indexingType();
1473     return hasBrokenIndexing(type);
1474 }
1475
1476 template<BadTimeFinderMode mode>
1477 inline IterationStatus ObjectsWithBrokenIndexingFinder<mode>::visit(JSObject* object)
1478 {
1479     VM& vm = m_vm;
1480
1481     // We only want to have a bad time in the affected global object, not in the entire
1482     // VM. But we have to be careful, since there may be objects that claim to belong to
1483     // a different global object that have prototypes from our global object.
1484     auto isInAffectedGlobalObject = [&] (JSObject* object) {
1485         JSGlobalObject* objectGlobalObject { nullptr };
1486         bool objectMayBePrototype { false };
1487
1488         if (mode == BadTimeFinderMode::SingleGlobal) {
1489             objectGlobalObject = object->globalObject(vm);
1490             if (objectGlobalObject == m_globalObject)
1491                 return true;
1492
1493             objectMayBePrototype = object->mayBePrototype();
1494         }
1495
1496         for (JSObject* current = object; ;) {
1497             JSGlobalObject* currentGlobalObject = current->globalObject(vm);
1498             if (mode == BadTimeFinderMode::SingleGlobal) {
1499                 if (objectMayBePrototype && currentGlobalObject != objectGlobalObject)
1500                     m_needsMultiGlobalsScan = true;
1501                 if (currentGlobalObject == m_globalObject)
1502                     return true;
1503             } else {
1504                 if (m_globalObjects->contains(currentGlobalObject))
1505                     return true;
1506             }
1507
1508             JSValue prototypeValue = current->getPrototypeDirect(vm);
1509             if (prototypeValue.isNull())
1510                 return false;
1511             current = asObject(prototypeValue);
1512         }
1513         RELEASE_ASSERT_NOT_REACHED();
1514     };
1515
1516     if (JSFunction* function = jsDynamicCast<JSFunction*>(vm, object)) {
1517         if (FunctionRareData* rareData = function->rareData()) {
1518             // We only use this to cache JSFinalObjects. They do not start off with a broken indexing type.
1519             ASSERT(!(rareData->objectAllocationStructure() && hasBrokenIndexing(rareData->objectAllocationStructure()->indexingType())));
1520
1521             if (Structure* structure = rareData->internalFunctionAllocationStructure()) {
1522                 if (hasBrokenIndexing(structure->indexingType())) {
1523                     bool isRelevantGlobalObject =
1524                         (mode == BadTimeFinderMode::SingleGlobal
1525                             ? m_globalObject == structure->globalObject()
1526                             : m_globalObjects->contains(structure->globalObject()))
1527                         || (structure->hasMonoProto() && !structure->storedPrototype().isNull() && isInAffectedGlobalObject(asObject(structure->storedPrototype())));
1528                     if (mode == BadTimeFinderMode::SingleGlobal && m_needsMultiGlobalsScan)
1529                         return IterationStatus::Done; // Bailing early and let the MultipleGlobals path handle everything.
1530                     if (isRelevantGlobalObject)
1531                         rareData->clearInternalFunctionAllocationProfile("have a bad time breaking internal function allocation");
1532                 }
1533             }
1534         }
1535     }
1536
1537     // Run this filter first, since it's cheap, and ought to filter out a lot of objects.
1538     if (!hasBrokenIndexing(object))
1539         return IterationStatus::Continue;
1540
1541     if (isInAffectedGlobalObject(object))
1542         m_foundObjects.append(object);
1543
1544     if (mode == BadTimeFinderMode::SingleGlobal && m_needsMultiGlobalsScan)
1545         return IterationStatus::Done; // Bailing early and let the MultipleGlobals path handle everything.
1546
1547     return IterationStatus::Continue;
1548 }
1549
1550 template<BadTimeFinderMode mode>
1551 IterationStatus ObjectsWithBrokenIndexingFinder<mode>::operator()(HeapCell* cell, HeapCell::Kind kind) const
1552 {
1553     if (isJSCellKind(kind) && static_cast<JSCell*>(cell)->isObject()) {
1554         // FIXME: This const_cast exists because this isn't a C++ lambda.
1555         // https://bugs.webkit.org/show_bug.cgi?id=159644
1556         return const_cast<ObjectsWithBrokenIndexingFinder*>(this)->visit(jsCast<JSObject*>(static_cast<JSCell*>(cell)));
1557     }
1558     return IterationStatus::Continue;
1559 }
1560
1561 } // end private namespace for helpers for JSGlobalObject::haveABadTime()
1562
1563 void JSGlobalObject::fireWatchpointAndMakeAllArrayStructuresSlowPut(VM& vm)
1564 {
1565     if (isHavingABadTime())
1566         return;
1567
1568     // Make sure that all allocations or indexed storage transitions that are inlining
1569     // the assumption that it's safe to transition to a non-SlowPut array storage don't
1570     // do so anymore.
1571     m_havingABadTimeWatchpoint->fireAll(vm, "Having a bad time");
1572     ASSERT(isHavingABadTime()); // The watchpoint is what tells us that we're having a bad time.
1573     
1574     // Make sure that all JSArray allocations that load the appropriate structure from
1575     // this object now load a structure that uses SlowPut.
1576     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
1577         m_arrayStructureForIndexingShapeDuringAllocation[i].set(vm, this, originalArrayStructureForIndexingType(ArrayWithSlowPutArrayStorage));
1578
1579     // Same for any special array structures.
1580     Structure* slowPutStructure;
1581     slowPutStructure = createRegExpMatchesArraySlowPutStructure(vm, this);
1582     m_regExpMatchesArrayStructure.set(vm, this, slowPutStructure);
1583     slowPutStructure = createRegExpMatchesArrayWithGroupsSlowPutStructure(vm, this);
1584     m_regExpMatchesArrayWithGroupsStructure.set(vm, this, slowPutStructure);
1585     slowPutStructure = ClonedArguments::createSlowPutStructure(vm, this, m_objectPrototype.get());
1586     m_clonedArgumentsStructure.set(vm, this, slowPutStructure);
1587 };
1588
1589 void JSGlobalObject::haveABadTime(VM& vm)
1590 {
1591     ASSERT(&vm == &this->vm());
1592     
1593     if (isHavingABadTime())
1594         return;
1595
1596     vm.structureCache.clear(); // We may be caching array structures in here.
1597
1598     DeferGC deferGC(vm.heap);
1599
1600     // Consider the following objects and prototype chains:
1601     //    O (of global G1) -> A (of global G1)
1602     //    B (of global G2) where G2 has a bad time
1603     //
1604     // If we set B as the prototype of A, G1 will need to have a bad time.
1605     // See comments in Structure::mayInterceptIndexedAccesses() for why.
1606     //
1607     // Now, consider the following objects and prototype chains:
1608     //    O1 (of global G1) -> A1 (of global G1) -> B1 (of global G2)
1609     //    O2 (of global G2) -> A2 (of global G2)
1610     //    B2 (of global G3) where G3 has a bad time.
1611     //
1612     // G1 and G2 does not have a bad time, but G3 already has a bad time.
1613     // If we set B2 as the prototype of A2, then G2 needs to have a bad time.
1614     // Note that by induction, G1 also now needs to have a bad time because of
1615     // O1 -> A1 -> B1.
1616     //
1617     // We describe this as global G1 being affected by global G2, and G2 by G3.
1618     // Similarly, we say that G1 is dependent on G2, and G2 on G3.
1619     // Hence, when G3 has a bad time, we need to ensure that all globals that
1620     // are transitively dependent on it also have a bad time (G2 and G1 in this
1621     // example).
1622     //
1623     // Apart from clearing the VM structure cache above, there are 2 more things
1624     // that we have to do when globals have a bad time:
1625     // 1. For each affected global:
1626     //    a. Fire its HaveABadTime watchpoint.
1627     //    b. Convert all of its array structures to SlowPutArrayStorage.
1628     // 2. Make sure that all affected objects  switch to the slow kind of
1629     //    indexed storage. An object is considered to be affected if it has
1630     //    indexed storage and has a prototype object which may have indexed
1631     //    accessors. If the prototype object belongs to a global having a bad
1632     //    time, then the prototype object is considered to possibly have indexed
1633     //    accessors. See comments in Structure::mayInterceptIndexedAccesses()
1634     //    for details.
1635     //
1636     // Note: step 1 must be completed before step 2 because step 2 relies on
1637     // the HaveABadTime watchpoint having already been fired on all affected
1638     // globals.
1639     //
1640     // In the common case, only this global will start having a bad time here,
1641     // and no other globals are affected by it. So, we first proceed on this assumption
1642     // with a simpler ObjectsWithBrokenIndexingFinder scan to find heap objects
1643     // affected by this global that need to be converted to SlowPutArrayStorage.
1644     // We'll also have the finder check for the presence of other global objects
1645     // depending on this one.
1646     //
1647     // If we do discover other globals depending on this one, we'll abort this
1648     // first ObjectsWithBrokenIndexingFinder scan because it will be insufficient
1649     // to find all affected objects that need to be converted to SlowPutArrayStorage.
1650     // It also does not make dependent globals have a bad time. Instead, we'll
1651     // take a more comprehensive approach of first creating a dependency graph
1652     // between globals, and then using that graph to determine all affected
1653     // globals and objects. With that, we can make all affected globals have a
1654     // bad time, and convert all affected objects to SlowPutArrayStorage.
1655
1656     fireWatchpointAndMakeAllArrayStructuresSlowPut(vm); // Step 1 above.
1657     
1658     Vector<JSObject*> foundObjects;
1659     ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::SingleGlobal> finder(vm, foundObjects, this);
1660     {
1661         HeapIterationScope iterationScope(vm.heap);
1662         vm.heap.objectSpace().forEachLiveCell(iterationScope, finder); // Attempt step 2 above.
1663     }
1664
1665     if (finder.needsMultiGlobalsScan()) {
1666         foundObjects.clear();
1667
1668         // Find all globals that will also have a bad time as a side effect of
1669         // this global having a bad time.
1670         GlobalObjectDependencyFinder dependencies(vm);
1671         {
1672             HeapIterationScope iterationScope(vm.heap);
1673             vm.heap.objectSpace().forEachLiveCell(iterationScope, dependencies);
1674         }
1675
1676         HashSet<JSGlobalObject*> globalsHavingABadTime;
1677         Deque<JSGlobalObject*> globals;
1678
1679         globals.append(this);
1680         while (!globals.isEmpty()) {
1681             JSGlobalObject* global = globals.takeFirst();
1682             global->fireWatchpointAndMakeAllArrayStructuresSlowPut(vm); // Step 1 above.
1683             auto result = globalsHavingABadTime.add(global);
1684             if (result.isNewEntry) {
1685                 if (HashSet<JSGlobalObject*>* dependents = dependencies.dependentsFor(global)) {
1686                     for (JSGlobalObject* dependentGlobal : *dependents)
1687                         globals.append(dependentGlobal);
1688                 }
1689             }
1690         }
1691
1692         ObjectsWithBrokenIndexingFinder<BadTimeFinderMode::MultipleGlobals> finder(vm, foundObjects, globalsHavingABadTime);
1693         {
1694             HeapIterationScope iterationScope(vm.heap);
1695             vm.heap.objectSpace().forEachLiveCell(iterationScope, finder); // Step 2 above.
1696         }
1697     }
1698
1699     while (!foundObjects.isEmpty()) {
1700         JSObject* object = asObject(foundObjects.last());
1701         foundObjects.removeLast();
1702         ASSERT(hasBrokenIndexing(object));
1703         object->switchToSlowPutArrayStorage(vm);
1704     }
1705 }
1706
1707 void JSGlobalObject::fixupPrototypeChainWithObjectPrototype(VM& vm)
1708 {
1709     JSObject* oldLastInPrototypeChain = lastInPrototypeChain(vm, this);
1710     JSObject* objectPrototype = m_objectPrototype.get();
1711     if (oldLastInPrototypeChain != objectPrototype)
1712         oldLastInPrototypeChain->setPrototypeDirect(vm, objectPrototype);
1713 }
1714
1715 // Set prototype, and also insert the object prototype at the end of the chain.
1716 void JSGlobalObject::resetPrototype(VM& vm, JSValue prototype)
1717 {
1718     if (getPrototypeDirect(vm) == prototype)
1719         return;
1720     setPrototypeDirect(vm, prototype);
1721     fixupPrototypeChainWithObjectPrototype(vm);
1722     // Whenever we change the prototype of the global object, we need to create a new JSProxy with the correct prototype.
1723     setGlobalThis(vm, JSNonDestructibleProxy::create(vm, JSNonDestructibleProxy::createStructure(vm, this, prototype, PureForwardingProxyType), this));
1724 }
1725
1726 void JSGlobalObject::visitChildren(JSCell* cell, SlotVisitor& visitor)
1727
1728     JSGlobalObject* thisObject = jsCast<JSGlobalObject*>(cell);
1729     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1730     Base::visitChildren(thisObject, visitor);
1731
1732     visitor.append(thisObject->m_globalThis);
1733
1734     visitor.append(thisObject->m_globalLexicalEnvironment);
1735     visitor.append(thisObject->m_globalScopeExtension);
1736     visitor.append(thisObject->m_globalCallee);
1737     visitor.append(thisObject->m_stackOverflowFrameCallee);
1738     thisObject->m_evalErrorStructure.visit(visitor);
1739     thisObject->m_rangeErrorStructure.visit(visitor);
1740     thisObject->m_referenceErrorStructure.visit(visitor);
1741     thisObject->m_syntaxErrorStructure.visit(visitor);
1742     thisObject->m_typeErrorStructure.visit(visitor);
1743     thisObject->m_URIErrorStructure.visit(visitor);
1744     visitor.append(thisObject->m_arrayConstructor);
1745     visitor.append(thisObject->m_regExpConstructor);
1746     visitor.append(thisObject->m_objectConstructor);
1747     visitor.append(thisObject->m_functionConstructor);
1748     visitor.append(thisObject->m_promiseConstructor);
1749     visitor.append(thisObject->m_internalPromiseConstructor);
1750
1751 #if ENABLE(INTL)
1752     thisObject->m_defaultCollator.visit(visitor);
1753     thisObject->m_collatorStructure.visit(visitor);
1754     thisObject->m_numberFormatStructure.visit(visitor);
1755     thisObject->m_dateTimeFormatStructure.visit(visitor);
1756     thisObject->m_pluralRulesStructure.visit(visitor);
1757 #endif
1758     visitor.append(thisObject->m_nullGetterFunction);
1759     visitor.append(thisObject->m_nullSetterFunction);
1760
1761     thisObject->m_parseIntFunction.visit(visitor);
1762     thisObject->m_parseFloatFunction.visit(visitor);
1763     thisObject->m_arrayProtoToStringFunction.visit(visitor);
1764     thisObject->m_arrayProtoValuesFunction.visit(visitor);
1765     thisObject->m_evalFunction.visit(visitor);
1766     thisObject->m_iteratorProtocolFunction.visit(visitor);
1767     thisObject->m_promiseResolveFunction.visit(visitor);
1768     visitor.append(thisObject->m_objectProtoValueOfFunction);
1769     visitor.append(thisObject->m_numberProtoToStringFunction);
1770     visitor.append(thisObject->m_functionProtoHasInstanceSymbolFunction);
1771     thisObject->m_throwTypeErrorGetterSetter.visit(visitor);
1772     visitor.append(thisObject->m_regExpProtoSymbolReplace);
1773     visitor.append(thisObject->m_throwTypeErrorArgumentsCalleeAndCallerGetterSetter);
1774     thisObject->m_moduleLoader.visit(visitor);
1775
1776     visitor.append(thisObject->m_objectPrototype);
1777     visitor.append(thisObject->m_functionPrototype);
1778     visitor.append(thisObject->m_arrayPrototype);
1779     visitor.append(thisObject->m_iteratorPrototype);
1780     visitor.append(thisObject->m_generatorFunctionPrototype);
1781     visitor.append(thisObject->m_generatorPrototype);
1782     visitor.append(thisObject->m_asyncFunctionPrototype);
1783     visitor.append(thisObject->m_asyncGeneratorPrototype);
1784     visitor.append(thisObject->m_asyncIteratorPrototype);
1785     visitor.append(thisObject->m_asyncGeneratorFunctionPrototype);
1786
1787     thisObject->m_debuggerScopeStructure.visit(visitor);
1788     thisObject->m_withScopeStructure.visit(visitor);
1789     thisObject->m_strictEvalActivationStructure.visit(visitor);
1790     visitor.append(thisObject->m_lexicalEnvironmentStructure);
1791     thisObject->m_moduleEnvironmentStructure.visit(visitor);
1792     visitor.append(thisObject->m_directArgumentsStructure);
1793     visitor.append(thisObject->m_scopedArgumentsStructure);
1794     visitor.append(thisObject->m_clonedArgumentsStructure);
1795     visitor.append(thisObject->m_objectStructureForObjectConstructor);
1796     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
1797         visitor.append(thisObject->m_originalArrayStructureForIndexingShape[i]);
1798     for (unsigned i = 0; i < NumberOfArrayIndexingModes; ++i)
1799         visitor.append(thisObject->m_arrayStructureForIndexingShapeDuringAllocation[i]);
1800     thisObject->m_callbackConstructorStructure.visit(visitor);
1801     thisObject->m_callbackFunctionStructure.visit(visitor);
1802     thisObject->m_callbackObjectStructure.visit(visitor);
1803 #if JSC_OBJC_API_ENABLED
1804     thisObject->m_objcCallbackFunctionStructure.visit(visitor);
1805     thisObject->m_objcWrapperObjectStructure.visit(visitor);
1806 #endif
1807 #ifdef JSC_GLIB_API_ENABLED
1808     thisObject->m_glibCallbackFunctionStructure.visit(visitor);
1809     thisObject->m_glibWrapperObjectStructure.visit(visitor);
1810 #endif
1811     visitor.append(thisObject->m_nullPrototypeObjectStructure);
1812     visitor.append(thisObject->m_calleeStructure);
1813
1814     visitor.append(thisObject->m_hostFunctionStructure);
1815     auto visitFunctionStructures = [&] (FunctionStructures& structures) {
1816         visitor.append(structures.arrowFunctionStructure);
1817         visitor.append(structures.sloppyFunctionStructure);
1818         visitor.append(structures.strictFunctionStructure);
1819     };
1820     visitFunctionStructures(thisObject->m_builtinFunctions);
1821     visitFunctionStructures(thisObject->m_ordinaryFunctions);
1822
1823     thisObject->m_customGetterSetterFunctionStructure.visit(visitor);
1824     thisObject->m_boundFunctionStructure.visit(visitor);
1825     thisObject->m_nativeStdFunctionStructure.visit(visitor);
1826     visitor.append(thisObject->m_regExpStructure);
1827     visitor.append(thisObject->m_generatorFunctionStructure);
1828     visitor.append(thisObject->m_asyncFunctionStructure);
1829     visitor.append(thisObject->m_asyncGeneratorFunctionStructure);
1830     visitor.append(thisObject->m_generatorStructure);
1831     visitor.append(thisObject->m_asyncGeneratorStructure);
1832     thisObject->m_iteratorResultObjectStructure.visit(visitor);
1833     visitor.append(thisObject->m_regExpMatchesArrayStructure);
1834     visitor.append(thisObject->m_regExpMatchesArrayWithGroupsStructure);
1835     thisObject->m_moduleRecordStructure.visit(visitor);
1836     thisObject->m_moduleNamespaceObjectStructure.visit(visitor);
1837     thisObject->m_proxyObjectStructure.visit(visitor);
1838     thisObject->m_callableProxyObjectStructure.visit(visitor);
1839     thisObject->m_proxyRevokeStructure.visit(visitor);
1840
1841     for (auto& property : thisObject->m_linkTimeConstants)
1842         property.visit(visitor);
1843     
1844 #if ENABLE(SHARED_ARRAY_BUFFER)
1845     visitor.append(thisObject->m_sharedArrayBufferPrototype);
1846     visitor.append(thisObject->m_sharedArrayBufferStructure);
1847 #endif
1848
1849 #define VISIT_SIMPLE_TYPE(CapitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) { \
1850         visitor.append(thisObject->m_ ## lowerName ## Prototype); \
1851         visitor.append(thisObject->m_ ## properName ## Structure); \
1852     }
1853
1854     FOR_EACH_SIMPLE_BUILTIN_TYPE(VISIT_SIMPLE_TYPE)
1855     FOR_EACH_BUILTIN_DERIVED_ITERATOR_TYPE(VISIT_SIMPLE_TYPE)
1856
1857 #define VISIT_LAZY_TYPE(CapitalName, lowerName, properName, instanceType, jsName, prototypeBase, featureFlag) if (featureFlag) \
1858         thisObject->m_ ## properName ## Structure.visit(visitor);
1859
1860     FOR_EACH_LAZY_BUILTIN_TYPE(VISIT_LAZY_TYPE)
1861
1862 #if ENABLE(WEBASSEMBLY)
1863     thisObject->m_webAssemblyModuleRecordStructure.visit(visitor);
1864     thisObject->m_webAssemblyFunctionStructure.visit(visitor);
1865     thisObject->m_jsToWasmICCalleeStructure.visit(visitor);
1866     thisObject->m_webAssemblyWrapperFunctionStructure.visit(visitor);
1867     thisObject->m_webAssemblyToJSCalleeStructure.visit(visitor);
1868     FOR_EACH_WEBASSEMBLY_CONSTRUCTOR_TYPE(VISIT_LAZY_TYPE)
1869 #endif // ENABLE(WEBASSEMBLY)
1870
1871 #undef VISIT_SIMPLE_TYPE
1872 #undef VISIT_LAZY_TYPE
1873
1874     for (unsigned i = NumberOfTypedArrayTypes; i--;)
1875         thisObject->lazyTypedArrayStructure(indexToTypedArrayType(i)).visit(visitor);
1876     
1877     visitor.append(thisObject->m_speciesGetterSetter);
1878     thisObject->m_typedArrayProto.visit(visitor);
1879     thisObject->m_typedArraySuperConstructor.visit(visitor);
1880     thisObject->m_regExpGlobalData.visitAggregate(visitor);
1881 }
1882
1883 CallFrame* JSGlobalObject::deprecatedCallFrameForDebugger()
1884 {
1885     return CallFrame::create(m_deprecatedCallFrameForDebugger);
1886 }
1887
1888 void JSGlobalObject::exposeDollarVM(VM& vm)
1889 {
1890     RELEASE_ASSERT(g_jscConfig.restrictedOptionsEnabled && Options::useDollarVM());
1891     if (hasOwnProperty(this, vm.propertyNames->builtinNames().dollarVMPrivateName()))
1892         return;
1893
1894     JSDollarVM* dollarVM = JSDollarVM::create(vm, JSDollarVM::createStructure(vm, this, m_objectPrototype.get()));
1895
1896     GlobalPropertyInfo extraStaticGlobals[] = {
1897         GlobalPropertyInfo(vm.propertyNames->builtinNames().dollarVMPrivateName(), dollarVM, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly),
1898     };
1899     addStaticGlobals(extraStaticGlobals, WTF_ARRAY_LENGTH(extraStaticGlobals));
1900
1901     putDirect(vm, Identifier::fromString(vm, "$vm"), dollarVM, static_cast<unsigned>(PropertyAttribute::DontEnum));
1902 }
1903
1904 void JSGlobalObject::addStaticGlobals(GlobalPropertyInfo* globals, int count)
1905 {
1906     ScopeOffset startOffset = addVariables(count, jsUndefined());
1907
1908     for (int i = 0; i < count; ++i) {
1909         GlobalPropertyInfo& global = globals[i];
1910         // This `configurable = false` is necessary condition for static globals,
1911         // otherwise lexical bindings can change the result of GlobalVar queries too.
1912         // We won't be able to declare a global lexical variable with the sanem name to
1913         // the static globals because configurable = false.
1914         ASSERT(global.attributes & PropertyAttribute::DontDelete);
1915         
1916         WatchpointSet* watchpointSet = nullptr;
1917         WriteBarrierBase<Unknown>* variable = nullptr;
1918         {
1919             ConcurrentJSLocker locker(symbolTable()->m_lock);
1920             ScopeOffset offset = symbolTable()->takeNextScopeOffset(locker);
1921             RELEASE_ASSERT(offset == startOffset + i);
1922             SymbolTableEntry newEntry(VarOffset(offset), global.attributes);
1923             newEntry.prepareToWatch();
1924             watchpointSet = newEntry.watchpointSet();
1925             symbolTable()->add(locker, global.identifier.impl(), WTFMove(newEntry));
1926             variable = &variableAt(offset);
1927         }
1928         symbolTablePutTouchWatchpointSet(vm(), this, global.identifier, global.value, variable, watchpointSet);
1929     }
1930 }
1931
1932 bool JSGlobalObject::getOwnPropertySlot(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, PropertySlot& slot)
1933 {
1934     if (Base::getOwnPropertySlot(object, globalObject, propertyName, slot))
1935         return true;
1936     return symbolTableGet(jsCast<JSGlobalObject*>(object), propertyName, slot);
1937 }
1938
1939 void JSGlobalObject::clearRareData(JSCell* cell)
1940 {
1941     jsCast<JSGlobalObject*>(cell)->m_rareData = nullptr;
1942 }
1943
1944 void JSGlobalObject::tryInstallArraySpeciesWatchpoint(JSGlobalObject* globalObject)
1945 {
1946     RELEASE_ASSERT(!m_arrayPrototypeConstructorWatchpoint);
1947     RELEASE_ASSERT(!m_arrayConstructorSpeciesWatchpoint);
1948
1949     VM& vm = globalObject->vm();
1950     auto scope = DECLARE_THROW_SCOPE(vm);
1951
1952     // First we need to make sure that the Array.prototype.constructor property points to Array
1953     // and that Array[Symbol.species] is the primordial GetterSetter.
1954     ArrayPrototype* arrayPrototype = this->arrayPrototype();
1955
1956     // We only initialize once so flattening the structures does not have any real cost.
1957     Structure* prototypeStructure = arrayPrototype->structure(vm);
1958     if (prototypeStructure->isDictionary())
1959         prototypeStructure = prototypeStructure->flattenDictionaryStructure(vm, arrayPrototype);
1960     RELEASE_ASSERT(!prototypeStructure->isDictionary());
1961
1962     ArrayConstructor* arrayConstructor = this->arrayConstructor();
1963
1964     auto invalidateWatchpoint = [&] {
1965         m_arraySpeciesWatchpointSet.invalidate(vm, StringFireDetail("Was not able to set up array species watchpoint."));
1966     };
1967
1968     PropertySlot constructorSlot(arrayPrototype, PropertySlot::InternalMethodType::VMInquiry);
1969     arrayPrototype->getOwnPropertySlot(arrayPrototype, globalObject, vm.propertyNames->constructor, constructorSlot);
1970     scope.assertNoException();
1971     if (constructorSlot.slotBase() != arrayPrototype
1972         || !constructorSlot.isCacheableValue()
1973         || constructorSlot.getValue(globalObject, vm.propertyNames->constructor) != arrayConstructor) {
1974         invalidateWatchpoint();
1975         return;
1976     }
1977
1978     Structure* constructorStructure = arrayConstructor->structure(vm);
1979     if (constructorStructure->isDictionary())
1980         constructorStructure = constructorStructure->flattenDictionaryStructure(vm, arrayConstructor);
1981
1982     PropertySlot speciesSlot(arrayConstructor, PropertySlot::InternalMethodType::VMInquiry);
1983     arrayConstructor->getOwnPropertySlot(arrayConstructor, globalObject, vm.propertyNames->speciesSymbol, speciesSlot);
1984     scope.assertNoException();
1985     if (speciesSlot.slotBase() != arrayConstructor
1986         || !speciesSlot.isCacheableGetter()
1987         || speciesSlot.getterSetter() != speciesGetterSetter()) {
1988         invalidateWatchpoint();
1989         return;
1990     }
1991
1992     // Now we need to setup the watchpoints to make sure these conditions remain valid.
1993     prototypeStructure->startWatchingPropertyForReplacements(vm, constructorSlot.cachedOffset());
1994     constructorStructure->startWatchingPropertyForReplacements(vm, speciesSlot.cachedOffset());
1995
1996     ObjectPropertyCondition constructorCondition = ObjectPropertyCondition::equivalence(vm, arrayPrototype, arrayPrototype, vm.propertyNames->constructor.impl(), arrayConstructor);
1997     ObjectPropertyCondition speciesCondition = ObjectPropertyCondition::equivalence(vm, arrayPrototype, arrayConstructor, vm.propertyNames->speciesSymbol.impl(), speciesGetterSetter());
1998
1999     if (!constructorCondition.isWatchable() || !speciesCondition.isWatchable()) {
2000         invalidateWatchpoint();
2001         return;
2002     }
2003
2004     // We only watch this from the DFG, and the DFG makes sure to only start watching if the watchpoint is in the IsWatched state.
2005     RELEASE_ASSERT(!m_arraySpeciesWatchpointSet.isBeingWatched());
2006     m_arraySpeciesWatchpointSet.touch(vm, "Set up array species watchpoint.");
2007
2008     m_arrayPrototypeConstructorWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, constructorCondition, m_arraySpeciesWatchpointSet);
2009     m_arrayPrototypeConstructorWatchpoint->install(vm);
2010
2011     m_arrayConstructorSpeciesWatchpoint = makeUnique<ObjectPropertyChangeAdaptiveWatchpoint<InlineWatchpointSet>>(this, speciesCondition, m_arraySpeciesWatchpointSet);
2012     m_arrayConstructorSpeciesWatchpoint->install(vm);
2013 }
2014
2015 void slowValidateCell(JSGlobalObject* globalObject)
2016 {
2017     RELEASE_ASSERT(globalObject->isGlobalObject());
2018     ASSERT_GC_OBJECT_INHERITS(globalObject, JSGlobalObject::info());
2019 }
2020
2021 void JSGlobalObject::setRemoteDebuggingEnabled(bool enabled)
2022 {
2023 #if ENABLE(REMOTE_INSPECTOR)
2024     m_inspectorDebuggable->setRemoteDebuggingAllowed(enabled);
2025 #else
2026     UNUSED_PARAM(enabled);
2027 #endif
2028 }
2029
2030 bool JSGlobalObject::remoteDebuggingEnabled() const
2031 {
2032 #if ENABLE(REMOTE_INSPECTOR)
2033     return m_inspectorDebuggable->remoteDebuggingAllowed();
2034 #else
2035     return false;
2036 #endif
2037 }
2038
2039 void JSGlobalObject::setName(const String& name)
2040 {
2041     m_name = name;
2042
2043 #if ENABLE(REMOTE_INSPECTOR)
2044     m_inspectorDebuggable->update();
2045 #endif
2046 }
2047
2048 # if ENABLE(INTL)
2049 static void addMissingScriptLocales(HashSet<String>& availableLocales)
2050 {
2051     if (availableLocales.contains("pa-Arab-PK"))
2052         availableLocales.add("pa-PK"_s);
2053     if (availableLocales.contains("zh-Hans-CN"))
2054         availableLocales.add("zh-CN"_s);
2055     if (availableLocales.contains("zh-Hant-HK"))
2056         availableLocales.add("zh-HK"_s);
2057     if (availableLocales.contains("zh-Hans-SG"))
2058         availableLocales.add("zh-SG"_s);
2059     if (availableLocales.contains("zh-Hant-TW"))
2060         availableLocales.add("zh-TW"_s);
2061 }
2062
2063 const HashSet<String>& JSGlobalObject::intlCollatorAvailableLocales()
2064 {
2065     if (m_intlCollatorAvailableLocales.isEmpty()) {
2066         int32_t count = ucol_countAvailable();
2067         for (int32_t i = 0; i < count; ++i) {
2068             String locale = convertICULocaleToBCP47LanguageTag(ucol_getAvailable(i));
2069             if (!locale.isEmpty())
2070                 m_intlCollatorAvailableLocales.add(locale);
2071         }
2072         addMissingScriptLocales(m_intlCollatorAvailableLocales);
2073     }
2074     return m_intlCollatorAvailableLocales;
2075 }
2076
2077 const HashSet<String>& JSGlobalObject::intlDateTimeFormatAvailableLocales()
2078 {
2079     if (m_intlDateTimeFormatAvailableLocales.isEmpty()) {
2080         int32_t count = udat_countAvailable();
2081         for (int32_t i = 0; i < count; ++i) {
2082             String locale = convertICULocaleToBCP47LanguageTag(udat_getAvailable(i));
2083             if (!locale.isEmpty())
2084                 m_intlDateTimeFormatAvailableLocales.add(locale);
2085         }
2086         addMissingScriptLocales(m_intlDateTimeFormatAvailableLocales);
2087     }
2088     return m_intlDateTimeFormatAvailableLocales;
2089 }
2090
2091 const HashSet<String>& JSGlobalObject::intlNumberFormatAvailableLocales()
2092 {
2093     if (m_intlNumberFormatAvailableLocales.isEmpty()) {
2094         int32_t count = unum_countAvailable();
2095         for (int32_t i = 0; i < count; ++i) {
2096             String locale = convertICULocaleToBCP47LanguageTag(unum_getAvailable(i));
2097             if (!locale.isEmpty())
2098                 m_intlNumberFormatAvailableLocales.add(locale);
2099         }
2100         addMissingScriptLocales(m_intlNumberFormatAvailableLocales);
2101     }
2102     return m_intlNumberFormatAvailableLocales;
2103 }
2104
2105 const HashSet<String>& JSGlobalObject::intlPluralRulesAvailableLocales()
2106 {
2107     if (m_intlPluralRulesAvailableLocales.isEmpty()) {
2108         int32_t count = uloc_countAvailable();
2109         for (int32_t i = 0; i < count; ++i) {
2110             String locale = convertICULocaleToBCP47LanguageTag(uloc_getAvailable(i));
2111             if (!locale.isEmpty())
2112                 m_intlPluralRulesAvailableLocales.add(locale);
2113         }
2114         addMissingScriptLocales(m_intlPluralRulesAvailableLocales);
2115     }
2116     return m_intlPluralRulesAvailableLocales;
2117 }
2118
2119 #endif // ENABLE(INTL)
2120
2121 void JSGlobalObject::bumpGlobalLexicalBindingEpoch(VM& vm)
2122 {
2123     if (++m_globalLexicalBindingEpoch == Options::thresholdForGlobalLexicalBindingEpoch()) {
2124         // Since the epoch overflows, we should rewrite all the CodeBlock to adjust to the newly started generation.
2125         m_globalLexicalBindingEpoch = 1;
2126         vm.heap.codeBlockSet().iterate([&] (CodeBlock* codeBlock) {
2127             if (codeBlock->globalObject() != this)
2128                 return;
2129             codeBlock->notifyLexicalBindingUpdate();
2130         });
2131     }
2132 }
2133
2134 void JSGlobalObject::queueMicrotask(Ref<Microtask>&& task)
2135 {
2136     if (globalObjectMethodTable()->queueTaskToEventLoop) {
2137         globalObjectMethodTable()->queueTaskToEventLoop(*this, WTFMove(task));
2138         return;
2139     }
2140
2141     vm().queueMicrotask(*this, WTFMove(task));
2142 }
2143
2144 void JSGlobalObject::setDebugger(Debugger* debugger)
2145 {
2146     m_debugger = debugger;
2147     if (debugger)
2148         vm().ensureShadowChicken();
2149 }
2150
2151 bool JSGlobalObject::hasDebugger() const
2152
2153     return m_debugger;
2154 }
2155
2156 bool JSGlobalObject::hasInteractiveDebugger() const 
2157
2158     return m_debugger && m_debugger->isInteractivelyDebugging();
2159 }
2160
2161 #if ENABLE(DFG_JIT)
2162 WatchpointSet* JSGlobalObject::getReferencedPropertyWatchpointSet(UniquedStringImpl* uid)
2163 {
2164     ConcurrentJSLocker locker(m_referencedGlobalPropertyWatchpointSetsLock);
2165     return m_referencedGlobalPropertyWatchpointSets.get(uid);
2166 }
2167
2168 WatchpointSet& JSGlobalObject::ensureReferencedPropertyWatchpointSet(UniquedStringImpl* uid)
2169 {
2170     ConcurrentJSLocker locker(m_referencedGlobalPropertyWatchpointSetsLock);
2171     return m_referencedGlobalPropertyWatchpointSets.ensure(uid, [] {
2172         return WatchpointSet::create(IsWatched);
2173     }).iterator->value.get();
2174 }
2175 #endif
2176
2177 JSGlobalObject* JSGlobalObject::create(VM& vm, Structure* structure)
2178 {
2179     JSGlobalObject* globalObject = new (NotNull, allocateCell<JSGlobalObject>(vm.heap)) JSGlobalObject(vm, structure);
2180     globalObject->finishCreation(vm);
2181     return globalObject;
2182 }
2183
2184 void JSGlobalObject::finishCreation(VM& vm)
2185 {
2186     Base::finishCreation(vm);
2187     structure(vm)->setGlobalObject(vm, this);
2188     m_runtimeFlags = m_globalObjectMethodTable->javaScriptRuntimeFlags(this);
2189     init(vm);
2190     setGlobalThis(vm, JSNonDestructibleProxy::create(vm, JSNonDestructibleProxy::createStructure(vm, this, getPrototypeDirect(vm), PureForwardingProxyType), this));
2191     ASSERT(type() == GlobalObjectType);
2192 }
2193
2194 void JSGlobalObject::finishCreation(VM& vm, JSObject* thisValue)
2195 {
2196     Base::finishCreation(vm);
2197     structure(vm)->setGlobalObject(vm, this);
2198     m_runtimeFlags = m_globalObjectMethodTable->javaScriptRuntimeFlags(this);
2199     init(vm);
2200     setGlobalThis(vm, thisValue);
2201     ASSERT(type() == GlobalObjectType);
2202 }
2203
2204 #ifdef JSC_GLIB_API_ENABLED
2205 void JSGlobalObject::setWrapperMap(std::unique_ptr<WrapperMap>&& map)
2206 {
2207     m_wrapperMap = WTFMove(map);
2208 }
2209 #endif
2210
2211 } // namespace JSC