Changeset 223002 in webkit


Ignore:
Timestamp:
Oct 6, 2017, 3:12:41 PM (8 years ago)
Author:
Ryan Haddad
Message:

Unreviewed, rolling out r222791 and r222873.
https://bugs.webkit.org/show_bug.cgi?id=178031

Caused crashes with workers/wasm LayoutTests (Requested by
ryanhaddad on #webkit).

Reverted changesets:

"WebAssembly: no VM / JS version of everything but Instance"
https://bugs.webkit.org/show_bug.cgi?id=177473
http://trac.webkit.org/changeset/222791

"WebAssembly: address no VM / JS follow-ups"
https://bugs.webkit.org/show_bug.cgi?id=177887
http://trac.webkit.org/changeset/222873

Patch by Commit Queue <commit-queue@webkit.org> on 2017-10-06

Location:
trunk
Files:
13 deleted
100 edited
2 moved

Legend:

Unmodified
Added
Removed
  • trunk/JSTests/ChangeLog

    r222901 r223002  
     12017-10-06  Commit Queue  <commit-queue@webkit.org>
     2
     3        Unreviewed, rolling out r222791 and r222873.
     4        https://bugs.webkit.org/show_bug.cgi?id=178031
     5
     6        Caused crashes with workers/wasm LayoutTests (Requested by
     7        ryanhaddad on #webkit).
     8
     9        Reverted changesets:
     10
     11        "WebAssembly: no VM / JS version of everything but Instance"
     12        https://bugs.webkit.org/show_bug.cgi?id=177473
     13        http://trac.webkit.org/changeset/222791
     14
     15        "WebAssembly: address no VM / JS follow-ups"
     16        https://bugs.webkit.org/show_bug.cgi?id=177887
     17        http://trac.webkit.org/changeset/222873
     18
    1192017-10-05  Saam Barati  <sbarati@apple.com>
    220
  • trunk/JSTests/wasm/js-api/memory-grow.js

    r222791 r223002  
    4646
    4747    // This shouldn't neuter the buffer since it fails.
    48     assertThrows(() => memory.grow(1000), RangeError, "WebAssembly.Memory.grow would exceed the memory's declared maximum size");
     48    assertThrows(() => memory.grow(1000), Error, "Out of memory");
    4949    assertEq(buffer.byteLength, 2*64*1024);
    5050    assertEq(memory.buffer, buffer);
  • trunk/JSTests/wasm/js-api/table.js

    r222791 r223002  
    167167         "WebAssembly.Module doesn't parse at byte 37 / 43: resizable limits has a initial page count of 4294967295 which is greater than its maximum 4294967294 (evaluating 'new WebAssembly.Module(builder.WebAssembly().get())')"],
    168168        [{initial: 2**31, element: "anyfunc"},
    169          "WebAssembly.Module doesn't parse at byte 24 / 27: Table's initial page count of 2147483648 is too big, maximum 10000000 (evaluating 'new WebAssembly.Module(builder.WebAssembly().get())')",
    170          "WebAssembly.Module doesn't parse at byte 32 / 38: Table's initial page count of 2147483648 is too big, maximum 10000000 (evaluating 'new WebAssembly.Module(builder.WebAssembly().get())')"],
     169         "WebAssembly.Module doesn't parse at byte 24 / 27: Table's initial page count of 2147483648 is invalid (evaluating 'new WebAssembly.Module(builder.WebAssembly().get())')",
     170         "WebAssembly.Module doesn't parse at byte 32 / 38: Table's initial page count of 2147483648 is invalid (evaluating 'new WebAssembly.Module(builder.WebAssembly().get())')"],
    171171    ];
    172172
  • trunk/Source/JavaScriptCore/ChangeLog

    r222981 r223002  
     12017-10-06  Commit Queue  <commit-queue@webkit.org>
     2
     3        Unreviewed, rolling out r222791 and r222873.
     4        https://bugs.webkit.org/show_bug.cgi?id=178031
     5
     6        Caused crashes with workers/wasm LayoutTests (Requested by
     7        ryanhaddad on #webkit).
     8
     9        Reverted changesets:
     10
     11        "WebAssembly: no VM / JS version of everything but Instance"
     12        https://bugs.webkit.org/show_bug.cgi?id=177473
     13        http://trac.webkit.org/changeset/222791
     14
     15        "WebAssembly: address no VM / JS follow-ups"
     16        https://bugs.webkit.org/show_bug.cgi?id=177887
     17        http://trac.webkit.org/changeset/222873
     18
    1192017-10-06  Robin Morisset  <rmorisset@apple.com>
    220
  • trunk/Source/JavaScriptCore/JavaScriptCore.xcodeproj/project.pbxproj

    r222954 r223002  
    10821082                79CFC6F01C33B10000C768EA /* LLIntPCRanges.h in Headers */ = {isa = PBXBuildFile; fileRef = 79CFC6EF1C33B10000C768EA /* LLIntPCRanges.h */; settings = {ATTRIBUTES = (Private, ); }; };
    10831083                79D5CD5B1C1106A900CECA07 /* SamplingProfiler.h in Headers */ = {isa = PBXBuildFile; fileRef = 79D5CD591C1106A900CECA07 /* SamplingProfiler.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1084                 79DAE27A1E03C82200B526AA /* WasmExceptionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 79DAE2791E03C82200B526AA /* WasmExceptionType.h */; settings = {ATTRIBUTES = (Private, ); }; };
     1084                79DAE27A1E03C82200B526AA /* WasmExceptionType.h in Headers */ = {isa = PBXBuildFile; fileRef = 79DAE2791E03C82200B526AA /* WasmExceptionType.h */; };
    10851085                79DFCBDB1D88C59600527D03 /* HasOwnPropertyCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 79DFCBDA1D88C59600527D03 /* HasOwnPropertyCache.h */; settings = {ATTRIBUTES = (Private, ); }; };
    10861086                79EE0C001B4AFB85000385C9 /* VariableEnvironment.h in Headers */ = {isa = PBXBuildFile; fileRef = 79EE0BFE1B4AFB85000385C9 /* VariableEnvironment.h */; settings = {ATTRIBUTES = (Private, ); }; };
     
    14601460                AD2FCC211DB59CB200B3E736 /* WebAssemblyTablePrototype.lut.h in Headers */ = {isa = PBXBuildFile; fileRef = AD2FCC151DB59C5900B3E736 /* WebAssemblyTablePrototype.lut.h */; };
    14611461                AD2FCC2D1DB838FD00B3E736 /* WebAssemblyPrototype.h in Headers */ = {isa = PBXBuildFile; fileRef = AD2FCC271DB838C400B3E736 /* WebAssemblyPrototype.h */; };
     1462                AD2FCC311DB83D4900B3E736 /* JSWebAssembly.h in Headers */ = {isa = PBXBuildFile; fileRef = AD2FCC2F1DB839F700B3E736 /* JSWebAssembly.h */; };
    14621463                AD412B341E7B2E9E008AF157 /* WasmContext.h in Headers */ = {isa = PBXBuildFile; fileRef = AD412B321E7B2E8A008AF157 /* WasmContext.h */; settings = {ATTRIBUTES = (Private, ); }; };
    14631464                AD4252511E5D0E14009D2A97 /* FullCodeOrigin.h in Headers */ = {isa = PBXBuildFile; fileRef = AD4252501E5D0DEB009D2A97 /* FullCodeOrigin.h */; };
     
    14671468                AD4B1DFA1DF244E20071AE32 /* WasmBinding.h in Headers */ = {isa = PBXBuildFile; fileRef = AD4B1DF81DF244D70071AE32 /* WasmBinding.h */; };
    14681469                AD5B416F1EBAFB77008EFA43 /* WasmName.h in Headers */ = {isa = PBXBuildFile; fileRef = AD5B416E1EBAFB65008EFA43 /* WasmName.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1469                 AD5C36DD1F688B65000BCAAF /* WasmEmbedder.h in Headers */ = {isa = PBXBuildFile; fileRef = AD5C36DC1F688B5F000BCAAF /* WasmEmbedder.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1470                 AD5C36E21F699EC0000BCAAF /* WasmInstance.h in Headers */ = {isa = PBXBuildFile; fileRef = AD5C36DF1F699EB6000BCAAF /* WasmInstance.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1471                 AD5C36E61F69EC91000BCAAF /* WasmTable.h in Headers */ = {isa = PBXBuildFile; fileRef = AD5C36E41F69EC8B000BCAAF /* WasmTable.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1472                 AD5C36EA1F75AD6A000BCAAF /* JSToWasm.h in Headers */ = {isa = PBXBuildFile; fileRef = AD8DD6CF1F67089F0004EB52 /* JSToWasm.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1473                 AD5C36EB1F75AD73000BCAAF /* JSWebAssembly.h in Headers */ = {isa = PBXBuildFile; fileRef = ADD09AF31F62482E001313C2 /* JSWebAssembly.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1474                 AD5C36EC1F75AD7C000BCAAF /* WasmToJS.h in Headers */ = {isa = PBXBuildFile; fileRef = ADD09AEE1F5F623F001313C2 /* WasmToJS.h */; settings = {ATTRIBUTES = (Private, ); }; };
    1475                 AD5C36EF1F7A263A000BCAAF /* WasmMemoryMode.h in Headers */ = {isa = PBXBuildFile; fileRef = AD5C36EE1F7A2629000BCAAF /* WasmMemoryMode.h */; settings = {ATTRIBUTES = (Private, ); }; };
    14761470                AD7438C01E0457A400FD0C2A /* WasmSignature.h in Headers */ = {isa = PBXBuildFile; fileRef = AD7438BF1E04579200FD0C2A /* WasmSignature.h */; settings = {ATTRIBUTES = (Private, ); }; };
    14771471                AD86A93E1AA4D88D002FE77F /* WeakGCMapInlines.h in Headers */ = {isa = PBXBuildFile; fileRef = AD86A93D1AA4D87C002FE77F /* WeakGCMapInlines.h */; settings = {ATTRIBUTES = (Private, ); }; };
     
    41654159                AD2FCC261DB838C400B3E736 /* WebAssemblyPrototype.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = WebAssemblyPrototype.cpp; path = js/WebAssemblyPrototype.cpp; sourceTree = "<group>"; };
    41664160                AD2FCC271DB838C400B3E736 /* WebAssemblyPrototype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = WebAssemblyPrototype.h; path = js/WebAssemblyPrototype.h; sourceTree = "<group>"; };
     4161                AD2FCC2E1DB839F700B3E736 /* JSWebAssembly.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSWebAssembly.cpp; sourceTree = "<group>"; };
     4162                AD2FCC2F1DB839F700B3E736 /* JSWebAssembly.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSWebAssembly.h; sourceTree = "<group>"; };
    41674163                AD2FCC321DC4045300B3E736 /* WasmFormat.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WasmFormat.cpp; sourceTree = "<group>"; };
    4168                 AD3F1E471F4BA78600669912 /* WABase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WABase.h; sourceTree = "<group>"; };
    4169                 AD3F1E4A1F4DE68C00669912 /* WAInstance.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAInstance.h; sourceTree = "<group>"; };
    4170                 AD3F1E4B1F4DE68C00669912 /* WATable.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WATable.h; sourceTree = "<group>"; };
    4171                 AD3F1E4C1F4DE68C00669912 /* WAMemory.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAMemory.h; sourceTree = "<group>"; };
    4172                 AD3F1E521F4F4AE500669912 /* WAMemory.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAMemory.cpp; sourceTree = "<group>"; };
    4173                 AD3F1E531F4F4AE500669912 /* WAModule.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAModule.cpp; sourceTree = "<group>"; };
    4174                 AD3F1E541F4F4AE500669912 /* WAInstance.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAInstance.cpp; sourceTree = "<group>"; };
    4175                 AD3F1E551F4F4AE500669912 /* WATable.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WATable.cpp; sourceTree = "<group>"; };
    4176                 AD3F1E641F50E57F00669912 /* WAException.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAException.h; sourceTree = "<group>"; };
    4177                 AD3F1E651F50E57F00669912 /* WAException.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAException.cpp; sourceTree = "<group>"; };
    4178                 AD3F1E681F547CB600669912 /* WAMemoryDescriptor.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAMemoryDescriptor.cpp; sourceTree = "<group>"; };
    4179                 AD3F1E691F547CB600669912 /* WAMemoryDescriptor.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAMemoryDescriptor.h; sourceTree = "<group>"; };
    4180                 AD3F1E6A1F547CB600669912 /* WAImportObject.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAImportObject.h; sourceTree = "<group>"; };
    4181                 AD3F1E6B1F547CB800669912 /* WATableDescriptor.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WATableDescriptor.h; sourceTree = "<group>"; };
    4182                 AD3F1E6C1F547CB800669912 /* WAImportObject.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAImportObject.cpp; sourceTree = "<group>"; };
    4183                 AD3F1E6D1F547CB800669912 /* WATableDescriptor.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WATableDescriptor.cpp; sourceTree = "<group>"; };
    4184                 AD3F1E701F54C3AA00669912 /* WAFunction.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAFunction.h; sourceTree = "<group>"; };
    4185                 AD3F1E711F54C3AA00669912 /* WAFunction.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WAFunction.cpp; sourceTree = "<group>"; };
    41864164                AD412B311E7B2E8A008AF157 /* WasmContext.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WasmContext.cpp; sourceTree = "<group>"; };
    41874165                AD412B321E7B2E8A008AF157 /* WasmContext.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WasmContext.h; sourceTree = "<group>"; };
     
    41984176                AD4B1DF81DF244D70071AE32 /* WasmBinding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WasmBinding.h; sourceTree = "<group>"; };
    41994177                AD5B416E1EBAFB65008EFA43 /* WasmName.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WasmName.h; sourceTree = "<group>"; };
    4200                 AD5C36DC1F688B5F000BCAAF /* WasmEmbedder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WasmEmbedder.h; sourceTree = "<group>"; };
    4201                 AD5C36DE1F699EB6000BCAAF /* WasmInstance.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WasmInstance.cpp; sourceTree = "<group>"; };
    4202                 AD5C36DF1F699EB6000BCAAF /* WasmInstance.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WasmInstance.h; sourceTree = "<group>"; };
    4203                 AD5C36E31F69EC8B000BCAAF /* WasmTable.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WasmTable.cpp; sourceTree = "<group>"; };
    4204                 AD5C36E41F69EC8B000BCAAF /* WasmTable.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WasmTable.h; sourceTree = "<group>"; };
    4205                 AD5C36EE1F7A2629000BCAAF /* WasmMemoryMode.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WasmMemoryMode.h; sourceTree = "<group>"; };
    4206                 AD5C36F01F7A26BF000BCAAF /* WasmMemoryMode.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = WasmMemoryMode.cpp; sourceTree = "<group>"; };
    42074178                AD7438BE1E04579200FD0C2A /* WasmSignature.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WasmSignature.cpp; sourceTree = "<group>"; };
    42084179                AD7438BF1E04579200FD0C2A /* WasmSignature.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WasmSignature.h; sourceTree = "<group>"; };
    42094180                AD86A93D1AA4D87C002FE77F /* WeakGCMapInlines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WeakGCMapInlines.h; sourceTree = "<group>"; };
    4210                 AD8DD6CF1F67089F0004EB52 /* JSToWasm.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = JSToWasm.h; path = js/JSToWasm.h; sourceTree = "<group>"; };
    4211                 AD8DD6D01F6708A30004EB52 /* JSToWasm.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = JSToWasm.cpp; path = js/JSToWasm.cpp; sourceTree = "<group>"; };
    42124181                AD8FF3951EB5BD850087FF82 /* WasmIndexOrName.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WasmIndexOrName.h; sourceTree = "<group>"; };
    42134182                AD8FF3961EB5BD850087FF82 /* WasmIndexOrName.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WasmIndexOrName.cpp; sourceTree = "<group>"; };
     
    42164185                ADBC54D21DF8EA00005BF738 /* WebAssemblyToJSCallee.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = WebAssemblyToJSCallee.cpp; path = js/WebAssemblyToJSCallee.cpp; sourceTree = "<group>"; };
    42174186                ADBC54D31DF8EA00005BF738 /* WebAssemblyToJSCallee.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = WebAssemblyToJSCallee.h; path = js/WebAssemblyToJSCallee.h; sourceTree = "<group>"; };
    4218                 ADD09AEE1F5F623F001313C2 /* WasmToJS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = WasmToJS.h; path = js/WasmToJS.h; sourceTree = "<group>"; };
    4219                 ADD09AEF1F5F623F001313C2 /* WasmToJS.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = WasmToJS.cpp; path = js/WasmToJS.cpp; sourceTree = "<group>"; };
    4220                 ADD09AF21F624829001313C2 /* JSWebAssembly.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; name = JSWebAssembly.cpp; path = js/JSWebAssembly.cpp; sourceTree = "<group>"; };
    4221                 ADD09AF31F62482E001313C2 /* JSWebAssembly.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = JSWebAssembly.h; path = js/JSWebAssembly.h; sourceTree = "<group>"; };
    42224187                ADD8FA431EB3077100DF542F /* WasmNameSectionParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WasmNameSectionParser.h; sourceTree = "<group>"; };
    42234188                ADD8FA441EB3077100DF542F /* WasmNameSectionParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WasmNameSectionParser.cpp; sourceTree = "<group>"; };
     
    42294194                ADE802971E08F1C90058DE78 /* WebAssemblyLinkErrorPrototype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = WebAssemblyLinkErrorPrototype.h; path = js/WebAssemblyLinkErrorPrototype.h; sourceTree = "<group>"; };
    42304195                ADE8029D1E08F2260058DE78 /* WebAssemblyLinkErrorConstructor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = WebAssemblyLinkErrorConstructor.cpp; path = js/WebAssemblyLinkErrorConstructor.cpp; sourceTree = "<group>"; };
    4231                 ADFC30F71F47A7B8006451D3 /* WebAssembly.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WebAssembly.h; sourceTree = "<group>"; };
    4232                 ADFC30F91F47A8C0006451D3 /* WAModule.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WAModule.h; sourceTree = "<group>"; };
    42334196                B59F89371891AD3300D5CCDC /* UnlinkedInstructionStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UnlinkedInstructionStream.h; sourceTree = "<group>"; };
    42344197                B59F89381891ADB500D5CCDC /* UnlinkedInstructionStream.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UnlinkedInstructionStream.cpp; sourceTree = "<group>"; };
     
    56845647                                E124A8F60E555775003091F1 /* OpaqueJSString.cpp */,
    56855648                                E124A8F50E555775003091F1 /* OpaqueJSString.h */,
    5686                                 AD3F1E471F4BA78600669912 /* WABase.h */,
    5687                                 AD3F1E651F50E57F00669912 /* WAException.cpp */,
    5688                                 AD3F1E641F50E57F00669912 /* WAException.h */,
    5689                                 AD3F1E711F54C3AA00669912 /* WAFunction.cpp */,
    5690                                 AD3F1E701F54C3AA00669912 /* WAFunction.h */,
    5691                                 AD3F1E6C1F547CB800669912 /* WAImportObject.cpp */,
    5692                                 AD3F1E6A1F547CB600669912 /* WAImportObject.h */,
    5693                                 AD3F1E541F4F4AE500669912 /* WAInstance.cpp */,
    5694                                 AD3F1E4A1F4DE68C00669912 /* WAInstance.h */,
    5695                                 AD3F1E521F4F4AE500669912 /* WAMemory.cpp */,
    5696                                 AD3F1E4C1F4DE68C00669912 /* WAMemory.h */,
    5697                                 AD3F1E681F547CB600669912 /* WAMemoryDescriptor.cpp */,
    5698                                 AD3F1E691F547CB600669912 /* WAMemoryDescriptor.h */,
    5699                                 AD3F1E531F4F4AE500669912 /* WAModule.cpp */,
    5700                                 ADFC30F91F47A8C0006451D3 /* WAModule.h */,
    5701                                 AD3F1E551F4F4AE500669912 /* WATable.cpp */,
    5702                                 AD3F1E4B1F4DE68C00669912 /* WATable.h */,
    5703                                 AD3F1E6D1F547CB800669912 /* WATableDescriptor.cpp */,
    5704                                 AD3F1E6B1F547CB800669912 /* WATableDescriptor.h */,
    5705                                 ADFC30F71F47A7B8006451D3 /* WebAssembly.h */,
    57065649                                5DE3D0F40DD8DDFB00468714 /* WebKitAvailability.h */,
    57075650                        );
     
    60636006                        children = (
    60646007                                AD2FCB8A1DB5840000B3E736 /* js */,
     6008                                AD2FCC2E1DB839F700B3E736 /* JSWebAssembly.cpp */,
     6009                                AD2FCC2F1DB839F700B3E736 /* JSWebAssembly.h */,
    60656010                                53F40E8E1D5902820099A1B6 /* WasmB3IRGenerator.cpp */,
    60666011                                53F40E921D5A4AB30099A1B6 /* WasmB3IRGenerator.h */,
     
    60786023                                AD412B311E7B2E8A008AF157 /* WasmContext.cpp */,
    60796024                                AD412B321E7B2E8A008AF157 /* WasmContext.h */,
    6080                                 AD5C36DC1F688B5F000BCAAF /* WasmEmbedder.h */,
    60816025                                79DAE2791E03C82200B526AA /* WasmExceptionType.h */,
    60826026                                5381B9361E60E9660090F794 /* WasmFaultSignalHandler.cpp */,
     
    60876031                                AD8FF3961EB5BD850087FF82 /* WasmIndexOrName.cpp */,
    60886032                                AD8FF3951EB5BD850087FF82 /* WasmIndexOrName.h */,
    6089                                 AD5C36DE1F699EB6000BCAAF /* WasmInstance.cpp */,
    6090                                 AD5C36DF1F699EB6000BCAAF /* WasmInstance.h */,
    60916033                                AD00659D1ECAC7FE000CA926 /* WasmLimits.h */,
    60926034                                53E9E0A91EAE83DE00FEE251 /* WasmMachineThreads.cpp */,
     
    60966038                                79B759711DFA4C600052174C /* WasmMemoryInformation.cpp */,
    60976039                                79B759721DFA4C600052174C /* WasmMemoryInformation.h */,
    6098                                 AD5C36F01F7A26BF000BCAAF /* WasmMemoryMode.cpp */,
    6099                                 AD5C36EE1F7A2629000BCAAF /* WasmMemoryMode.h */,
    61006040                                790081361E95A8EC0052D7CD /* WasmModule.cpp */,
    61016041                                790081371E95A8EC0052D7CD /* WasmModule.h */,
     
    61196059                                AD7438BE1E04579200FD0C2A /* WasmSignature.cpp */,
    61206060                                AD7438BF1E04579200FD0C2A /* WasmSignature.h */,
    6121                                 AD5C36E31F69EC8B000BCAAF /* WasmTable.cpp */,
    6122                                 AD5C36E41F69EC8B000BCAAF /* WasmTable.h */,
    61236061                                5250D2CF1E8DA05A0029A932 /* WasmThunks.cpp */,
    61246062                                5250D2D01E8DA05A0029A932 /* WasmThunks.h */,
     
    77267664                        isa = PBXGroup;
    77277665                        children = (
    7728                                 AD8DD6D01F6708A30004EB52 /* JSToWasm.cpp */,
    7729                                 AD8DD6CF1F67089F0004EB52 /* JSToWasm.h */,
    7730                                 ADD09AF21F624829001313C2 /* JSWebAssembly.cpp */,
    7731                                 ADD09AF31F62482E001313C2 /* JSWebAssembly.h */,
    77327666                                5383AA2F1E65E8A100A532FC /* JSWebAssemblyCodeBlock.cpp */,
    77337667                                AD9E852E1E8A0C6E008DE39E /* JSWebAssemblyCodeBlock.h */,
     
    77497683                                AD2FCBAE1DB58DA400B3E736 /* JSWebAssemblyTable.cpp */,
    77507684                                AD2FCBAF1DB58DA400B3E736 /* JSWebAssemblyTable.h */,
    7751                                 ADD09AEF1F5F623F001313C2 /* WasmToJS.cpp */,
    7752                                 ADD09AEE1F5F623F001313C2 /* WasmToJS.h */,
    77537685                                AD2FCBB01DB58DA400B3E736 /* WebAssemblyCompileErrorConstructor.cpp */,
    77547686                                AD2FCBB11DB58DA400B3E736 /* WebAssemblyCompileErrorConstructor.h */,
     
    80267958                                0FDF67D21D9C6D27001B9825 /* B3Kind.h in Headers */,
    80277959                                436E54531C468E7400B5AF73 /* B3LegalizeMemoryOffsets.h in Headers */,
    8028                                 AD5C36EC1F75AD7C000BCAAF /* WasmToJS.h in Headers */,
    80297960                                0F338E1E1BF286EA0013C88F /* B3LowerMacros.h in Headers */,
    80307961                                4319DA041C1BE40D001D260B /* B3LowerMacrosAfterOptimizations.h in Headers */,
     
    81178048                                6514F21918B3E1670098FF8B /* Bytecodes.h in Headers */,
    81188049                                0F885E111849A3BE00F1E3FA /* BytecodeUseDef.h in Headers */,
    8119                                 AD5C36EB1F75AD73000BCAAF /* JSWebAssembly.h in Headers */,
    81208050                                0F8023EA1613832B00A0BA45 /* ByValInfo.h in Headers */,
    81218051                                65B8392E1BACAD360044E824 /* CachedRecovery.h in Headers */,
     
    83238253                                DCEE220D1CEBAF75000C2396 /* DFGNullAbstractState.h in Headers */,
    83248254                                0F2B9CE719D0BA7D00B1D1B5 /* DFGObjectAllocationSinkingPhase.h in Headers */,
    8325                                 AD5C36DD1F688B65000BCAAF /* WasmEmbedder.h in Headers */,
    83268255                                0F2B9CE919D0BA7D00B1D1B5 /* DFGObjectMaterializationData.h in Headers */,
    83278256                                86EC9DD01328DF82002B2AD7 /* DFGOperations.h in Headers */,
     
    84348363                                0FB105861675481200F8AB6E /* ExitKind.h in Headers */,
    84358364                                0F0B83AB14BCF5BB00885B4F /* ExpressionRangeInfo.h in Headers */,
    8436                                 AD5C36EA1F75AD6A000BCAAF /* JSToWasm.h in Headers */,
    84378365                                0FEC3C571F33A45300F59B6C /* FastMallocAlignedMemoryAllocator.h in Headers */,
    84388366                                A7A8AF3817ADB5F3005AB174 /* Float32Array.h in Headers */,
    8439                                 AD5C36E21F699EC0000BCAAF /* WasmInstance.h in Headers */,
    84408367                                A7A8AF3917ADB5F3005AB174 /* Float64Array.h in Headers */,
    84418368                                0F24E54317EA9F5900ABB217 /* FPRInfo.h in Headers */,
     
    88398766                                0F0B286B1EB8E6CF000EB5D2 /* JSWeakPrivate.h in Headers */,
    88408767                                709FB8681AE335C60039D069 /* JSWeakSet.h in Headers */,
     8768                                AD2FCC311DB83D4900B3E736 /* JSWebAssembly.h in Headers */,
    88418769                                AD9E852F1E8A0C7C008DE39E /* JSWebAssemblyCodeBlock.h in Headers */,
    88428770                                79EFD4841EBC045C00F3DFEA /* JSWebAssemblyCodeBlockSubspace.h in Headers */,
     
    90318959                                0F7C39FB1C8F629300480151 /* RegExpInlines.h in Headers */,
    90328960                                A1712B4111C7B235007A5315 /* RegExpKey.h in Headers */,
    9033                                 AD5C36E61F69EC91000BCAAF /* WasmTable.h in Headers */,
    90348961                                BC18C45B0E16F5CD00B34460 /* RegExpObject.h in Headers */,
    90358962                                0F7C39FD1C8F659500480151 /* RegExpObjectInlines.h in Headers */,
     
    92019128                                0F426A491460CBB700131F8F /* VirtualRegister.h in Headers */,
    92029129                                0F1FB3931E177A7200A9BE50 /* VisitingTimeout.h in Headers */,
    9203                                 AD5C36EF1F7A263A000BCAAF /* WasmMemoryMode.h in Headers */,
    92049130                                0F952AA11DF7860900E06FBD /* VisitRaceKey.h in Headers */,
    92059131                                BC18C4200E16F5CD00B34460 /* VM.h in Headers */,
  • trunk/Source/JavaScriptCore/Sources.txt

    r222827 r223002  
    938938tools/VMInspector.cpp
    939939
     940wasm/JSWebAssembly.cpp
    940941wasm/WasmB3IRGenerator.cpp
    941942wasm/WasmBBQPlan.cpp
     
    945946wasm/WasmCodeBlock.cpp
    946947wasm/WasmContext.cpp
    947 wasm/WasmEmbedder.h
    948948wasm/WasmFaultSignalHandler.cpp
    949949wasm/WasmFormat.cpp
    950950wasm/WasmIndexOrName.cpp
    951 wasm/WasmInstance.cpp
    952 wasm/WasmInstance.h
    953951wasm/WasmMachineThreads.cpp
    954952wasm/WasmMemory.cpp
    955953wasm/WasmMemoryInformation.cpp
    956 wasm/WasmMemoryMode.cpp
    957954wasm/WasmModule.cpp
    958955wasm/WasmModuleInformation.cpp
     
    964961wasm/WasmPlan.cpp
    965962wasm/WasmSignature.cpp
    966 wasm/WasmTable.cpp
    967 wasm/WasmTable.h
    968963wasm/WasmThunks.cpp
    969964wasm/WasmValidate.cpp
    970965wasm/WasmWorklist.cpp
    971966
    972 wasm/js/JSToWasm.cpp
    973 wasm/js/JSToWasm.h
    974 wasm/js/JSWebAssembly.cpp
    975967wasm/js/JSWebAssemblyCodeBlock.cpp
    976968wasm/js/JSWebAssemblyCodeBlockSubspace.cpp
     
    982974wasm/js/JSWebAssemblyRuntimeError.cpp
    983975wasm/js/JSWebAssemblyTable.cpp
    984 wasm/js/WasmToJS.cpp
    985 wasm/js/WasmToJS.h
    986976wasm/js/WebAssemblyCompileErrorConstructor.cpp
    987977wasm/js/WebAssemblyCompileErrorPrototype.cpp
  • trunk/Source/JavaScriptCore/bytecode/PolymorphicAccess.cpp

    r222891 r223002  
    180180{
    181181    restoreScratch();
    182     jit->copyCalleeSavesToEntryFrameCalleeSavesBuffer(m_vm.topEntryFrame);
     182    jit->copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(m_vm);
    183183    if (needsToRestoreRegistersIfException()) {
    184184        // To the JIT that produces the original exception handling
  • trunk/Source/JavaScriptCore/debugger/Debugger.cpp

    r222791 r223002  
    11/*
    2  *  Copyright (C) 2008-2017 Apple Inc. All rights reserved.
     2 *  Copyright (C) 2008, 2013, 2014, 2016 Apple Inc. All rights reserved.
    33 *  Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
    44 *  Copyright (C) 2001 Peter Kelly (pmk@post.com)
     
    653653        return;
    654654
    655     EntryFrame* topEntryFrame = m_vm.topEntryFrame;
    656     m_pauseOnCallFrame = m_currentCallFrame ? m_currentCallFrame->callerFrame(topEntryFrame) : nullptr;
     655    VMEntryFrame* topVMEntryFrame = m_vm.topVMEntryFrame;
     656    m_pauseOnCallFrame = m_currentCallFrame ? m_currentCallFrame->callerFrame(topVMEntryFrame) : nullptr;
    657657    m_pauseOnStepOut = true;
    658658    setSteppingMode(SteppingModeEnabled);
     
    832832        return;
    833833
    834     EntryFrame* topEntryFrame = m_vm.topEntryFrame;
    835     CallFrame* callerFrame = m_currentCallFrame->callerFrame(topEntryFrame);
     834    VMEntryFrame* topVMEntryFrame = m_vm.topVMEntryFrame;
     835    CallFrame* callerFrame = m_currentCallFrame->callerFrame(topVMEntryFrame);
    836836
    837837    // Returning from a call, there was at least one expression on the statement we are returning to.
     
    857857        return;
    858858
    859     EntryFrame* topEntryFrame = m_vm.topEntryFrame;
    860     CallFrame* callerFrame = m_currentCallFrame->callerFrame(topEntryFrame);
     859    VMEntryFrame* topVMEntryFrame = m_vm.topVMEntryFrame;
     860    CallFrame* callerFrame = m_currentCallFrame->callerFrame(topVMEntryFrame);
    861861
    862862    // Treat stepping over an exception location like a step-out.
     
    887887        return;
    888888
    889     EntryFrame* topEntryFrame = m_vm.topEntryFrame;
    890     CallFrame* callerFrame = m_currentCallFrame->callerFrame(topEntryFrame);
     889    VMEntryFrame* topVMEntryFrame = m_vm.topVMEntryFrame;
     890    CallFrame* callerFrame = m_currentCallFrame->callerFrame(topVMEntryFrame);
    891891
    892892    // Returning from a program, could be eval(), there was at least one expression on the statement we are returning to.
  • trunk/Source/JavaScriptCore/dfg/DFGJITCompiler.cpp

    r222871 r223002  
    150150        m_exceptionChecksWithCallFrameRollback.link(this);
    151151
    152         copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     152        copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
    153153
    154154        // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
     
    170170        m_exceptionChecks.link(this);
    171171
    172         copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     172        copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
    173173
    174174        // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
  • trunk/Source/JavaScriptCore/dfg/DFGOSREntry.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2011-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2011, 2013-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    318318
    319319    unsigned registerCount = registerSaveLocations->size();
    320     VMEntryRecord* record = vmEntryRecord(vm->topEntryFrame);
     320    VMEntryRecord* record = vmEntryRecord(vm->topVMEntryFrame);
    321321    for (unsigned i = 0; i < registerCount; i++) {
    322322        RegisterAtOffset currentEntry = registerSaveLocations->at(i);
  • trunk/Source/JavaScriptCore/dfg/DFGOSRExit.cpp

    r222871 r223002  
    11/*
    2  * Copyright (C) 2011-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2011, 2013 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    10451045            // We are acting as a defacto op_catch because we arrive here from genericUnwind().
    10461046            // So, we must restore our call frame and stack pointer.
    1047             jit.restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(vm->topEntryFrame);
     1047            jit.restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(*vm);
    10481048            jit.loadPtr(vm->addressOfCallFrameForCatch(), GPRInfo::callFrameRegister);
    10491049        }
     
    13971397
    13981398    if (exit.isExceptionHandler())
    1399         jit.copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm.topEntryFrame);
     1399        jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(vm);
    14001400
    14011401    // Do all data format conversions and store the results into the stack.
  • trunk/Source/JavaScriptCore/dfg/DFGThunks.cpp

    r222871 r223002  
    144144
    145145    ok.link(&jit);
    146     jit.restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(vm->topEntryFrame);
     146    jit.restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(*vm);
    147147    jit.emitMaterializeTagCheckRegisters();
    148148
  • trunk/Source/JavaScriptCore/ftl/FTLCompile.cpp

    r222791 r223002  
    132132    // Emit the exception handler.
    133133    *state.exceptionHandler = jit.label();
    134     jit.copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm.topEntryFrame);
     134    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(vm);
    135135    jit.move(MacroAssembler::TrustedImmPtr(&vm), GPRInfo::argumentGPR0);
    136136    jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
  • trunk/Source/JavaScriptCore/ftl/FTLLink.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2013, 2014 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    144144
    145145            auto noException = jit.branch32(CCallHelpers::GreaterThanOrEqual, GPRInfo::returnValueGPR, CCallHelpers::TrustedImm32(0));
    146             jit.copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm.topEntryFrame);
     146            jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(vm);
    147147            jit.move(CCallHelpers::TrustedImmPtr(&vm), GPRInfo::argumentGPR0);
    148148            jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
  • trunk/Source/JavaScriptCore/ftl/FTLLowerDFGToB3.cpp

    r222827 r223002  
    265265                        MacroAssembler::TrustedImm32(callSiteIndex.bits()),
    266266                        CCallHelpers::tagFor(VirtualRegister(CallFrameSlot::argumentCount)));
    267                     jit.copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm->topEntryFrame);
     267                    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm);
    268268
    269269                    jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR0);
  • trunk/Source/JavaScriptCore/ftl/FTLOSRExitCompiler.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2013-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    187187    if (exit.isGenericUnwindHandler()) {
    188188        RELEASE_ASSERT(vm->callFrameForCatch); // The first time we hit this exit, like at all other times, this field should be non-null.
    189         jit.restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(vm->topEntryFrame);
     189        jit.restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(*vm);
    190190        jit.loadPtr(vm->addressOfCallFrameForCatch(), MacroAssembler::framePointerRegister);
    191191        jit.addPtr(CCallHelpers::TrustedImm32(codeBlock->stackPointerOffset() * sizeof(Register)),
     
    413413    RegisterSet vmCalleeSavesToSkip = RegisterSet::stackRegisters();
    414414    if (exit.isExceptionHandler()) {
    415         jit.loadPtr(&vm->topEntryFrame, GPRInfo::regT1);
    416         jit.addPtr(CCallHelpers::TrustedImm32(EntryFrame::calleeSaveRegistersBufferOffset()), GPRInfo::regT1);
     415        jit.loadPtr(&vm->topVMEntryFrame, GPRInfo::regT1);
     416        jit.addPtr(CCallHelpers::TrustedImm32(VMEntryFrame::calleeSaveRegistersBufferOffset()), GPRInfo::regT1);
    417417    }
    418418
  • trunk/Source/JavaScriptCore/interpreter/CallFrame.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2008-2017 Apple Inc. All Rights Reserved.
     2 * Copyright (C) 2008, 2013-2014, 2016 Apple Inc. All Rights Reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    3131#include "Interpreter.h"
    3232#include "JSCInlines.h"
    33 #include "JSWebAssemblyInstance.h"
    3433#include "VMEntryScope.h"
    3534#include "WasmContext.h"
     
    219218    if (!callee().isWasm())
    220219        return lexicalGlobalObject();
    221     return vm.wasmContext.load()->globalObject();
     220    return Wasm::loadContext(vm)->globalObject();
    222221#else
    223222    UNUSED_PARAM(vm);
     
    239238}
    240239
    241 CallFrame* CallFrame::callerFrame(EntryFrame*& currEntryFrame)
    242 {
    243     if (callerFrameOrEntryFrame() == currEntryFrame) {
    244         VMEntryRecord* currVMEntryRecord = vmEntryRecord(currEntryFrame);
    245         currEntryFrame = currVMEntryRecord->prevTopEntryFrame();
     240CallFrame* CallFrame::callerFrame(VMEntryFrame*& currVMEntryFrame)
     241{
     242    if (callerFrameOrVMEntryFrame() == currVMEntryFrame) {
     243        VMEntryRecord* currVMEntryRecord = vmEntryRecord(currVMEntryFrame);
     244        currVMEntryFrame = currVMEntryRecord->prevTopVMEntryFrame();
    246245        return currVMEntryRecord->prevTopCallFrame();
    247246    }
    248     return static_cast<CallFrame*>(callerFrameOrEntryFrame());
    249 }
    250 
    251 SUPPRESS_ASAN CallFrame* CallFrame::unsafeCallerFrame(EntryFrame*& currEntryFrame)
    252 {
    253     if (unsafeCallerFrameOrEntryFrame() == currEntryFrame) {
    254         VMEntryRecord* currVMEntryRecord = vmEntryRecord(currEntryFrame);
    255         currEntryFrame = currVMEntryRecord->unsafePrevTopEntryFrame();
     247    return static_cast<CallFrame*>(callerFrameOrVMEntryFrame());
     248}
     249
     250SUPPRESS_ASAN CallFrame* CallFrame::unsafeCallerFrame(VMEntryFrame*& currVMEntryFrame)
     251{
     252    if (unsafeCallerFrameOrVMEntryFrame() == currVMEntryFrame) {
     253        VMEntryRecord* currVMEntryRecord = vmEntryRecord(currVMEntryFrame);
     254        currVMEntryFrame = currVMEntryRecord->unsafePrevTopVMEntryFrame();
    256255        return currVMEntryRecord->unsafePrevTopCallFrame();
    257256    }
    258     return static_cast<CallFrame*>(unsafeCallerFrameOrEntryFrame());
     257    return static_cast<CallFrame*>(unsafeCallerFrameOrVMEntryFrame());
    259258}
    260259
  • trunk/Source/JavaScriptCore/interpreter/CallFrame.h

    r222791 r223002  
    142142        CallFrame& operator=(const Register& r) { *static_cast<Register*>(this) = r; return *this; }
    143143
    144         CallFrame* callerFrame() const { return static_cast<CallFrame*>(callerFrameOrEntryFrame()); }
    145         void* callerFrameOrEntryFrame() const { return callerFrameAndPC().callerFrame; }
    146         SUPPRESS_ASAN void* unsafeCallerFrameOrEntryFrame() const { return unsafeCallerFrameAndPC().callerFrame; }
    147 
    148         CallFrame* unsafeCallerFrame(EntryFrame*&);
    149         JS_EXPORT_PRIVATE CallFrame* callerFrame(EntryFrame*&);
     144        CallFrame* callerFrame() const { return static_cast<CallFrame*>(callerFrameOrVMEntryFrame()); }
     145        void* callerFrameOrVMEntryFrame() const { return callerFrameAndPC().callerFrame; }
     146        SUPPRESS_ASAN void* unsafeCallerFrameOrVMEntryFrame() const { return unsafeCallerFrameAndPC().callerFrame; }
     147
     148        CallFrame* unsafeCallerFrame(VMEntryFrame*&);
     149        JS_EXPORT_PRIVATE CallFrame* callerFrame(VMEntryFrame*&);
    150150
    151151        JS_EXPORT_PRIVATE SourceOrigin callerSourceOrigin();
  • trunk/Source/JavaScriptCore/interpreter/FrameTracers.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    3131namespace JSC {
    3232
    33 struct EntryFrame;
     33struct VMEntryFrame;
    3434
    3535class SuspendExceptionScope {
     
    7575        ASSERT(vm);
    7676        ASSERT(callFrame);
    77         ASSERT(reinterpret_cast<void*>(callFrame) < reinterpret_cast<void*>(vm->topEntryFrame));
     77        ASSERT(reinterpret_cast<void*>(callFrame) < reinterpret_cast<void*>(vm->topVMEntryFrame));
    7878        vm->topCallFrame = callFrame;
    7979    }
     
    8282class NativeCallFrameTracerWithRestore {
    8383public:
    84     ALWAYS_INLINE NativeCallFrameTracerWithRestore(VM* vm, EntryFrame* EntryFrame, CallFrame* callFrame)
     84    ALWAYS_INLINE NativeCallFrameTracerWithRestore(VM* vm, VMEntryFrame* vmEntryFrame, CallFrame* callFrame)
    8585        : m_vm(vm)
    8686    {
    8787        ASSERT(vm);
    8888        ASSERT(callFrame);
    89         m_savedTopEntryFrame = vm->topEntryFrame;
     89        m_savedTopVMEntryFrame = vm->topVMEntryFrame;
    9090        m_savedTopCallFrame = vm->topCallFrame;
    91         vm->topEntryFrame = EntryFrame;
     91        vm->topVMEntryFrame = vmEntryFrame;
    9292        vm->topCallFrame = callFrame;
    9393    }
     
    9595    ALWAYS_INLINE ~NativeCallFrameTracerWithRestore()
    9696    {
    97         m_vm->topEntryFrame = m_savedTopEntryFrame;
     97        m_vm->topVMEntryFrame = m_savedTopVMEntryFrame;
    9898        m_vm->topCallFrame = m_savedTopCallFrame;
    9999    }
     
    101101private:
    102102    VM* m_vm;
    103     EntryFrame* m_savedTopEntryFrame;
     103    VMEntryFrame* m_savedTopVMEntryFrame;
    104104    CallFrame* m_savedTopCallFrame;
    105105};
  • trunk/Source/JavaScriptCore/interpreter/Interpreter.cpp

    r222791 r223002  
    654654        notifyDebuggerOfUnwinding(m_vm, m_callFrame);
    655655
    656         copyCalleeSavesToEntryFrameCalleeSavesBuffer(visitor);
    657 
    658         bool shouldStopUnwinding = visitor->callerIsEntryFrame();
     656        copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(visitor);
     657
     658        bool shouldStopUnwinding = visitor->callerIsVMEntryFrame();
    659659        if (shouldStopUnwinding)
    660660            return StackVisitor::Done;
     
    664664
    665665private:
    666     void copyCalleeSavesToEntryFrameCalleeSavesBuffer(StackVisitor& visitor) const
     666    void copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(StackVisitor& visitor) const
    667667    {
    668668#if ENABLE(JIT) && NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
     
    677677
    678678        unsigned registerCount = currentCalleeSaves->size();
    679         VMEntryRecord* record = vmEntryRecord(m_vm.topEntryFrame);
     679        VMEntryRecord* record = vmEntryRecord(m_vm.topVMEntryFrame);
    680680        for (unsigned i = 0; i < registerCount; i++) {
    681681            RegisterAtOffset currentEntry = currentCalleeSaves->at(i);
     
    703703
    704704    if (unwindStart == UnwindFromCallerFrame) {
    705         if (callFrame->callerFrameOrEntryFrame() == vm.topEntryFrame)
     705        if (callFrame->callerFrameOrVMEntryFrame() == vm.topVMEntryFrame)
    706706            return nullptr;
    707707
  • trunk/Source/JavaScriptCore/interpreter/StackVisitor.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2013, 2015-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2013, 2015-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    4545    if (startFrame) {
    4646        ASSERT(vm);
    47         m_frame.m_entryFrame = vm->topEntryFrame;
     47        m_frame.m_VMEntryFrame = vm->topVMEntryFrame;
    4848        topFrame = vm->topCallFrame;
    4949       
    50         if (topFrame && static_cast<void*>(m_frame.m_entryFrame) == static_cast<void*>(topFrame)) {
    51             topFrame = vmEntryRecord(m_frame.m_entryFrame)->m_prevTopCallFrame;
    52             m_frame.m_entryFrame = vmEntryRecord(m_frame.m_entryFrame)->m_prevTopEntryFrame;
     50        if (topFrame && static_cast<void*>(m_frame.m_VMEntryFrame) == static_cast<void*>(topFrame)) {
     51            topFrame = vmEntryRecord(m_frame.m_VMEntryFrame)->m_prevTopCallFrame;
     52            m_frame.m_VMEntryFrame = vmEntryRecord(m_frame.m_VMEntryFrame)->m_prevTopVMEntryFrame;
    5353        }
    5454    } else {
    55         m_frame.m_entryFrame = 0;
     55        m_frame.m_VMEntryFrame = 0;
    5656        topFrame = 0;
    5757    }
    58     m_frame.m_callerIsEntryFrame = false;
     58    m_frame.m_callerIsVMEntryFrame = false;
    5959    readFrame(topFrame);
    6060
     
    7676                inlineCallFrame = m_frame.inlineCallFrame();
    7777            }
    78             m_frame.m_entryFrame = m_frame.m_callerEntryFrame;
     78            m_frame.m_VMEntryFrame = m_frame.m_CallerVMEntryFrame;
    7979            readFrame(m_frame.callerFrame());
    8080        } else
     
    8383    }
    8484#endif // ENABLE(DFG_JIT)
    85     m_frame.m_entryFrame = m_frame.m_callerEntryFrame;
     85    m_frame.m_VMEntryFrame = m_frame.m_CallerVMEntryFrame;
    8686    readFrame(m_frame.callerFrame());
    8787}
     
    153153    m_frame.m_callFrame = callFrame;
    154154    m_frame.m_argumentCountIncludingThis = callFrame->argumentCountIncludingThis();
    155     m_frame.m_callerEntryFrame = m_frame.m_entryFrame;
    156     m_frame.m_callerFrame = callFrame->callerFrame(m_frame.m_callerEntryFrame);
    157     m_frame.m_callerIsEntryFrame = m_frame.m_callerEntryFrame != m_frame.m_entryFrame;
     155    m_frame.m_CallerVMEntryFrame = m_frame.m_VMEntryFrame;
     156    m_frame.m_callerFrame = callFrame->callerFrame(m_frame.m_CallerVMEntryFrame);
     157    m_frame.m_callerIsVMEntryFrame = m_frame.m_CallerVMEntryFrame != m_frame.m_VMEntryFrame;
    158158    m_frame.m_isWasmFrame = false;
    159159
     
    501501            indent--;
    502502        }
    503         out.print(indent, "EntryFrame: ", RawPointer(m_entryFrame), "\n");
     503        out.print(indent, "vmEntryFrame: ", RawPointer(vmEntryFrame()), "\n");
    504504        indent--;
    505505    }
  • trunk/Source/JavaScriptCore/interpreter/StackVisitor.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2013, 2015-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    6363        size_t index() const { return m_index; }
    6464        size_t argumentCountIncludingThis() const { return m_argumentCountIncludingThis; }
    65         bool callerIsEntryFrame() const { return m_callerIsEntryFrame; }
     65        bool callerIsVMEntryFrame() const { return m_callerIsVMEntryFrame; }
    6666        CallFrame* callerFrame() const { return m_callerFrame; }
    6767        CalleeBits callee() const { return m_callee; }
     
    9898
    9999        ClonedArguments* createArguments();
     100        VMEntryFrame* vmEntryFrame() const { return m_VMEntryFrame; }
    100101        CallFrame* callFrame() const { return m_callFrame; }
    101102       
     
    114115#endif
    115116        CallFrame* m_callFrame;
    116         EntryFrame* m_entryFrame;
    117         EntryFrame* m_callerEntryFrame;
     117        VMEntryFrame* m_VMEntryFrame;
     118        VMEntryFrame* m_CallerVMEntryFrame;
    118119        CallFrame* m_callerFrame;
    119120        CalleeBits m_callee;
     
    123124        unsigned m_bytecodeOffset;
    124125        Wasm::IndexOrName m_wasmFunctionIndexOrName;
    125         bool m_callerIsEntryFrame : 1;
     126        bool m_callerIsVMEntryFrame : 1;
    126127        bool m_isWasmFrame : 1;
    127128
  • trunk/Source/JavaScriptCore/interpreter/VMEntryRecord.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2014-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2014, 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    3030namespace JSC {
    3131
    32 struct EntryFrame;
     32struct VMEntryFrame;
    3333class ExecState;
    3434class VM;
     
    4141    VM* m_vm;
    4242    ExecState* m_prevTopCallFrame;
    43     EntryFrame* m_prevTopEntryFrame;
     43    VMEntryFrame* m_prevTopVMEntryFrame;
    4444
    4545#if ENABLE(JIT) && NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
     
    5050    SUPPRESS_ASAN ExecState* unsafePrevTopCallFrame() { return m_prevTopCallFrame; }
    5151
    52     EntryFrame* prevTopEntryFrame() { return m_prevTopEntryFrame; }
    53     SUPPRESS_ASAN EntryFrame* unsafePrevTopEntryFrame() { return m_prevTopEntryFrame; }
     52    VMEntryFrame* prevTopVMEntryFrame() { return m_prevTopVMEntryFrame; }
     53    SUPPRESS_ASAN VMEntryFrame* unsafePrevTopVMEntryFrame() { return m_prevTopVMEntryFrame; }
    5454};
    5555
    56 extern "C" VMEntryRecord* vmEntryRecord(EntryFrame*);
     56extern "C" VMEntryRecord* vmEntryRecord(VMEntryFrame*);
    5757
    58 struct EntryFrame {
     58struct VMEntryFrame {
    5959#if ENABLE(JIT) && NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
    6060    static ptrdiff_t vmEntryRecordOffset()
    6161    {
    62         EntryFrame* fakeEntryFrame = reinterpret_cast<EntryFrame*>(0x1000);
    63         VMEntryRecord* record = vmEntryRecord(fakeEntryFrame);
     62        VMEntryFrame* fakeVMEntryFrame = reinterpret_cast<VMEntryFrame*>(0x1000);
     63        VMEntryRecord* record = vmEntryRecord(fakeVMEntryFrame);
    6464        return static_cast<ptrdiff_t>(
    65             reinterpret_cast<char*>(record) - reinterpret_cast<char*>(fakeEntryFrame));
     65            reinterpret_cast<char*>(record) - reinterpret_cast<char*>(fakeVMEntryFrame));
    6666    }
    6767
  • trunk/Source/JavaScriptCore/jit/AssemblyHelpers.cpp

    r222791 r223002  
    583583#endif
    584584
    585 void AssemblyHelpers::restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(EntryFrame*& topEntryFrame)
     585void AssemblyHelpers::restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(VM& vm)
    586586{
    587587#if NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
     
    606606    ASSERT(scratch != InvalidGPRReg);
    607607
    608     loadPtr(&topEntryFrame, scratch);
    609     addPtr(TrustedImm32(EntryFrame::calleeSaveRegistersBufferOffset()), scratch);
     608    loadPtr(&vm.topVMEntryFrame, scratch);
     609    addPtr(TrustedImm32(VMEntryFrame::calleeSaveRegistersBufferOffset()), scratch);
    610610
    611611    // Restore all callee saves except for the scratch.
     
    628628    loadPtr(Address(scratch, entry.offset()), scratch);
    629629#else
    630     UNUSED_PARAM(topEntryFrame);
     630    UNUSED_PARAM(vm);
    631631#endif
    632632}
     
    779779
    780780#if ENABLE(WEBASSEMBLY)
    781 void AssemblyHelpers::loadWasmContextInstance(GPRReg dst)
     781void AssemblyHelpers::loadWasmContext(GPRReg dst)
    782782{
    783783#if ENABLE(FAST_TLS_JIT)
    784     if (Wasm::Context::useFastTLS()) {
     784    if (Wasm::useFastTLSForContext()) {
    785785        loadFromTLSPtr(fastTLSOffsetForKey(WTF_WASM_CONTEXT_KEY), dst);
    786786        return;
    787787    }
    788788#endif
    789     move(Wasm::PinnedRegisterInfo::get().wasmContextInstancePointer, dst);
    790 }
    791 
    792 void AssemblyHelpers::storeWasmContextInstance(GPRReg src)
     789    move(Wasm::PinnedRegisterInfo::get().wasmContextPointer, dst);
     790}
     791
     792void AssemblyHelpers::storeWasmContext(GPRReg src)
    793793{
    794794#if ENABLE(FAST_TLS_JIT)
    795     if (Wasm::Context::useFastTLS()) {
     795    if (Wasm::useFastTLSForContext()) {
    796796        storeToTLSPtr(src, fastTLSOffsetForKey(WTF_WASM_CONTEXT_KEY));
    797797        return;
    798798    }
    799799#endif
    800     move(src, Wasm::PinnedRegisterInfo::get().wasmContextInstancePointer);
    801 }
    802 
    803 bool AssemblyHelpers::loadWasmContextInstanceNeedsMacroScratchRegister()
     800    move(src, Wasm::PinnedRegisterInfo::get().wasmContextPointer);
     801}
     802
     803bool AssemblyHelpers::loadWasmContextNeedsMacroScratchRegister()
    804804{
    805805#if ENABLE(FAST_TLS_JIT)
    806     if (Wasm::Context::useFastTLS())
     806    if (Wasm::useFastTLSForContext())
    807807        return loadFromTLSPtrNeedsMacroScratchRegister();
    808808#endif
     
    810810}
    811811
    812 bool AssemblyHelpers::storeWasmContextInstanceNeedsMacroScratchRegister()
     812bool AssemblyHelpers::storeWasmContextNeedsMacroScratchRegister()
    813813{
    814814#if ENABLE(FAST_TLS_JIT)
    815     if (Wasm::Context::useFastTLS())
     815    if (Wasm::useFastTLSForContext())
    816816        return storeToTLSPtrNeedsMacroScratchRegister();
    817817#endif
     
    876876}
    877877
    878 void AssemblyHelpers::copyCalleeSavesToEntryFrameCalleeSavesBufferImpl(GPRReg calleeSavesBuffer)
     878void AssemblyHelpers::copyCalleeSavesToVMEntryFrameCalleeSavesBufferImpl(GPRReg calleeSavesBuffer)
    879879{
    880880#if NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
    881     addPtr(TrustedImm32(EntryFrame::calleeSaveRegistersBufferOffset()), calleeSavesBuffer);
     881    addPtr(TrustedImm32(VMEntryFrame::calleeSaveRegistersBufferOffset()), calleeSavesBuffer);
    882882
    883883    RegisterAtOffsetList* allCalleeSaves = VM::getAllCalleeSaveRegisterOffsets();
  • trunk/Source/JavaScriptCore/jit/AssemblyHelpers.h

    r222791 r223002  
    361361    {
    362362#if NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
    363         loadPtr(Address(vmGPR, VM::topEntryFrameOffset()), vmGPR);
    364         copyCalleeSavesToEntryFrameCalleeSavesBufferImpl(vmGPR);
     363        loadPtr(Address(vmGPR, VM::topVMEntryFrameOffset()), vmGPR);
     364        copyCalleeSavesToVMEntryFrameCalleeSavesBufferImpl(vmGPR);
    365365#else
    366366        UNUSED_PARAM(vmGPR);
     
    368368    }
    369369
    370     void copyCalleeSavesToEntryFrameCalleeSavesBuffer(EntryFrame*& topEntryFrame, const TempRegisterSet& usedRegisters = { RegisterSet::stubUnavailableRegisters() })
     370    void copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(VM& vm, const TempRegisterSet& usedRegisters = { RegisterSet::stubUnavailableRegisters() })
    371371    {
    372372#if NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
    373373        GPRReg temp1 = usedRegisters.getFreeGPR(0);
    374         loadPtr(&topEntryFrame, temp1);
    375         copyCalleeSavesToEntryFrameCalleeSavesBufferImpl(temp1);
    376 #else
    377         UNUSED_PARAM(topEntryFrame);
     374        loadPtr(&vm.topVMEntryFrame, temp1);
     375        copyCalleeSavesToVMEntryFrameCalleeSavesBufferImpl(temp1);
     376#else
     377        UNUSED_PARAM(vm);
    378378        UNUSED_PARAM(usedRegisters);
    379379#endif
    380380    }
    381381
    382     void restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(EntryFrame*&);
    383 
    384     void copyCalleeSavesFromFrameOrRegisterToEntryFrameCalleeSavesBuffer(EntryFrame*& topEntryFrame, const TempRegisterSet& usedRegisters = { RegisterSet::stubUnavailableRegisters() })
     382    void restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(VM&);
     383
     384    void copyCalleeSavesFromFrameOrRegisterToVMEntryFrameCalleeSavesBuffer(VM& vm, const TempRegisterSet& usedRegisters = { RegisterSet::stubUnavailableRegisters() })
    385385    {
    386386#if NUMBER_OF_CALLEE_SAVES_REGISTERS > 0
     
    393393
    394394        // Copy saved calleeSaves on stack or unsaved calleeSaves in register to vm calleeSave buffer
    395         loadPtr(&topEntryFrame, temp1);
    396         addPtr(TrustedImm32(EntryFrame::calleeSaveRegistersBufferOffset()), temp1);
     395        loadPtr(&vm.topVMEntryFrame, temp1);
     396        addPtr(TrustedImm32(VMEntryFrame::calleeSaveRegistersBufferOffset()), temp1);
    397397
    398398        RegisterAtOffsetList* allCalleeSaves = VM::getAllCalleeSaveRegisterOffsets();
     
    402402
    403403        for (unsigned i = 0; i < registerCount; i++) {
    404             RegisterAtOffset entry = allCalleeSaves->at(i);
    405             if (dontCopyRegisters.get(entry.reg()))
     404            RegisterAtOffset vmEntry = allCalleeSaves->at(i);
     405            if (dontCopyRegisters.get(vmEntry.reg()))
    406406                continue;
    407             RegisterAtOffset* currentFrameEntry = currentCalleeSaves->find(entry.reg());
    408 
    409             if (entry.reg().isGPR()) {
     407            RegisterAtOffset* currentFrameEntry = currentCalleeSaves->find(vmEntry.reg());
     408
     409            if (vmEntry.reg().isGPR()) {
    410410                GPRReg regToStore;
    411411                if (currentFrameEntry) {
     
    415415                } else
    416416                    // Just store callee save directly
    417                     regToStore = entry.reg().gpr();
    418 
    419                 storePtr(regToStore, Address(temp1, entry.offset()));
     417                    regToStore = vmEntry.reg().gpr();
     418
     419                storePtr(regToStore, Address(temp1, vmEntry.offset()));
    420420            } else {
    421421                FPRReg fpRegToStore;
     
    426426                } else
    427427                    // Just store callee save directly
    428                     fpRegToStore = entry.reg().fpr();
    429 
    430                 storeDouble(fpRegToStore, Address(temp1, entry.offset()));
     428                    fpRegToStore = vmEntry.reg().fpr();
     429
     430                storeDouble(fpRegToStore, Address(temp1, vmEntry.offset()));
    431431            }
    432432        }
    433433#else
    434         UNUSED_PARAM(topEntryFrame);
     434        UNUSED_PARAM(vm);
    435435        UNUSED_PARAM(usedRegisters);
    436436#endif
     
    16451645
    16461646#if ENABLE(WEBASSEMBLY)
    1647     void loadWasmContextInstance(GPRReg dst);
    1648     void storeWasmContextInstance(GPRReg src);
    1649     static bool loadWasmContextInstanceNeedsMacroScratchRegister();
    1650     static bool storeWasmContextInstanceNeedsMacroScratchRegister();
     1647    void loadWasmContext(GPRReg dst);
     1648    void storeWasmContext(GPRReg src);
     1649    static bool loadWasmContextNeedsMacroScratchRegister();
     1650    static bool storeWasmContextNeedsMacroScratchRegister();
    16511651#endif
    16521652
    16531653protected:
    1654     void copyCalleeSavesToEntryFrameCalleeSavesBufferImpl(GPRReg calleeSavesBuffer);
     1654    void copyCalleeSavesToVMEntryFrameCalleeSavesBufferImpl(GPRReg calleeSavesBuffer);
    16551655
    16561656    CodeBlock* m_codeBlock;
  • trunk/Source/JavaScriptCore/jit/JIT.cpp

    r222791 r223002  
    112112    ASSERT(!m_bytecodeOffset);
    113113
    114     copyCalleeSavesFromFrameOrRegisterToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     114    copyCalleeSavesFromFrameOrRegisterToVMEntryFrameCalleeSavesBuffer(*vm());
    115115
    116116    callOperation(operationOptimize, m_bytecodeOffset);
     
    886886        m_exceptionChecksWithCallFrameRollback.link(this);
    887887
    888         copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     888        copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
    889889
    890890        // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
     
    906906        m_exceptionChecks.link(this);
    907907
    908         copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     908        copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
    909909
    910910        // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
  • trunk/Source/JavaScriptCore/jit/JITExceptions.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2012-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2012-2013, 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    5757    ExecState* shadowChickenTopFrame = callFrame;
    5858    if (unwindStart == UnwindFromCallerFrame) {
    59         EntryFrame* topEntryFrame = vm->topEntryFrame;
    60         shadowChickenTopFrame = callFrame->callerFrame(topEntryFrame);
     59        VMEntryFrame* topVMEntryFrame = vm->topVMEntryFrame;
     60        shadowChickenTopFrame = callFrame->callerFrame(topVMEntryFrame);
    6161    }
    6262    vm->shadowChicken().log(*vm, shadowChickenTopFrame, ShadowChicken::Packet::throwPacket());
     
    8585        catchRoutine = LLInt::getCodePtr(handleUncaughtException);
    8686   
    87     ASSERT(bitwise_cast<uintptr_t>(callFrame) < bitwise_cast<uintptr_t>(vm->topEntryFrame));
     87    ASSERT(bitwise_cast<uintptr_t>(callFrame) < bitwise_cast<uintptr_t>(vm->topVMEntryFrame));
    8888
    8989    vm->callFrameForCatch = callFrame;
  • trunk/Source/JavaScriptCore/jit/JITOpcodes.cpp

    r222827 r223002  
    461461{
    462462    ASSERT(regT0 == returnValueGPR);
    463     copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     463    copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
    464464    emitGetVirtualRegister(currentInstruction[1].u.operand, regT0);
    465465    callOperationNoExceptionCheck(operationThrow, regT0);
     
    540540void JIT::emit_op_catch(Instruction* currentInstruction)
    541541{
    542     restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     542    restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(*vm());
    543543
    544544    move(TrustedImmPtr(m_vm), regT3);
     
    958958        linkSlowCase(iter);
    959959
    960         copyCalleeSavesFromFrameOrRegisterToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     960        copyCalleeSavesFromFrameOrRegisterToVMEntryFrameCalleeSavesBuffer(*vm());
    961961
    962962        callOperation(operationOptimize, m_bytecodeOffset);
  • trunk/Source/JavaScriptCore/jit/JITOpcodes32_64.cpp

    r222827 r223002  
    11/*
    2  * Copyright (C) 2009-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2009, 2012-2016 Apple Inc. All rights reserved.
    33 * Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com>
    44 *
     
    771771{
    772772    ASSERT(regT0 == returnValueGPR);
    773     copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     773    copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
    774774    emitLoad(currentInstruction[1].u.operand, regT1, regT0);
    775775    callOperationNoExceptionCheck(operationThrow, regT1, regT0);
     
    832832void JIT::emit_op_catch(Instruction* currentInstruction)
    833833{
    834     restoreCalleeSavesFromEntryFrameCalleeSavesBuffer(vm()->topEntryFrame);
     834    restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(*vm());
    835835
    836836    move(TrustedImmPtr(m_vm), regT3);
  • trunk/Source/JavaScriptCore/jit/JITOperations.cpp

    r222791 r223002  
    104104    auto scope = DECLARE_THROW_SCOPE(*vm);
    105105
    106     EntryFrame* entryFrame = vm->topEntryFrame;
    107     CallFrame* callerFrame = exec->callerFrame(entryFrame);
     106    VMEntryFrame* vmEntryFrame = vm->topVMEntryFrame;
     107    CallFrame* callerFrame = exec->callerFrame(vmEntryFrame);
    108108    if (!callerFrame) {
    109109        callerFrame = exec;
    110         entryFrame = vm->topEntryFrame;
    111     }
    112 
    113     NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
     110        vmEntryFrame = vm->topVMEntryFrame;
     111    }
     112
     113    NativeCallFrameTracerWithRestore tracer(vm, vmEntryFrame, callerFrame);
    114114    throwStackOverflowError(callerFrame, scope);
    115115}
     
    121121    auto scope = DECLARE_THROW_SCOPE(*vm);
    122122
    123     EntryFrame* entryFrame = vm->topEntryFrame;
    124     CallFrame* callerFrame = exec->callerFrame(entryFrame);
    125 
    126     NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
     123    VMEntryFrame* vmEntryFrame = vm->topVMEntryFrame;
     124    CallFrame* callerFrame = exec->callerFrame(vmEntryFrame);
     125
     126    NativeCallFrameTracerWithRestore tracer(vm, vmEntryFrame, callerFrame);
    127127    ErrorHandlingScope errorScope(*vm);
    128128    throwException(callerFrame, scope, createError(callerFrame, ASCIILiteral("Division by zero or division overflow.")));
     
    134134    auto scope = DECLARE_THROW_SCOPE(*vm);
    135135
    136     EntryFrame* entryFrame = vm->topEntryFrame;
    137     CallFrame* callerFrame = exec->callerFrame(entryFrame);
    138 
    139     NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
     136    VMEntryFrame* vmEntryFrame = vm->topVMEntryFrame;
     137    CallFrame* callerFrame = exec->callerFrame(vmEntryFrame);
     138
     139    NativeCallFrameTracerWithRestore tracer(vm, vmEntryFrame, callerFrame);
    140140    ErrorHandlingScope errorScope(*vm);
    141141    throwException(callerFrame, scope, createError(callerFrame, ASCIILiteral("Out-of-bounds access.")));
     
    150150    int32_t missingArgCount = CommonSlowPaths::arityCheckFor(exec, *vm, CodeForCall);
    151151    if (missingArgCount < 0) {
    152         EntryFrame* entryFrame = vm->topEntryFrame;
    153         CallFrame* callerFrame = exec->callerFrame(entryFrame);
    154         NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
     152        VMEntryFrame* vmEntryFrame = vm->topVMEntryFrame;
     153        CallFrame* callerFrame = exec->callerFrame(vmEntryFrame);
     154        NativeCallFrameTracerWithRestore tracer(vm, vmEntryFrame, callerFrame);
    155155        throwStackOverflowError(callerFrame, scope);
    156156    }
     
    166166    int32_t missingArgCount = CommonSlowPaths::arityCheckFor(exec, *vm, CodeForConstruct);
    167167    if (missingArgCount < 0) {
    168         EntryFrame* entryFrame = vm->topEntryFrame;
    169         CallFrame* callerFrame = exec->callerFrame(entryFrame);
    170         NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
     168        VMEntryFrame* vmEntryFrame = vm->topVMEntryFrame;
     169        CallFrame* callerFrame = exec->callerFrame(vmEntryFrame);
     170        NativeCallFrameTracerWithRestore tracer(vm, vmEntryFrame, callerFrame);
    171171        throwStackOverflowError(callerFrame, scope);
    172172    }
  • trunk/Source/JavaScriptCore/jit/ThunkGenerators.cpp

    r222791 r223002  
    6767    jit.preserveReturnAddressAfterCall(GPRInfo::nonPreservedNonReturnGPR);
    6868
    69     jit.copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm->topEntryFrame);
     69    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm);
    7070
    7171    jit.setupArguments(CCallHelpers::TrustedImmPtr(vm), GPRInfo::callFrameRegister);
     
    363363    exceptionHandler.link(&jit);
    364364
    365     jit.copyCalleeSavesToEntryFrameCalleeSavesBuffer(vm->topEntryFrame);
     365    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm);
    366366    jit.storePtr(JSInterfaceJIT::callFrameRegister, &vm->topCallFrame);
    367367
  • trunk/Source/JavaScriptCore/jsc.cpp

    r222895 r223002  
    20602060{
    20612061    VM& vm = exec->vm();
    2062     EntryFrame* topEntryFrame = vm.topEntryFrame;
    2063     ExecState* callerFrame = exec->callerFrame(topEntryFrame);
     2062    VMEntryFrame* topVMEntryFrame = vm.topVMEntryFrame;
     2063    ExecState* callerFrame = exec->callerFrame(topVMEntryFrame);
    20642064    if (callerFrame)
    20652065        vm.interpreter->dumpCallFrame(callerFrame);
  • trunk/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp

    r222827 r223002  
    482482    auto throwScope = DECLARE_THROW_SCOPE(vm);
    483483
    484     EntryFrame* topEntryFrame = vm.topEntryFrame;
    485     CallFrame* callerFrame = exec->callerFrame(topEntryFrame);
     484    VMEntryFrame* vmEntryFrame = vm.topVMEntryFrame;
     485    CallFrame* callerFrame = exec->callerFrame(vmEntryFrame);
    486486    if (!callerFrame) {
    487487        callerFrame = exec;
    488         topEntryFrame = vm.topEntryFrame;
    489     }
    490     NativeCallFrameTracerWithRestore tracer(&vm, topEntryFrame, callerFrame);
     488        vmEntryFrame = vm.topVMEntryFrame;
     489    }
     490    NativeCallFrameTracerWithRestore tracer(&vm, vmEntryFrame, callerFrame);
    491491
    492492    LLINT_SET_PC_FOR_STUBS();
  • trunk/Source/JavaScriptCore/llint/LLIntThunks.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2012-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2012-2013, 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    117117}
    118118
    119 extern "C" VMEntryRecord* vmEntryRecord(EntryFrame* entryFrame)
     119extern "C" VMEntryRecord* vmEntryRecord(VMEntryFrame* entryFrame)
    120120{
    121121    // The C Loop doesn't have any callee save registers, so the VMEntryRecord is allocated at the base of the frame.
  • trunk/Source/JavaScriptCore/llint/LowLevelInterpreter.asm

    r222791 r223002  
    660660macro copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(vm, temp)
    661661    if ARM64 or X86_64 or X86_64_WIN
    662         loadp VM::topEntryFrame[vm], temp
     662        loadp VM::topVMEntryFrame[vm], temp
    663663        vmEntryRecord(temp, temp)
    664664        leap VMEntryRecord::calleeSaveRegistersBuffer[temp], temp
     
    702702macro restoreCalleeSavesFromVMEntryFrameCalleeSavesBuffer(vm, temp)
    703703    if ARM64 or X86_64 or X86_64_WIN
    704         loadp VM::topEntryFrame[vm], temp
     704        loadp VM::topVMEntryFrame[vm], temp
    705705        vmEntryRecord(temp, temp)
    706706        leap VMEntryRecord::calleeSaveRegistersBuffer[temp], temp
     
    11451145        ret
    11461146   
    1147     # VMEntryRecord* vmEntryRecord(const EntryFrame* entryFrame)
     1147    # VMEntryRecord* vmEntryRecord(const VMEntryFrame* entryFrame)
    11481148    global _vmEntryRecord
    11491149    _vmEntryRecord:
  • trunk/Source/JavaScriptCore/llint/LowLevelInterpreter32_64.asm

    r222791 r223002  
    126126    loadp VM::topCallFrame[vm], t4
    127127    storep t4, VMEntryRecord::m_prevTopCallFrame[sp]
    128     loadp VM::topEntryFrame[vm], t4
    129     storep t4, VMEntryRecord::m_prevTopEntryFrame[sp]
     128    loadp VM::topVMEntryFrame[vm], t4
     129    storep t4, VMEntryRecord::m_prevTopVMEntryFrame[sp]
    130130
    131131    # Align stack pointer
     
    190190    loadp VMEntryRecord::m_prevTopCallFrame[sp], t4
    191191    storep t4, VM::topCallFrame[t5]
    192     loadp VMEntryRecord::m_prevTopEntryFrame[sp], t4
    193     storep t4, VM::topEntryFrame[t5]
     192    loadp VMEntryRecord::m_prevTopVMEntryFrame[sp], t4
     193    storep t4, VM::topVMEntryFrame[t5]
    194194
    195195    if ARMv7
     
    242242.copyArgsDone:
    243243    storep sp, VM::topCallFrame[vm]
    244     storep cfr, VM::topEntryFrame[vm]
     244    storep cfr, VM::topVMEntryFrame[vm]
    245245
    246246    makeCall(entry, t3, t4)
     
    256256    loadp VMEntryRecord::m_prevTopCallFrame[sp], t4
    257257    storep t4, VM::topCallFrame[t5]
    258     loadp VMEntryRecord::m_prevTopEntryFrame[sp], t4
    259     storep t4, VM::topEntryFrame[t5]
     258    loadp VMEntryRecord::m_prevTopVMEntryFrame[sp], t4
     259    storep t4, VM::topVMEntryFrame[t5]
    260260
    261261    if ARMv7
     
    325325    loadp VMEntryRecord::m_prevTopCallFrame[sp], t5
    326326    storep t5, VM::topCallFrame[t3]
    327     loadp VMEntryRecord::m_prevTopEntryFrame[sp], t5
    328     storep t5, VM::topEntryFrame[t3]
     327    loadp VMEntryRecord::m_prevTopVMEntryFrame[sp], t5
     328    storep t5, VM::topVMEntryFrame[t3]
    329329
    330330    if ARMv7
  • trunk/Source/JavaScriptCore/llint/LowLevelInterpreter64.asm

    r222791 r223002  
    130130    loadp VM::topCallFrame[vm], t4
    131131    storep t4, VMEntryRecord::m_prevTopCallFrame[sp]
    132     loadp VM::topEntryFrame[vm], t4
    133     storep t4, VMEntryRecord::m_prevTopEntryFrame[sp]
     132    loadp VM::topVMEntryFrame[vm], t4
     133    storep t4, VMEntryRecord::m_prevTopVMEntryFrame[sp]
    134134
    135135    loadi ProtoCallFrame::paddedArgCount[protoCallFrame], t4
     
    172172    loadp VMEntryRecord::m_prevTopCallFrame[t4], extraTempReg
    173173    storep extraTempReg, VM::topCallFrame[vm]
    174     loadp VMEntryRecord::m_prevTopEntryFrame[t4], extraTempReg
    175     storep extraTempReg, VM::topEntryFrame[vm]
     174    loadp VMEntryRecord::m_prevTopVMEntryFrame[t4], extraTempReg
     175    storep extraTempReg, VM::topVMEntryFrame[vm]
    176176
    177177    subp cfr, CalleeRegisterSaveSize, sp
     
    221221        storep sp, VM::topCallFrame[vm]
    222222    end
    223     storep cfr, VM::topEntryFrame[vm]
     223    storep cfr, VM::topVMEntryFrame[vm]
    224224
    225225    checkStackPointerAlignment(extraTempReg, 0xbad0dc02)
     
    237237    loadp VMEntryRecord::m_prevTopCallFrame[t4], t2
    238238    storep t2, VM::topCallFrame[vm]
    239     loadp VMEntryRecord::m_prevTopEntryFrame[t4], t2
    240     storep t2, VM::topEntryFrame[vm]
     239    loadp VMEntryRecord::m_prevTopVMEntryFrame[t4], t2
     240    storep t2, VM::topVMEntryFrame[vm]
    241241
    242242    subp cfr, CalleeRegisterSaveSize, sp
     
    277277end
    278278
     279
    279280_handleUncaughtException:
    280281    loadp Callee[cfr], t3
     
    291292    loadp VMEntryRecord::m_prevTopCallFrame[t2], extraTempReg
    292293    storep extraTempReg, VM::topCallFrame[t3]
    293     loadp VMEntryRecord::m_prevTopEntryFrame[t2], extraTempReg
    294     storep extraTempReg, VM::topEntryFrame[t3]
     294    loadp VMEntryRecord::m_prevTopVMEntryFrame[t2], extraTempReg
     295    storep extraTempReg, VM::topVMEntryFrame[t3]
    295296
    296297    subp cfr, CalleeRegisterSaveSize, sp
  • trunk/Source/JavaScriptCore/runtime/Options.cpp

    r222925 r223002  
    407407
    408408    if (!Options::useWebAssembly())
    409         Options::useFastTLSForWasmContext() = false;
     409        Options::useWebAssemblyFastTLS() = false;
    410410   
    411411    if (Options::dumpDisassembly()
  • trunk/Source/JavaScriptCore/runtime/Options.h

    r222871 r223002  
    469469    v(bool, crashIfWebAssemblyCantFastMemory, false, Normal, "If true, we will crash if we can't obtain fast memory for wasm.") \
    470470    v(unsigned, maxNumWebAssemblyFastMemories, 4, Normal, nullptr) \
    471     v(bool, useFastTLSForWasmContext, true, Normal, "If true, we will store context in fast TLS. If false, we will pin it to a register.") \
     471    v(bool, useWebAssemblyFastTLS, true, Normal, "If true, we will try to use fast thread-local storage if available on the current platform.") \
     472    v(bool, useFastTLSForWasmContext, true, Normal, "If true (and fast TLS is enabled), we will store context in fast TLS. If false, we will pin it to a register.") \
    472473    v(bool, useCallICsForWebAssemblyToJSCalls, true, Normal, "If true, we will use CallLinkInfo to inline cache Wasm to JS calls.") \
    473474    v(bool, useObjectRestSpread, true, Normal, "If true, we will enable Object Rest/Spread feature.") \
  • trunk/Source/JavaScriptCore/runtime/SamplingProfiler.cpp

    r222791 r223002  
    8484        : m_vm(vm)
    8585        , m_callFrame(callFrame)
    86         , m_entryFrame(vm.topEntryFrame)
     86        , m_vmEntryFrame(vm.topVMEntryFrame)
    8787        , m_codeBlockSetLocker(codeBlockSetLocker)
    8888        , m_machineThreadsLocker(machineThreadsLocker)
     
    131131    void advanceToParentFrame()
    132132    {
    133         m_callFrame = m_callFrame->unsafeCallerFrame(m_entryFrame);
     133        m_callFrame = m_callFrame->unsafeCallerFrame(m_vmEntryFrame);
    134134    }
    135135
     
    189189    VM& m_vm;
    190190    ExecState* m_callFrame;
    191     EntryFrame* m_entryFrame;
     191    VMEntryFrame* m_vmEntryFrame;
    192192    const AbstractLocker& m_codeBlockSetLocker;
    193193    const AbstractLocker& m_machineThreadsLocker;
     
    578578                // This might also be false for various reasons (known and unknown), even though
    579579                // it's super unlikely. One reason that this can be false is when we throw from a DFG frame,
    580                 // and we end up having to unwind past an EntryFrame, we will end up executing
     580                // and we end up having to unwind past a VMEntryFrame, we will end up executing
    581581                // inside the LLInt's handleUncaughtException. So we just protect against this
    582582                // by ignoring it.
  • trunk/Source/JavaScriptCore/runtime/ThrowScope.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    5858    bool willBeHandleByLLIntOrJIT = false;
    5959    void* previousScope = m_previousScope;
    60     void* topEntryFrame = m_vm.topEntryFrame;
     60    void* topVMEntryFrame = m_vm.topVMEntryFrame;
    6161
    62     // If the topEntryFrame was pushed on the stack after the previousScope was instantiated,
     62    // If the topVMEntryFrame was pushed on the stack after the previousScope was instantiated,
    6363    // then this throwScope will be returning to LLINT or JIT code that always do an exception
    6464    // check. In that case, skip the simulated throw because the LLInt and JIT will be
    6565    // checking for the exception their own way instead of calling ThrowScope::exception().
    66     if (topEntryFrame && previousScope > topEntryFrame)
     66    if (topVMEntryFrame && previousScope > topVMEntryFrame)
    6767        willBeHandleByLLIntOrJIT = true;
    6868   
  • trunk/Source/JavaScriptCore/runtime/VM.cpp

    r222791 r223002  
    185185    , vmType(vmType)
    186186    , clientData(0)
    187     , topEntryFrame(nullptr)
     187    , topVMEntryFrame(nullptr)
    188188    , topCallFrame(CallFrame::noCaller())
    189189    , promiseDeferredTimer(std::make_unique<PromiseDeferredTimer>(*this))
     
    369369#if ENABLE(WEBASSEMBLY)
    370370    if (Wasm::existingWorklistOrNull())
    371         Wasm::ensureWorklist().stopAllPlansForContext(wasmContext);
     371        Wasm::ensureWorklist().stopAllPlansForVM(*this);
    372372#endif
    373373    if (UNLIKELY(m_watchdog))
  • trunk/Source/JavaScriptCore/runtime/VM.h

    r222791 r223002  
    5656#include "VMEntryRecord.h"
    5757#include "VMTraps.h"
    58 #include "WasmContext.h"
    5958#include "Watchpoint.h"
    6059#include <wtf/BumpPointerAllocator.h>
     
    331330    VMType vmType;
    332331    ClientData* clientData;
    333     EntryFrame* topEntryFrame;
     332    VMEntryFrame* topVMEntryFrame;
    334333    // NOTE: When throwing an exception while rolling back the call frame, this may be equal to
    335     // topEntryFrame.
     334    // topVMEntryFrame.
    336335    // FIXME: This should be a void*, because it might not point to a CallFrame.
    337336    // https://bugs.webkit.org/show_bug.cgi?id=160441
    338337    ExecState* topCallFrame { nullptr };
    339 #if ENABLE(WEBASSEMBLY)
    340     Wasm::Context wasmContext;
    341 #endif
     338    // FIXME: Save this state elsewhere to allow PIC. https://bugs.webkit.org/show_bug.cgi?id=169773
     339    JSWebAssemblyInstance* wasmContext { nullptr };
    342340    Strong<Structure> structureStructure;
    343341    Strong<Structure> structureRareDataStructure;
     
    504502    }
    505503
    506     static ptrdiff_t topEntryFrameOffset()
    507     {
    508         return OBJECT_OFFSETOF(VM, topEntryFrame);
     504    static ptrdiff_t topVMEntryFrameOffset()
     505    {
     506        return OBJECT_OFFSETOF(VM, topVMEntryFrame);
    509507    }
    510508
  • trunk/Source/JavaScriptCore/runtime/VMTraps.cpp

    r222791 r223002  
    9090}
    9191
    92 static bool isSaneFrame(CallFrame* frame, CallFrame* calleeFrame, EntryFrame* entryFrame, StackBounds stackBounds)
     92static bool isSaneFrame(CallFrame* frame, CallFrame* calleeFrame, VMEntryFrame* entryFrame, StackBounds stackBounds)
    9393{
    9494    if (reinterpret_cast<void*>(frame) >= reinterpret_cast<void*>(entryFrame))
     
    122122
    123123    CodeBlock* foundCodeBlock = nullptr;
    124     EntryFrame* entryFrame = vm.topEntryFrame;
     124    VMEntryFrame* vmEntryFrame = vm.topVMEntryFrame;
    125125
    126126    // We don't have a callee to start with. So, use the end of the stack to keep the
     
    129129    CallFrame* calleeFrame = reinterpret_cast<CallFrame*>(stackBounds.end());
    130130
    131     if (!entryFrame || !callFrame)
     131    if (!vmEntryFrame || !callFrame)
    132132        return; // Not running JS code. Let the SignalSender try again later.
    133133
    134134    do {
    135         if (!isSaneFrame(callFrame, calleeFrame, entryFrame, stackBounds))
     135        if (!isSaneFrame(callFrame, calleeFrame, vmEntryFrame, stackBounds))
    136136            return; // Let the SignalSender try again later.
    137137
     
    143143
    144144        calleeFrame = callFrame;
    145         callFrame = callFrame->callerFrame(entryFrame);
    146 
    147     } while (callFrame && entryFrame);
     145        callFrame = callFrame->callerFrame(vmEntryFrame);
     146
     147    } while (callFrame && vmEntryFrame);
    148148
    149149    if (!foundCodeBlock) {
     
    182182    m_needToInvalidatedCodeBlocks = false;
    183183
    184     EntryFrame* entryFrame = vm().topEntryFrame;
     184    VMEntryFrame* vmEntryFrame = vm().topVMEntryFrame;
    185185    CallFrame* callFrame = topCallFrame;
    186186
    187     if (!entryFrame)
     187    if (!vmEntryFrame)
    188188        return; // Not running JS code. Nothing to invalidate.
    189189
     
    192192        if (codeBlock && JITCode::isOptimizingJIT(codeBlock->jitType()))
    193193            codeBlock->jettison(Profiler::JettisonDueToVMTraps);
    194         callFrame = callFrame->callerFrame(entryFrame);
     194        callFrame = callFrame->callerFrame(vmEntryFrame);
    195195    }
    196196}
  • trunk/Source/JavaScriptCore/wasm/JSWebAssembly.h

    r223001 r223002  
    2929
    3030#include "JSObject.h"
    31 #include "JSWebAssemblyCompileError.h"
    32 #include "JSWebAssemblyInstance.h"
    33 #include "JSWebAssemblyLinkError.h"
    34 #include "JSWebAssemblyMemory.h"
    35 #include "JSWebAssemblyModule.h"
    36 #include "JSWebAssemblyRuntimeError.h"
    37 #include "JSWebAssemblyTable.h"
    38 #include "WebAssemblyCompileErrorConstructor.h"
    39 #include "WebAssemblyCompileErrorPrototype.h"
    40 #include "WebAssemblyFunction.h"
    41 #include "WebAssemblyInstanceConstructor.h"
    42 #include "WebAssemblyInstancePrototype.h"
    43 #include "WebAssemblyLinkErrorConstructor.h"
    44 #include "WebAssemblyLinkErrorPrototype.h"
    45 #include "WebAssemblyMemoryConstructor.h"
    46 #include "WebAssemblyMemoryPrototype.h"
    47 #include "WebAssemblyModuleConstructor.h"
    48 #include "WebAssemblyModulePrototype.h"
    49 #include "WebAssemblyModuleRecord.h"
    50 #include "WebAssemblyPrototype.h"
    51 #include "WebAssemblyRuntimeErrorConstructor.h"
    52 #include "WebAssemblyRuntimeErrorPrototype.h"
    53 #include "WebAssemblyTableConstructor.h"
    54 #include "WebAssemblyTablePrototype.h"
    55 #include "WebAssemblyToJSCallee.h"
     31#include "js/JSWebAssemblyCompileError.h"
     32#include "js/JSWebAssemblyInstance.h"
     33#include "js/JSWebAssemblyLinkError.h"
     34#include "js/JSWebAssemblyMemory.h"
     35#include "js/JSWebAssemblyModule.h"
     36#include "js/JSWebAssemblyRuntimeError.h"
     37#include "js/JSWebAssemblyTable.h"
     38#include "js/WebAssemblyCompileErrorConstructor.h"
     39#include "js/WebAssemblyCompileErrorPrototype.h"
     40#include "js/WebAssemblyFunction.h"
     41#include "js/WebAssemblyInstanceConstructor.h"
     42#include "js/WebAssemblyInstancePrototype.h"
     43#include "js/WebAssemblyLinkErrorConstructor.h"
     44#include "js/WebAssemblyLinkErrorPrototype.h"
     45#include "js/WebAssemblyMemoryConstructor.h"
     46#include "js/WebAssemblyMemoryPrototype.h"
     47#include "js/WebAssemblyModuleConstructor.h"
     48#include "js/WebAssemblyModulePrototype.h"
     49#include "js/WebAssemblyModuleRecord.h"
     50#include "js/WebAssemblyPrototype.h"
     51#include "js/WebAssemblyRuntimeErrorConstructor.h"
     52#include "js/WebAssemblyRuntimeErrorPrototype.h"
     53#include "js/WebAssemblyTableConstructor.h"
     54#include "js/WebAssemblyTablePrototype.h"
     55#include "js/WebAssemblyToJSCallee.h"
    5656
    5757namespace JSC {
  • trunk/Source/JavaScriptCore/wasm/WasmB3IRGenerator.cpp

    r222878 r223002  
    5050#include "JSCInlines.h"
    5151#include "JSWebAssemblyInstance.h"
     52#include "JSWebAssemblyModule.h"
     53#include "JSWebAssemblyRuntimeError.h"
    5254#include "ScratchRegisterAllocator.h"
    5355#include "VirtualRegister.h"
     
    177179    } while (0)
    178180
    179     B3IRGenerator(const ModuleInformation&, Procedure&, InternalFunction*, Vector<UnlinkedWasmToWasmCall>&, MemoryMode, CompilationMode, unsigned functionIndex, TierUpCount*, ThrowWasmException);
     181    B3IRGenerator(const ModuleInformation&, Procedure&, InternalFunction*, Vector<UnlinkedWasmToWasmCall>&, MemoryMode, CompilationMode, unsigned functionIndex, TierUpCount*);
    180182
    181183    PartialResult WARN_UNUSED_RETURN addArguments(const Signature&);
     
    246248    int32_t WARN_UNUSED_RETURN fixupPointerPlusOffset(ExpressionType&, uint32_t);
    247249
    248     void restoreWasmContextInstance(Procedure&, BasicBlock*, Value*);
     250    void restoreWasmContext(Procedure&, BasicBlock*, Value*);
    249251    void restoreWebAssemblyGlobalState(const MemoryInformation&, Value* instance, Procedure&, BasicBlock*);
    250252
     
    266268    GPRReg m_memoryBaseGPR { InvalidGPRReg };
    267269    GPRReg m_memorySizeGPR { InvalidGPRReg };
    268     GPRReg m_wasmContextInstanceGPR { InvalidGPRReg };
     270    GPRReg m_wasmContextGPR { InvalidGPRReg };
    269271    bool m_makesCalls { false };
    270272
     
    290292}
    291293
    292 void B3IRGenerator::restoreWasmContextInstance(Procedure& proc, BasicBlock* block, Value* arg)
    293 {
    294     if (Context::useFastTLS()) {
     294void B3IRGenerator::restoreWasmContext(Procedure& proc, BasicBlock* block, Value* arg)
     295{
     296    if (useFastTLSForContext()) {
    295297        PatchpointValue* patchpoint = block->appendNew<PatchpointValue>(proc, B3::Void, Origin());
    296         if (CCallHelpers::storeWasmContextInstanceNeedsMacroScratchRegister())
     298        if (CCallHelpers::storeWasmContextNeedsMacroScratchRegister())
    297299            patchpoint->clobber(RegisterSet::macroScratchRegisters());
    298300        patchpoint->append(ConstrainedValue(arg, ValueRep::SomeRegister));
    299301        patchpoint->setGenerator(
    300302            [=] (CCallHelpers& jit, const StackmapGenerationParams& params) {
    301                 AllowMacroScratchRegisterUsageIf allowScratch(jit, CCallHelpers::storeWasmContextInstanceNeedsMacroScratchRegister());
    302                 jit.storeWasmContextInstance(params[0].gpr());
     303                AllowMacroScratchRegisterUsageIf allowScratch(jit, CCallHelpers::storeWasmContextNeedsMacroScratchRegister());
     304                jit.storeWasmContext(params[0].gpr());
    303305            });
    304306        return;
    305307    }
    306308
    307     // FIXME: Because WasmToWasm call clobbers wasmContextInstance register and does not restore it, we need to restore it in the caller side.
     309    // FIXME: Because WasmToWasm call clobbers wasmContext register and does not restore it, we need to restore it in the caller side.
    308310    // This prevents us from using ArgumentReg to this (logically) immutable pinned register.
    309311    PatchpointValue* patchpoint = block->appendNew<PatchpointValue>(proc, B3::Void, Origin());
     
    312314    effects.reads = B3::HeapRange::top();
    313315    patchpoint->effects = effects;
    314     patchpoint->clobberLate(RegisterSet(m_wasmContextInstanceGPR));
     316    patchpoint->clobberLate(RegisterSet(m_wasmContextGPR));
    315317    patchpoint->append(instanceValue(), ValueRep::SomeRegister);
    316     GPRReg wasmContextInstanceGPR = m_wasmContextInstanceGPR;
     318    GPRReg wasmContextGPR = m_wasmContextGPR;
    317319    patchpoint->setGenerator([=] (CCallHelpers& jit, const StackmapGenerationParams& param) {
    318         jit.move(param[0].gpr(), wasmContextInstanceGPR);
    319     });
    320 }
    321 
    322 B3IRGenerator::B3IRGenerator(const ModuleInformation& info, Procedure& procedure, InternalFunction* compilation, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, MemoryMode mode, CompilationMode compilationMode, unsigned functionIndex, TierUpCount* tierUp, ThrowWasmException throwWasmException)
     320        jit.move(param[0].gpr(), wasmContextGPR);
     321    });
     322}
     323
     324B3IRGenerator::B3IRGenerator(const ModuleInformation& info, Procedure& procedure, InternalFunction* compilation, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, MemoryMode mode, CompilationMode compilationMode, unsigned functionIndex, TierUpCount* tierUp)
    323325    : m_info(info)
    324326    , m_mode(mode)
     
    338340    m_proc.pinRegister(m_memoryBaseGPR);
    339341
    340     m_wasmContextInstanceGPR = pinnedRegs.wasmContextInstancePointer;
    341     if (!Context::useFastTLS())
    342         m_proc.pinRegister(m_wasmContextInstanceGPR);
     342    m_wasmContextGPR = pinnedRegs.wasmContextPointer;
     343    if (!useFastTLSForContext())
     344        m_proc.pinRegister(m_wasmContextGPR);
    343345
    344346    if (mode != MemoryMode::Signaling) {
     
    348350            m_proc.pinRegister(regInfo.sizeRegister);
    349351    }
    350 
    351     if (throwWasmException)
    352         Thunks::singleton().setThrowWasmException(throwWasmException);
    353352
    354353    if (info.memory) {
     
    365364            this->emitExceptionCheck(jit, ExceptionType::OutOfBoundsMemoryAccess);
    366365        });
    367 
    368         switch (m_mode) {
    369         case MemoryMode::BoundsChecking:
    370             break;
    371         case MemoryMode::Signaling:
    372             // Most memory accesses in signaling mode don't do an explicit
    373             // exception check because they can rely on fault handling to detect
    374             // out-of-bounds accesses. FaultSignalHandler nonetheless needs the
    375             // thunk to exist so that it can jump to that thunk.
    376             if (UNLIKELY(!Thunks::singleton().stub(throwExceptionFromWasmThunkGenerator)))
    377                 CRASH();
    378             break;
    379         }
    380366    }
    381367
     
    388374        stackOverflowCheck->appendSomeRegister(framePointer);
    389375        stackOverflowCheck->clobber(RegisterSet::macroScratchRegisters());
    390         if (!Context::useFastTLS()) {
    391             // FIXME: Because WasmToWasm call clobbers wasmContextInstance register and does not restore it, we need to restore it in the caller side.
     376        if (!useFastTLSForContext()) {
     377            // FIXME: Because WasmToWasm call clobbers wasmContext register and does not restore it, we need to restore it in the caller side.
    392378            // This prevents us from using ArgumentReg to this (logically) immutable pinned register.
    393379            stackOverflowCheck->effects.writesPinned = false;
    394380            stackOverflowCheck->effects.readsPinned = true;
    395             stackOverflowCheck->resultConstraint = ValueRep::reg(m_wasmContextInstanceGPR);
     381            stackOverflowCheck->resultConstraint = ValueRep::reg(m_wasmContextGPR);
    396382        }
    397383        stackOverflowCheck->numGPScratchRegisters = 2;
     
    416402            bool needsOverflowCheck = m_makesCalls || wasmFrameSize >= minimumParentCheckSize || needUnderflowCheck;
    417403
    418             GPRReg contextInstance = Context::useFastTLS() ? params[0].gpr() : m_wasmContextInstanceGPR;
     404            GPRReg context = useFastTLSForContext() ? params[0].gpr() : m_wasmContextGPR;
    419405
    420406            // This allows leaf functions to not do stack checks if their frame size is within
     
    426412                GPRReg scratch2 = params.gpScratch(1);
    427413
    428                 if (Context::useFastTLS())
    429                     jit.loadWasmContextInstance(contextInstance);
    430 
    431                 jit.loadPtr(CCallHelpers::Address(contextInstance, JSWebAssemblyInstance::offsetOfCachedStackLimit()), scratch2);
     414                if (useFastTLSForContext())
     415                    jit.loadWasmContext(context);
     416
     417                jit.loadPtr(CCallHelpers::Address(context, Context::offsetOfCachedStackLimit()), scratch2);
    432418                jit.addPtr(CCallHelpers::TrustedImm32(-checkSize), fp, scratch1);
    433419                MacroAssembler::JumpList overflow;
     
    438424                    linkBuffer.link(overflow, CodeLocationLabel(Thunks::singleton().stub(throwStackOverflowFromWasmThunkGenerator).code()));
    439425                });
    440             } else if (m_usesInstanceValue && Context::useFastTLS()) {
     426            } else if (m_usesInstanceValue && useFastTLSForContext()) {
    441427                // No overflow check is needed, but the instance values still needs to be correct.
    442                 AllowMacroScratchRegisterUsageIf allowScratch(jit, CCallHelpers::loadWasmContextInstanceNeedsMacroScratchRegister());
    443                 jit.loadWasmContextInstance(contextInstance);
     428                AllowMacroScratchRegisterUsageIf allowScratch(jit, CCallHelpers::loadWasmContextNeedsMacroScratchRegister());
     429                jit.loadWasmContext(context);
    444430            } else {
    445431                // We said we'd return a pointer. We don't actually need to because it isn't used, but the patchpoint conservatively said it had effects (potential stack check) which prevent it from getting removed.
     
    453439void B3IRGenerator::restoreWebAssemblyGlobalState(const MemoryInformation& memory, Value* instance, Procedure& proc, BasicBlock* block)
    454440{
    455     restoreWasmContextInstance(proc, block, instance);
     441    restoreWasmContext(proc, block, instance);
    456442
    457443    if (!!memory) {
     
    473459        patchpoint->setGenerator([pinnedRegs] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
    474460            GPRReg baseMemory = pinnedRegs->baseMemoryPointer;
    475             jit.loadPtr(CCallHelpers::Address(params[0].gpr(), JSWebAssemblyInstance::offsetOfWasmMemory()), baseMemory);
     461            jit.loadPtr(CCallHelpers::Address(params[0].gpr(), JSWebAssemblyInstance::offsetOfMemory()), baseMemory);
    476462            const auto& sizeRegs = pinnedRegs->sizeRegisters;
    477463            ASSERT(sizeRegs.size() >= 1);
    478464            ASSERT(!sizeRegs[0].sizeOffset); // The following code assumes we start at 0, and calculates subsequent size registers relative to 0.
    479             jit.loadPtr(CCallHelpers::Address(baseMemory, Memory::offsetOfSize()), sizeRegs[0].sizeRegister);
    480             jit.loadPtr(CCallHelpers::Address(baseMemory, Memory::offsetOfMemory()), baseMemory);
     465            jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyMemory::offsetOfSize()), sizeRegs[0].sizeRegister);
     466            jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyMemory::offsetOfMemory()), baseMemory);
    481467            for (unsigned i = 1; i < sizeRegs.size(); ++i)
    482468                jit.add64(CCallHelpers::TrustedImm32(-sizeRegs[i].sizeOffset), sizeRegs[0].sizeRegister, sizeRegs[i].sizeRegister);
     
    556542auto B3IRGenerator::addGrowMemory(ExpressionType delta, ExpressionType& result) -> PartialResult
    557543{
    558     int32_t (*growMemory)(JSWebAssemblyInstance*, int32_t) = [] (JSWebAssemblyInstance* instance, int32_t delta) -> int32_t {
     544    int32_t (*growMemory) (Context*, int32_t) = [] (Context* wasmContext, int32_t delta) -> int32_t {
     545        VM& vm = *wasmContext->vm();
     546        auto scope = DECLARE_THROW_SCOPE(vm);
     547
     548        JSWebAssemblyMemory* wasmMemory = wasmContext->memory();
     549
    559550        if (delta < 0)
    560551            return -1;
    561552
    562         auto grown = instance->internalMemory().grow(PageCount(delta));
    563         if (!grown) {
    564             switch (grown.error()) {
    565             case Memory::GrowFailReason::InvalidDelta:
    566             case Memory::GrowFailReason::InvalidGrowSize:
    567             case Memory::GrowFailReason::WouldExceedMaximum:
    568             case Memory::GrowFailReason::OutOfMemory:
    569                 return -1;
    570             }
    571         }
    572 
    573         return grown.value().pageCount();
     553        bool shouldThrowExceptionsOnFailure = false;
     554        // grow() does not require ExecState* if it doesn't throw exceptions.
     555        ExecState* exec = nullptr;
     556        PageCount result = wasmMemory->grow(vm, exec, static_cast<uint32_t>(delta), shouldThrowExceptionsOnFailure);
     557        scope.releaseAssertNoException();
     558        if (!result)
     559            return -1;
     560
     561        return result.pageCount();
    574562    };
    575563
     
    585573auto B3IRGenerator::addCurrentMemory(ExpressionType& result) -> PartialResult
    586574{
    587     Value* memoryObject = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfWasmMemory()));
    588 
    589     static_assert(sizeof(decltype(static_cast<Memory*>(nullptr)->size())) == sizeof(uint64_t), "codegen relies on this size");
    590     Value* size = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int64, origin(), memoryObject, safeCast<int32_t>(Memory::offsetOfSize()));
     575    Value* memoryObject = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfMemory()));
     576
     577    static_assert(sizeof(decltype(static_cast<JSWebAssemblyInstance*>(nullptr)->memory()->memory().size())) == sizeof(uint64_t), "codegen relies on this size");
     578    Value* size = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int64, origin(), memoryObject, safeCast<int32_t>(JSWebAssemblyMemory::offsetOfSize()));
    591579   
    592580    constexpr uint32_t shiftValue = 16;
    593     static_assert(PageCount::pageSize == 1ull << shiftValue, "This must hold for the code below to be correct.");
     581    static_assert(PageCount::pageSize == 1 << shiftValue, "This must hold for the code below to be correct.");
    594582    Value* numPages = m_currentBlock->appendNew<Value>(m_proc, ZShr, origin(),
    595583        size, m_currentBlock->appendNew<Const32Value>(m_proc, origin(), shiftValue));
     
    10821070
    10831071        // FIXME imports can be linked here, instead of generating a patchpoint, because all import stubs are generated before B3 compilation starts. https://bugs.webkit.org/show_bug.cgi?id=166462
    1084         Value* targetInstance = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfTargetInstance(functionIndex)));
    1085         Value* isWasmCall = m_currentBlock->appendNew<Value>(m_proc, NotEqual, origin(), targetInstance, m_currentBlock->appendNew<Const64Value>(m_proc, origin(), 0));
     1072        Value* functionImport = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfImportFunction(functionIndex)));
     1073        Value* jsTypeOfImport = m_currentBlock->appendNew<MemoryValue>(m_proc, Load8Z, origin(), functionImport, safeCast<int32_t>(JSCell::typeInfoTypeOffset()));
     1074        Value* isWasmCall = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(), jsTypeOfImport, m_currentBlock->appendNew<Const32Value>(m_proc, origin(), WebAssemblyFunctionType));
    10861075
    10871076        BasicBlock* isWasmBlock = m_proc.addBlock();
    1088         BasicBlock* isEmbedderBlock = m_proc.addBlock();
     1077        BasicBlock* isJSBlock = m_proc.addBlock();
    10891078        BasicBlock* continuation = m_proc.addBlock();
    1090         m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(), isWasmCall, FrequentedBlock(isWasmBlock), FrequentedBlock(isEmbedderBlock));
     1079        m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(), isWasmCall, FrequentedBlock(isWasmBlock), FrequentedBlock(isJSBlock));
    10911080
    10921081        Value* wasmCallResult = wasmCallingConvention().setupCall(m_proc, isWasmBlock, origin(), args, toB3Type(returnType),
     
    11091098        isWasmBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
    11101099
    1111         // FIXME: Let's remove this indirection by creating a PIC friendly IC
     1100        // FIXME: Lets remove this indirection by creating a PIC friendly IC
    11121101        // for calls out to JS. This shouldn't be that hard to do. We could probably
    1113         // implement the IC to be over Context*.
     1102        // implement the IC to be over Wasm::Context*.
    11141103        // https://bugs.webkit.org/show_bug.cgi?id=170375
    1115         Value* codeBlock = isEmbedderBlock->appendNew<MemoryValue>(m_proc,
    1116             Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfWasmCodeBlock()));
    1117         Value* jumpDestination = isEmbedderBlock->appendNew<MemoryValue>(m_proc,
    1118             Load, pointerType(), origin(), codeBlock, safeCast<int32_t>(CodeBlock::offsetOfImportWasmToEmbedderStub(functionIndex)));
    1119         Value* embedderCallResult = wasmCallingConvention().setupCall(m_proc, isEmbedderBlock, origin(), args, toB3Type(returnType),
     1104        Value* codeBlock = isJSBlock->appendNew<MemoryValue>(m_proc,
     1105            Load, pointerType(), origin(), instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfCodeBlock()));
     1106        Value* jumpDestination = isJSBlock->appendNew<MemoryValue>(m_proc,
     1107            Load, pointerType(), origin(), codeBlock, safeCast<int32_t>(JSWebAssemblyCodeBlock::offsetOfImportWasmToJSStub(functionIndex)));
     1108        Value* jsCallResult = wasmCallingConvention().setupCall(m_proc, isJSBlock, origin(), args, toB3Type(returnType),
    11201109            [&] (PatchpointValue* patchpoint) {
    11211110                patchpoint->effects.writesPinned = true;
     
    11311120                });
    11321121            });
    1133         UpsilonValue* embedderCallResultUpsilon = returnType == Void ? nullptr : isEmbedderBlock->appendNew<UpsilonValue>(m_proc, origin(), embedderCallResult);
    1134         isEmbedderBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
     1122        UpsilonValue* jsCallResultUpsilon = returnType == Void ? nullptr : isJSBlock->appendNew<UpsilonValue>(m_proc, origin(), jsCallResult);
     1123        isJSBlock->appendNewControlValue(m_proc, Jump, origin(), continuation);
    11351124
    11361125        m_currentBlock = continuation;
     
    11411130            result = continuation->appendNew<Value>(m_proc, Phi, toB3Type(returnType), origin());
    11421131            wasmCallResultUpsilon->setPhi(result);
    1143             embedderCallResultUpsilon->setPhi(result);
     1132            jsCallResultUpsilon->setPhi(result);
    11441133        }
    11451134
     
    11771166
    11781167    ExpressionType callableFunctionBuffer;
    1179     ExpressionType instancesBuffer;
     1168    ExpressionType jsFunctionBuffer;
    11801169    ExpressionType callableFunctionBufferSize;
    11811170    {
    11821171        ExpressionType table = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
    1183             instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfWasmTable()));
     1172            instanceValue(), safeCast<int32_t>(JSWebAssemblyInstance::offsetOfTable()));
    11841173        callableFunctionBuffer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
    1185             table, safeCast<int32_t>(Table::offsetOfFunctions()));
    1186         instancesBuffer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
    1187             table, safeCast<int32_t>(Table::offsetOfInstances()));
     1174            table, safeCast<int32_t>(JSWebAssemblyTable::offsetOfFunctions()));
     1175        jsFunctionBuffer = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
     1176            table, safeCast<int32_t>(JSWebAssemblyTable::offsetOfJSFunctions()));
    11881177        callableFunctionBufferSize = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(),
    1189             table, safeCast<int32_t>(Table::offsetOfSize()));
     1178            table, safeCast<int32_t>(JSWebAssemblyTable::offsetOfSize()));
    11901179    }
    11911180
     
    12071196
    12081197    // Check that the CallableFunction is initialized. We trap if it isn't. An "invalid" SignatureIndex indicates it's not initialized.
    1209     // FIXME: when we have trap handlers, we can just let the call fail because Signature::invalidIndex is 0. https://bugs.webkit.org/show_bug.cgi?id=177210
    12101198    static_assert(sizeof(CallableFunction::signatureIndex) == sizeof(uint32_t), "Load codegen assumes i32");
    12111199    ExpressionType calleeSignatureIndex = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, Int32, origin(), callableFunction, safeCast<int32_t>(OBJECT_OFFSETOF(CallableFunction, signatureIndex)));
     
    12361224        Value* offset = m_currentBlock->appendNew<Value>(m_proc, Mul, origin(),
    12371225            m_currentBlock->appendNew<Value>(m_proc, ZExt32, origin(), calleeIndex),
    1238             constant(pointerType(), sizeof(Instance*)));
    1239         Value* newContextInstance = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
    1240             m_currentBlock->appendNew<Value>(m_proc, Add, origin(), instancesBuffer, offset));
     1226            constant(pointerType(), sizeof(WriteBarrier<JSObject>)));
     1227        Value* jsObject = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
     1228            m_currentBlock->appendNew<Value>(m_proc, Add, origin(), jsFunctionBuffer, offset));
    12411229
    12421230        BasicBlock* continuation = m_proc.addBlock();
    12431231        BasicBlock* doContextSwitch = m_proc.addBlock();
    12441232
    1245         Value* isSameContextInstance = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(),
    1246             newContextInstance, instanceValue());
     1233        Value* newContext = m_currentBlock->appendNew<MemoryValue>(m_proc, Load, pointerType(), origin(),
     1234            jsObject, safeCast<int32_t>(WebAssemblyFunctionBase::offsetOfInstance()));
     1235        Value* isSameContext = m_currentBlock->appendNew<Value>(m_proc, Equal, origin(),
     1236            newContext, instanceValue());
    12471237        m_currentBlock->appendNewControlValue(m_proc, B3::Branch, origin(),
    1248             isSameContextInstance, FrequentedBlock(continuation), FrequentedBlock(doContextSwitch));
     1238            isSameContext, FrequentedBlock(continuation), FrequentedBlock(doContextSwitch));
    12491239
    12501240        PatchpointValue* patchpoint = doContextSwitch->appendNew<PatchpointValue>(m_proc, B3::Void, origin());
     
    12541244        patchpoint->clobber(PinnedRegisterInfo::get().toSave(MemoryMode::BoundsChecking));
    12551245        patchpoint->clobber(RegisterSet::macroScratchRegisters());
    1256         patchpoint->append(newContextInstance, ValueRep::SomeRegister);
     1246        patchpoint->append(newContext, ValueRep::SomeRegister);
    12571247        patchpoint->append(instanceValue(), ValueRep::SomeRegister);
    12581248        patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
    12591249            AllowMacroScratchRegisterUsage allowScratch(jit);
    1260             GPRReg newContextInstance = params[0].gpr();
    1261             GPRReg oldContextInstance = params[1].gpr();
     1250            GPRReg newContext = params[0].gpr();
     1251            GPRReg oldContext = params[1].gpr();
    12621252            const PinnedRegisterInfo& pinnedRegs = PinnedRegisterInfo::get();
    12631253            const auto& sizeRegs = pinnedRegs.sizeRegisters;
    12641254            GPRReg baseMemory = pinnedRegs.baseMemoryPointer;
    1265             ASSERT(newContextInstance != baseMemory);
    1266             jit.loadPtr(CCallHelpers::Address(oldContextInstance, JSWebAssemblyInstance::offsetOfCachedStackLimit()), baseMemory);
    1267             jit.storePtr(baseMemory, CCallHelpers::Address(newContextInstance, JSWebAssemblyInstance::offsetOfCachedStackLimit()));
    1268             jit.storeWasmContextInstance(newContextInstance);
    1269             jit.loadPtr(CCallHelpers::Address(newContextInstance, JSWebAssemblyInstance::offsetOfWasmMemory()), baseMemory); // Memory*.
     1255            ASSERT(newContext != baseMemory);
     1256            jit.loadPtr(CCallHelpers::Address(oldContext, Context::offsetOfCachedStackLimit()), baseMemory);
     1257            jit.storePtr(baseMemory, CCallHelpers::Address(newContext, Context::offsetOfCachedStackLimit()));
     1258            jit.storeWasmContext(newContext);
     1259            jit.loadPtr(CCallHelpers::Address(newContext, Context::offsetOfMemory()), baseMemory); // JSWebAssemblyMemory*.
    12701260            ASSERT(sizeRegs.size() == 1);
    12711261            ASSERT(sizeRegs[0].sizeRegister != baseMemory);
    1272             ASSERT(sizeRegs[0].sizeRegister != newContextInstance);
     1262            ASSERT(sizeRegs[0].sizeRegister != newContext);
    12731263            ASSERT(!sizeRegs[0].sizeOffset);
    1274             jit.loadPtr(CCallHelpers::Address(baseMemory, Memory::offsetOfSize()), sizeRegs[0].sizeRegister); // Memory size.
    1275             jit.loadPtr(CCallHelpers::Address(baseMemory, Memory::offsetOfMemory()), baseMemory); // Memory::void*.
     1264            jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyMemory::offsetOfSize()), sizeRegs[0].sizeRegister); // Memory size.
     1265            jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyMemory::offsetOfMemory()), baseMemory); // WasmMemory::void*.
    12761266        });
    12771267        doContextSwitch->appendNewControlValue(m_proc, Jump, origin(), continuation);
     
    13501340}
    13511341
     1342std::unique_ptr<InternalFunction> createJSToWasmWrapper(CompilationContext& compilationContext, const Signature& signature, Vector<UnlinkedWasmToWasmCall>* unlinkedWasmToWasmCalls, const ModuleInformation& info, MemoryMode mode, unsigned functionIndex)
     1343{
     1344    CCallHelpers& jit = *compilationContext.jsEntrypointJIT;
     1345
     1346    auto result = std::make_unique<InternalFunction>();
     1347    jit.emitFunctionPrologue();
     1348
     1349    // FIXME Stop using 0 as codeBlocks. https://bugs.webkit.org/show_bug.cgi?id=165321
     1350    jit.store64(CCallHelpers::TrustedImm64(0), CCallHelpers::Address(GPRInfo::callFrameRegister, CallFrameSlot::codeBlock * static_cast<int>(sizeof(Register))));
     1351    MacroAssembler::DataLabelPtr calleeMoveLocation = jit.moveWithPatch(MacroAssembler::TrustedImmPtr(nullptr), GPRInfo::nonPreservedNonReturnGPR);
     1352    jit.storePtr(GPRInfo::nonPreservedNonReturnGPR, CCallHelpers::Address(GPRInfo::callFrameRegister, CallFrameSlot::callee * static_cast<int>(sizeof(Register))));
     1353    CodeLocationDataLabelPtr* linkedCalleeMove = &result->calleeMoveLocation;
     1354    jit.addLinkTask([=] (LinkBuffer& linkBuffer) {
     1355        *linkedCalleeMove = linkBuffer.locationOf(calleeMoveLocation);
     1356    });
     1357
     1358    const PinnedRegisterInfo& pinnedRegs = PinnedRegisterInfo::get();
     1359    RegisterSet toSave = pinnedRegs.toSave(mode);
     1360
     1361#if !ASSERT_DISABLED
     1362    unsigned toSaveSize = toSave.numberOfSetGPRs();
     1363    // They should all be callee saves.
     1364    toSave.filter(RegisterSet::calleeSaveRegisters());
     1365    ASSERT(toSave.numberOfSetGPRs() == toSaveSize);
     1366#endif
     1367
     1368    RegisterAtOffsetList registersToSpill(toSave, RegisterAtOffsetList::OffsetBaseType::FramePointerBased);
     1369    result->entrypoint.calleeSaveRegisters = registersToSpill;
     1370
     1371    unsigned totalFrameSize = registersToSpill.size() * sizeof(void*);
     1372    totalFrameSize += WasmCallingConvention::headerSizeInBytes();
     1373    totalFrameSize -= sizeof(CallerFrameAndPC);
     1374    unsigned numGPRs = 0;
     1375    unsigned numFPRs = 0;
     1376    for (unsigned i = 0; i < signature.argumentCount(); i++) {
     1377        switch (signature.argument(i)) {
     1378        case Wasm::I64:
     1379        case Wasm::I32:
     1380            if (numGPRs >= wasmCallingConvention().m_gprArgs.size())
     1381                totalFrameSize += sizeof(void*);
     1382            ++numGPRs;
     1383            break;
     1384        case Wasm::F32:
     1385        case Wasm::F64:
     1386            if (numFPRs >= wasmCallingConvention().m_fprArgs.size())
     1387                totalFrameSize += sizeof(void*);
     1388            ++numFPRs;
     1389            break;
     1390        default:
     1391            RELEASE_ASSERT_NOT_REACHED();
     1392        }
     1393    }
     1394
     1395    totalFrameSize = WTF::roundUpToMultipleOf(stackAlignmentBytes(), totalFrameSize);
     1396    jit.subPtr(MacroAssembler::TrustedImm32(totalFrameSize), MacroAssembler::stackPointerRegister);
     1397
     1398    // We save all these registers regardless of having a memory or not.
     1399    // The reason is that we use one of these as a scratch. That said,
     1400    // almost all real wasm programs use memory, so it's not really
     1401    // worth optimizing for the case that they don't.
     1402    for (const RegisterAtOffset& regAtOffset : registersToSpill) {
     1403        GPRReg reg = regAtOffset.reg().gpr();
     1404        ptrdiff_t offset = regAtOffset.offset();
     1405        jit.storePtr(reg, CCallHelpers::Address(GPRInfo::callFrameRegister, offset));
     1406    }
     1407
     1408    GPRReg wasmContextGPR = pinnedRegs.wasmContextPointer;
     1409
     1410    {
     1411        CCallHelpers::Address calleeFrame = CCallHelpers::Address(MacroAssembler::stackPointerRegister, -static_cast<ptrdiff_t>(sizeof(CallerFrameAndPC)));
     1412        numGPRs = 0;
     1413        numFPRs = 0;
     1414        // We're going to set the pinned registers after this. So
     1415        // we can use this as a scratch for now since we saved it above.
     1416        GPRReg scratchReg = pinnedRegs.baseMemoryPointer;
     1417
     1418        ptrdiff_t jsOffset = CallFrameSlot::thisArgument * sizeof(EncodedJSValue);
     1419
     1420        // vmEntryToWasm passes Wasm::Context* as the first JS argument when we're
     1421        // not using fast TLS to hold the Wasm::Context*.
     1422        if (!useFastTLSForContext()) {
     1423            jit.loadPtr(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), wasmContextGPR);
     1424            jsOffset += sizeof(EncodedJSValue);
     1425        }
     1426
     1427        ptrdiff_t wasmOffset = CallFrame::headerSizeInRegisters * sizeof(void*);
     1428        for (unsigned i = 0; i < signature.argumentCount(); i++) {
     1429            switch (signature.argument(i)) {
     1430            case Wasm::I32:
     1431            case Wasm::I64:
     1432                if (numGPRs >= wasmCallingConvention().m_gprArgs.size()) {
     1433                    if (signature.argument(i) == Wasm::I32) {
     1434                        jit.load32(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), scratchReg);
     1435                        jit.store32(scratchReg, calleeFrame.withOffset(wasmOffset));
     1436                    } else {
     1437                        jit.load64(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), scratchReg);
     1438                        jit.store64(scratchReg, calleeFrame.withOffset(wasmOffset));
     1439                    }
     1440                    wasmOffset += sizeof(void*);
     1441                } else {
     1442                    if (signature.argument(i) == Wasm::I32)
     1443                        jit.load32(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), wasmCallingConvention().m_gprArgs[numGPRs].gpr());
     1444                    else
     1445                        jit.load64(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), wasmCallingConvention().m_gprArgs[numGPRs].gpr());
     1446                }
     1447                ++numGPRs;
     1448                break;
     1449            case Wasm::F32:
     1450            case Wasm::F64:
     1451                if (numFPRs >= wasmCallingConvention().m_fprArgs.size()) {
     1452                    if (signature.argument(i) == Wasm::F32) {
     1453                        jit.load32(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), scratchReg);
     1454                        jit.store32(scratchReg, calleeFrame.withOffset(wasmOffset));
     1455                    } else {
     1456                        jit.load64(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), scratchReg);
     1457                        jit.store64(scratchReg, calleeFrame.withOffset(wasmOffset));
     1458                    }
     1459                    wasmOffset += sizeof(void*);
     1460                } else {
     1461                    if (signature.argument(i) == Wasm::F32)
     1462                        jit.loadFloat(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), wasmCallingConvention().m_fprArgs[numFPRs].fpr());
     1463                    else
     1464                        jit.loadDouble(CCallHelpers::Address(GPRInfo::callFrameRegister, jsOffset), wasmCallingConvention().m_fprArgs[numFPRs].fpr());
     1465                }
     1466                ++numFPRs;
     1467                break;
     1468            default:
     1469                RELEASE_ASSERT_NOT_REACHED();
     1470            }
     1471
     1472            jsOffset += sizeof(EncodedJSValue);
     1473        }
     1474    }
     1475
     1476    if (!!info.memory) {
     1477        GPRReg baseMemory = pinnedRegs.baseMemoryPointer;
     1478
     1479        if (!useFastTLSForContext())
     1480            jit.loadPtr(CCallHelpers::Address(wasmContextGPR, JSWebAssemblyInstance::offsetOfMemory()), baseMemory);
     1481        else {
     1482            jit.loadWasmContext(baseMemory);
     1483            jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyInstance::offsetOfMemory()), baseMemory);
     1484        }
     1485
     1486        if (mode != MemoryMode::Signaling) {
     1487            const auto& sizeRegs = pinnedRegs.sizeRegisters;
     1488            ASSERT(sizeRegs.size() >= 1);
     1489            ASSERT(!sizeRegs[0].sizeOffset); // The following code assumes we start at 0, and calculates subsequent size registers relative to 0.
     1490            jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyMemory::offsetOfSize()), sizeRegs[0].sizeRegister);
     1491            for (unsigned i = 1; i < sizeRegs.size(); ++i)
     1492                jit.add64(CCallHelpers::TrustedImm32(-sizeRegs[i].sizeOffset), sizeRegs[0].sizeRegister, sizeRegs[i].sizeRegister);
     1493        }
     1494
     1495        jit.loadPtr(CCallHelpers::Address(baseMemory, JSWebAssemblyMemory::offsetOfMemory()), baseMemory);
     1496    }
     1497
     1498    CCallHelpers::Call call = jit.threadSafePatchableNearCall();
     1499    unsigned functionIndexSpace = functionIndex + info.importFunctionCount();
     1500    ASSERT(functionIndexSpace < info.functionIndexSpaceSize());
     1501    jit.addLinkTask([unlinkedWasmToWasmCalls, call, functionIndexSpace] (LinkBuffer& linkBuffer) {
     1502        unlinkedWasmToWasmCalls->append({ linkBuffer.locationOfNearCall(call), functionIndexSpace });
     1503    });
     1504
     1505
     1506    for (const RegisterAtOffset& regAtOffset : registersToSpill) {
     1507        GPRReg reg = regAtOffset.reg().gpr();
     1508        ASSERT(reg != GPRInfo::returnValueGPR);
     1509        ptrdiff_t offset = regAtOffset.offset();
     1510        jit.loadPtr(CCallHelpers::Address(GPRInfo::callFrameRegister, offset), reg);
     1511    }
     1512
     1513    switch (signature.returnType()) {
     1514    case Wasm::F32:
     1515        jit.moveFloatTo32(FPRInfo::returnValueFPR, GPRInfo::returnValueGPR);
     1516        break;
     1517    case Wasm::F64:
     1518        jit.moveDoubleTo64(FPRInfo::returnValueFPR, GPRInfo::returnValueGPR);
     1519        break;
     1520    default:
     1521        break;
     1522    }
     1523
     1524    jit.emitFunctionEpilogue();
     1525    jit.ret();
     1526
     1527    return result;
     1528}
     1529
    13521530auto B3IRGenerator::origin() -> Origin
    13531531{
     
    13571535}
    13581536
    1359 Expected<std::unique_ptr<InternalFunction>, String> parseAndCompile(CompilationContext& compilationContext, const uint8_t* functionStart, size_t functionLength, const Signature& signature, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, const ModuleInformation& info, MemoryMode mode, CompilationMode compilationMode, uint32_t functionIndex, TierUpCount* tierUp, ThrowWasmException throwWasmException)
     1537Expected<std::unique_ptr<InternalFunction>, String> parseAndCompile(CompilationContext& compilationContext, const uint8_t* functionStart, size_t functionLength, const Signature& signature, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, const ModuleInformation& info, MemoryMode mode, CompilationMode compilationMode, uint32_t functionIndex, TierUpCount* tierUp)
    13601538{
    13611539    auto result = std::make_unique<InternalFunction>();
     
    13811559        : Options::webAssemblyOMGOptimizationLevel());
    13821560
    1383     B3IRGenerator irGenerator(info, procedure, result.get(), unlinkedWasmToWasmCalls, mode, compilationMode, functionIndex, tierUp, throwWasmException);
    1384     FunctionParser<B3IRGenerator> parser(irGenerator, functionStart, functionLength, signature, info);
     1561    B3IRGenerator context(info, procedure, result.get(), unlinkedWasmToWasmCalls, mode, compilationMode, functionIndex, tierUp);
     1562    FunctionParser<B3IRGenerator> parser(context, functionStart, functionLength, signature, info);
    13851563    WASM_FAIL_IF_HELPER_FAILS(parser.parse());
    13861564
    1387     irGenerator.insertConstants();
     1565    context.insertConstants();
    13881566
    13891567    procedure.resetReachability();
  • trunk/Source/JavaScriptCore/wasm/WasmB3IRGenerator.h

    r222791 r223002  
    3232#include "B3OpaqueByproducts.h"
    3333#include "CCallHelpers.h"
    34 #include "WasmEmbedder.h"
    3534#include "WasmMemory.h"
    3635#include "WasmModuleInformation.h"
     
    5655};
    5756
    58 Expected<std::unique_ptr<InternalFunction>, String> parseAndCompile(CompilationContext&, const uint8_t*, size_t, const Signature&, Vector<UnlinkedWasmToWasmCall>&, const ModuleInformation&, MemoryMode, CompilationMode, uint32_t functionIndex, TierUpCount* = nullptr, ThrowWasmException = nullptr);
     57Expected<std::unique_ptr<InternalFunction>, String> parseAndCompile(CompilationContext&, const uint8_t*, size_t, const Signature&, Vector<UnlinkedWasmToWasmCall>&, const ModuleInformation&, MemoryMode, CompilationMode, uint32_t functionIndex, TierUpCount* = nullptr);
     58
     59std::unique_ptr<InternalFunction> createJSToWasmWrapper(CompilationContext&, const Signature&, Vector<UnlinkedWasmToWasmCall>*, const ModuleInformation&, MemoryMode, uint32_t functionIndex);
    5960
    6061} } // namespace JSC::Wasm
  • trunk/Source/JavaScriptCore/wasm/WasmBBQPlan.cpp

    r222791 r223002  
    3030
    3131#include "B3Compilation.h"
     32#include "JSCInlines.h"
     33#include "JSGlobalObject.h"
    3234#include "WasmB3IRGenerator.h"
    3335#include "WasmBinding.h"
     
    5254}
    5355
    54 BBQPlan::BBQPlan(Context* context, Ref<ModuleInformation> info, AsyncWork work, CompletionTask&& task, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
    55     : Base(context, WTFMove(info), WTFMove(task), WTFMove(createEmbedderWrapper), throwWasmException)
     56BBQPlan::BBQPlan(VM* vm, Ref<ModuleInformation> info, AsyncWork work, CompletionTask&& task)
     57    : Base(vm, WTFMove(info), WTFMove(task))
    5658    , m_state(State::Validated)
    5759    , m_asyncWork(work)
     
    5961}
    6062
    61 BBQPlan::BBQPlan(Context* context, Vector<uint8_t>&& source, AsyncWork work, CompletionTask&& task, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
    62     : BBQPlan(context, adoptRef(*new ModuleInformation(WTFMove(source))), work, WTFMove(task), WTFMove(createEmbedderWrapper), throwWasmException)
     63BBQPlan::BBQPlan(VM* vm, Vector<uint8_t>&& source, AsyncWork work, CompletionTask&& task)
     64    : BBQPlan(vm, adoptRef(*new ModuleInformation(WTFMove(source))), work, WTFMove(task))
    6365{
    6466    m_state = State::Initial;
    6567}
    6668
    67 BBQPlan::BBQPlan(Context* context, const uint8_t* source, size_t sourceLength, AsyncWork work, CompletionTask&& task)
    68     : Base(context, source, sourceLength, WTFMove(task))
     69BBQPlan::BBQPlan(VM* vm, const uint8_t* source, size_t sourceLength, AsyncWork work, CompletionTask&& task)
     70    : Base(vm, source, sourceLength, WTFMove(task))
    6971    , m_state(State::Initial)
    7072    , m_asyncWork(work)
     
    268270        m_unlinkedWasmToWasmCalls[functionIndex] = Vector<UnlinkedWasmToWasmCall>();
    269271        TierUpCount* tierUp = Options::useBBQTierUpChecks() ? &m_tierUpCounts[functionIndex] : nullptr;
    270         auto parseAndCompileResult = parseAndCompile(m_compilationContexts[functionIndex], functionStart, functionLength, signature, m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, CompilationMode::BBQMode, functionIndex, tierUp, m_throwWasmException);
     272        auto parseAndCompileResult = parseAndCompile(m_compilationContexts[functionIndex], functionStart, functionLength, signature, m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, CompilationMode::BBQMode, functionIndex, tierUp);
    271273
    272274        if (UNLIKELY(!parseAndCompileResult)) {
     
    284286        if (m_exportedFunctionIndices.contains(functionIndex)) {
    285287            auto locker = holdLock(m_lock);
    286             auto result = m_embedderToWasmInternalFunctions.add(functionIndex, m_createEmbedderWrapper(m_compilationContexts[functionIndex], signature, &m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, functionIndex));
     288            auto result = m_jsToWasmInternalFunctions.add(functionIndex, createJSToWasmWrapper(m_compilationContexts[functionIndex], signature, &m_unlinkedWasmToWasmCalls[functionIndex], m_moduleInformation.get(), m_mode, functionIndex));
    287289            ASSERT_UNUSED(result, result.isNewEntry);
    288290        }
     
    313315            }
    314316
    315             if (auto embedderToWasmInternalFunction = m_embedderToWasmInternalFunctions.get(functionIndex)) {
     317            if (auto jsToWasmInternalFunction = m_jsToWasmInternalFunctions.get(functionIndex)) {
    316318                LinkBuffer linkBuffer(*context.jsEntrypointJIT, nullptr, JITCompilationCanFail);
    317319                if (UNLIKELY(linkBuffer.didFailToAllocate())) {
     
    320322                }
    321323
    322                 embedderToWasmInternalFunction->entrypoint.compilation = std::make_unique<B3::Compilation>(
     324                jsToWasmInternalFunction->entrypoint.compilation = std::make_unique<B3::Compilation>(
    323325                    FINALIZE_CODE(linkBuffer, ("JavaScript->WebAssembly entrypoint[%i] %s", functionIndex, SignatureInformation::get(signatureIndex).toString().ascii().data())),
    324326                    WTFMove(context.jsEntrypointByproducts));
  • trunk/Source/JavaScriptCore/wasm/WasmBBQPlan.h

    r222791 r223002  
    2929
    3030#include "CompilationResult.h"
     31#include "VM.h"
    3132#include "WasmB3IRGenerator.h"
    3233#include "WasmModuleInformation.h"
     
    3435#include "WasmTierUpCount.h"
    3536#include <wtf/Bag.h>
    36 #include <wtf/Function.h>
    3737#include <wtf/SharedTask.h>
    3838#include <wtf/ThreadSafeRefCounted.h>
     
    4242
    4343class CallLinkInfo;
     44class JSGlobalObject;
     45class JSPromiseDeferred;
    4446
    4547namespace Wasm {
     
    4951    using Base = Plan;
    5052    enum AsyncWork : uint8_t { FullCompile, Validation };
    51 
    5253    // Note: CompletionTask should not hold a reference to the Plan otherwise there will be a reference cycle.
    53     BBQPlan(Context*, Ref<ModuleInformation>, AsyncWork, CompletionTask&&, CreateEmbedderWrapper&&, ThrowWasmException);
    54     JS_EXPORT_PRIVATE BBQPlan(Context*, Vector<uint8_t>&&, AsyncWork, CompletionTask&&, CreateEmbedderWrapper&&, ThrowWasmException);
     54    BBQPlan(VM*, Ref<ModuleInformation>, AsyncWork, CompletionTask&&);
     55    JS_EXPORT_PRIVATE BBQPlan(VM*, Vector<uint8_t>&&, AsyncWork, CompletionTask&&);
    5556    // Note: This constructor should only be used if you are not actually building a module e.g. validation/function tests
    5657    // FIXME: When we get rid of function tests we should remove AsyncWork from this constructor.
    57     JS_EXPORT_PRIVATE BBQPlan(Context*, const uint8_t*, size_t, AsyncWork, CompletionTask&&);
     58    JS_EXPORT_PRIVATE BBQPlan(VM*, const uint8_t*, size_t, AsyncWork, CompletionTask&&);
    5859
    5960    bool parseAndValidateModule();
     
    141142    Vector<std::unique_ptr<InternalFunction>> m_wasmInternalFunctions;
    142143    HashSet<uint32_t, typename DefaultHash<uint32_t>::Hash, WTF::UnsignedWithZeroKeyHashTraits<uint32_t>> m_exportedFunctionIndices;
    143     HashMap<uint32_t, std::unique_ptr<InternalFunction>, typename DefaultHash<uint32_t>::Hash, WTF::UnsignedWithZeroKeyHashTraits<uint32_t>> m_embedderToWasmInternalFunctions;
     144    HashMap<uint32_t, std::unique_ptr<InternalFunction>, typename DefaultHash<uint32_t>::Hash, WTF::UnsignedWithZeroKeyHashTraits<uint32_t>> m_jsToWasmInternalFunctions;
    144145    Vector<CompilationContext> m_compilationContexts;
    145146    Vector<TierUpCount> m_tierUpCounts;
  • trunk/Source/JavaScriptCore/wasm/WasmBBQPlanInlines.h

    r222791 r223002  
    4040    for (unsigned internalFunctionIndex = 0; internalFunctionIndex < m_wasmInternalFunctions.size(); ++internalFunctionIndex) {
    4141
    42         RefPtr<Wasm::Callee> embedderEntrypointCallee;
    43         if (auto embedderToWasmFunction = m_embedderToWasmInternalFunctions.get(internalFunctionIndex)) {
    44             embedderEntrypointCallee = Wasm::Callee::create(WTFMove(embedderToWasmFunction->entrypoint));
    45             MacroAssembler::repatchPointer(embedderToWasmFunction->calleeMoveLocation, CalleeBits::boxWasm(embedderEntrypointCallee.get()));
     42        RefPtr<Wasm::Callee> jsEntrypointCallee;
     43        if (auto jsToWasmFunction = m_jsToWasmInternalFunctions.get(internalFunctionIndex)) {
     44            jsEntrypointCallee = Wasm::Callee::create(WTFMove(jsToWasmFunction->entrypoint));
     45            MacroAssembler::repatchPointer(jsToWasmFunction->calleeMoveLocation, CalleeBits::boxWasm(jsEntrypointCallee.get()));
    4646        }
    4747
     
    5151        MacroAssembler::repatchPointer(function->calleeMoveLocation, CalleeBits::boxWasm(wasmEntrypointCallee.ptr()));
    5252
    53         callback(internalFunctionIndex, WTFMove(embedderEntrypointCallee), WTFMove(wasmEntrypointCallee));
     53        callback(internalFunctionIndex, WTFMove(jsEntrypointCallee), WTFMove(wasmEntrypointCallee));
    5454    }
    5555}
  • trunk/Source/JavaScriptCore/wasm/WasmBinding.cpp

    r222791 r223002  
    3030
    3131#include "CCallHelpers.h"
     32#include "FrameTracers.h"
     33#include "JITExceptions.h"
    3234#include "JSCInlines.h"
    3335#include "JSWebAssemblyInstance.h"
    3436#include "LinkBuffer.h"
     37#include "NativeErrorConstructor.h"
     38#include "ThunkGenerators.h"
     39#include "WasmCallingConvention.h"
     40#include "WasmContext.h"
     41#include "WasmExceptionType.h"
    3542
    3643namespace JSC { namespace Wasm {
    3744
    3845using JIT = CCallHelpers;
     46
     47static void materializeImportJSCell(JIT& jit, unsigned importIndex, GPRReg result)
     48{
     49    // We're calling out of the current WebAssembly.Instance. That Instance has a list of all its import functions.
     50    jit.loadWasmContext(result);
     51    jit.loadPtr(JIT::Address(result, JSWebAssemblyInstance::offsetOfImportFunction(importIndex)), result);
     52}
     53
     54Expected<MacroAssemblerCodeRef, BindingFailure> wasmToJs(VM* vm, Bag<CallLinkInfo>& callLinkInfos, SignatureIndex signatureIndex, unsigned importIndex)
     55{
     56    // FIXME: This function doesn't properly abstract away the calling convention.
     57    // It'd be super easy to do so: https://bugs.webkit.org/show_bug.cgi?id=169401
     58    const WasmCallingConvention& wasmCC = wasmCallingConvention();
     59    const JSCCallingConvention& jsCC = jscCallingConvention();
     60    const Signature& signature = SignatureInformation::get(signatureIndex);
     61    unsigned argCount = signature.argumentCount();
     62    JIT jit;
     63
     64    // Note: WasmB3IRGenerator assumes that this stub treats SP as a callee save.
     65    // If we ever change this, we will also need to change WasmB3IRGenerator.
     66
     67    // Below, we assume that the JS calling convention is always on the stack.
     68    ASSERT(!jsCC.m_gprArgs.size());
     69    ASSERT(!jsCC.m_fprArgs.size());
     70
     71    jit.emitFunctionPrologue();
     72    jit.store64(JIT::TrustedImm32(0), JIT::Address(GPRInfo::callFrameRegister, CallFrameSlot::codeBlock * static_cast<int>(sizeof(Register)))); // FIXME Stop using 0 as codeBlocks. https://bugs.webkit.org/show_bug.cgi?id=165321
     73
     74    {
     75        bool hasBadI64Use = false;
     76        hasBadI64Use |= signature.returnType() == I64;
     77        for (unsigned argNum = 0; argNum < argCount && !hasBadI64Use; ++argNum) {
     78            Type argType = signature.argument(argNum);
     79            switch (argType) {
     80            case Void:
     81            case Func:
     82            case Anyfunc:
     83                RELEASE_ASSERT_NOT_REACHED();
     84
     85            case I64: {
     86                hasBadI64Use = true;
     87                break;
     88            }
     89
     90            default:
     91                break;
     92            }
     93        }
     94
     95        if (hasBadI64Use) {
     96            jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm);
     97            jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR0);
     98            jit.loadWasmContext(GPRInfo::argumentGPR1);
     99
     100            // Store Callee.
     101            jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR1, JSWebAssemblyInstance::offsetOfCallee()), GPRInfo::argumentGPR2);
     102            jit.storePtr(GPRInfo::argumentGPR2, JIT::Address(GPRInfo::callFrameRegister, CallFrameSlot::callee * static_cast<int>(sizeof(Register))));
     103
     104            auto call = jit.call();
     105            jit.jumpToExceptionHandler(*vm);
     106
     107            void (*throwBadI64)(ExecState*, JSWebAssemblyInstance*) = [] (ExecState* exec, JSWebAssemblyInstance* wasmContext) -> void {
     108                VM* vm = &exec->vm();
     109                NativeCallFrameTracer tracer(vm, exec);
     110
     111                {
     112                    auto throwScope = DECLARE_THROW_SCOPE(*vm);
     113                    JSGlobalObject* globalObject = wasmContext->globalObject();
     114                    auto* error = ErrorInstance::create(exec, *vm, globalObject->typeErrorConstructor()->errorStructure(), ASCIILiteral("i64 not allowed as return type or argument to an imported function"));
     115                    throwException(exec, throwScope, error);
     116                }
     117
     118                genericUnwind(vm, exec);
     119                ASSERT(!!vm->callFrameForCatch);
     120            };
     121
     122            LinkBuffer linkBuffer(jit, GLOBAL_THUNK_ID, JITCompilationCanFail);
     123            if (UNLIKELY(linkBuffer.didFailToAllocate()))
     124                return makeUnexpected(BindingFailure::OutOfMemory);
     125
     126            linkBuffer.link(call, throwBadI64);
     127            return FINALIZE_CODE(linkBuffer, ("WebAssembly->JavaScript invalid i64 use in import[%i]", importIndex));
     128        }
     129    }
     130
     131    // Here we assume that the JS calling convention saves at least all the wasm callee saved. We therefore don't need to save and restore more registers since the wasm callee already took care of this.
     132    RegisterSet missingCalleeSaves = wasmCC.m_calleeSaveRegisters;
     133    missingCalleeSaves.exclude(jsCC.m_calleeSaveRegisters);
     134    ASSERT(missingCalleeSaves.isEmpty());
     135
     136    if (!Options::useCallICsForWebAssemblyToJSCalls()) {
     137        ScratchBuffer* scratchBuffer = vm->scratchBufferForSize(argCount * sizeof(uint64_t));
     138        char* buffer = argCount ? static_cast<char*>(scratchBuffer->dataBuffer()) : nullptr;
     139        unsigned marshalledGPRs = 0;
     140        unsigned marshalledFPRs = 0;
     141        unsigned bufferOffset = 0;
     142        unsigned frOffset = CallFrame::headerSizeInRegisters * static_cast<int>(sizeof(Register));
     143        const GPRReg scratchGPR = GPRInfo::regCS0;
     144        jit.subPtr(MacroAssembler::TrustedImm32(WTF::roundUpToMultipleOf(stackAlignmentBytes(), sizeof(Register))), MacroAssembler::stackPointerRegister);
     145        jit.storePtr(scratchGPR, MacroAssembler::Address(MacroAssembler::stackPointerRegister));
     146
     147        for (unsigned argNum = 0; argNum < argCount; ++argNum) {
     148            Type argType = signature.argument(argNum);
     149            switch (argType) {
     150            case Void:
     151            case Func:
     152            case Anyfunc:
     153            case I64:
     154                RELEASE_ASSERT_NOT_REACHED();
     155            case I32: {
     156                GPRReg gprReg;
     157                if (marshalledGPRs < wasmCC.m_gprArgs.size())
     158                    gprReg = wasmCC.m_gprArgs[marshalledGPRs].gpr();
     159                else {
     160                    // We've already spilled all arguments, these registers are available as scratch.
     161                    gprReg = GPRInfo::argumentGPR0;
     162                    jit.load64(JIT::Address(GPRInfo::callFrameRegister, frOffset), gprReg);
     163                    frOffset += sizeof(Register);
     164                }
     165                jit.zeroExtend32ToPtr(gprReg, gprReg);
     166                jit.store64(gprReg, buffer + bufferOffset);
     167                ++marshalledGPRs;
     168                break;
     169            }
     170            case F32: {
     171                FPRReg fprReg;
     172                if (marshalledFPRs < wasmCC.m_fprArgs.size())
     173                    fprReg = wasmCC.m_fprArgs[marshalledFPRs].fpr();
     174                else {
     175                    // We've already spilled all arguments, these registers are available as scratch.
     176                    fprReg = FPRInfo::argumentFPR0;
     177                    jit.loadFloat(JIT::Address(GPRInfo::callFrameRegister, frOffset), fprReg);
     178                    frOffset += sizeof(Register);
     179                }
     180                jit.convertFloatToDouble(fprReg, fprReg);
     181                jit.moveDoubleTo64(fprReg, scratchGPR);
     182                jit.store64(scratchGPR, buffer + bufferOffset);
     183                ++marshalledFPRs;
     184                break;
     185            }
     186            case F64: {
     187                FPRReg fprReg;
     188                if (marshalledFPRs < wasmCC.m_fprArgs.size())
     189                    fprReg = wasmCC.m_fprArgs[marshalledFPRs].fpr();
     190                else {
     191                    // We've already spilled all arguments, these registers are available as scratch.
     192                    fprReg = FPRInfo::argumentFPR0;
     193                    jit.loadDouble(JIT::Address(GPRInfo::callFrameRegister, frOffset), fprReg);
     194                    frOffset += sizeof(Register);
     195                }
     196                jit.moveDoubleTo64(fprReg, scratchGPR);
     197                jit.store64(scratchGPR, buffer + bufferOffset);
     198                ++marshalledFPRs;
     199                break;
     200            }
     201            }
     202
     203            bufferOffset += sizeof(Register);
     204        }
     205        jit.loadPtr(MacroAssembler::Address(MacroAssembler::stackPointerRegister), scratchGPR);
     206        if (argCount) {
     207            // The GC should not look at this buffer at all, these aren't JSValues.
     208            jit.move(CCallHelpers::TrustedImmPtr(scratchBuffer->addressOfActiveLength()), GPRInfo::argumentGPR0);
     209            jit.storePtr(CCallHelpers::TrustedImmPtr(0), GPRInfo::argumentGPR0);
     210        }
     211
     212        uint64_t (*callFunc)(ExecState*, JSObject*, SignatureIndex, uint64_t*) =
     213            [] (ExecState* exec, JSObject* callee, SignatureIndex signatureIndex, uint64_t* buffer) -> uint64_t {
     214                VM* vm = &exec->vm();
     215                NativeCallFrameTracer tracer(vm, exec);
     216                auto throwScope = DECLARE_THROW_SCOPE(*vm);
     217                const Signature& signature = SignatureInformation::get(signatureIndex);
     218                MarkedArgumentBuffer args;
     219                for (unsigned argNum = 0; argNum < signature.argumentCount(); ++argNum) {
     220                    Type argType = signature.argument(argNum);
     221                    JSValue arg;
     222                    switch (argType) {
     223                    case Void:
     224                    case Func:
     225                    case Anyfunc:
     226                    case I64:
     227                        RELEASE_ASSERT_NOT_REACHED();
     228                    case I32:
     229                        arg = jsNumber(static_cast<int32_t>(buffer[argNum]));
     230                        break;
     231                    case F32:
     232                    case F64:
     233                        arg = jsNumber(bitwise_cast<double>(buffer[argNum]));
     234                        break;
     235                    }
     236                    args.append(arg);
     237                }
     238
     239                CallData callData;
     240                CallType callType = callee->methodTable(*vm)->getCallData(callee, callData);
     241                RELEASE_ASSERT(callType != CallType::None);
     242                JSValue result = call(exec, callee, callType, callData, jsUndefined(), args);
     243                RETURN_IF_EXCEPTION(throwScope, 0);
     244
     245                uint64_t realResult;
     246                switch (signature.returnType()) {
     247                case Func:
     248                case Anyfunc:
     249                case I64:
     250                    RELEASE_ASSERT_NOT_REACHED();
     251                    break;
     252                case Void:
     253                    break;
     254                case I32: {
     255                    realResult = static_cast<uint64_t>(static_cast<uint32_t>(result.toInt32(exec)));
     256                    break;
     257                }
     258                case F64:
     259                case F32: {
     260                    realResult = bitwise_cast<uint64_t>(result.toNumber(exec));
     261                    break;
     262                }
     263                }
     264
     265                RETURN_IF_EXCEPTION(throwScope, 0);
     266                return realResult;
     267            };
     268       
     269        jit.loadWasmContext(GPRInfo::argumentGPR0);
     270        jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR0, JSWebAssemblyInstance::offsetOfCallee()), GPRInfo::argumentGPR0);
     271        jit.storePtr(GPRInfo::argumentGPR0, JIT::Address(GPRInfo::callFrameRegister, CallFrameSlot::callee * static_cast<int>(sizeof(Register))));
     272       
     273        materializeImportJSCell(jit, importIndex, GPRInfo::argumentGPR1);
     274        static_assert(GPRInfo::numberOfArgumentRegisters >= 4, "We rely on this with the call below.");
     275        jit.setupArgumentsWithExecState(GPRInfo::argumentGPR1, CCallHelpers::TrustedImm32(signatureIndex), CCallHelpers::TrustedImmPtr(buffer));
     276        auto call = jit.call();
     277        auto noException = jit.emitExceptionCheck(*vm, AssemblyHelpers::InvertedExceptionCheck);
     278
     279        // exception here.
     280        jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm);
     281        jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR0);
     282        void (*doUnwinding)(ExecState*) = [] (ExecState* exec) -> void {
     283            VM* vm = &exec->vm();
     284            NativeCallFrameTracer tracer(vm, exec);
     285            genericUnwind(vm, exec);
     286            ASSERT(!!vm->callFrameForCatch);
     287        };
     288        auto exceptionCall = jit.call();
     289        jit.jumpToExceptionHandler(*vm);
     290
     291        noException.link(&jit);
     292        switch (signature.returnType()) {
     293        case F64: {
     294            jit.move64ToDouble(GPRInfo::returnValueGPR, FPRInfo::returnValueFPR);
     295            break;
     296        }
     297        case F32: {
     298            jit.move64ToDouble(GPRInfo::returnValueGPR, FPRInfo::returnValueFPR);
     299            jit.convertDoubleToFloat(FPRInfo::returnValueFPR, FPRInfo::returnValueFPR);
     300            break;
     301        }
     302        default:
     303            break;
     304        }
     305
     306        jit.emitFunctionEpilogue();
     307        jit.ret();
     308
     309        LinkBuffer linkBuffer(jit, GLOBAL_THUNK_ID, JITCompilationCanFail);
     310        if (UNLIKELY(linkBuffer.didFailToAllocate()))
     311            return makeUnexpected(BindingFailure::OutOfMemory);
     312
     313        linkBuffer.link(call, callFunc);
     314        linkBuffer.link(exceptionCall, doUnwinding);
     315
     316        return FINALIZE_CODE(linkBuffer, ("WebAssembly->JavaScript import[%i] %s", importIndex, signature.toString().ascii().data()));
     317    }
     318
     319    // Note: We don't need to perform a stack check here since WasmB3IRGenerator
     320    // will do the stack check for us. Whenever it detects that it might make
     321    // a call to this thunk, it'll make sure its stack check includes space
     322    // for us here.
     323
     324    const unsigned numberOfParameters = argCount + 1; // There is a "this" argument.
     325    const unsigned numberOfRegsForCall = CallFrame::headerSizeInRegisters + numberOfParameters;
     326    const unsigned numberOfBytesForCall = numberOfRegsForCall * sizeof(Register) - sizeof(CallerFrameAndPC);
     327    const unsigned stackOffset = WTF::roundUpToMultipleOf(stackAlignmentBytes(), numberOfBytesForCall);
     328    jit.subPtr(MacroAssembler::TrustedImm32(stackOffset), MacroAssembler::stackPointerRegister);
     329    JIT::Address calleeFrame = CCallHelpers::Address(MacroAssembler::stackPointerRegister, -static_cast<ptrdiff_t>(sizeof(CallerFrameAndPC)));
     330
     331    // FIXME make these loops which switch on Signature if there are many arguments on the stack. It'll otherwise be huge for huge signatures. https://bugs.webkit.org/show_bug.cgi?id=165547
     332   
     333    // First go through the integer parameters, freeing up their register for use afterwards.
     334    {
     335        unsigned marshalledGPRs = 0;
     336        unsigned marshalledFPRs = 0;
     337        unsigned calleeFrameOffset = CallFrameSlot::firstArgument * static_cast<int>(sizeof(Register));
     338        unsigned frOffset = CallFrame::headerSizeInRegisters * static_cast<int>(sizeof(Register));
     339        for (unsigned argNum = 0; argNum < argCount; ++argNum) {
     340            Type argType = signature.argument(argNum);
     341            switch (argType) {
     342            case Void:
     343            case Func:
     344            case Anyfunc:
     345            case I64:
     346                RELEASE_ASSERT_NOT_REACHED(); // Handled above.
     347            case I32: {
     348                GPRReg gprReg;
     349                if (marshalledGPRs < wasmCC.m_gprArgs.size())
     350                    gprReg = wasmCC.m_gprArgs[marshalledGPRs].gpr();
     351                else {
     352                    // We've already spilled all arguments, these registers are available as scratch.
     353                    gprReg = GPRInfo::argumentGPR0;
     354                    jit.load64(JIT::Address(GPRInfo::callFrameRegister, frOffset), gprReg);
     355                    frOffset += sizeof(Register);
     356                }
     357                ++marshalledGPRs;
     358                jit.zeroExtend32ToPtr(gprReg, gprReg); // Clear non-int32 and non-tag bits.
     359                jit.boxInt32(gprReg, JSValueRegs(gprReg), DoNotHaveTagRegisters);
     360                jit.store64(gprReg, calleeFrame.withOffset(calleeFrameOffset));
     361                calleeFrameOffset += sizeof(Register);
     362                break;
     363            }
     364            case F32:
     365            case F64:
     366                // Skipped: handled below.
     367                if (marshalledFPRs >= wasmCC.m_fprArgs.size())
     368                    frOffset += sizeof(Register);
     369                ++marshalledFPRs;
     370                calleeFrameOffset += sizeof(Register);
     371                break;
     372            }
     373        }
     374    }
     375   
     376    {
     377        // Integer registers have already been spilled, these are now available.
     378        GPRReg doubleEncodeOffsetGPRReg = GPRInfo::argumentGPR0;
     379        GPRReg scratch = GPRInfo::argumentGPR1;
     380        bool hasMaterializedDoubleEncodeOffset = false;
     381        auto materializeDoubleEncodeOffset = [&hasMaterializedDoubleEncodeOffset, &jit] (GPRReg dest) {
     382            if (!hasMaterializedDoubleEncodeOffset) {
     383                static_assert(DoubleEncodeOffset == 1ll << 48, "codegen assumes this below");
     384                jit.move(JIT::TrustedImm32(1), dest);
     385                jit.lshift64(JIT::TrustedImm32(48), dest);
     386                hasMaterializedDoubleEncodeOffset = true;
     387            }
     388        };
     389
     390        unsigned marshalledGPRs = 0;
     391        unsigned marshalledFPRs = 0;
     392        unsigned calleeFrameOffset = CallFrameSlot::firstArgument * static_cast<int>(sizeof(Register));
     393        unsigned frOffset = CallFrame::headerSizeInRegisters * static_cast<int>(sizeof(Register));
     394        for (unsigned argNum = 0; argNum < argCount; ++argNum) {
     395            Type argType = signature.argument(argNum);
     396            switch (argType) {
     397            case Void:
     398            case Func:
     399            case Anyfunc:
     400            case I64:
     401                RELEASE_ASSERT_NOT_REACHED(); // Handled above.
     402            case I32:
     403                // Skipped: handled above.
     404                if (marshalledGPRs >= wasmCC.m_gprArgs.size())
     405                    frOffset += sizeof(Register);
     406                ++marshalledGPRs;
     407                calleeFrameOffset += sizeof(Register);
     408                break;
     409            case F32: {
     410                FPRReg fprReg;
     411                if (marshalledFPRs < wasmCC.m_fprArgs.size())
     412                    fprReg = wasmCC.m_fprArgs[marshalledFPRs].fpr();
     413                else {
     414                    // We've already spilled all arguments, these registers are available as scratch.
     415                    fprReg = FPRInfo::argumentFPR0;
     416                    jit.loadFloat(JIT::Address(GPRInfo::callFrameRegister, frOffset), fprReg);
     417                    frOffset += sizeof(Register);
     418                }
     419                jit.convertFloatToDouble(fprReg, fprReg);
     420                jit.purifyNaN(fprReg);
     421                jit.moveDoubleTo64(fprReg, scratch);
     422                materializeDoubleEncodeOffset(doubleEncodeOffsetGPRReg);
     423                jit.add64(doubleEncodeOffsetGPRReg, scratch);
     424                jit.store64(scratch, calleeFrame.withOffset(calleeFrameOffset));
     425                calleeFrameOffset += sizeof(Register);
     426                ++marshalledFPRs;
     427                break;
     428            }
     429            case F64: {
     430                FPRReg fprReg;
     431                if (marshalledFPRs < wasmCC.m_fprArgs.size())
     432                    fprReg = wasmCC.m_fprArgs[marshalledFPRs].fpr();
     433                else {
     434                    // We've already spilled all arguments, these registers are available as scratch.
     435                    fprReg = FPRInfo::argumentFPR0;
     436                    jit.loadDouble(JIT::Address(GPRInfo::callFrameRegister, frOffset), fprReg);
     437                    frOffset += sizeof(Register);
     438                }
     439                jit.purifyNaN(fprReg);
     440                jit.moveDoubleTo64(fprReg, scratch);
     441                materializeDoubleEncodeOffset(doubleEncodeOffsetGPRReg);
     442                jit.add64(doubleEncodeOffsetGPRReg, scratch);
     443                jit.store64(scratch, calleeFrame.withOffset(calleeFrameOffset));
     444                calleeFrameOffset += sizeof(Register);
     445                ++marshalledFPRs;
     446                break;
     447            }
     448            }
     449        }
     450    }
     451
     452    jit.loadWasmContext(GPRInfo::argumentGPR0);
     453    jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR0, JSWebAssemblyInstance::offsetOfCallee()), GPRInfo::argumentGPR0);
     454    jit.storePtr(GPRInfo::argumentGPR0, JIT::Address(GPRInfo::callFrameRegister, CallFrameSlot::callee * static_cast<int>(sizeof(Register))));
     455
     456    GPRReg importJSCellGPRReg = GPRInfo::regT0; // Callee needs to be in regT0 for slow path below.
     457    ASSERT(!wasmCC.m_calleeSaveRegisters.get(importJSCellGPRReg));
     458
     459    materializeImportJSCell(jit, importIndex, importJSCellGPRReg);
     460
     461    jit.store64(importJSCellGPRReg, calleeFrame.withOffset(CallFrameSlot::callee * static_cast<int>(sizeof(Register))));
     462    jit.store32(JIT::TrustedImm32(numberOfParameters), calleeFrame.withOffset(CallFrameSlot::argumentCount * static_cast<int>(sizeof(Register)) + PayloadOffset));
     463    jit.store64(JIT::TrustedImm64(ValueUndefined), calleeFrame.withOffset(CallFrameSlot::thisArgument * static_cast<int>(sizeof(Register))));
     464
     465    // FIXME Tail call if the wasm return type is void and no registers were spilled. https://bugs.webkit.org/show_bug.cgi?id=165488
     466
     467    CallLinkInfo* callLinkInfo = callLinkInfos.add();
     468    callLinkInfo->setUpCall(CallLinkInfo::Call, CodeOrigin(), importJSCellGPRReg);
     469    JIT::DataLabelPtr targetToCheck;
     470    JIT::TrustedImmPtr initialRightValue(0);
     471    JIT::Jump slowPath = jit.branchPtrWithPatch(MacroAssembler::NotEqual, importJSCellGPRReg, targetToCheck, initialRightValue);
     472    JIT::Call fastCall = jit.nearCall();
     473    JIT::Jump done = jit.jump();
     474    slowPath.link(&jit);
     475    // Callee needs to be in regT0 here.
     476    jit.move(MacroAssembler::TrustedImmPtr(callLinkInfo), GPRInfo::regT2); // Link info needs to be in regT2.
     477    JIT::Call slowCall = jit.nearCall();
     478    done.link(&jit);
     479
     480    CCallHelpers::JumpList exceptionChecks;
     481
     482    switch (signature.returnType()) {
     483    case Void:
     484        // Discard.
     485        break;
     486    case Func:
     487    case Anyfunc:
     488        // For the JavaScript embedding, imports with these types in their signature return are a WebAssembly.Module validation error.
     489        RELEASE_ASSERT_NOT_REACHED();
     490        break;
     491    case I64: {
     492        RELEASE_ASSERT_NOT_REACHED(); // Handled above.
     493    }
     494    case I32: {
     495        CCallHelpers::JumpList done;
     496        CCallHelpers::JumpList slowPath;
     497
     498        slowPath.append(jit.branchIfNotNumber(GPRInfo::returnValueGPR, DoNotHaveTagRegisters));
     499        slowPath.append(jit.branchIfNotInt32(JSValueRegs(GPRInfo::returnValueGPR), DoNotHaveTagRegisters));
     500        jit.zeroExtend32ToPtr(GPRInfo::returnValueGPR, GPRInfo::returnValueGPR);
     501        done.append(jit.jump());
     502
     503        slowPath.link(&jit);
     504        jit.setupArgumentsWithExecState(GPRInfo::returnValueGPR);
     505        auto call = jit.call();
     506        exceptionChecks.append(jit.emitJumpIfException(*vm));
     507
     508        int32_t (*convertToI32)(ExecState*, JSValue) = [] (ExecState* exec, JSValue v) -> int32_t {
     509            VM* vm = &exec->vm();
     510            NativeCallFrameTracer tracer(vm, exec);
     511            return v.toInt32(exec);
     512        };
     513        jit.addLinkTask([=] (LinkBuffer& linkBuffer) {
     514            linkBuffer.link(call, convertToI32);
     515        });
     516
     517        done.link(&jit);
     518        break;
     519    }
     520    case F32: {
     521        CCallHelpers::JumpList done;
     522        auto notANumber = jit.branchIfNotNumber(GPRInfo::returnValueGPR, DoNotHaveTagRegisters);
     523        auto isDouble = jit.branchIfNotInt32(JSValueRegs(GPRInfo::returnValueGPR), DoNotHaveTagRegisters);
     524        // We're an int32
     525        jit.signExtend32ToPtr(GPRInfo::returnValueGPR, GPRInfo::returnValueGPR);
     526        jit.convertInt64ToFloat(GPRInfo::returnValueGPR, FPRInfo::returnValueFPR);
     527        done.append(jit.jump());
     528
     529        isDouble.link(&jit);
     530        jit.move(JIT::TrustedImm64(TagTypeNumber), GPRInfo::returnValueGPR2);
     531        jit.add64(GPRInfo::returnValueGPR2, GPRInfo::returnValueGPR);
     532        jit.move64ToDouble(GPRInfo::returnValueGPR, FPRInfo::returnValueFPR);
     533        jit.convertDoubleToFloat(FPRInfo::returnValueFPR, FPRInfo::returnValueFPR);
     534        done.append(jit.jump());
     535
     536        notANumber.link(&jit);
     537        jit.setupArgumentsWithExecState(GPRInfo::returnValueGPR);
     538        auto call = jit.call();
     539        exceptionChecks.append(jit.emitJumpIfException(*vm));
     540
     541        float (*convertToF32)(ExecState*, JSValue) = [] (ExecState* exec, JSValue v) -> float {
     542            VM* vm = &exec->vm();
     543            NativeCallFrameTracer tracer(vm, exec);
     544            return static_cast<float>(v.toNumber(exec));
     545        };
     546        jit.addLinkTask([=] (LinkBuffer& linkBuffer) {
     547            linkBuffer.link(call, convertToF32);
     548        });
     549
     550        done.link(&jit);
     551        break;
     552    }
     553    case F64: {
     554        CCallHelpers::JumpList done;
     555        auto notANumber = jit.branchIfNotNumber(GPRInfo::returnValueGPR, DoNotHaveTagRegisters);
     556        auto isDouble = jit.branchIfNotInt32(JSValueRegs(GPRInfo::returnValueGPR), DoNotHaveTagRegisters);
     557        // We're an int32
     558        jit.signExtend32ToPtr(GPRInfo::returnValueGPR, GPRInfo::returnValueGPR);
     559        jit.convertInt64ToDouble(GPRInfo::returnValueGPR, FPRInfo::returnValueFPR);
     560        done.append(jit.jump());
     561
     562        isDouble.link(&jit);
     563        jit.move(JIT::TrustedImm64(TagTypeNumber), GPRInfo::returnValueGPR2);
     564        jit.add64(GPRInfo::returnValueGPR2, GPRInfo::returnValueGPR);
     565        jit.move64ToDouble(GPRInfo::returnValueGPR, FPRInfo::returnValueFPR);
     566        done.append(jit.jump());
     567
     568        notANumber.link(&jit);
     569        jit.setupArgumentsWithExecState(GPRInfo::returnValueGPR);
     570        auto call = jit.call();
     571        exceptionChecks.append(jit.emitJumpIfException(*vm));
     572
     573        double (*convertToF64)(ExecState*, JSValue) = [] (ExecState* exec, JSValue v) -> double {
     574            VM* vm = &exec->vm();
     575            NativeCallFrameTracer tracer(vm, exec);
     576            return v.toNumber(exec);
     577        };
     578        jit.addLinkTask([=] (LinkBuffer& linkBuffer) {
     579            linkBuffer.link(call, convertToF64);
     580        });
     581
     582        done.link(&jit);
     583        break;
     584    }
     585    }
     586
     587    jit.emitFunctionEpilogue();
     588    jit.ret();
     589
     590    if (!exceptionChecks.empty()) {
     591        exceptionChecks.link(&jit);
     592        jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm);
     593        jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR0);
     594        auto call = jit.call();
     595        jit.jumpToExceptionHandler(*vm);
     596
     597        void (*doUnwinding)(ExecState*) = [] (ExecState* exec) -> void {
     598            VM* vm = &exec->vm();
     599            NativeCallFrameTracer tracer(vm, exec);
     600            genericUnwind(vm, exec);
     601            ASSERT(!!vm->callFrameForCatch);
     602        };
     603
     604        jit.addLinkTask([=] (LinkBuffer& linkBuffer) {
     605            linkBuffer.link(call, doUnwinding);
     606        });
     607    }
     608
     609    LinkBuffer patchBuffer(jit, GLOBAL_THUNK_ID, JITCompilationCanFail);
     610    if (UNLIKELY(patchBuffer.didFailToAllocate()))
     611        return makeUnexpected(BindingFailure::OutOfMemory);
     612
     613    patchBuffer.link(slowCall, FunctionPtr(vm->getCTIStub(linkCallThunkGenerator).code().executableAddress()));
     614    CodeLocationLabel callReturnLocation(patchBuffer.locationOfNearCall(slowCall));
     615    CodeLocationLabel hotPathBegin(patchBuffer.locationOf(targetToCheck));
     616    CodeLocationNearCall hotPathOther = patchBuffer.locationOfNearCall(fastCall);
     617    callLinkInfo->setCallLocations(callReturnLocation, hotPathBegin, hotPathOther);
     618
     619    return FINALIZE_CODE(patchBuffer, ("WebAssembly->JavaScript import[%i] %s", importIndex, signature.toString().ascii().data()));
     620}
    39621
    40622Expected<MacroAssemblerCodeRef, BindingFailure> wasmToWasm(unsigned importIndex)
     
    52634    GPRReg sizeRegAsScratch = sizeRegs[0].sizeRegister;
    53635
     636    static_assert(std::is_same<Context, JSWebAssemblyInstance>::value, "This is assumed in the code below.");
    54637    // B3's call codegen ensures that the JSCell is a WebAssemblyFunction.
    55     jit.loadWasmContextInstance(sizeRegAsScratch); // Old Instance*
    56     // Get the callee's WebAssembly.Instance and set it as WasmContext's instance. The caller will take care of restoring its own Instance.
    57     jit.loadPtr(JIT::Address(sizeRegAsScratch, JSWebAssemblyInstance::offsetOfTargetInstance(importIndex)), baseMemory); // JSWebAssemblyInstance*.
    58     // While we're accessing that cacheline, also get the wasm entrypoint so we can tail call to it below.
    59     jit.loadPtr(JIT::Address(sizeRegAsScratch, JSWebAssemblyInstance::offsetOfWasmEntrypoint(importIndex)), scratch); // Wasm::WasmEntrypointLoadLocation.
    60     jit.storeWasmContextInstance(baseMemory);
     638    jit.loadWasmContext(sizeRegAsScratch); // Old Instance*
     639    jit.loadPtr(JIT::Address(sizeRegAsScratch, JSWebAssemblyInstance::offsetOfImportFunction(importIndex)), scratch);
     640
     641    // Get the callee's WebAssembly.Instance and set it as WasmContext. The caller will take care of restoring its own Instance.
     642    jit.loadPtr(JIT::Address(scratch, WebAssemblyFunction::offsetOfInstance()), baseMemory); // Instance*.
     643    jit.storeWasmContext(baseMemory);
    61644
    62645    jit.loadPtr(JIT::Address(sizeRegAsScratch, JSWebAssemblyInstance::offsetOfCachedStackLimit()), sizeRegAsScratch);
     
    65648    // FIXME the following code assumes that all WebAssembly.Instance have the same pinned registers. https://bugs.webkit.org/show_bug.cgi?id=162952
    66649    // Set up the callee's baseMemory register as well as the memory size registers.
    67     jit.loadPtr(JIT::Address(baseMemory, JSWebAssemblyInstance::offsetOfWasmMemory()), baseMemory); // Wasm::Memory*.
     650    jit.loadPtr(JIT::Address(baseMemory, JSWebAssemblyInstance::offsetOfMemory()), baseMemory); // JSWebAssemblyMemory*.
    68651    ASSERT(!sizeRegs[0].sizeOffset); // The following code assumes we start at 0, and calculates subsequent size registers relative to 0.
    69     jit.loadPtr(JIT::Address(baseMemory, Wasm::Memory::offsetOfSize()), sizeRegs[0].sizeRegister); // Memory size.
    70     jit.loadPtr(JIT::Address(baseMemory, Wasm::Memory::offsetOfMemory()), baseMemory); // Wasm::Memory::void*.
     652    jit.loadPtr(JIT::Address(baseMemory, JSWebAssemblyMemory::offsetOfSize()), sizeRegs[0].sizeRegister); // Memory size.
     653    jit.loadPtr(JIT::Address(baseMemory, JSWebAssemblyMemory::offsetOfMemory()), baseMemory); // WasmMemory::void*.
    71654    for (unsigned i = 1; i < sizeRegs.size(); ++i) {
    72655        ASSERT(sizeRegs[i].sizeRegister != baseMemory);
     
    76659
    77660    // Tail call into the callee WebAssembly function.
     661    jit.loadPtr(JIT::Address(scratch, WebAssemblyFunction::offsetOfWasmEntrypointLoadLocation()), scratch);
    78662    jit.loadPtr(scratch, scratch);
    79663    jit.jump(scratch);
  • trunk/Source/JavaScriptCore/wasm/WasmBinding.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2929
    3030#include "B3Compilation.h"
     31#include "VM.h"
    3132#include "WasmFormat.h"
     33#include <wtf/Bag.h>
    3234#include <wtf/Expected.h>
    3335
     
    4345
    4446Expected<MacroAssemblerCodeRef, BindingFailure> wasmToWasm(unsigned importIndex);
     47Expected<MacroAssemblerCodeRef, BindingFailure> wasmToJs(VM*, Bag<CallLinkInfo>& callLinkInfos, SignatureIndex, unsigned importIndex);
    4548
    4649} } // namespace JSC::Wasm
  • trunk/Source/JavaScriptCore/wasm/WasmCodeBlock.cpp

    r222791 r223002  
    3232#include "WasmBBQPlanInlines.h"
    3333#include "WasmCallee.h"
    34 #include "WasmFormat.h"
    3534#include "WasmWorklist.h"
    3635
    3736namespace JSC { namespace Wasm {
    3837
    39 Ref<CodeBlock> CodeBlock::create(Context* context, MemoryMode mode, ModuleInformation& moduleInformation, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
    40 {
    41     size_t importFunctionCount = moduleInformation.importFunctionCount();
    42     auto* result = new (NotNull, fastMalloc(allocationSize(importFunctionCount))) CodeBlock(context, mode, moduleInformation, WTFMove(createEmbedderWrapper), throwWasmException);
    43     for (size_t i = 0; i < importFunctionCount; ++i)
    44         result->importWasmToEmbedderStub(i) = nullptr;
    45     return adoptRef(*result);
    46 }
    47 
    48 CodeBlock::CodeBlock(Context* context, MemoryMode mode, ModuleInformation& moduleInformation, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
     38CodeBlock::CodeBlock(MemoryMode mode, ModuleInformation& moduleInformation)
    4939    : m_calleeCount(moduleInformation.internalFunctionCount())
    5040    , m_mode(mode)
    5141{
    5242    RefPtr<CodeBlock> protectedThis = this;
    53 
    54     m_plan = adoptRef(*new BBQPlan(context, makeRef(moduleInformation), BBQPlan::FullCompile, createSharedTask<Plan::CallbackType>([this, protectedThis = WTFMove(protectedThis)] (Plan&) {
     43    m_plan = adoptRef(*new BBQPlan(nullptr, makeRef(moduleInformation), BBQPlan::FullCompile, createSharedTask<Plan::CallbackType>([this, protectedThis = WTFMove(protectedThis)] (VM*, Plan&) {
    5544        auto locker = holdLock(m_lock);
    5645        if (m_plan->failed()) {
    5746            m_errorMessage = m_plan->errorMessage();
    58             setCompilationFinished();
     47            m_plan = nullptr;
    5948            return;
    6049        }
     
    7867        m_tierUpCounts = m_plan->takeTierUpCounts();
    7968
    80         setCompilationFinished();
    81     }), WTFMove(createEmbedderWrapper), throwWasmException));
     69        m_plan = nullptr;
     70    })));
     71
    8272    m_plan->setMode(mode);
    83 
    8473    auto& worklist = Wasm::ensureWorklist();
    8574    // Note, immediately after we enqueue the plan, there is a chance the above callback will be called.
     
    10493}
    10594
    106 void CodeBlock::compileAsync(Context* context, AsyncCompilationCallback&& task)
     95void CodeBlock::compileAsync(VM& vm, AsyncCompilationCallback&& task)
    10796{
    10897    RefPtr<Plan> plan;
     
    116105        // a RefPtr on the Plan until the plan finishes notifying all of its callbacks.
    117106        RefPtr<CodeBlock> protectedThis = this;
    118         plan->addCompletionTask(context, createSharedTask<Plan::CallbackType>([this, task = WTFMove(task), protectedThis = WTFMove(protectedThis)] (Plan&) {
    119             task->run(makeRef(*this));
     107        plan->addCompletionTask(vm, createSharedTask<Plan::CallbackType>([this, task = WTFMove(task), protectedThis = WTFMove(protectedThis)] (VM* vm, Plan&) {
     108            ASSERT(vm);
     109            task->run(*vm, makeRef(*this));
    120110        }));
    121111    } else
    122         task->run(makeRef(*this));
     112        task->run(vm, makeRef(*this));
    123113}
    124114
     
    141131}
    142132
    143 
    144 void CodeBlock::setCompilationFinished()
    145 {
    146     m_plan = nullptr;
    147     m_compilationFinished.store(true);
    148 }
    149 
    150133} } // namespace JSC::Wasm
    151134
  • trunk/Source/JavaScriptCore/wasm/WasmCodeBlock.h

    r222791 r223002  
    2929
    3030#include "MacroAssemblerCodeRef.h"
    31 #include "WasmEmbedder.h"
    3231#include "WasmTierUpCount.h"
    3332#include <wtf/Lock.h>
     
    3938namespace JSC {
    4039
     40class VM;
     41
    4142namespace Wasm {
    4243
    4344class Callee;
    44 struct Context;
    4545class BBQPlan;
    4646class OMGPlan;
     
    5252class CodeBlock : public ThreadSafeRefCounted<CodeBlock> {
    5353public:
    54     typedef void CallbackType(Ref<CodeBlock>&&);
     54    typedef void CallbackType(VM&, Ref<CodeBlock>&&);
    5555    using AsyncCompilationCallback = RefPtr<WTF::SharedTask<CallbackType>>;
    56     static Ref<CodeBlock> create(Context*, MemoryMode, ModuleInformation&, CreateEmbedderWrapper&&, ThrowWasmException);
    57 
    58     static size_t offsetOfImportStubs()
     56    static Ref<CodeBlock> create(MemoryMode mode, ModuleInformation& moduleInformation)
    5957    {
    60         return WTF::roundUpToMultipleOf<sizeof(void*)>(sizeof(CodeBlock));
    61     }
    62 
    63     static size_t allocationSize(Checked<size_t> functionImportCount)
    64     {
    65         return (offsetOfImportStubs() + sizeof(void*) * functionImportCount).unsafeGet();
    66     }
    67 
    68     void*& importWasmToEmbedderStub(unsigned importIndex)
    69     {
    70         return *bitwise_cast<void**>(bitwise_cast<char*>(this) + offsetOfImportWasmToEmbedderStub(importIndex));
    71     }
    72 
    73     static ptrdiff_t offsetOfImportWasmToEmbedderStub(unsigned importIndex)
    74     {
    75         return offsetOfImportStubs() + sizeof(void*) * importIndex;
    76     }
    77 
    78     Wasm::WasmEntrypointLoadLocation wasmToJSCallStubForImport(unsigned importIndex)
    79     {
    80         ASSERT(runnable());
    81         return &importWasmToEmbedderStub(importIndex);
     58        return adoptRef(*new CodeBlock(mode, moduleInformation));
    8259    }
    8360
    8461    void waitUntilFinished();
    85     void compileAsync(Context*, AsyncCompilationCallback&&);
     62    void compileAsync(VM&, AsyncCompilationCallback&&);
    8663
    8764    bool compilationFinished()
    8865    {
    89         return m_compilationFinished.load();
     66        auto locker = holdLock(m_lock);
     67        return !m_plan;
    9068    }
    9169    bool runnable() { return compilationFinished() && !m_errorMessage; }
     
    10280    unsigned functionImportCount() const { return m_wasmToWasmExitStubs.size(); }
    10381
    104     // These two callee getters are only valid once the callees have been populated.
    105 
    10682    Callee& jsEntrypointCalleeFromFunctionIndexSpace(unsigned functionIndexSpace)
    10783    {
    108         ASSERT(runnable());
    10984        RELEASE_ASSERT(functionIndexSpace >= functionImportCount());
    11085        unsigned calleeIndex = functionIndexSpace - functionImportCount();
     
    11691    Callee& wasmEntrypointCalleeFromFunctionIndexSpace(unsigned functionIndexSpace)
    11792    {
    118         ASSERT(runnable());
    11993        RELEASE_ASSERT(functionIndexSpace >= functionImportCount());
    12094        unsigned calleeIndex = functionIndexSpace - functionImportCount();
     
    144118    friend class OMGPlan;
    145119
    146     CodeBlock(Context*, MemoryMode, ModuleInformation&, CreateEmbedderWrapper&&, ThrowWasmException);
    147     void setCompilationFinished();
     120    CodeBlock(MemoryMode, ModuleInformation&);
    148121    unsigned m_calleeCount;
    149122    MemoryMode m_mode;
     
    156129    Vector<MacroAssemblerCodeRef> m_wasmToWasmExitStubs;
    157130    RefPtr<BBQPlan> m_plan;
    158     std::atomic<bool> m_compilationFinished { false };
    159131    String m_errorMessage;
    160132    Lock m_lock;
  • trunk/Source/JavaScriptCore/wasm/WasmContext.cpp

    r222873 r223002  
    2929#if ENABLE(WEBASSEMBLY)
    3030
    31 #include "JSWebAssemblyInstance.h"
    32 #include "Options.h"
    33 
     31#include "VM.h"
    3432#include <mutex>
    3533#include <wtf/FastTLS.h>
     
    3735namespace JSC { namespace Wasm {
    3836
    39 bool Context::useFastTLS()
     37Context* loadContext(VM& vm)
    4038{
    4139#if ENABLE(FAST_TLS_JIT)
    42     return Options::useFastTLSForWasmContext();
    43 #else
    44     return false;
     40    if (useFastTLSForContext())
     41        return bitwise_cast<Context*>(_pthread_getspecific_direct(WTF_WASM_CONTEXT_KEY));
    4542#endif
     43    return vm.wasmContext;
    4644}
    4745
    48 JSWebAssemblyInstance* Context::load() const
     46void storeContext(VM& vm, Context* context)
    4947{
    5048#if ENABLE(FAST_TLS_JIT)
    51     if (useFastTLS())
    52         return bitwise_cast<JSWebAssemblyInstance*>(_pthread_getspecific_direct(WTF_WASM_CONTEXT_KEY));
     49    if (useFastTLSForContext())
     50        _pthread_setspecific_direct(WTF_WASM_CONTEXT_KEY, bitwise_cast<void*>(context));
    5351#endif
    54     return instance;
    55 }
    56 
    57 void Context::store(JSWebAssemblyInstance* inst, void* softStackLimit)
    58 {
    59 #if ENABLE(FAST_TLS_JIT)
    60     if (useFastTLS())
    61         _pthread_setspecific_direct(WTF_WASM_CONTEXT_KEY, bitwise_cast<void*>(inst));
    62 #endif
    63     instance = inst;
    64     if (instance)
    65         instance->setCachedStackLimit(softStackLimit);
     52    vm.wasmContext = context;
     53    if (context)
     54        context->setCachedStackLimit(vm.softStackLimit());
    6655}
    6756
  • trunk/Source/JavaScriptCore/wasm/WasmContext.h

    r222791 r223002  
    2828#if ENABLE(WEBASSEMBLY)
    2929
     30#include "JSWebAssemblyInstance.h"
     31#include "Options.h"
     32
    3033namespace JSC {
    3134
    32 class JSWebAssemblyInstance;
     35class VM;
    3336
    3437namespace Wasm {
    3538
    36 struct Context {
    37     JSWebAssemblyInstance* instance { nullptr };
     39// FIXME: We might want this to be something else at some point:
     40// https://bugs.webkit.org/show_bug.cgi?id=170260
     41using Context = JSWebAssemblyInstance;
    3842
    39     JSWebAssemblyInstance* load() const;
    40     void store(JSWebAssemblyInstance*, void* softStackLimit);
     43inline bool useFastTLS()
     44{
     45#if ENABLE(FAST_TLS_JIT)
     46    return Options::useWebAssemblyFastTLS();
     47#else
     48    return false;
     49#endif
     50}
    4151
    42     static bool useFastTLS();
    43 };
     52inline bool useFastTLSForContext()
     53{
     54    if (useFastTLS())
     55        return Options::useFastTLSForWasmContext();
     56    return false;
     57}
     58
     59Context* loadContext(VM&);
     60void storeContext(VM&, Context*);
    4461
    4562} } // namespace JSC::Wasm
  • trunk/Source/JavaScriptCore/wasm/WasmFaultSignalHandler.cpp

    r222791 r223002  
    3131#include "ExecutableAllocator.h"
    3232#include "MachineContext.h"
     33#include "VM.h"
    3334#include "WasmExceptionType.h"
    3435#include "WasmMemory.h"
    3536#include "WasmThunks.h"
    3637
    37 #include <wtf/HashSet.h>
    3838#include <wtf/Lock.h>
    3939#include <wtf/NeverDestroyed.h>
  • trunk/Source/JavaScriptCore/wasm/WasmFaultSignalHandler.h

    r222791 r223002  
    2828namespace JSC {
    2929
     30class VM;
     31
    3032namespace Wasm {
    3133
  • trunk/Source/JavaScriptCore/wasm/WasmFormat.h

    r222791 r223002  
    4545namespace JSC {
    4646
     47class JSFunction;
     48
    4749namespace B3 {
    4850class Compilation;
     
    5052
    5153namespace Wasm {
    52 
    53 struct CompilationContext;
    54 struct ModuleInformation;
    5554
    5655inline bool isValueType(Type type)
  • trunk/Source/JavaScriptCore/wasm/WasmMemory.cpp

    r222791 r223002  
    2929#if ENABLE(WEBASSEMBLY)
    3030
    31 #include "Options.h"
    32 #include <wtf/DataLog.h>
     31#include "VM.h"
     32#include "WasmThunks.h"
    3333#include <wtf/Gigacage.h>
    3434#include <wtf/Lock.h>
    35 #include <wtf/OSAllocator.h>
    36 #include <wtf/PageBlock.h>
    3735#include <wtf/Platform.h>
    3836#include <wtf/PrintStream.h>
    3937#include <wtf/RAMSize.h>
    40 #include <wtf/Vector.h>
    41 
    42 #include <cstring>
    43 #include <mutex>
    4438
    4539namespace JSC { namespace Wasm {
     
    5852    enum Kind {
    5953        Success,
    60         SuccessAndNotifyMemoryPressure,
    61         SyncTryToReclaimMemory
     54        SuccessAndAsyncGC,
     55        SyncGCAndRetry
    6256    };
    63 
     57   
    6458    static const char* toString(Kind kind)
    6559    {
     
    6761        case Success:
    6862            return "Success";
    69         case SuccessAndNotifyMemoryPressure:
    70             return "SuccessAndNotifyMemoryPressure";
    71         case SyncTryToReclaimMemory:
    72             return "SyncTryToReclaimMemory";
     63        case SuccessAndAsyncGC:
     64            return "SuccessAndAsyncGC";
     65        case SyncGCAndRetry:
     66            return "SyncGCAndRetry";
    7367        }
    7468        RELEASE_ASSERT_NOT_REACHED();
     
    10599            auto holder = holdLock(m_lock);
    106100            if (m_memories.size() >= m_maxCount)
    107                 return MemoryResult(nullptr, MemoryResult::SyncTryToReclaimMemory);
     101                return MemoryResult(nullptr, MemoryResult::SyncGCAndRetry);
    108102           
    109103            void* result = Gigacage::tryAllocateVirtualPages(Gigacage::Primitive, Memory::fastMappedBytes());
    110104            if (!result)
    111                 return MemoryResult(nullptr, MemoryResult::SyncTryToReclaimMemory);
     105                return MemoryResult(nullptr, MemoryResult::SyncGCAndRetry);
    112106           
    113107            m_memories.append(result);
     
    115109            return MemoryResult(
    116110                result,
    117                 m_memories.size() >= m_maxCount / 2 ? MemoryResult::SuccessAndNotifyMemoryPressure : MemoryResult::Success);
     111                m_memories.size() >= m_maxCount / 2 ? MemoryResult::SuccessAndAsyncGC : MemoryResult::Success);
    118112        }();
    119113       
     
    160154            auto holder = holdLock(m_lock);
    161155            if (m_physicalBytes + bytes > memoryLimit())
    162                 return MemoryResult::SyncTryToReclaimMemory;
     156                return MemoryResult::SyncGCAndRetry;
    163157           
    164158            m_physicalBytes += bytes;
    165159           
    166160            if (m_physicalBytes >= memoryLimit() / 2)
    167                 return MemoryResult::SuccessAndNotifyMemoryPressure;
     161                return MemoryResult::SuccessAndAsyncGC;
    168162           
    169163            return MemoryResult::Success;
     
    212206
    213207template<typename Func>
    214 bool tryAllocate(const Func& allocate, const WTF::Function<void(Memory::NotifyPressure)>& notifyMemoryPressure, const WTF::Function<void(Memory::SyncTryToReclaim)>& syncTryToReclaimMemory)
     208bool tryAndGC(VM& vm, const Func& allocate)
    215209{
    216210    unsigned numTries = 2;
     
    221215            done = true;
    222216            break;
    223         case MemoryResult::SuccessAndNotifyMemoryPressure:
    224             if (notifyMemoryPressure)
    225                 notifyMemoryPressure(Memory::NotifyPressureTag);
     217        case MemoryResult::SuccessAndAsyncGC:
     218            vm.heap.collectAsync(CollectionScope::Full);
    226219            done = true;
    227220            break;
    228         case MemoryResult::SyncTryToReclaimMemory:
     221        case MemoryResult::SyncGCAndRetry:
    229222            if (i + 1 == numTries)
    230223                break;
    231             if (syncTryToReclaimMemory)
    232                 syncTryToReclaimMemory(Memory::SyncTryToReclaimTag);
     224            vm.heap.collectSync(CollectionScope::Full);
    233225            break;
    234226        }
     
    239231} // anonymous namespace
    240232
    241 Memory::Memory()
    242 {
    243 }
    244 
    245 Memory::Memory(PageCount initial, PageCount maximum, Function<void(NotifyPressure)>&& notifyMemoryPressure, Function<void(SyncTryToReclaim)>&& syncTryToReclaimMemory, WTF::Function<void(GrowSuccess, PageCount, PageCount)>&& growSuccessCallback)
     233const char* makeString(MemoryMode mode)
     234{
     235    switch (mode) {
     236    case MemoryMode::BoundsChecking: return "BoundsChecking";
     237    case MemoryMode::Signaling: return "Signaling";
     238    }
     239    RELEASE_ASSERT_NOT_REACHED();
     240    return "";
     241}
     242
     243Memory::Memory(PageCount initial, PageCount maximum)
    246244    : m_initial(initial)
    247245    , m_maximum(maximum)
    248     , m_notifyMemoryPressure(WTFMove(notifyMemoryPressure))
    249     , m_syncTryToReclaimMemory(WTFMove(syncTryToReclaimMemory))
    250     , m_growSuccessCallback(WTFMove(growSuccessCallback))
    251246{
    252247    ASSERT(!initial.bytes());
     
    255250}
    256251
    257 Memory::Memory(void* memory, PageCount initial, PageCount maximum, size_t mappedCapacity, MemoryMode mode, Function<void(NotifyPressure)>&& notifyMemoryPressure, Function<void(SyncTryToReclaim)>&& syncTryToReclaimMemory, WTF::Function<void(GrowSuccess, PageCount, PageCount)>&& growSuccessCallback)
     252Memory::Memory(void* memory, PageCount initial, PageCount maximum, size_t mappedCapacity, MemoryMode mode)
    258253    : m_memory(memory)
    259254    , m_size(initial.bytes())
     
    262257    , m_mappedCapacity(mappedCapacity)
    263258    , m_mode(mode)
    264     , m_notifyMemoryPressure(WTFMove(notifyMemoryPressure))
    265     , m_syncTryToReclaimMemory(WTFMove(syncTryToReclaimMemory))
    266     , m_growSuccessCallback(WTFMove(growSuccessCallback))
    267259{
    268260    dataLogLnIf(verbose, "Memory::Memory allocating ", *this);
     
    284276}
    285277
    286 RefPtr<Memory> Memory::create()
    287 {
    288     return adoptRef(new Memory());
    289 }
    290 
    291 RefPtr<Memory> Memory::create(PageCount initial, PageCount maximum, WTF::Function<void(NotifyPressure)>&& notifyMemoryPressure, WTF::Function<void(SyncTryToReclaim)>&& syncTryToReclaimMemory, WTF::Function<void(GrowSuccess, PageCount, PageCount)>&& growSuccessCallback)
     278RefPtr<Memory> Memory::create(VM& vm, PageCount initial, PageCount maximum)
    292279{
    293280    ASSERT(initial);
     
    296283    const size_t initialBytes = initial.bytes();
    297284    const size_t maximumBytes = maximum ? maximum.bytes() : 0;
     285
     286    // We need to be sure we have a stub prior to running code.
     287    if (UNLIKELY(!Thunks::singleton().stub(throwExceptionFromWasmThunkGenerator)))
     288        return nullptr;
    298289
    299290    if (maximum && !maximumBytes) {
    300291        // User specified a zero maximum, initial size must also be zero.
    301292        RELEASE_ASSERT(!initialBytes);
    302         return adoptRef(new Memory(initial, maximum, WTFMove(notifyMemoryPressure), WTFMove(syncTryToReclaimMemory), WTFMove(growSuccessCallback)));
    303     }
    304    
    305     bool done = tryAllocate(
     293        return adoptRef(new Memory(initial, maximum));
     294    }
     295   
     296    bool done = tryAndGC(
     297        vm,
    306298        [&] () -> MemoryResult::Kind {
    307299            return memoryManager().tryAllocatePhysicalBytes(initialBytes);
    308         }, notifyMemoryPressure, syncTryToReclaimMemory);
     300        });
    309301    if (!done)
    310302        return nullptr;
     
    312304    char* fastMemory = nullptr;
    313305    if (Options::useWebAssemblyFastMemory()) {
    314         tryAllocate(
     306        tryAndGC(
     307            vm,
    315308            [&] () -> MemoryResult::Kind {
    316309                auto result = memoryManager().tryAllocateVirtualPages();
    317310                fastMemory = bitwise_cast<char*>(result.basePtr);
    318311                return result.kind;
    319             }, notifyMemoryPressure, syncTryToReclaimMemory);
     312            });
    320313    }
    321314   
     
    328321
    329322        commitZeroPages(fastMemory, initialBytes);
    330 
    331         return adoptRef(new Memory(fastMemory, initial, maximum, Memory::fastMappedBytes(), MemoryMode::Signaling, WTFMove(notifyMemoryPressure), WTFMove(syncTryToReclaimMemory), WTFMove(growSuccessCallback)));
     323       
     324        return adoptRef(new Memory(fastMemory, initial, maximum, Memory::fastMappedBytes(), MemoryMode::Signaling));
    332325    }
    333326   
     
    336329
    337330    if (!initialBytes)
    338         return adoptRef(new Memory(initial, maximum, WTFMove(notifyMemoryPressure), WTFMove(syncTryToReclaimMemory), WTFMove(growSuccessCallback)));
     331        return adoptRef(new Memory(initial, maximum));
    339332   
    340333    void* slowMemory = Gigacage::tryAlignedMalloc(Gigacage::Primitive, WTF::pageSize(), initialBytes);
     
    344337    }
    345338    memset(slowMemory, 0, initialBytes);
    346     return adoptRef(new Memory(slowMemory, initial, maximum, initialBytes, MemoryMode::BoundsChecking, WTFMove(notifyMemoryPressure), WTFMove(syncTryToReclaimMemory), WTFMove(growSuccessCallback)));
     339    return adoptRef(new Memory(slowMemory, initial, maximum, initialBytes, MemoryMode::BoundsChecking));
    347340}
    348341
     
    353346        switch (m_mode) {
    354347        case MemoryMode::Signaling:
    355             if (mprotect(m_memory, Memory::fastMappedBytes(), PROT_READ | PROT_WRITE)) {
    356                 dataLog("mprotect failed: ", strerror(errno), "\n");
    357                 RELEASE_ASSERT_NOT_REACHED();
    358             }
     348            mprotect(m_memory, Memory::fastMappedBytes(), PROT_READ | PROT_WRITE);
    359349            memoryManager().freeVirtualPages(m_memory);
    360350            break;
     
    382372}
    383373
    384 Expected<PageCount, Memory::GrowFailReason> Memory::grow(PageCount delta)
    385 {
    386     const Wasm::PageCount oldPageCount = sizeInPages();
    387 
    388     if (!delta.isValid())
    389         return makeUnexpected(GrowFailReason::InvalidDelta);
    390    
    391     const Wasm::PageCount newPageCount = oldPageCount + delta;
    392     if (!newPageCount)
    393         return makeUnexpected(GrowFailReason::InvalidGrowSize);
    394 
    395     auto success = [&] () {
    396         m_growSuccessCallback(GrowSuccessTag, oldPageCount, newPageCount);
    397         return oldPageCount;
    398     };
    399 
    400     if (delta.pageCount() == 0)
    401         return success();
    402 
    403     dataLogLnIf(verbose, "Memory::grow(", delta, ") to ", newPageCount, " from ", *this);
    404     RELEASE_ASSERT(newPageCount > PageCount::fromBytes(m_size));
    405 
    406     if (maximum() && newPageCount > maximum())
    407         return makeUnexpected(GrowFailReason::WouldExceedMaximum);
    408 
    409     size_t desiredSize = newPageCount.bytes();
     374bool Memory::grow(VM& vm, PageCount newSize)
     375{
     376    RELEASE_ASSERT(newSize > PageCount::fromBytes(m_size));
     377
     378    dataLogLnIf(verbose, "Memory::grow to ", newSize, " from ", *this);
     379
     380    if (maximum() && newSize > maximum())
     381        return false;
     382
     383    size_t desiredSize = newSize.bytes();
    410384    RELEASE_ASSERT(desiredSize > m_size);
    411385    size_t extraBytes = desiredSize - m_size;
    412386    RELEASE_ASSERT(extraBytes);
    413     bool allocationSuccess = tryAllocate(
     387    bool success = tryAndGC(
     388        vm,
    414389        [&] () -> MemoryResult::Kind {
    415390            return memoryManager().tryAllocatePhysicalBytes(extraBytes);
    416         }, m_notifyMemoryPressure, m_syncTryToReclaimMemory);
    417     if (!allocationSuccess)
    418         return makeUnexpected(GrowFailReason::OutOfMemory);
    419 
     391        });
     392    if (!success)
     393        return false;
     394       
    420395    switch (mode()) {
    421396    case MemoryMode::BoundsChecking: {
    422397        RELEASE_ASSERT(maximum().bytes() != 0);
    423 
     398       
    424399        void* newMemory = Gigacage::tryAlignedMalloc(Gigacage::Primitive, WTF::pageSize(), desiredSize);
    425400        if (!newMemory)
    426             return makeUnexpected(GrowFailReason::OutOfMemory);
    427 
     401            return false;
    428402        memcpy(newMemory, m_memory, m_size);
    429403        memset(static_cast<char*>(newMemory) + m_size, 0, desiredSize - m_size);
     
    433407        m_mappedCapacity = desiredSize;
    434408        m_size = desiredSize;
    435         return success();
     409        return true;
    436410    }
    437411    case MemoryMode::Signaling: {
     
    442416        dataLogLnIf(verbose, "Marking WebAssembly memory's ", RawPointer(m_memory), " as read+write in range [", RawPointer(startAddress), ", ", RawPointer(startAddress + extraBytes), ")");
    443417        if (mprotect(startAddress, extraBytes, PROT_READ | PROT_WRITE)) {
    444             dataLog("mprotect failed: ", strerror(errno), "\n");
    445             RELEASE_ASSERT_NOT_REACHED();
     418            dataLogLnIf(verbose, "Memory::grow in-place failed ", *this);
     419            return false;
    446420        }
    447421        commitZeroPages(startAddress, extraBytes);
    448422        m_size = desiredSize;
    449         return success();
    450     }
    451     }
    452 
     423        return true;
     424    } }
     425   
    453426    RELEASE_ASSERT_NOT_REACHED();
    454     return oldPageCount;
     427    return false;
    455428}
    456429
  • trunk/Source/JavaScriptCore/wasm/WasmMemory.h

    r222791 r223002  
    2828#if ENABLE(WEBASSEMBLY)
    2929
    30 #include "WasmMemoryMode.h"
    3130#include "WasmPageCount.h"
    3231
    33 #include <wtf/Expected.h>
    34 #include <wtf/Function.h>
    3532#include <wtf/RefCounted.h>
    3633#include <wtf/RefPtr.h>
     
    4239namespace JSC {
    4340
     41class VM;
     42
    4443namespace Wasm {
     44
     45// FIXME: We should support other modes. see: https://bugs.webkit.org/show_bug.cgi?id=162693
     46enum class MemoryMode : uint8_t {
     47    BoundsChecking,
     48    Signaling
     49};
     50static constexpr size_t NumberOfMemoryModes = 2;
     51JS_EXPORT_PRIVATE const char* makeString(MemoryMode);
    4552
    4653class Memory : public RefCounted<Memory> {
     
    5259    explicit operator bool() const { return !!m_memory; }
    5360   
    54     enum NotifyPressure { NotifyPressureTag };
    55     enum SyncTryToReclaim { SyncTryToReclaimTag };
    56     enum GrowSuccess { GrowSuccessTag };
    57 
    58     static RefPtr<Memory> create();
    59     static RefPtr<Memory> create(PageCount initial, PageCount maximum, WTF::Function<void(NotifyPressure)>&& notifyMemoryPressure, WTF::Function<void(SyncTryToReclaim)>&& syncTryToReclaimMemory, WTF::Function<void(GrowSuccess, PageCount, PageCount)>&& growSuccessCallback);
     61    static RefPtr<Memory> create(VM&, PageCount initial, PageCount maximum);
    6062
    6163    ~Memory();
     
    7476    MemoryMode mode() const { return m_mode; }
    7577
    76     enum class GrowFailReason {
    77         InvalidDelta,
    78         InvalidGrowSize,
    79         WouldExceedMaximum,
    80         OutOfMemory,
    81     };
    82     Expected<PageCount, GrowFailReason> grow(PageCount);
     78    // grow() should only be called from the JSWebAssemblyMemory object since that object needs to update internal
     79    // pointers with the current base and size.
     80    bool grow(VM&, PageCount);
    8381
    8482    void check() {  ASSERT(!deletionHasBegun()); }
     83private:
     84    Memory(void* memory, PageCount initial, PageCount maximum, size_t mappedCapacity, MemoryMode);
     85    Memory(PageCount initial, PageCount maximum);
    8586
    86     static ptrdiff_t offsetOfMemory() { return OBJECT_OFFSETOF(Memory, m_memory); }
    87     static ptrdiff_t offsetOfSize() { return OBJECT_OFFSETOF(Memory, m_size); }
    88 
    89 private:
    90     Memory();
    91     Memory(void* memory, PageCount initial, PageCount maximum, size_t mappedCapacity, MemoryMode, WTF::Function<void(NotifyPressure)>&& notifyMemoryPressure, WTF::Function<void(SyncTryToReclaim)>&& syncTryToReclaimMemory, WTF::Function<void(GrowSuccess, PageCount, PageCount)>&& growSuccessCallback);
    92     Memory(PageCount initial, PageCount maximum, WTF::Function<void(NotifyPressure)>&& notifyMemoryPressure, WTF::Function<void(SyncTryToReclaim)>&& syncTryToReclaimMemory, WTF::Function<void(GrowSuccess, PageCount, PageCount)>&& growSuccessCallback);
    93 
    94     // FIXME: we cache these on the instances to avoid a load on instance->instance calls. This will require updating all the instances when grow is called. https://bugs.webkit.org/show_bug.cgi?id=177305
     87    // FIXME: we should move these to the instance to avoid a load on instance->instance calls.
    9588    void* m_memory { nullptr };
    9689    size_t m_size { 0 };
     
    9992    size_t m_mappedCapacity { 0 };
    10093    MemoryMode m_mode { MemoryMode::BoundsChecking };
    101     WTF::Function<void(NotifyPressure)> m_notifyMemoryPressure;
    102     WTF::Function<void(SyncTryToReclaim)> m_syncTryToReclaimMemory;
    103     WTF::Function<void(GrowSuccess, PageCount, PageCount)> m_growSuccessCallback;
    10494};
    10595
  • trunk/Source/JavaScriptCore/wasm/WasmMemoryInformation.cpp

    r222791 r223002  
    5858        Vector<PinnedSizeRegisterInfo> sizeRegisters;
    5959        GPRReg baseMemoryPointer = InvalidGPRReg;
    60         GPRReg wasmContextInstancePointer = InvalidGPRReg;
     60        GPRReg wasmContextPointer = InvalidGPRReg;
    6161
    6262        // FIXME: We should support more than one memory size register, and we should allow different
     
    6666        Vector<unsigned> pinnedSizes = { 0 };
    6767        unsigned numberOfPinnedRegisters = pinnedSizes.size() + 1;
    68         if (!Context::useFastTLS())
     68        if (!useFastTLSForContext())
    6969            ++numberOfPinnedRegisters;
    7070        Vector<GPRReg> pinnedRegs = getPinnedRegisters(numberOfPinnedRegisters);
    7171
    7272        baseMemoryPointer = pinnedRegs.takeLast();
    73         if (!Context::useFastTLS())
    74             wasmContextInstancePointer = pinnedRegs.takeLast();
     73        if (!useFastTLSForContext())
     74            wasmContextPointer = pinnedRegs.takeLast();
    7575
    7676        ASSERT(pinnedSizes.size() == pinnedRegs.size());
    7777        for (unsigned i = 0; i < pinnedSizes.size(); ++i)
    7878            sizeRegisters.append({ pinnedRegs[i], pinnedSizes[i] });
    79         staticPinnedRegisterInfo.construct(WTFMove(sizeRegisters), baseMemoryPointer, wasmContextInstancePointer);
     79        staticPinnedRegisterInfo.construct(WTFMove(sizeRegisters), baseMemoryPointer, wasmContextPointer);
    8080    });
    8181
     
    8383}
    8484
    85 PinnedRegisterInfo::PinnedRegisterInfo(Vector<PinnedSizeRegisterInfo>&& sizeRegisters, GPRReg baseMemoryPointer, GPRReg wasmContextInstancePointer)
     85PinnedRegisterInfo::PinnedRegisterInfo(Vector<PinnedSizeRegisterInfo>&& sizeRegisters, GPRReg baseMemoryPointer, GPRReg wasmContextPointer)
    8686    : sizeRegisters(WTFMove(sizeRegisters))
    8787    , baseMemoryPointer(baseMemoryPointer)
    88     , wasmContextInstancePointer(wasmContextInstancePointer)
     88    , wasmContextPointer(wasmContextPointer)
    8989{
    9090}
  • trunk/Source/JavaScriptCore/wasm/WasmMemoryInformation.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    4545    Vector<PinnedSizeRegisterInfo> sizeRegisters;
    4646    GPRReg baseMemoryPointer;
    47     GPRReg wasmContextInstancePointer;
     47    GPRReg wasmContextPointer;
    4848    static const PinnedRegisterInfo& get();
    4949    PinnedRegisterInfo(Vector<PinnedSizeRegisterInfo>&&, GPRReg, GPRReg);
     
    5353        RegisterSet result;
    5454        result.set(baseMemoryPointer);
    55         if (wasmContextInstancePointer != InvalidGPRReg)
    56             result.set(wasmContextInstancePointer);
     55        if (wasmContextPointer != InvalidGPRReg)
     56            result.set(wasmContextPointer);
    5757        if (mode != MemoryMode::Signaling) {
    5858            for (const auto& info : sizeRegisters)
  • trunk/Source/JavaScriptCore/wasm/WasmModule.cpp

    r222878 r223002  
    5757static Plan::CompletionTask makeValidationCallback(Module::AsyncValidationCallback&& callback)
    5858{
    59     return createSharedTask<Plan::CallbackType>([callback = WTFMove(callback)] (Plan& plan) {
     59    return createSharedTask<Plan::CallbackType>([callback = WTFMove(callback)] (VM* vm, Plan& plan) {
    6060        ASSERT(!plan.hasWork());
    61         callback->run(makeValidationResult(static_cast<BBQPlan&>(plan)));
     61        ASSERT(vm);
     62        callback->run(*vm, makeValidationResult(static_cast<BBQPlan&>(plan)));
    6263    });
    6364}
    6465
    65 Module::ValidationResult Module::validateSync(Context* context, Vector<uint8_t>&& source)
     66Module::ValidationResult Module::validateSync(VM& vm, Vector<uint8_t>&& source)
    6667{
    67     Ref<BBQPlan> plan = adoptRef(*new BBQPlan(context, WTFMove(source), BBQPlan::Validation, Plan::dontFinalize(), nullptr, nullptr));
     68    Ref<BBQPlan> plan = adoptRef(*new BBQPlan(&vm, WTFMove(source), BBQPlan::Validation, Plan::dontFinalize()));
    6869    plan->parseAndValidateModule();
    6970    return makeValidationResult(plan.get());
    7071}
    7172
    72 void Module::validateAsync(Context* context, Vector<uint8_t>&& source, Module::AsyncValidationCallback&& callback)
     73void Module::validateAsync(VM& vm, Vector<uint8_t>&& source, Module::AsyncValidationCallback&& callback)
    7374{
    74     Ref<Plan> plan = adoptRef(*new BBQPlan(context, WTFMove(source), BBQPlan::Validation, makeValidationCallback(WTFMove(callback)), nullptr, nullptr));
     75    Ref<Plan> plan = adoptRef(*new BBQPlan(&vm, WTFMove(source), BBQPlan::Validation, makeValidationCallback(WTFMove(callback))));
    7576    Wasm::ensureWorklist().enqueue(WTFMove(plan));
    7677}
    7778
    78 Ref<CodeBlock> Module::getOrCreateCodeBlock(Context* context, MemoryMode mode, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
     79Ref<CodeBlock> Module::getOrCreateCodeBlock(MemoryMode mode)
    7980{
    8081    RefPtr<CodeBlock> codeBlock;
     
    8788    // https://bugs.webkit.org/show_bug.cgi?id=170607
    8889    if (!codeBlock || (codeBlock->compilationFinished() && !codeBlock->runnable())) {
    89         codeBlock = CodeBlock::create(context, mode, const_cast<ModuleInformation&>(moduleInformation()), WTFMove(createEmbedderWrapper), throwWasmException);
     90        codeBlock = CodeBlock::create(mode, const_cast<ModuleInformation&>(moduleInformation()));
    9091        m_codeBlocks[static_cast<uint8_t>(mode)] = codeBlock;
    9192    }
     
    9394}
    9495
    95 Ref<CodeBlock> Module::compileSync(Context* context, MemoryMode mode, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
     96Ref<CodeBlock> Module::compileSync(MemoryMode mode)
    9697{
    97     Ref<CodeBlock> codeBlock = getOrCreateCodeBlock(context, mode, WTFMove(createEmbedderWrapper), throwWasmException);
     98    Ref<CodeBlock> codeBlock = getOrCreateCodeBlock(mode);
    9899    codeBlock->waitUntilFinished();
    99100    return codeBlock;
    100101}
    101102
    102 void Module::compileAsync(Context* context, MemoryMode mode, CodeBlock::AsyncCompilationCallback&& task, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
     103void Module::compileAsync(VM& vm, MemoryMode mode, CodeBlock::AsyncCompilationCallback&& task)
    103104{
    104     Ref<CodeBlock> codeBlock = getOrCreateCodeBlock(context, mode, WTFMove(createEmbedderWrapper), throwWasmException);
    105     codeBlock->compileAsync(context, WTFMove(task));
     105    Ref<CodeBlock> codeBlock = getOrCreateCodeBlock(mode);
     106    codeBlock->compileAsync(vm, WTFMove(task));
    106107}
    107108
  • trunk/Source/JavaScriptCore/wasm/WasmModule.h

    r222791 r223002  
    2929
    3030#include "WasmCodeBlock.h"
    31 #include "WasmEmbedder.h"
    3231#include "WasmMemory.h"
    3332#include <wtf/Expected.h>
     
    3837namespace JSC { namespace Wasm {
    3938
    40 struct Context;
    4139struct ModuleInformation;
    4240class Plan;
    4341
    4442using SignatureIndex = uint32_t;
    45 
     43   
    4644class Module : public ThreadSafeRefCounted<Module> {
    4745public:
    4846    using ValidationResult = WTF::Expected<RefPtr<Module>, String>;
    49     typedef void CallbackType(ValidationResult&&);
     47    typedef void CallbackType(VM&, ValidationResult&&);
    5048    using AsyncValidationCallback = RefPtr<SharedTask<CallbackType>>;
    5149
    52     static ValidationResult validateSync(Context*, Vector<uint8_t>&& source);
    53     static void validateAsync(Context*, Vector<uint8_t>&& source, Module::AsyncValidationCallback&&);
     50    static ValidationResult validateSync(VM&, Vector<uint8_t>&& source);
     51    static void validateAsync(VM&, Vector<uint8_t>&& source, Module::AsyncValidationCallback&&);
    5452
    5553    static Ref<Module> create(Ref<ModuleInformation>&& moduleInformation)
     
    6159    const Wasm::ModuleInformation& moduleInformation() const { return m_moduleInformation.get(); }
    6260
    63     Ref<CodeBlock> compileSync(Context*, MemoryMode, CreateEmbedderWrapper&&, ThrowWasmException);
    64     void compileAsync(Context*, MemoryMode, CodeBlock::AsyncCompilationCallback&&, CreateEmbedderWrapper&&, ThrowWasmException);
     61    Ref<CodeBlock> compileSync(MemoryMode);
     62    void compileAsync(VM&, MemoryMode, CodeBlock::AsyncCompilationCallback&&);
    6563
    6664    JS_EXPORT_PRIVATE ~Module();
     
    6866    CodeBlock* codeBlockFor(MemoryMode mode) { return m_codeBlocks[static_cast<uint8_t>(mode)].get(); }
    6967private:
    70     Ref<CodeBlock> getOrCreateCodeBlock(Context*, MemoryMode, CreateEmbedderWrapper&&, ThrowWasmException);
     68    Ref<CodeBlock> getOrCreateCodeBlock(MemoryMode);
    7169
    7270    Module(Ref<ModuleInformation>&&);
  • trunk/Source/JavaScriptCore/wasm/WasmModuleParser.cpp

    r222791 r223002  
    3030
    3131#include "IdentifierInlines.h"
     32#include "JSWebAssemblyTable.h"
    3233#include "WasmMemoryInformation.h"
    3334#include "WasmNameSectionParser.h"
     
    265266    if (UNLIKELY(!limits))
    266267        return limits.getUnexpected();
    267     WASM_PARSER_FAIL_IF(initial > maxTableEntries, "Table's initial page count of ", initial, " is too big, maximum ", maxTableEntries);
     268    WASM_PARSER_FAIL_IF(!JSWebAssemblyTable::isValidSize(initial), "Table's initial page count of ", initial, " is invalid");
    268269
    269270    ASSERT(!maximum || *maximum >= initial);
  • trunk/Source/JavaScriptCore/wasm/WasmOMGPlan.cpp

    r222791 r223002  
    3232#include "B3OpaqueByproducts.h"
    3333#include "JSCInlines.h"
    34 #include "JSWebAssemblyInstance.h"
     34#include "JSWebAssemblyModule.h"
    3535#include "LinkBuffer.h"
    3636#include "WasmB3IRGenerator.h"
    37 #include "WasmCallee.h"
    3837#include "WasmContext.h"
    3938#include "WasmMachineThreads.h"
     
    5352}
    5453
    55 OMGPlan::OMGPlan(Context* context, Ref<Module>&& module, uint32_t functionIndex, MemoryMode mode, CompletionTask&& task)
    56     : Base(context, makeRef(const_cast<ModuleInformation&>(module->moduleInformation())), WTFMove(task))
    57     , m_module(WTFMove(module))
    58     , m_codeBlock(*m_module->codeBlockFor(mode))
     54OMGPlan::OMGPlan(Ref<Module> module, uint32_t functionIndex, MemoryMode mode, CompletionTask&& task)
     55    : Base(nullptr, makeRef(const_cast<ModuleInformation&>(module->moduleInformation())), WTFMove(task))
     56    , m_module(module.copyRef())
     57    , m_codeBlock(*module->codeBlockFor(mode))
    5958    , m_functionIndex(functionIndex)
    6059{
     
    164163}
    165164
    166 void OMGPlan::runForIndex(JSWebAssemblyInstance* instance, uint32_t functionIndex)
     165void runOMGPlanForIndex(Context* context, uint32_t functionIndex)
    167166{
    168     Wasm::CodeBlock& codeBlock = instance->wasmCodeBlock();
    169     ASSERT(instance->wasmMemory()->mode() == codeBlock.mode());
     167    JSWebAssemblyCodeBlock* codeBlock = context->codeBlock();
     168    ASSERT(context->memoryMode() == codeBlock->m_codeBlock->mode());
    170169
    171     if (codeBlock.tierUpCount(functionIndex).shouldStartTierUp()) {
    172         Ref<Plan> plan = adoptRef(*new OMGPlan(instance->context(), Ref<Wasm::Module>(instance->wasmModule()), functionIndex, codeBlock.mode(), Plan::dontFinalize()));
     170    if (codeBlock->m_codeBlock->tierUpCount(functionIndex).shouldStartTierUp()) {
     171        Ref<Plan> plan = adoptRef(*new OMGPlan(context->module()->module(), functionIndex, codeBlock->m_codeBlock->mode(), Plan::dontFinalize()));
    173172        ensureWorklist().enqueue(plan.copyRef());
    174173        if (UNLIKELY(!Options::useConcurrentJIT()))
  • trunk/Source/JavaScriptCore/wasm/WasmOMGPlan.h

    r222791 r223002  
    2828#if ENABLE(WEBASSEMBLY)
    2929
     30#include "VM.h"
    3031#include "WasmContext.h"
    3132#include "WasmModule.h"
     
    4142public:
    4243    using Base = Plan;
     44    // Note: CompletionTask should not hold a reference to the Plan otherwise there will be a reference cycle.
     45    OMGPlan(Ref<Module>, uint32_t functionIndex, MemoryMode, CompletionTask&&);
    4346
    4447    bool hasWork() const override { return !m_completed; }
     
    4649    bool multiThreaded() const override { return false; }
    4750
    48     static void runForIndex(JSWebAssemblyInstance*, uint32_t functionIndex);
    49 
    5051private:
    5152    // For some reason friendship doesn't extend to parent classes...
    5253    using Base::m_lock;
    53 
    54     // Note: CompletionTask should not hold a reference to the Plan otherwise there will be a reference cycle.
    55     OMGPlan(Context*, Ref<Module>&&, uint32_t functionIndex, MemoryMode, CompletionTask&&);
    5654
    5755    bool isComplete() const override { return m_completed; }
     
    6866};
    6967
     68void runOMGPlanForIndex(Context*, uint32_t functionIndex);
     69
    7070} } // namespace JSC::Wasm
    7171
  • trunk/Source/JavaScriptCore/wasm/WasmPageCount.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    5858        return pageCount <= maxPageCount;
    5959    }
    60    
    61     bool isValid() const
    62     {
    63         return isValid(m_pageCount);
    64     }
    6560
    6661    static PageCount fromBytes(uint64_t bytes)
  • trunk/Source/JavaScriptCore/wasm/WasmPlan.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    3030
    3131#include "B3Compilation.h"
     32#include "JSCInlines.h"
     33#include "JSGlobalObject.h"
    3234#include "WasmB3IRGenerator.h"
    3335#include "WasmBinding.h"
     
    5052}
    5153
    52 Plan::Plan(Context* context, Ref<ModuleInformation> info, CompletionTask&& task, CreateEmbedderWrapper&& createEmbedderWrapper, ThrowWasmException throwWasmException)
     54Plan::Plan(VM* vm, Ref<ModuleInformation> info, CompletionTask&& task)
    5355    : m_moduleInformation(WTFMove(info))
    54     , m_createEmbedderWrapper(WTFMove(createEmbedderWrapper))
    55     , m_throwWasmException(throwWasmException)
    5656    , m_source(m_moduleInformation->source.data())
    5757    , m_sourceLength(m_moduleInformation->source.size())
    5858{
    59     m_completionTasks.append(std::make_pair(context, WTFMove(task)));
     59    m_completionTasks.append(std::make_pair(vm, WTFMove(task)));
    6060}
    6161
    62 Plan::Plan(Context* context, Ref<ModuleInformation> info, CompletionTask&& task)
    63     : Plan(context, WTFMove(info), WTFMove(task), nullptr, nullptr)
    64 {
    65 }
    66 
    67 Plan::Plan(Context* context, const uint8_t* source, size_t sourceLength, CompletionTask&& task)
     62Plan::Plan(VM* vm, const uint8_t* source, size_t sourceLength, CompletionTask&& task)
    6863    : m_moduleInformation(adoptRef(*new ModuleInformation(Vector<uint8_t>())))
    6964    , m_source(source)
    7065    , m_sourceLength(sourceLength)
    7166{
    72     m_completionTasks.append(std::make_pair(context, WTFMove(task)));
     67    m_completionTasks.append(std::make_pair(vm, WTFMove(task)));
    7368}
    7469
     
    7873
    7974    for (auto& task : m_completionTasks)
    80         task.second->run(*this);
     75        task.second->run(task.first, *this);
    8176    m_completionTasks.clear();
    8277    m_completed.notifyAll();
    8378}
    8479
    85 void Plan::addCompletionTask(Context* context, CompletionTask&& task)
     80void Plan::addCompletionTask(VM& vm, CompletionTask&& task)
    8681{
    8782    LockHolder locker(m_lock);
    8883    if (!isComplete())
    89         m_completionTasks.append(std::make_pair(context, WTFMove(task)));
     84        m_completionTasks.append(std::make_pair(&vm, WTFMove(task)));
    9085    else
    91         task->run(*this);
     86        task->run(&vm, *this);
    9287}
    9388
     
    10095}
    10196
    102 bool Plan::tryRemoveContextAndCancelIfLast(Context& context)
     97bool Plan::tryRemoveVMAndCancelIfLast(VM& vm)
    10398{
    10499    LockHolder locker(m_lock);
    105100
    106101    if (!ASSERT_DISABLED) {
    107         // We allow the first completion task to not have a Context.
     102        // We allow the first completion task to not have a vm.
    108103        for (unsigned i = 1; i < m_completionTasks.size(); ++i)
    109104            ASSERT(m_completionTasks[i].first);
     
    111106
    112107    bool removedAnyTasks = false;
    113     m_completionTasks.removeAllMatching([&] (const std::pair<Context*, CompletionTask>& pair) {
    114         bool shouldRemove = pair.first == &context;
     108    m_completionTasks.removeAllMatching([&] (const std::pair<VM*, CompletionTask>& pair) {
     109        bool shouldRemove = pair.first == &vm;
    115110        removedAnyTasks |= shouldRemove;
    116111        return shouldRemove;
  • trunk/Source/JavaScriptCore/wasm/WasmPlan.h

    r222791 r223002  
    2929
    3030#include "CompilationResult.h"
     31#include "VM.h"
    3132#include "WasmB3IRGenerator.h"
    32 #include "WasmEmbedder.h"
    3333#include "WasmModuleInformation.h"
    3434#include <wtf/Bag.h>
     
    4040
    4141class CallLinkInfo;
     42class JSGlobalObject;
     43class JSPromiseDeferred;
    4244
    4345namespace Wasm {
    4446
    45 struct Context;
    46 
    4747class Plan : public ThreadSafeRefCounted<Plan> {
    4848public:
    49     typedef void CallbackType(Plan&);
     49    typedef void CallbackType(VM*, Plan&);
    5050    using CompletionTask = RefPtr<SharedTask<CallbackType>>;
    51 
    52     static CompletionTask dontFinalize() { return createSharedTask<CallbackType>([](Plan&) { }); }
    53     Plan(Context*, Ref<ModuleInformation>, CompletionTask&&, CreateEmbedderWrapper&&, ThrowWasmException);
    54     Plan(Context*, Ref<ModuleInformation>, CompletionTask&&);
     51    static CompletionTask dontFinalize() { return createSharedTask<CallbackType>([](VM*, Plan&) { }); }
     52    Plan(VM*, Ref<ModuleInformation>, CompletionTask&&);
    5553
    5654    // Note: This constructor should only be used if you are not actually building a module e.g. validation/function tests
    57     JS_EXPORT_PRIVATE Plan(Context*, const uint8_t*, size_t, CompletionTask&&);
     55    JS_EXPORT_PRIVATE Plan(VM*, const uint8_t*, size_t, CompletionTask&&);
    5856    virtual JS_EXPORT_PRIVATE ~Plan();
    5957
    6058    // If you guarantee the ordering here, you can rely on FIFO of the
    6159    // completion tasks being called.
    62     void addCompletionTask(Context*, CompletionTask&&);
     60    void addCompletionTask(VM&, CompletionTask&&);
    6361
    6462    void setMode(MemoryMode mode) { m_mode = mode; }
     
    7573    void waitForCompletion();
    7674    // Returns true if it cancelled the plan.
    77     bool tryRemoveContextAndCancelIfLast(Context&);
     75    bool tryRemoveVMAndCancelIfLast(VM&);
    7876
    7977protected:
     
    8684    Ref<ModuleInformation> m_moduleInformation;
    8785
    88     Vector<std::pair<Context*, CompletionTask>, 1> m_completionTasks;
    89 
    90     CreateEmbedderWrapper m_createEmbedderWrapper;
    91     ThrowWasmException m_throwWasmException { nullptr };
     86    Vector<std::pair<VM*, CompletionTask>, 1> m_completionTasks;
    9287
    9388    const uint8_t* m_source;
  • trunk/Source/JavaScriptCore/wasm/WasmSignature.cpp

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2929#if ENABLE(WEBASSEMBLY)
    3030
     31#include "VM.h"
    3132#include <wtf/FastMalloc.h>
    3233#include <wtf/HashFunctions.h>
    3334#include <wtf/PrintStream.h>
    34 #include <wtf/text/WTFString.h>
    3535
    3636namespace JSC { namespace Wasm {
  • trunk/Source/JavaScriptCore/wasm/WasmSignature.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    4343
    4444namespace JSC {
     45
     46class VM;
    4547
    4648namespace Wasm {
     
    155157namespace JSC { namespace Wasm {
    156158
    157 // Signature information is held globally and shared by the entire process to allow all signatures to be unique. This is required when wasm calls another wasm instance, and must work when modules are shared between multiple VMs.
     159// Signature information is held globally and shared by VMs to allow all signatures to be unique. This is required when wasm calls another wasm instance, and must work when modules are shared between multiple VMs.
    158160// Note: signatures are never removed because that would require accounting for all WebAssembly.Module and which signatures they use. The maximum number of signatures is bounded, and isn't worth the counting overhead. We could clear everything when we reach zero outstanding WebAssembly.Module. https://bugs.webkit.org/show_bug.cgi?id=166037
    159161class SignatureInformation {
  • trunk/Source/JavaScriptCore/wasm/WasmThunks.cpp

    r222791 r223002  
    3030
    3131#include "CCallHelpers.h"
     32#include "FrameTracers.h"
    3233#include "HeapCellInlines.h"
    3334#include "JITExceptions.h"
    3435#include "JSWebAssemblyInstance.h"
     36#include "JSWebAssemblyRuntimeError.h"
    3537#include "LinkBuffer.h"
    3638#include "ScratchRegisterAllocator.h"
     
    4749    // The thing that jumps here must move ExceptionType into the argumentGPR1 before jumping here.
    4850    // We're allowed to use temp registers here. We are not allowed to use callee saves.
    49     jit.loadWasmContextInstance(GPRInfo::argumentGPR2);
    50     jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR2, JSWebAssemblyInstance::offsetOfVM()), GPRInfo::argumentGPR0);
     51    jit.loadWasmContext(GPRInfo::argumentGPR2);
     52    jit.loadPtr(CCallHelpers::Address(GPRInfo::argumentGPR2, Context::offsetOfVM()), GPRInfo::argumentGPR0);
    5153    jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(GPRInfo::argumentGPR0);
    5254    jit.move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR0);
     
    5557    jit.breakpoint(); // We should not reach this.
    5658
    57     ThrowWasmException throwWasmException = Thunks::singleton().throwWasmException();
    58     RELEASE_ASSERT(throwWasmException);
     59    void* (*throwWasmException)(ExecState*, Wasm::ExceptionType, Wasm::Context*) = [] (ExecState* exec, Wasm::ExceptionType type, Wasm::Context* wasmContext) -> void* {
     60        VM* vm = wasmContext->vm();
     61        NativeCallFrameTracer tracer(vm, exec);
     62
     63        {
     64            auto throwScope = DECLARE_THROW_SCOPE(*vm);
     65            JSGlobalObject* globalObject = wasmContext->globalObject();
     66
     67            JSObject* error;
     68            if (type == ExceptionType::StackOverflow)
     69                error = createStackOverflowError(exec, globalObject);
     70            else
     71                error = JSWebAssemblyRuntimeError::create(exec, *vm, globalObject->WebAssemblyRuntimeErrorStructure(), Wasm::errorMessageForExceptionType(type));
     72            throwException(exec, throwScope, error);
     73        }
     74
     75        genericUnwind(vm, exec);
     76        ASSERT(!!vm->callFrameForCatch);
     77        ASSERT(!!vm->targetMachinePCForThrow);
     78        // FIXME: We could make this better:
     79        // This is a total hack, but the llint (both op_catch and handleUncaughtException)
     80        // require a cell in the callee field to load the VM. (The baseline JIT does not require
     81        // this since it is compiled with a constant VM pointer.) We could make the calling convention
     82        // for exceptions first load callFrameForCatch info call frame register before jumping
     83        // to the exception handler. If we did this, we could remove this terrible hack.
     84        // https://bugs.webkit.org/show_bug.cgi?id=170440
     85        bitwise_cast<uint64_t*>(exec)[CallFrameSlot::callee] = bitwise_cast<uint64_t>(wasmContext->webAssemblyToJSCallee());
     86        return vm->targetMachinePCForThrow;
     87    };
     88
    5989    LinkBuffer linkBuffer(jit, GLOBAL_THUNK_ID);
    60     linkBuffer.link(call, FunctionPtr(throwWasmException));
     90    linkBuffer.link(call, throwWasmException);
    6191    return FINALIZE_CODE(linkBuffer, ("Throw exception from Wasm"));
    6292}
     
    90120    unsigned numberOfStackBytesUsedForRegisterPreservation = ScratchRegisterAllocator::preserveRegistersToStackForCall(jit, registersToSpill, extraPaddingBytes);
    91121
    92     jit.loadWasmContextInstance(GPRInfo::argumentGPR0);
    93     typedef void (*Run)(JSWebAssemblyInstance*, uint32_t);
    94     Run run = OMGPlan::runForIndex;
    95     jit.move(MacroAssembler::TrustedImmPtr(reinterpret_cast<void*>(run)), GPRInfo::argumentGPR2);
     122    jit.loadWasmContext(GPRInfo::argumentGPR0);
     123    jit.move(MacroAssembler::TrustedImmPtr(reinterpret_cast<void*>(runOMGPlanForIndex)), GPRInfo::argumentGPR2);
    96124    jit.call(GPRInfo::argumentGPR2);
    97125
     
    113141    ASSERT(thunks);
    114142    return *thunks;
    115 }
    116 
    117 void Thunks::setThrowWasmException(ThrowWasmException throwWasmException)
    118 {
    119     auto locker = holdLock(m_lock);
    120     // The thunks are unique for the entire process, therefore changing the throwing function changes it for all uses of WebAssembly.
    121     RELEASE_ASSERT(!m_throwWasmException || m_throwWasmException == throwWasmException);
    122     m_throwWasmException = throwWasmException;
    123 }
    124 
    125 ThrowWasmException Thunks::throwWasmException()
    126 {
    127     return m_throwWasmException;
    128143}
    129144
  • trunk/Source/JavaScriptCore/wasm/WasmThunks.h

    r222791 r223002  
    2929
    3030#include "MacroAssemblerCodeRef.h"
    31 #include "WasmEmbedder.h"
    3231
    3332namespace JSC { namespace Wasm {
     
    4443    static Thunks& singleton();
    4544
    46     void setThrowWasmException(ThrowWasmException);
    47     ThrowWasmException throwWasmException();
    48 
    4945    MacroAssemblerCodeRef stub(ThunkGenerator);
    5046    MacroAssemblerCodeRef stub(const AbstractLocker&, ThunkGenerator);
     
    5551
    5652    HashMap<ThunkGenerator, MacroAssemblerCodeRef> m_stubs;
    57     ThrowWasmException m_throwWasmException { nullptr };
    5853    Lock m_lock;
    5954};
  • trunk/Source/JavaScriptCore/wasm/WasmWorklist.cpp

    r222791 r223002  
    2323 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    2424 */
    25 
    2625#include "config.h"
    2726#include "WasmWorklist.h"
     
    174173}
    175174
    176 void Worklist::stopAllPlansForContext(Context& context)
     175void Worklist::stopAllPlansForVM(VM& vm)
    177176{
    178177    LockHolder locker(*m_lock);
     
    180179    while (!m_queue.isEmpty()) {
    181180        QueueElement element = m_queue.dequeue();
    182         bool didCancel = element.plan->tryRemoveContextAndCancelIfLast(context);
     181        bool didCancel = element.plan->tryRemoveVMAndCancelIfLast(vm);
    183182        if (!didCancel)
    184183            elements.append(WTFMove(element));
     
    190189    for (auto& thread : m_threads) {
    191190        if (thread->element.plan) {
    192             bool didCancel = thread->element.plan->tryRemoveContextAndCancelIfLast(context);
     191            bool didCancel = thread->element.plan->tryRemoveVMAndCancelIfLast(vm);
    193192            if (didCancel) {
    194193                // We don't have to worry about the deadlocking since the thread can't block without checking for a new plan and must hold the lock to do so.
  • trunk/Source/JavaScriptCore/wasm/WasmWorklist.h

    r222791 r223002  
    2828#if ENABLE(WEBASSEMBLY)
    2929
     30#include "VM.h"
     31
    3032#include <queue>
    3133
     
    3638namespace JSC {
    3739
     40class JSPromiseDeferred;
     41
    3842namespace Wasm {
    3943
    40 struct Context;
    4144class Plan;
    4245
     
    4851
    4952    JS_EXPORT_PRIVATE void enqueue(Ref<Plan>);
    50     void stopAllPlansForContext(Context&);
     53    void stopAllPlansForVM(VM&);
    5154
    5255    JS_EXPORT_PRIVATE void completePlanSynchronously(Plan&);
     56
     57    void activatePlan(JSPromiseDeferred*, Plan*);
     58    void deactivePlan(JSPromiseDeferred*, Plan*);
    5359
    5460    enum class Priority {
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyCodeBlock.cpp

    r222791 r223002  
    3333#include "JSWebAssemblyMemory.h"
    3434#include "JSWebAssemblyModule.h"
     35#include "WasmBinding.h"
    3536#include "WasmModuleInformation.h"
    36 #include "WasmToJS.h"
    3737
    3838#include <wtf/CurrentTime.h>
     
    4545{
    4646    const Wasm::ModuleInformation& moduleInformation = module->module().moduleInformation();
    47     auto* result = new (NotNull, allocateCell<JSWebAssemblyCodeBlock>(vm.heap)) JSWebAssemblyCodeBlock(vm, WTFMove(codeBlock), moduleInformation);
     47    auto* result = new (NotNull, allocateCell<JSWebAssemblyCodeBlock>(vm.heap, allocationSize(moduleInformation.importFunctionCount()))) JSWebAssemblyCodeBlock(vm, WTFMove(codeBlock), moduleInformation);
    4848    result->finishCreation(vm, module);
    4949    return result;
     
    5959    for (unsigned importIndex = 0; importIndex < m_codeBlock->functionImportCount(); ++importIndex) {
    6060        Wasm::SignatureIndex signatureIndex = moduleInformation.importFunctionSignatureIndices.at(importIndex);
    61         auto binding = Wasm::wasmToJS(&vm, m_callLinkInfos, signatureIndex, importIndex);
     61        auto binding = Wasm::wasmToJs(&vm, m_callLinkInfos, signatureIndex, importIndex);
    6262        if (UNLIKELY(!binding)) {
    6363            switch (binding.error()) {
     
    6969        }
    7070        m_wasmToJSExitStubs.uncheckedAppend(binding.value());
    71         m_codeBlock->importWasmToEmbedderStub(importIndex) = m_wasmToJSExitStubs[importIndex].code().executableAddress();
     71        importWasmToJSStub(importIndex) = m_wasmToJSExitStubs[importIndex].code().executableAddress();
    7272    }
    7373}
     
    8282{
    8383    static_cast<JSWebAssemblyCodeBlock*>(cell)->JSWebAssemblyCodeBlock::~JSWebAssemblyCodeBlock();
     84}
     85
     86bool JSWebAssemblyCodeBlock::isSafeToRun(JSWebAssemblyMemory* memory) const
     87{
     88    return m_codeBlock->isSafeToRun(memory->memory().mode());
    8489}
    8590
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyCodeBlock.h

    r222791 r223002  
    6565    }
    6666
    67     Wasm::CodeBlock& codeBlock() { return m_codeBlock.get(); }
    68 
     67    unsigned functionImportCount() const { return m_codeBlock->functionImportCount(); }
    6968    JSWebAssemblyModule* module() const { return m_module.get(); }
    7069
     70    bool isSafeToRun(JSWebAssemblyMemory*) const;
     71
    7172    void finishCreation(VM&, JSWebAssemblyModule*);
     73
     74    // These two callee getters are only valid once the callees have been populated.
     75
     76    Wasm::Callee& jsEntrypointCalleeFromFunctionIndexSpace(unsigned functionIndexSpace)
     77    {
     78        ASSERT(runnable());
     79        return m_codeBlock->jsEntrypointCalleeFromFunctionIndexSpace(functionIndexSpace);
     80    }
     81    Wasm::WasmEntrypointLoadLocation wasmEntrypointLoadLocationFromFunctionIndexSpace(unsigned functionIndexSpace)
     82    {
     83        ASSERT(runnable());
     84        return m_codeBlock->wasmEntrypointLoadLocationFromFunctionIndexSpace(functionIndexSpace);
     85    }
     86
     87    Wasm::WasmEntrypointLoadLocation wasmToJsCallStubForImport(unsigned importIndex)
     88    {
     89        ASSERT(runnable());
     90        return &importWasmToJSStub(importIndex);
     91    }
     92
     93    static ptrdiff_t offsetOfImportWasmToJSStub(unsigned importIndex)
     94    {
     95        return offsetOfImportStubs() + sizeof(void*) * importIndex;
     96    }
     97
     98    Wasm::CodeBlock& codeBlock() { return m_codeBlock.get(); }
    7299
    73100    void clearJSCallICs(VM&);
     
    88115    static void visitChildren(JSCell*, SlotVisitor&);
    89116
     117    static size_t offsetOfImportStubs()
     118    {
     119        return WTF::roundUpToMultipleOf<sizeof(void*)>(sizeof(JSWebAssemblyCodeBlock));
     120    }
     121
     122    static size_t allocationSize(Checked<size_t> functionImportCount)
     123    {
     124        return (offsetOfImportStubs() + sizeof(void*) * functionImportCount).unsafeGet();
     125    }
     126
     127    void*& importWasmToJSStub(unsigned importIndex)
     128    {
     129        return *bitwise_cast<void**>(bitwise_cast<char*>(this) + offsetOfImportWasmToJSStub(importIndex));
     130    }
     131
    90132    class UnconditionalFinalizer : public JSC::UnconditionalFinalizer {
    91133        void finalizeUnconditionally() override;
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyInstance.cpp

    r222873 r223002  
    5050}
    5151
    52 JSWebAssemblyInstance::JSWebAssemblyInstance(VM& vm, Structure* structure, unsigned numImportFunctions, Ref<Wasm::Instance>&& instance)
     52JSWebAssemblyInstance::JSWebAssemblyInstance(VM& vm, Structure* structure, unsigned numImportFunctions)
    5353    : Base(vm, structure)
    54     , m_instance(WTFMove(instance))
    5554    , m_vm(&vm)
    56     , m_wasmModule(m_instance->module())
    57     , m_wasmTable(m_instance->m_table.get())
    58     , m_globals(m_instance->m_globals.get())
    5955    , m_numImportFunctions(numImportFunctions)
    6056{
    61     for (unsigned i = 0; i < m_numImportFunctions; ++i)
    62         default_construct_at(importFunctionInfo(i));
     57    memset(importFunctions(), 0, m_numImportFunctions * sizeof(WriteBarrier<JSObject>));
    6358}
    6459
     
    6964
    7065    m_module.set(vm, this, module);
     66    const size_t extraMemorySize = globalMemoryByteSize();
     67    m_globals = MallocPtr<uint64_t>::malloc(extraMemorySize);
     68    heap()->reportExtraMemoryAllocated(extraMemorySize);
     69
    7170    m_moduleNamespaceObject.set(vm, this, moduleNamespaceObject);
    7271    m_callee.set(vm, this, module->callee());
    73    
    74     heap()->reportExtraMemoryAllocated(m_instance->extraMemoryAllocated());
    7572}
    7673
     
    9289    visitor.append(thisObject->m_table);
    9390    visitor.append(thisObject->m_callee);
    94     visitor.reportExtraMemoryVisited(thisObject->m_instance->extraMemoryAllocated());
     91    visitor.reportExtraMemoryVisited(thisObject->globalMemoryByteSize());
    9592    for (unsigned i = 0; i < thisObject->m_numImportFunctions; ++i)
    96         visitor.append(thisObject->importFunctionInfo(i)->importFunction); // This also keeps the functions' JSWebAssemblyInstance alive.
     93        visitor.append(thisObject->importFunctions()[i]);
    9794}
    9895
    9996void JSWebAssemblyInstance::finalizeCreation(VM& vm, ExecState* exec, Ref<Wasm::CodeBlock>&& wasmCodeBlock)
    10097{
    101     m_instance->finalizeCreation(wasmCodeBlock.copyRef());
    102     m_wasmCodeBlock = wasmCodeBlock.ptr();
    103 
    10498    auto scope = DECLARE_THROW_SCOPE(vm);
    105 
    10699    if (!wasmCodeBlock->runnable()) {
    107100        throwException(exec, scope, JSWebAssemblyLinkError::create(exec, vm, globalObject()->WebAssemblyLinkErrorStructure(), wasmCodeBlock->errorMessage()));
     
    110103
    111104    RELEASE_ASSERT(wasmCodeBlock->isSafeToRun(memoryMode()));
    112     JSWebAssemblyCodeBlock* jsCodeBlock = m_module->codeBlock(memoryMode());
    113     if (jsCodeBlock) {
     105    JSWebAssemblyCodeBlock* codeBlock = module()->codeBlock(memoryMode());
     106    if (codeBlock) {
    114107        // A CodeBlock might have already been compiled. If so, it means
    115108        // that the CodeBlock we are trying to compile must be the same
    116109        // because we will never compile a CodeBlock again once it's
    117110        // runnable.
    118         ASSERT(&jsCodeBlock->codeBlock() == wasmCodeBlock.ptr());
    119         m_codeBlock.set(vm, this, jsCodeBlock);
     111        ASSERT(&codeBlock->codeBlock() == wasmCodeBlock.ptr());
     112        m_codeBlock.set(vm, this, codeBlock);
    120113    } else {
    121         jsCodeBlock = JSWebAssemblyCodeBlock::create(vm, WTFMove(wasmCodeBlock), m_module.get());
    122         if (UNLIKELY(!jsCodeBlock->runnable())) {
    123             throwException(exec, scope, JSWebAssemblyLinkError::create(exec, vm, globalObject()->WebAssemblyLinkErrorStructure(), jsCodeBlock->errorMessage()));
     114        codeBlock = JSWebAssemblyCodeBlock::create(vm, wasmCodeBlock.copyRef(), m_module.get());
     115        if (UNLIKELY(!codeBlock->runnable())) {
     116            throwException(exec, scope, JSWebAssemblyLinkError::create(exec, vm, globalObject()->WebAssemblyLinkErrorStructure(), codeBlock->errorMessage()));
    124117            return;
    125118        }
    126         m_codeBlock.set(vm, this, jsCodeBlock);
    127         m_module->setCodeBlock(vm, memoryMode(), jsCodeBlock);
     119        m_codeBlock.set(vm, this, codeBlock);
     120        module()->setCodeBlock(vm, memoryMode(), codeBlock);
    128121    }
    129122
    130123    auto* moduleRecord = jsCast<WebAssemblyModuleRecord*>(m_moduleNamespaceObject->moduleRecord());
    131     moduleRecord->link(exec, m_module.get(), this);
     124    moduleRecord->link(exec, module(), this);
    132125    RETURN_IF_EXCEPTION(scope, void());
    133126
     
    137130}
    138131
    139 JSWebAssemblyInstance* JSWebAssemblyInstance::create(VM& vm, ExecState* exec, JSWebAssemblyModule* jsModule, JSObject* importObject, Structure* instanceStructure, Ref<Wasm::Instance>&& instance)
     132JSWebAssemblyInstance* JSWebAssemblyInstance::create(VM& vm, ExecState* exec, JSWebAssemblyModule* jsModule, JSObject* importObject, Structure* instanceStructure)
    140133{
    141134    auto throwScope = DECLARE_THROW_SCOPE(vm);
     
    166159    JSModuleNamespaceObject* moduleNamespace = moduleRecord->getModuleNamespace(exec);
    167160    // FIXME: These objects could be pretty big we should try to throw OOM here.
    168     auto* jsInstance = new (NotNull, allocateCell<JSWebAssemblyInstance>(vm.heap, allocationSize(moduleInformation.importFunctionCount()))) JSWebAssemblyInstance(vm, instanceStructure, moduleInformation.importFunctionCount(), WTFMove(instance));
    169     jsInstance->finishCreation(vm, jsModule, moduleNamespace);
     161    auto* instance = new (NotNull, allocateCell<JSWebAssemblyInstance>(vm.heap, allocationSize(moduleInformation.importFunctionCount()))) JSWebAssemblyInstance(vm, instanceStructure, moduleInformation.importFunctionCount());
     162    instance->finishCreation(vm, jsModule, moduleNamespace);
    170163    RETURN_IF_EXCEPTION(throwScope, nullptr);
    171164
     
    198191                return exception(createJSWebAssemblyLinkError(exec, vm, importFailMessage(import, "import function", "must be callable")));
    199192
    200             JSWebAssemblyInstance* calleeInstance = nullptr;
    201             Wasm::WasmEntrypointLoadLocation wasmEntrypoint = nullptr;
    202193            JSObject* function = jsCast<JSObject*>(value);
    203 
    204194            // ii. If v is an Exported Function Exotic Object:
    205195            WebAssemblyFunction* wasmFunction;
     
    208198                // a. If the signature of v does not match the signature of i, throw a WebAssembly.LinkError.
    209199                Wasm::SignatureIndex importedSignatureIndex;
    210                 if (wasmFunction) {
     200                if (wasmFunction)
    211201                    importedSignatureIndex = wasmFunction->signatureIndex();
    212                     calleeInstance = wasmFunction->instance();
    213                     wasmEntrypoint = wasmFunction->wasmEntrypointLoadLocation();
    214                 }
    215202                else {
    216203                    importedSignatureIndex = wasmWrapperFunction->signatureIndex();
     
    229216
    230217            ASSERT(numImportFunctions == import.kindIndex);
    231             ImportFunctionInfo* info = jsInstance->importFunctionInfo(numImportFunctions++);
    232             info->targetInstance = calleeInstance;
    233             info->wasmEntrypoint = wasmEntrypoint;
    234             info->importFunction.set(vm, jsInstance, function);
     218            instance->importFunctions()[numImportFunctions++].set(vm, instance, function);
    235219            // v. Append closure to imports.
    236220            break;
     
    260244            // ii. Append v to tables.
    261245            // iii. Append v.[[Table]] to imports.
    262             jsInstance->m_table.set(vm, jsInstance, table);
    263             jsInstance->m_wasmTable = table->table();
     246            instance->m_table.set(vm, instance, table);
    264247            break;
    265248        }
     
    291274            // ii. Append v to memories.
    292275            // iii. Append v.[[Memory]] to imports.
    293             ASSERT(!jsInstance->m_memory);
    294             jsInstance->setMemory(vm, memory);
     276            ASSERT(!instance->m_memory);
     277            instance->m_memory.set(vm, instance, memory);
    295278            RETURN_IF_EXCEPTION(throwScope, nullptr);
    296279            break;
     
    309292            switch (moduleInformation.globals[import.kindIndex].type) {
    310293            case Wasm::I32:
    311                 jsInstance->instance().setGlobal(numImportGlobals++, value.toInt32(exec));
     294                instance->setGlobal(numImportGlobals++, value.toInt32(exec));
    312295                break;
    313296            case Wasm::F32:
    314                 jsInstance->instance().setGlobal(numImportGlobals++, bitwise_cast<uint32_t>(value.toFloat(exec)));
     297                instance->setGlobal(numImportGlobals++, bitwise_cast<uint32_t>(value.toFloat(exec)));
    315298                break;
    316299            case Wasm::F64:
    317                 jsInstance->instance().setGlobal(numImportGlobals++, bitwise_cast<uint64_t>(value.asNumber()));
     300                instance->setGlobal(numImportGlobals++, bitwise_cast<uint64_t>(value.asNumber()));
    318301                break;
    319302            default:
     
    333316
    334317        if (moduleInformation.memory && !hasMemoryImport) {
     318            RELEASE_ASSERT(!moduleInformation.memory.isImport());
    335319            // We create a memory when it's a memory definition.
    336             RELEASE_ASSERT(!moduleInformation.memory.isImport());
    337 
    338             auto* jsMemory = JSWebAssemblyMemory::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure());
    339             RETURN_IF_EXCEPTION(throwScope, nullptr);
    340 
    341             RefPtr<Wasm::Memory> memory = Wasm::Memory::create(moduleInformation.memory.initial(), moduleInformation.memory.maximum(),
    342                 [&vm] (Wasm::Memory::NotifyPressure) { vm.heap.collectAsync(CollectionScope::Full); },
    343                 [&vm] (Wasm::Memory::SyncTryToReclaim) { vm.heap.collectSync(CollectionScope::Full); },
    344                 [&vm, jsMemory] (Wasm::Memory::GrowSuccess, Wasm::PageCount oldPageCount, Wasm::PageCount newPageCount) { jsMemory->growSuccessCallback(vm, oldPageCount, newPageCount); });
     320            RefPtr<Wasm::Memory> memory = Wasm::Memory::create(vm, moduleInformation.memory.initial(), moduleInformation.memory.maximum());
    345321            if (!memory)
    346322                return exception(createOutOfMemoryError(exec));
    347323
    348             jsMemory->adopt(memory.releaseNonNull());
    349             jsInstance->setMemory(vm, jsMemory);
     324            instance->m_memory.set(vm, instance,
     325                JSWebAssemblyMemory::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure(), memory.releaseNonNull()));
    350326            RETURN_IF_EXCEPTION(throwScope, nullptr);
    351327        }
     
    361337            RELEASE_ASSERT(!moduleInformation.tableInformation.isImport());
    362338            // We create a Table when it's a Table definition.
    363             RefPtr<Wasm::Table> wasmTable = Wasm::Table::create(moduleInformation.tableInformation.initial(), moduleInformation.tableInformation.maximum());
    364             if (!wasmTable)
    365                 return exception(createJSWebAssemblyLinkError(exec, vm, "couldn't create Table"));
    366             JSWebAssemblyTable* table = JSWebAssemblyTable::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyTableStructure(), wasmTable.releaseNonNull());
     339            JSWebAssemblyTable* table = JSWebAssemblyTable::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyTableStructure(),
     340                moduleInformation.tableInformation.initial(), moduleInformation.tableInformation.maximum());
    367341            // We should always be able to allocate a JSWebAssemblyTable we've defined.
    368342            // If it's defined to be too large, we should have thrown a validation error.
    369343            throwScope.assertNoException();
    370344            ASSERT(table);
    371             jsInstance->m_table.set(vm, jsInstance, table);
    372             jsInstance->m_wasmTable = table->table();
     345            instance->m_table.set(vm, instance, table);
    373346        }
    374347    }
    375348   
    376     if (!jsInstance->memory()) {
     349    if (!instance->memory()) {
    377350        // Make sure we have a dummy memory, so that wasm -> wasm thunks avoid checking for a nullptr Memory when trying to set pinned registers.
    378         auto* jsMemory = JSWebAssemblyMemory::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure());
    379         jsMemory->adopt(Wasm::Memory::create().releaseNonNull());
    380         jsInstance->setMemory(vm, jsMemory);
     351        instance->m_memory.set(vm, instance, JSWebAssemblyMemory::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure(), Wasm::Memory::create(vm, 0, 0).releaseNonNull()));
    381352        RETURN_IF_EXCEPTION(throwScope, nullptr);
    382353    }
     
    390361            if (global.initializationType == Wasm::Global::FromGlobalImport) {
    391362                ASSERT(global.initialBitsOrImportNumber < numImportGlobals);
    392                 jsInstance->instance().setGlobal(globalIndex, jsInstance->instance().loadI64Global(global.initialBitsOrImportNumber));
     363                instance->setGlobal(globalIndex, instance->loadI64Global(global.initialBitsOrImportNumber));
    393364            } else
    394                 jsInstance->instance().setGlobal(globalIndex, global.initialBitsOrImportNumber);
    395         }
    396     }
    397 
    398     return jsInstance;
     365                instance->setGlobal(globalIndex, global.initialBitsOrImportNumber);
     366        }
     367    }
     368
     369    ASSERT(!instance->codeBlock());
     370
     371    return instance;
     372}
     373
     374size_t JSWebAssemblyInstance::globalMemoryByteSize() const
     375{
     376    return m_module->moduleInformation().globals.size() * sizeof(Register);
    399377}
    400378
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyInstance.h

    r222791 r223002  
    3333#include "JSWebAssemblyMemory.h"
    3434#include "JSWebAssemblyTable.h"
    35 #include "WasmContext.h"
    36 #include "WasmInstance.h"
    3735
    3836namespace JSC {
     
    4240class WebAssemblyToJSCallee;
    4341
    44 namespace Wasm {
    45 class CodeBlock;
    46 class Table; // FIXME remove this after refactoring. https://webkit.org/b/177472
    47 }
    48 
    4942class JSWebAssemblyInstance : public JSDestructibleObject {
    5043public:
    5144    typedef JSDestructibleObject Base;
    5245
    53     static JSWebAssemblyInstance* create(VM&, ExecState*, JSWebAssemblyModule*, JSObject* importObject, Structure*, Ref<Wasm::Instance>&&);
     46    static JSWebAssemblyInstance* create(VM&, ExecState*, JSWebAssemblyModule*, JSObject* importObject, Structure*);
    5447    static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
    5548
    5649    DECLARE_EXPORT_INFO;
    5750
     51    JSWebAssemblyCodeBlock* codeBlock() const { return m_codeBlock.get(); }
    5852    void finalizeCreation(VM&, ExecState*, Ref<Wasm::CodeBlock>&&);
    59    
    60     Wasm::Instance& instance() { return m_instance.get(); }
    61     Wasm::Context* context() const { return &m_vm->wasmContext; }
     53
     54    JSWebAssemblyModule* module() const { return m_module.get(); }
     55
     56    JSObject* importFunction(unsigned idx) { RELEASE_ASSERT(idx < m_numImportFunctions); return importFunctions()[idx].get(); }
     57
    6258    JSModuleNamespaceObject* moduleNamespaceObject() { return m_moduleNamespaceObject.get(); }
     59
     60    JSWebAssemblyMemory* memory() { return m_memory.get(); }
     61    void setMemory(VM& vm, JSWebAssemblyMemory* value) { ASSERT(!memory()); m_memory.set(vm, this, value); }
     62    Wasm::MemoryMode memoryMode() { return memory()->memory().mode(); }
     63
    6364    JSWebAssemblyTable* table() { return m_table.get(); }
     65
     66    int32_t loadI32Global(unsigned i) const { return m_globals.get()[i]; }
     67    int64_t loadI64Global(unsigned i) const { return m_globals.get()[i]; }
     68    float loadF32Global(unsigned i) const { return bitwise_cast<float>(loadI32Global(i)); }
     69    double loadF64Global(unsigned i) const { return bitwise_cast<double>(loadI64Global(i)); }
     70    void setGlobal(unsigned i, int64_t bits) { m_globals.get()[i] = bits; }
     71
     72    static ptrdiff_t offsetOfMemory() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_memory); }
     73    static ptrdiff_t offsetOfTable() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_table); }
     74    static ptrdiff_t offsetOfCallee() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_callee); }
     75    static ptrdiff_t offsetOfGlobals() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_globals); }
     76    static ptrdiff_t offsetOfVM() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_vm); }
     77    static ptrdiff_t offsetOfCodeBlock() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_codeBlock); }
     78    static ptrdiff_t offsetOfCachedStackLimit() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_cachedStackLimit); }
     79    static size_t offsetOfImportFunctions() { return WTF::roundUpToMultipleOf<sizeof(WriteBarrier<JSCell>)>(sizeof(JSWebAssemblyInstance)); }
     80    static size_t offsetOfImportFunction(size_t importFunctionNum) { return offsetOfImportFunctions() + importFunctionNum * sizeof(sizeof(WriteBarrier<JSCell>)); }
     81
    6482    WebAssemblyToJSCallee* webAssemblyToJSCallee() { return m_callee.get(); }
    6583
    66     JSWebAssemblyMemory* memory() { return m_memory.get(); }
    67     void setMemory(VM& vm, JSWebAssemblyMemory* value) { ASSERT(!memory()); m_memory.set(vm, this, value); m_wasmMemory = &memory()->memory(); }
    68     Wasm::MemoryMode memoryMode() { return memory()->memory().mode(); }
    69 
    70     // Tail accessors.
    71     static size_t offsetOfTail() { return WTF::roundUpToMultipleOf<sizeof(uint64_t)>(sizeof(JSWebAssemblyInstance)); }
    72     struct ImportFunctionInfo {
    73         // Target instance and entrypoint are only set for wasm->wasm calls, and are otherwise nullptr. The embedder-specific logic occurs through import function.
    74         JSWebAssemblyInstance* targetInstance { nullptr };
    75         Wasm::WasmEntrypointLoadLocation wasmEntrypoint { nullptr };
    76         WriteBarrier<JSObject> importFunction { WriteBarrier<JSObject>() };
    77     };
    78     ImportFunctionInfo* importFunctionInfo(size_t importFunctionNum) { return &bitwise_cast<ImportFunctionInfo*>(bitwise_cast<char*>(this) + offsetOfTail())[importFunctionNum]; }
    79     static size_t offsetOfTargetInstance(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, targetInstance); }
    80     static size_t offsetOfWasmEntrypoint(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, wasmEntrypoint); }
    81     static size_t offsetOfImportFunction(size_t importFunctionNum) { return offsetOfTail() + importFunctionNum * sizeof(ImportFunctionInfo) + OBJECT_OFFSETOF(ImportFunctionInfo, importFunction); }
    82     JSObject* importFunction(unsigned importFunctionNum) { RELEASE_ASSERT(importFunctionNum < m_numImportFunctions); return importFunctionInfo(importFunctionNum)->importFunction.get(); }
    83    
    84     // FIXME remove these after refactoring them out. https://webkit.org/b/177472
    85     Wasm::Memory& internalMemory() { return memory()->memory(); }
    86     Wasm::CodeBlock& wasmCodeBlock() const { return *m_instance->codeBlock(); }
    87     static ptrdiff_t offsetOfWasmTable() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_wasmTable); }
    88     static ptrdiff_t offsetOfCallee() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_callee); }
    89     static ptrdiff_t offsetOfVM() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_vm); }
    90     static ptrdiff_t offsetOfGlobals() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_globals); }
    91     static ptrdiff_t offsetOfCodeBlock() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_codeBlock); }
    92     static ptrdiff_t offsetOfWasmCodeBlock() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_wasmCodeBlock); }
    93     static ptrdiff_t offsetOfCachedStackLimit() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_cachedStackLimit); }
    94     static ptrdiff_t offsetOfWasmMemory() { return OBJECT_OFFSETOF(JSWebAssemblyInstance, m_wasmMemory); }
    95     void* cachedStackLimit() const { RELEASE_ASSERT(m_instance->cachedStackLimit() == m_cachedStackLimit); return m_cachedStackLimit; }
    96     void setCachedStackLimit(void* limit) { m_instance->setCachedStackLimit(limit); m_cachedStackLimit = limit; }
    97     Wasm::Memory* wasmMemory() { return m_wasmMemory; }
    98     Wasm::Module& wasmModule() { return m_wasmModule; }
     84    void* cachedStackLimit() const { return m_cachedStackLimit; }
     85    void setCachedStackLimit(void* limit) { m_cachedStackLimit = limit; }
    9986
    10087protected:
    101     JSWebAssemblyInstance(VM&, Structure*, unsigned numImportFunctions, Ref<Wasm::Instance>&&);
     88    JSWebAssemblyInstance(VM&, Structure*, unsigned numImportFunctions);
    10289    void finishCreation(VM&, JSWebAssemblyModule*, JSModuleNamespaceObject*);
    10390    static void destroy(JSCell*);
     
    10693    static size_t allocationSize(Checked<size_t> numImportFunctions)
    10794    {
    108         return (offsetOfTail() + sizeof(ImportFunctionInfo) * numImportFunctions).unsafeGet();
     95        return (offsetOfImportFunctions() + sizeof(WriteBarrier<JSCell>) * numImportFunctions).unsafeGet();
    10996    }
    11097
    11198private:
    112     JSWebAssemblyModule* module() const { return m_module.get(); }
     99    VM* m_vm;
     100    WriteBarrier<JSObject>* importFunctions() { return bitwise_cast<WriteBarrier<JSObject>*>(bitwise_cast<char*>(this) + offsetOfImportFunctions()); }
     101    size_t globalMemoryByteSize() const;
    113102
    114     Ref<Wasm::Instance> m_instance;
    115 
    116     VM* m_vm;
    117103    WriteBarrier<JSWebAssemblyModule> m_module;
    118104    WriteBarrier<JSWebAssemblyCodeBlock> m_codeBlock;
     
    121107    WriteBarrier<JSWebAssemblyTable> m_table;
    122108    WriteBarrier<WebAssemblyToJSCallee> m_callee;
    123    
    124     // FIXME remove these after refactoring them out. https://webkit.org/b/177472
     109    MallocPtr<uint64_t> m_globals;
    125110    void* m_cachedStackLimit { bitwise_cast<void*>(std::numeric_limits<uintptr_t>::max()) };
    126     Wasm::CodeBlock* m_wasmCodeBlock { nullptr };
    127     Wasm::Module& m_wasmModule;
    128     Wasm::Memory* m_wasmMemory { nullptr };
    129     Wasm::Table* m_wasmTable { nullptr };
    130     uint64_t* m_globals { nullptr };
    131 
    132111    unsigned m_numImportFunctions;
    133112};
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyMemory.cpp

    r222791 r223002  
    3838const ClassInfo JSWebAssemblyMemory::s_info = { "WebAssembly.Memory", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSWebAssemblyMemory) };
    3939
    40 JSWebAssemblyMemory* JSWebAssemblyMemory::create(ExecState* exec, VM& vm, Structure* structure)
     40JSWebAssemblyMemory* JSWebAssemblyMemory::create(ExecState* exec, VM& vm, Structure* structure, Ref<Wasm::Memory>&& memory)
    4141{
    4242    auto throwScope = DECLARE_THROW_SCOPE(vm);
     
    5151        return exception(createEvalError(exec, globalObject->webAssemblyDisabledErrorMessage()));
    5252
    53     auto* memory = new (NotNull, allocateCell<JSWebAssemblyMemory>(vm.heap)) JSWebAssemblyMemory(vm, structure);
    54     memory->finishCreation(vm);
    55     return memory;
    56 }
    57    
    58 void JSWebAssemblyMemory::adopt(Ref<Wasm::Memory>&& memory)
    59 {
    60     m_memory.swap(memory);
    61     ASSERT(m_memory->refCount() == 1);
    62     m_memory->check();
     53    auto* instance = new (NotNull, allocateCell<JSWebAssemblyMemory>(vm.heap)) JSWebAssemblyMemory(vm, structure, WTFMove(memory));
     54    instance->m_memory->check();
     55    instance->finishCreation(vm);
     56    return instance;
    6357}
    6458
     
    6862}
    6963
    70 JSWebAssemblyMemory::JSWebAssemblyMemory(VM& vm, Structure* structure)
     64JSWebAssemblyMemory::JSWebAssemblyMemory(VM& vm, Structure* structure, Ref<Wasm::Memory>&& memory)
    7165    : Base(vm, structure)
    72     , m_memory(Wasm::Memory::create().releaseNonNull())
     66    , m_memory(WTFMove(memory))
    7367{
     68    ASSERT(m_memory->refCount() == 1);
     69    m_memoryBase = m_memory->memory();
     70    m_memorySize = m_memory->size();
    7471}
    7572
     
    8986}
    9087
    91 Wasm::PageCount JSWebAssemblyMemory::grow(VM& vm, ExecState* exec, uint32_t delta)
     88Wasm::PageCount JSWebAssemblyMemory::grow(VM& vm, ExecState* exec, uint32_t delta, bool shouldThrowExceptionsOnFailure)
    9289{
     90    // Note: We can only use exec if shouldThrowExceptionsOnFailure is true.
    9391    auto throwScope = DECLARE_THROW_SCOPE(vm);
    9492
    95     auto grown = memory().grow(Wasm::PageCount(delta));
    96     if (!grown) {
    97         switch (grown.error()) {
    98         case Wasm::Memory::GrowFailReason::InvalidDelta:
     93    Wasm::PageCount oldPageCount = memory().sizeInPages();
     94
     95    if (!Wasm::PageCount::isValid(delta)) {
     96        if (shouldThrowExceptionsOnFailure)
    9997            throwException(exec, throwScope, createRangeError(exec, ASCIILiteral("WebAssembly.Memory.grow expects the delta to be a valid page count")));
    100             break;
    101         case Wasm::Memory::GrowFailReason::InvalidGrowSize:
    102             throwException(exec, throwScope, createRangeError(exec, ASCIILiteral("WebAssembly.Memory.grow expects the grown size to be a valid page count")));
    103             break;
    104         case Wasm::Memory::GrowFailReason::WouldExceedMaximum:
    105             throwException(exec, throwScope, createRangeError(exec, ASCIILiteral("WebAssembly.Memory.grow would exceed the memory's declared maximum size")));
    106             break;
    107         case Wasm::Memory::GrowFailReason::OutOfMemory:
    108             throwException(exec, throwScope, createOutOfMemoryError(exec));
    109             break;
    110         }
    11198        return Wasm::PageCount();
    11299    }
    113100
    114     return grown.value();
    115 }
     101    Wasm::PageCount newSize = oldPageCount + Wasm::PageCount(delta);
     102    if (!newSize) {
     103        if (shouldThrowExceptionsOnFailure)
     104            throwException(exec, throwScope, createRangeError(exec, ASCIILiteral("WebAssembly.Memory.grow expects the grown size to be a valid page count")));
     105        return Wasm::PageCount();
     106    }
    116107
    117 void JSWebAssemblyMemory::growSuccessCallback(VM& vm, Wasm::PageCount oldPageCount, Wasm::PageCount newPageCount)
    118 {
    119     // We need to clear out the old array buffer because it might now be pointing to stale memory.
     108    if (delta) {
     109        bool success = memory().grow(vm, newSize);
     110        if (!success) {
     111            ASSERT(m_memoryBase == memory().memory());
     112            ASSERT(m_memorySize == memory().size());
     113            if (shouldThrowExceptionsOnFailure)
     114                throwException(exec, throwScope, createOutOfMemoryError(exec));
     115            return Wasm::PageCount();
     116        }
     117        m_memoryBase = memory().memory();
     118        m_memorySize = memory().size();
     119    }
     120
     121    // We need to clear out the old array buffer because it might now be pointing
     122    // to stale memory.
    120123    // Neuter the old array.
    121124    if (m_buffer) {
     
    124127        m_bufferWrapper.clear();
    125128    }
    126    
     129
    127130    memory().check();
    128    
    129     vm.heap.reportExtraMemoryAllocated(newPageCount.bytes() - oldPageCount.bytes());
     131
     132    vm.heap.reportExtraMemoryAllocated(Wasm::PageCount(delta).bytes());
     133    return oldPageCount;
    130134}
    131135
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyMemory.h

    r222791 r223002  
    4949    }
    5050
    51     static JSWebAssemblyMemory* create(ExecState*, VM&, Structure*);
     51    static JSWebAssemblyMemory* create(ExecState*, VM&, Structure*, Ref<Wasm::Memory>&&);
    5252    static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
    5353
    5454    DECLARE_EXPORT_INFO;
    5555
    56     void adopt(Ref<Wasm::Memory>&&);
    5756    Wasm::Memory& memory() { return m_memory.get(); }
    5857    JSArrayBuffer* buffer(VM& vm, JSGlobalObject*);
    59     Wasm::PageCount grow(VM&, ExecState*, uint32_t delta);
    60     void growSuccessCallback(VM&, Wasm::PageCount oldPageCount, Wasm::PageCount newPageCount);
     58    Wasm::PageCount grow(VM&, ExecState*, uint32_t delta, bool shouldThrowExceptionsOnFailure);
     59
     60    static ptrdiff_t offsetOfMemory() { return OBJECT_OFFSETOF(JSWebAssemblyMemory, m_memoryBase); }
     61    static ptrdiff_t offsetOfSize() { return OBJECT_OFFSETOF(JSWebAssemblyMemory, m_memorySize); }
    6162
    6263private:
    63     JSWebAssemblyMemory(VM&, Structure*);
     64    JSWebAssemblyMemory(VM&, Structure*, Ref<Wasm::Memory>&&);
    6465    void finishCreation(VM&);
    6566    static void destroy(JSCell*);
    6667    static void visitChildren(JSCell*, SlotVisitor&);
    6768
     69    void* m_memoryBase;
     70    size_t m_memorySize;
    6871    Ref<Wasm::Memory> m_memory;
    6972    WriteBarrier<JSArrayBuffer> m_bufferWrapper;
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyModule.cpp

    r222791 r223002  
    3636#include "WasmFormat.h"
    3737#include "WasmMemory.h"
    38 #include "WasmModule.h"
    3938#include "WasmPlan.h"
    4039#include "WebAssemblyToJSCallee.h"
     
    6261    return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
    6362}
    64 
    6563
    6664JSWebAssemblyModule::JSWebAssemblyModule(VM& vm, Structure* structure, Ref<Wasm::Module>&& module)
     
    9492}
    9593
    96 const Wasm::ModuleInformation& JSWebAssemblyModule::moduleInformation() const
    97 {
    98     return m_module->moduleInformation();
    99 }
    100 
    101 SymbolTable* JSWebAssemblyModule::exportSymbolTable() const
    102 {
    103     return m_exportSymbolTable.get();
    104 }
    105 
    106 Wasm::SignatureIndex JSWebAssemblyModule::signatureIndexFromFunctionIndexSpace(unsigned functionIndexSpace) const
    107 {
    108     return m_module->signatureIndexFromFunctionIndexSpace(functionIndexSpace);
    109 }
    110 
    111 WebAssemblyToJSCallee* JSWebAssemblyModule::callee() const
    112 {
    113     return m_callee.get();
    114 }
    115 
    116 JSWebAssemblyCodeBlock* JSWebAssemblyModule::codeBlock(Wasm::MemoryMode mode)
    117 {
    118     return m_codeBlocks[static_cast<size_t>(mode)].get();
    119 }
    120 
    121 Wasm::Module& JSWebAssemblyModule::module()
    122 {
    123     return m_module.get();
    124 }
    125 
    12694void JSWebAssemblyModule::setCodeBlock(VM& vm, Wasm::MemoryMode mode, JSWebAssemblyCodeBlock* codeBlock)
    12795{
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyModule.h

    r222791 r223002  
    3131#include "JSObject.h"
    3232#include "UnconditionalFinalizer.h"
    33 #include "WasmMemoryMode.h"
     33#include "WasmModule.h"
    3434#include <wtf/Bag.h>
    35 #include <wtf/Expected.h>
    3635#include <wtf/Forward.h>
    37 #include <wtf/text/WTFString.h>
    3836
    3937namespace JSC {
     
    4139namespace Wasm {
    4240class Module;
    43 struct ModuleInformation;
    4441class Plan;
    45 using SignatureIndex = uint32_t;
    4642}
    4743
     
    5753    DECLARE_EXPORT_INFO;
    5854
    59     JS_EXPORT_PRIVATE static JSWebAssemblyModule* createStub(VM&, ExecState*, Structure*, WTF::Expected<RefPtr<Wasm::Module>, String>&&);
     55    JS_EXPORT_PRIVATE static JSWebAssemblyModule* createStub(VM&, ExecState*, Structure*, Wasm::Module::ValidationResult&&);
    6056    static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
    6157
    62     const Wasm::ModuleInformation& moduleInformation() const;
    63     SymbolTable* exportSymbolTable() const;
    64     Wasm::SignatureIndex signatureIndexFromFunctionIndexSpace(unsigned functionIndexSpace) const;
    65     WebAssemblyToJSCallee* callee() const;
     58    const Wasm::ModuleInformation& moduleInformation() const { return m_module->moduleInformation(); }
     59    SymbolTable* exportSymbolTable() const { return m_exportSymbolTable.get(); }
     60    Wasm::SignatureIndex signatureIndexFromFunctionIndexSpace(unsigned functionIndexSpace) const
     61    {
     62        return m_module->signatureIndexFromFunctionIndexSpace(functionIndexSpace);
     63    }
     64    WebAssemblyToJSCallee* callee() const { return m_callee.get(); }
    6665
    67     JSWebAssemblyCodeBlock* codeBlock(Wasm::MemoryMode mode);
    68     void setCodeBlock(VM&, Wasm::MemoryMode, JSWebAssemblyCodeBlock*);
     66    JSWebAssemblyCodeBlock* codeBlock(Wasm::MemoryMode mode) { return m_codeBlocks[static_cast<size_t>(mode)].get(); }
    6967
    7068    const Vector<uint8_t>& source() const;
    7169
    72     JS_EXPORT_PRIVATE Wasm::Module& module();
     70    Wasm::Module& module() { return m_module.get(); }
     71    void setCodeBlock(VM&, Wasm::MemoryMode, JSWebAssemblyCodeBlock*);
    7372
    7473private:
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyTable.cpp

    r222873 r223002  
    3030
    3131#include "JSCInlines.h"
     32#include "WasmFormat.h"
     33#include <wtf/CheckedArithmetic.h>
    3234
    3335namespace JSC {
     
    3537const ClassInfo JSWebAssemblyTable::s_info = { "WebAssembly.Table", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSWebAssemblyTable) };
    3638
    37 JSWebAssemblyTable* JSWebAssemblyTable::create(ExecState* exec, VM& vm, Structure* structure, Ref<Wasm::Table>&& table)
     39JSWebAssemblyTable* JSWebAssemblyTable::create(ExecState* exec, VM& vm, Structure* structure, uint32_t initial, std::optional<uint32_t> maximum)
    3840{
    3941    auto throwScope = DECLARE_THROW_SCOPE(vm);
    4042    auto* globalObject = exec->lexicalGlobalObject();
    4143
    42     if (!globalObject->webAssemblyEnabled()) {
    43         throwException(exec, throwScope, createEvalError(exec, globalObject->webAssemblyDisabledErrorMessage()));
     44    auto exception = [&] (JSObject* error) {
     45        throwException(exec, throwScope, error);
    4446        return nullptr;
    45     }
     47    };
    4648
    47     auto* instance = new (NotNull, allocateCell<JSWebAssemblyTable>(vm.heap)) JSWebAssemblyTable(vm, structure, WTFMove(table));
     49    if (!globalObject->webAssemblyEnabled())
     50        return exception(createEvalError(exec, globalObject->webAssemblyDisabledErrorMessage()));
     51
     52    if (!isValidSize(initial))
     53        return exception(createOutOfMemoryError(exec));
     54
     55    auto* instance = new (NotNull, allocateCell<JSWebAssemblyTable>(vm.heap)) JSWebAssemblyTable(vm, structure, initial, maximum);
    4856    instance->finishCreation(vm);
    4957    return instance;
     
    5563}
    5664
    57 JSWebAssemblyTable::JSWebAssemblyTable(VM& vm, Structure* structure, Ref<Wasm::Table>&& table)
     65JSWebAssemblyTable::JSWebAssemblyTable(VM& vm, Structure* structure, uint32_t initial, std::optional<uint32_t> maximum)
    5866    : Base(vm, structure)
    59     , m_table(WTFMove(table))
    6067{
     68    m_size = initial;
     69    ASSERT(isValidSize(m_size));
     70    m_maximum = maximum;
     71    ASSERT(!m_maximum || *m_maximum >= m_size);
     72
    6173    // FIXME: It might be worth trying to pre-allocate maximum here. The spec recommends doing so.
    6274    // But for now, we're not doing that.
    63     m_jsFunctions = MallocPtr<WriteBarrier<JSObject>>::malloc(sizeof(WriteBarrier<JSObject>) * static_cast<size_t>(size()));
    64     for (uint32_t i = 0; i < size(); ++i)
    65         default_construct_at(&m_jsFunctions.get()[i]);
     75    m_functions = MallocPtr<Wasm::CallableFunction>::malloc(sizeof(Wasm::CallableFunction) * static_cast<size_t>(m_size));
     76    m_jsFunctions = MallocPtr<WriteBarrier<JSObject>>::malloc(sizeof(WriteBarrier<JSObject>) * static_cast<size_t>(m_size));
     77    for (uint32_t i = 0; i < m_size; ++i) {
     78        new (&m_functions.get()[i]) Wasm::CallableFunction();
     79        ASSERT(m_functions.get()[i].signatureIndex == Wasm::Signature::invalidIndex); // We rely on this in compiled code.
     80        new (&m_jsFunctions.get()[i]) WriteBarrier<JSObject>();
     81    }
    6682}
    6783
     
    84100    Base::visitChildren(thisObject, visitor);
    85101
    86     for (unsigned i = 0; i < thisObject->size(); ++i)
     102    for (unsigned i = 0; i < thisObject->m_size; ++i)
    87103        visitor.append(thisObject->m_jsFunctions.get()[i]);
    88104}
     
    92108    if (delta == 0)
    93109        return true;
    94 
    95     size_t oldSize = size();
    96 
    97     auto grew = m_table->grow(delta);
    98     if (!grew)
     110    Checked<uint32_t, RecordOverflow> newSizeChecked = m_size;
     111    newSizeChecked += delta;
     112    uint32_t newSize;
     113    if (newSizeChecked.safeGet(newSize) == CheckedState::DidOverflow)
     114        return false;
     115    if (maximum() && newSize > *maximum())
     116        return false;
     117    if (!isValidSize(newSize))
    99118        return false;
    100119
    101     size_t newSize = grew.value();
    102     m_jsFunctions.realloc(sizeof(WriteBarrier<JSObject>) * newSize);
     120    m_functions.realloc(sizeof(Wasm::CallableFunction) * static_cast<size_t>(newSize));
     121    m_jsFunctions.realloc(sizeof(WriteBarrier<JSObject>) * static_cast<size_t>(newSize));
    103122
    104     for (size_t i = oldSize; i < newSize; ++i)
    105         default_construct_at(&m_jsFunctions.get()[i]);
    106 
     123    for (uint32_t i = m_size; i < newSize; ++i) {
     124        new (&m_functions.get()[i]) Wasm::CallableFunction();
     125        new (&m_jsFunctions.get()[i]) WriteBarrier<JSObject>();
     126    }
     127    m_size = newSize;
    107128    return true;
    108 }
    109 
    110 JSObject* JSWebAssemblyTable::getFunction(uint32_t index)
    111 {
    112     RELEASE_ASSERT(index < size());
    113     return m_jsFunctions.get()[index].get();
    114129}
    115130
    116131void JSWebAssemblyTable::clearFunction(uint32_t index)
    117132{
    118     m_table->clearFunction(index);
     133    RELEASE_ASSERT(index < m_size);
    119134    m_jsFunctions.get()[index] = WriteBarrier<JSObject>();
     135    m_functions.get()[index] = Wasm::CallableFunction();
     136    ASSERT(m_functions.get()[index].signatureIndex == Wasm::Signature::invalidIndex); // We rely on this in compiled code.
    120137}
    121138
    122139void JSWebAssemblyTable::setFunction(VM& vm, uint32_t index, WebAssemblyFunction* function)
    123140{
    124     m_table->setFunction(index, function->callableFunction(), function->instance());
     141    RELEASE_ASSERT(index < m_size);
    125142    m_jsFunctions.get()[index].set(vm, this, function);
     143    m_functions.get()[index] = function->callableFunction();
    126144}
    127145
    128146void JSWebAssemblyTable::setFunction(VM& vm, uint32_t index, WebAssemblyWrapperFunction* function)
    129147{
    130     m_table->setFunction(index, function->callableFunction(), function->instance());
     148    RELEASE_ASSERT(index < m_size);
    131149    m_jsFunctions.get()[index].set(vm, this, function);
     150    m_functions.get()[index] = function->callableFunction();
    132151}
    133152
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyTable.h

    r222791 r223002  
    11/*
    2  * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    3030#include "JSDestructibleObject.h"
    3131#include "JSObject.h"
    32 #include "WasmLimits.h"
    33 #include "WasmTable.h"
    3432#include "WebAssemblyWrapperFunction.h"
    3533#include "WebAssemblyFunction.h"
     
    3836namespace JSC {
    3937
     38namespace Wasm {
     39struct CallableFunction;
     40}
     41
    4042class JSWebAssemblyTable : public JSDestructibleObject {
    4143public:
    4244    typedef JSDestructibleObject Base;
    4345
    44     static JSWebAssemblyTable* create(ExecState*, VM&, Structure*, Ref<Wasm::Table>&&);
     46    static JSWebAssemblyTable* create(ExecState*, VM&, Structure*, uint32_t initial, std::optional<uint32_t> maximum);
    4547    static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
    4648
    4749    DECLARE_INFO;
    4850
    49     static bool isValidSize(uint32_t size) { return Wasm::Table::isValidSize(size); }
    50     std::optional<uint32_t> maximum() const { return m_table->maximum(); }
    51     uint32_t size() const { return m_table->size(); }
     51    std::optional<uint32_t> maximum() const { return m_maximum; }
     52    uint32_t size() const { return m_size; }
    5253    bool grow(uint32_t delta) WARN_UNUSED_RETURN;
    53     JSObject* getFunction(uint32_t);
    54     void clearFunction(uint32_t);
    55     void setFunction(VM&, uint32_t, WebAssemblyFunction*);
    56     void setFunction(VM&, uint32_t, WebAssemblyWrapperFunction*);
     54    JSObject* getFunction(uint32_t index)
     55    {
     56        RELEASE_ASSERT(index < m_size);
     57        return m_jsFunctions.get()[index].get();
     58    }
     59    void clearFunction(uint32_t index);
     60    void setFunction(VM&, uint32_t index, WebAssemblyFunction*);
     61    void setFunction(VM&, uint32_t index, WebAssemblyWrapperFunction*);
    5762
    58     Wasm::Table* table() { return m_table.ptr(); }
     63    static ptrdiff_t offsetOfSize() { return OBJECT_OFFSETOF(JSWebAssemblyTable, m_size); }
     64    static ptrdiff_t offsetOfFunctions() { return OBJECT_OFFSETOF(JSWebAssemblyTable, m_functions); }
     65    static ptrdiff_t offsetOfJSFunctions() { return OBJECT_OFFSETOF(JSWebAssemblyTable, m_jsFunctions); }
     66
     67    static bool isValidSize(uint32_t size)
     68    {
     69        // This tops out at ~384 MB worth of data in this class.
     70        return size < (1 << 24);
     71    }
    5972
    6073private:
    61     JSWebAssemblyTable(VM&, Structure*, Ref<Wasm::Table>&&);
     74    JSWebAssemblyTable(VM&, Structure*, uint32_t initial, std::optional<uint32_t> maximum);
    6275    void finishCreation(VM&);
    6376    static void destroy(JSCell*);
    6477    static void visitChildren(JSCell*, SlotVisitor&);
    6578
    66     Ref<Wasm::Table> m_table;
     79    MallocPtr<Wasm::CallableFunction> m_functions;
    6780    MallocPtr<WriteBarrier<JSObject>> m_jsFunctions;
     81    std::optional<uint32_t> m_maximum;
     82    uint32_t m_size;
    6883};
    6984
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyFunction.cpp

    r222791 r223002  
    6161
    6262    // Make sure that the memory we think we are going to run with matches the one we expect.
    63     ASSERT(wasmFunction->instance()->instance().codeBlock()->isSafeToRun(wasmFunction->instance()->memory()->memory().mode()));
     63    ASSERT(wasmFunction->instance()->codeBlock()->isSafeToRun(wasmFunction->instance()->memory()));
    6464    {
    6565        // Check if we have a disallowed I64 use.
     
    8383
    8484    Vector<JSValue> boxedArgs;
    85     JSWebAssemblyInstance* instance = wasmFunction->instance();
    86     // When we don't use fast TLS to store the context, the JS
    87     // entry wrapper expects the instance as the first argument.
    88     if (!Wasm::Context::useFastTLS())
    89         boxedArgs.append(instance);
     85    Wasm::Context* wasmContext = wasmFunction->instance();
     86    // When we don't use fast TLS to store the context, the js
     87    // entry wrapper expects the WasmContext* as the first argument.
     88    if (!Wasm::useFastTLSForContext())
     89        boxedArgs.append(wasmContext);
    9090
    9191    for (unsigned argIndex = 0; argIndex < signature.argumentCount(); ++argIndex) {
     
    128128
    129129    // FIXME Do away with this entire function, and only use the entrypoint generated by B3. https://bugs.webkit.org/show_bug.cgi?id=166486
    130     JSWebAssemblyInstance* prevInstance = vm.wasmContext.load();
     130    Wasm::Context* prevWasmContext = Wasm::loadContext(vm);
    131131    {
    132132        // We do the stack check here for the wrapper function because we don't
     
    138138            return JSValue::encode(throwException(exec, scope, createStackOverflowError(exec)));
    139139    }
    140     vm.wasmContext.store(instance, vm.softStackLimit());
     140    Wasm::storeContext(vm, wasmContext);
    141141    ASSERT(wasmFunction->instance());
    142     ASSERT(wasmFunction->instance() == vm.wasmContext.load());
     142    ASSERT(wasmFunction->instance() == Wasm::loadContext(vm));
    143143    EncodedJSValue rawResult = vmEntryToWasm(wasmFunction->jsEntrypoint(), &vm, &protoCallFrame);
    144144    // We need to make sure this is in a register or on the stack since it's stored in Vector<JSValue>.
    145145    // This probably isn't strictly necessary, since the WebAssemblyFunction* should keep the instance
    146146    // alive. But it's good hygiene.
    147     instance->use();
    148     if (prevInstance != instance) {
     147    wasmContext->use();
     148    if (prevWasmContext != wasmContext) {
    149149        // This is just for some extra safety instead of leaving a cached
    150150        // value in there. If we ever forget to set the value to be a real
    151151        // bounds, this will force every stack overflow check to immediately
    152152        // fire.
    153         instance->setCachedStackLimit(bitwise_cast<void*>(std::numeric_limits<uintptr_t>::max()));
    154     }
    155     vm.wasmContext.store(prevInstance, vm.softStackLimit());
     153        wasmContext->setCachedStackLimit(bitwise_cast<void*>(std::numeric_limits<uintptr_t>::max()));
     154    }
     155    Wasm::storeContext(vm, prevWasmContext);
    156156    RETURN_IF_EXCEPTION(scope, { });
    157157
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyInstanceConstructor.cpp

    r222791 r223002  
    3333#include "JSModuleEnvironment.h"
    3434#include "JSModuleNamespaceObject.h"
    35 #include "JSToWasm.h"
    3635#include "JSWebAssemblyHelpers.h"
    3736#include "JSWebAssemblyInstance.h"
     
    4039#include "JSWebAssemblyModule.h"
    4140#include "WasmPlan.h"
    42 #include "WasmToJS.h"
    4341#include "WasmWorklist.h"
    4442#include "WebAssemblyFunction.h"
     
    7876    RETURN_IF_EXCEPTION(scope, { });
    7977
    80     JSWebAssemblyInstance* instance = JSWebAssemblyInstance::create(vm, exec, module, importObject, instanceStructure, Wasm::Instance::create(Ref<Wasm::Module>(module->module())));
     78    JSWebAssemblyInstance* instance = JSWebAssemblyInstance::create(vm, exec, module, importObject, instanceStructure);
    8179    RETURN_IF_EXCEPTION(scope, { });
    8280
    83     instance->finalizeCreation(vm, exec, module->module().compileSync(&vm.wasmContext, instance->memoryMode(), &Wasm::createJSToWasmWrapper, &Wasm::wasmToJSException));
     81    instance->finalizeCreation(vm, exec, module->module().compileSync(instance->memoryMode()));
    8482    RETURN_IF_EXCEPTION(scope, { });
    8583    return JSValue::encode(instance);
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyMemoryConstructor.cpp

    r222791 r223002  
    9797    }
    9898
    99     auto* jsMemory = JSWebAssemblyMemory::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure());
    100     RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
    101 
    102     RefPtr<Wasm::Memory> memory = Wasm::Memory::create(initialPageCount, maximumPageCount,
    103         [&vm] (Wasm::Memory::NotifyPressure) { vm.heap.collectAsync(CollectionScope::Full); },
    104         [&vm] (Wasm::Memory::SyncTryToReclaim) { vm.heap.collectSync(CollectionScope::Full); },
    105         [&vm, jsMemory] (Wasm::Memory::GrowSuccess, Wasm::PageCount oldPageCount, Wasm::PageCount newPageCount) { jsMemory->growSuccessCallback(vm, oldPageCount, newPageCount); });
     99    RefPtr<Wasm::Memory> memory = Wasm::Memory::create(vm, initialPageCount, maximumPageCount);
    106100    if (!memory)
    107101        return JSValue::encode(throwException(exec, throwScope, createOutOfMemoryError(exec)));
    108102
    109     jsMemory->adopt(memory.releaseNonNull());
    110    
     103    auto* jsMemory = JSWebAssemblyMemory::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyMemoryStructure(), adoptRef(*memory.leakRef()));
     104    RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
     105
    111106    return JSValue::encode(jsMemory);
    112107}
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyMemoryPrototype.cpp

    r222791 r223002  
    7878    RETURN_IF_EXCEPTION(throwScope, { });
    7979
    80     Wasm::PageCount result = memory->grow(vm, exec, delta);
     80    bool shouldThrowExceptionsOnFailure = true;
     81    Wasm::PageCount result = memory->grow(vm, exec, delta, shouldThrowExceptionsOnFailure);
    8182    RETURN_IF_EXCEPTION(throwScope, { });
    8283
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleConstructor.cpp

    r222791 r223002  
    162162{
    163163    VM& vm = exec->vm();
    164     auto scope = DECLARE_THROW_SCOPE(vm);
    165    
    166     Vector<uint8_t> source = createSourceBufferFromValue(vm, exec, exec->argument(0));
    167     RETURN_IF_EXCEPTION(scope, { });
    168 
    169     scope.release();
    170     return JSValue::encode(WebAssemblyModuleConstructor::createModule(exec, WTFMove(source)));
     164    auto throwScope = DECLARE_THROW_SCOPE(vm);
     165    auto* structure = InternalFunction::createSubclassStructure(exec, exec->newTarget(), exec->lexicalGlobalObject()->WebAssemblyModuleStructure());
     166    RETURN_IF_EXCEPTION(throwScope, encodedJSValue());
     167    throwScope.release();
     168    return JSValue::encode(WebAssemblyModuleConstructor::createModule(exec, exec->argument(0), structure));
    171169}
    172170
     
    178176}
    179177
    180 JSWebAssemblyModule* WebAssemblyModuleConstructor::createModule(ExecState* exec, Vector<uint8_t>&& buffer)
     178JSValue WebAssemblyModuleConstructor::createModule(ExecState* exec, JSValue buffer, Structure* structure)
    181179{
    182180    VM& vm = exec->vm();
    183181    auto scope = DECLARE_THROW_SCOPE(vm);
    184182
    185     auto* structure = InternalFunction::createSubclassStructure(exec, exec->newTarget(), exec->lexicalGlobalObject()->WebAssemblyModuleStructure());
    186     RETURN_IF_EXCEPTION(scope, nullptr);
     183    Vector<uint8_t> source = createSourceBufferFromValue(vm, exec, buffer);
     184    RETURN_IF_EXCEPTION(scope, { });
    187185
    188186    scope.release();
    189     return JSWebAssemblyModule::createStub(vm, exec, structure, Wasm::Module::validateSync(&vm.wasmContext, WTFMove(buffer)));
     187    return JSWebAssemblyModule::createStub(vm, exec, structure, Wasm::Module::validateSync(vm, WTFMove(source)));
    190188}
    191189
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleConstructor.h

    r222791 r223002  
    3131#include "JSObject.h"
    3232
    33 #include <wtf/Vector.h>
    34 
    3533namespace JSC {
    3634
    37 class JSWebAssemblyModule;
    3835class WebAssemblyModulePrototype;
    3936
     
    4845    DECLARE_INFO;
    4946
    50     static JSWebAssemblyModule* createModule(ExecState*, Vector<uint8_t>&& buffer);
     47    static JSValue createModule(ExecState*, JSValue buffer, Structure*);
    5148
    5249protected:
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleRecord.cpp

    r222791 r223002  
    9494    auto* globalObject = exec->lexicalGlobalObject();
    9595
    96     Wasm::CodeBlock* codeBlock = instance->instance().codeBlock();
     96    JSWebAssemblyCodeBlock* codeBlock = instance->codeBlock();
    9797    const Wasm::ModuleInformation& moduleInformation = module->moduleInformation();
    9898
     
    153153            switch (global.type) {
    154154            case Wasm::I32:
    155                 exportedValue = JSValue(instance->instance().loadI32Global(exp.kindIndex));
     155                exportedValue = JSValue(instance->loadI32Global(exp.kindIndex));
    156156                break;
    157157
     
    161161
    162162            case Wasm::F32:
    163                 exportedValue = JSValue(instance->instance().loadF32Global(exp.kindIndex));
     163                exportedValue = JSValue(instance->loadF32Global(exp.kindIndex));
    164164                break;
    165165
    166166            case Wasm::F64:
    167                 exportedValue = JSValue(instance->instance().loadF64Global(exp.kindIndex));
     167                exportedValue = JSValue(instance->loadF64Global(exp.kindIndex));
    168168                break;
    169169
     
    218218    auto scope = DECLARE_THROW_SCOPE(vm);
    219219
    220     Wasm::Module& module = m_instance->instance().module();
    221     Wasm::CodeBlock* codeBlock = m_instance->instance().codeBlock();
    222     const Wasm::ModuleInformation& moduleInformation = module.moduleInformation();
     220    JSWebAssemblyModule* module = m_instance->module();
     221    JSWebAssemblyCodeBlock* codeBlock = m_instance->codeBlock();
     222    const Wasm::ModuleInformation& moduleInformation = module->moduleInformation();
    223223    JSWebAssemblyTable* table = m_instance->table();
    224224
    225     const Vector<Wasm::Segment::Ptr>& data = moduleInformation.data;
     225    const Vector<Wasm::Segment::Ptr>& data = m_instance->module()->moduleInformation().data;
    226226    JSWebAssemblyMemory* jsMemory = m_instance->memory();
    227227
     
    240240
    241241            uint32_t tableIndex = element.offset.isGlobalImport()
    242                 ? static_cast<uint32_t>(m_instance->instance().loadI32Global(element.offset.globalImportIndex()))
     242                ? static_cast<uint32_t>(m_instance->loadI32Global(element.offset.globalImportIndex()))
    243243                : element.offset.constValue();
    244244
     
    256256        for (const Wasm::Segment::Ptr& segment : data) {
    257257            uint32_t offset = segment->offset.isGlobalImport()
    258                 ? static_cast<uint32_t>(m_instance->instance().loadI32Global(segment->offset.globalImportIndex()))
     258                ? static_cast<uint32_t>(m_instance->loadI32Global(segment->offset.globalImportIndex()))
    259259                : segment->offset.constValue();
    260260
     
    294294            // https://bugs.webkit.org/show_bug.cgi?id=165510
    295295            uint32_t functionIndex = element.functionIndices[i];
    296             Wasm::SignatureIndex signatureIndex = module.signatureIndexFromFunctionIndexSpace(functionIndex);
     296            Wasm::SignatureIndex signatureIndex = module->signatureIndexFromFunctionIndexSpace(functionIndex);
    297297            if (functionIndex < codeBlock->functionImportCount()) {
    298298                JSObject* functionImport = jsCast<JSObject*>(m_instance->importFunction(functionIndex));
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyPrototype.cpp

    r222791 r223002  
    3434#include "JSCInlines.h"
    3535#include "JSPromiseDeferred.h"
    36 #include "JSToWasm.h"
    3736#include "JSWebAssemblyHelpers.h"
    3837#include "JSWebAssemblyInstance.h"
     
    4241#include "StrongInlines.h"
    4342#include "WasmBBQPlan.h"
    44 #include "WasmToJS.h"
    4543#include "WasmWorklist.h"
    4644#include "WebAssemblyInstanceConstructor.h"
     
    9795        reject(exec, scope, promise);
    9896    else {
    99         Wasm::Module::validateAsync(&vm.wasmContext, WTFMove(source), createSharedTask<Wasm::Module::CallbackType>([promise, globalObject, &vm] (Wasm::Module::ValidationResult&& result) mutable {
     97        Wasm::Module::validateAsync(vm, WTFMove(source), createSharedTask<Wasm::Module::CallbackType>([promise, globalObject] (VM& vm, Wasm::Module::ValidationResult&& result) mutable {
    10098            vm.promiseDeferredTimer->scheduleWorkSoon(promise, [promise, globalObject, result = WTFMove(result), &vm] () mutable {
    10199                auto scope = DECLARE_CATCH_SCOPE(vm);
     
    138136    auto scope = DECLARE_CATCH_SCOPE(vm);
    139137    // In order to avoid potentially recompiling a module. We first gather all the import/memory information prior to compiling code.
    140     JSWebAssemblyInstance* instance = JSWebAssemblyInstance::create(vm, exec, module, importObject, exec->lexicalGlobalObject()->WebAssemblyInstanceStructure(), Wasm::Instance::create(Ref<Wasm::Module>(module->module())));
     138    JSWebAssemblyInstance* instance = JSWebAssemblyInstance::create(vm, exec, module, importObject, exec->lexicalGlobalObject()->WebAssemblyInstanceStructure());
    141139    RETURN_IF_EXCEPTION(scope, reject(exec, scope, promise));
    142140
     
    146144    vm.promiseDeferredTimer->addPendingPromise(promise, WTFMove(dependencies));
    147145    // Note: This completion task may or may not get called immediately.
    148     module->module().compileAsync(&vm.wasmContext, instance->memoryMode(), createSharedTask<Wasm::CodeBlock::CallbackType>([promise, instance, module, resolveKind, &vm] (Ref<Wasm::CodeBlock>&& refCodeBlock) mutable {
     146    module->module().compileAsync(vm, instance->memoryMode(), createSharedTask<Wasm::CodeBlock::CallbackType>([promise, instance, module, resolveKind] (VM& vm, Ref<Wasm::CodeBlock>&& refCodeBlock) mutable {
    149147        RefPtr<Wasm::CodeBlock> codeBlock = WTFMove(refCodeBlock);
    150148        vm.promiseDeferredTimer->scheduleWorkSoon(promise, [promise, instance, module, resolveKind, &vm, codeBlock = WTFMove(codeBlock)] () mutable {
     
    152150            resolve(vm, exec, promise, instance, module, codeBlock.releaseNonNull(), resolveKind);
    153151        });
    154     }), &Wasm::createJSToWasmWrapper, &Wasm::wasmToJSException);
     152    }));
    155153}
    156154
     
    168166    RETURN_IF_EXCEPTION(scope, reject(exec, scope, promise));
    169167
    170     Wasm::Module::validateAsync(&vm.wasmContext, WTFMove(source), createSharedTask<Wasm::Module::CallbackType>([promise, importObject, globalObject, &vm] (Wasm::Module::ValidationResult&& result) mutable {
     168    Wasm::Module::validateAsync(vm, WTFMove(source), createSharedTask<Wasm::Module::CallbackType>([promise, importObject, globalObject] (VM& vm, Wasm::Module::ValidationResult&& result) mutable {
    171169        vm.promiseDeferredTimer->scheduleWorkSoon(promise, [promise, importObject, globalObject, result = WTFMove(result), &vm] () mutable {
    172170            auto scope = DECLARE_CATCH_SCOPE(vm);
     
    216214    uint8_t* base = getWasmBufferFromValue(exec, exec->argument(0), byteOffset, byteSize);
    217215    RETURN_IF_EXCEPTION(scope, encodedJSValue());
    218     BBQPlan plan(&vm.wasmContext, base + byteOffset, byteSize, BBQPlan::Validation, Plan::dontFinalize());
     216    BBQPlan plan(&vm, base + byteOffset, byteSize, BBQPlan::Validation, Plan::dontFinalize());
    219217    // FIXME: We might want to throw an OOM exception here if we detect that something will OOM.
    220218    // https://bugs.webkit.org/show_bug.cgi?id=166015
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyTableConstructor.cpp

    r222791 r223002  
    9191    }
    9292
    93     RefPtr<Wasm::Table> wasmTable = Wasm::Table::create(initial, maximum);
    94     if (!wasmTable) {
    95         return JSValue::encode(throwException(exec, throwScope,
    96             createRangeError(exec, ASCIILiteral("couldn't create Table"))));
    97     }
    98 
    9993    throwScope.release();
    100 
    101     return JSValue::encode(JSWebAssemblyTable::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyTableStructure(), wasmTable.releaseNonNull()));
     94    return JSValue::encode(JSWebAssemblyTable::create(exec, vm, exec->lexicalGlobalObject()->WebAssemblyTableStructure(), initial, maximum));
    10295}
    10396
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyWrapperFunction.cpp

    r222791 r223002  
    6464    String name = "";
    6565    NativeExecutable* executable = vm.getHostFunction(callWebAssemblyWrapperFunction, NoIntrinsic, callHostFunctionAsConstructor, nullptr, name);
    66     WebAssemblyWrapperFunction* result = new (NotNull, allocateCell<WebAssemblyWrapperFunction>(vm.heap)) WebAssemblyWrapperFunction(vm, globalObject, globalObject->webAssemblyWrapperFunctionStructure(), Wasm::CallableFunction { signatureIndex, instance->wasmCodeBlock().wasmToJSCallStubForImport(importIndex) } );
     66    WebAssemblyWrapperFunction* result = new (NotNull, allocateCell<WebAssemblyWrapperFunction>(vm.heap)) WebAssemblyWrapperFunction(vm, globalObject, globalObject->webAssemblyWrapperFunctionStructure(), { signatureIndex, instance->codeBlock()->wasmToJsCallStubForImport(importIndex) });
    6767    const Wasm::Signature& signature = Wasm::SignatureInformation::get(signatureIndex);
    6868    result->finishCreation(vm, executable, signature.argumentCount(), name, function, instance);
  • trunk/Source/WTF/ChangeLog

    r222977 r223002  
     12017-10-06  Commit Queue  <commit-queue@webkit.org>
     2
     3        Unreviewed, rolling out r222791 and r222873.
     4        https://bugs.webkit.org/show_bug.cgi?id=178031
     5
     6        Caused crashes with workers/wasm LayoutTests (Requested by
     7        ryanhaddad on #webkit).
     8
     9        Reverted changesets:
     10
     11        "WebAssembly: no VM / JS version of everything but Instance"
     12        https://bugs.webkit.org/show_bug.cgi?id=177473
     13        http://trac.webkit.org/changeset/222791
     14
     15        "WebAssembly: address no VM / JS follow-ups"
     16        https://bugs.webkit.org/show_bug.cgi?id=177887
     17        http://trac.webkit.org/changeset/222873
     18
    1192017-10-06  Antti Koivisto  <antti@apple.com>
    220
  • trunk/Source/WTF/wtf/StdLibExtras.h

    r222791 r223002  
    161161}
    162162
    163 template<typename T>
    164 inline T& default_construct_at(T* addr)
    165 {
    166     return *new (addr) T();
    167 }
    168 
    169163// Returns a count of the number of bits set in 'bits'.
    170164inline size_t bitCount(unsigned bits)
     
    542536using WTF::binarySearch;
    543537using WTF::bitwise_cast;
    544 using WTF::default_construct_at;
    545538using WTF::callStatelessLambda;
    546539using WTF::checkAndSet;
  • trunk/Source/WebCore/ChangeLog

    r223001 r223002  
     12017-10-06  Commit Queue  <commit-queue@webkit.org>
     2
     3        Unreviewed, rolling out r222791 and r222873.
     4        https://bugs.webkit.org/show_bug.cgi?id=178031
     5
     6        Caused crashes with workers/wasm LayoutTests (Requested by
     7        ryanhaddad on #webkit).
     8
     9        Reverted changesets:
     10
     11        "WebAssembly: no VM / JS version of everything but Instance"
     12        https://bugs.webkit.org/show_bug.cgi?id=177473
     13        http://trac.webkit.org/changeset/222791
     14
     15        "WebAssembly: address no VM / JS follow-ups"
     16        https://bugs.webkit.org/show_bug.cgi?id=177887
     17        http://trac.webkit.org/changeset/222873
     18
    1192017-10-06  Alex Christensen  <achristensen@webkit.org>
    220
  • trunk/Source/WebCore/bindings/js/SerializedScriptValue.cpp

    r222791 r223002  
    8080#include <runtime/TypedArrays.h>
    8181#include <wasm/js/JSWebAssemblyModule.h>
    82 #include <wasm/WasmModule.h>
    8382#include <wtf/HashTraits.h>
    8483#include <wtf/MainThread.h>
Note: See TracChangeset for help on using the changeset viewer.