-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ShaderModule.mm
305 lines (261 loc) · 11.9 KB
/
ShaderModule.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
* Copyright (c) 2021-2022 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "ShaderModule.h"
#import "APIConversions.h"
#import "Device.h"
#import "PipelineLayout.h"
namespace WebGPU {
struct ShaderModuleParameters {
const WGPUShaderModuleWGSLDescriptor& wgsl;
const WGPUShaderModuleDescriptorHints* hints;
};
static std::optional<ShaderModuleParameters> findShaderModuleParameters(const WGPUShaderModuleDescriptor& descriptor)
{
const WGPUShaderModuleWGSLDescriptor* wgsl = nullptr;
const WGPUShaderModuleDescriptorHints* hints = nullptr;
for (const WGPUChainedStruct* ptr = descriptor.nextInChain; ptr; ptr = ptr->next) {
auto type = ptr->sType;
switch (static_cast<int>(type)) {
case WGPUSType_ShaderModuleWGSLDescriptor:
if (wgsl)
return std::nullopt;
wgsl = reinterpret_cast<const WGPUShaderModuleWGSLDescriptor*>(ptr);
break;
case WGPUSTypeExtended_ShaderModuleDescriptorHints:
if (hints)
return std::nullopt;
hints = reinterpret_cast<const WGPUShaderModuleDescriptorHints*>(ptr);
break;
default:
return std::nullopt;
}
}
if (!wgsl)
return std::nullopt;
return { { *wgsl, hints } };
}
id<MTLLibrary> ShaderModule::createLibrary(id<MTLDevice> device, const String& msl, String&& label)
{
auto options = [MTLCompileOptions new];
options.fastMathEnabled = YES;
NSError *error = nil;
// FIXME(PERFORMANCE): Run the asynchronous version of this
id<MTLLibrary> library = [device newLibraryWithSource:msl options:options error:&error];
if (error)
WTFLogAlways("MSL compilation error: %@", error);
library.label = label;
return library;
}
static RefPtr<ShaderModule> earlyCompileShaderModule(Device& device, std::variant<WGSL::SuccessfulCheck, WGSL::FailedCheck>&& checkResult, const WGPUShaderModuleDescriptorHints& suppliedHints, String&& label, const char* code)
{
HashMap<String, Ref<PipelineLayout>> hints;
HashMap<String, WGSL::PipelineLayout> wgslHints;
for (uint32_t i = 0; i < suppliedHints.hintsCount; ++i) {
const auto& hint = suppliedHints.hints[i];
if (hint.nextInChain)
return nullptr;
auto hintKey = fromAPI(hint.key);
hints.add(hintKey, WebGPU::fromAPI(hint.hint.layout));
auto convertedPipelineLayout = ShaderModule::convertPipelineLayout(WebGPU::fromAPI(hint.hint.layout));
wgslHints.add(hintKey, WTFMove(convertedPipelineLayout));
}
auto prepareResult = WGSL::prepare(std::get<WGSL::SuccessfulCheck>(checkResult).ast, wgslHints);
// FIXME: remove the ternary when the shader compiler is more functional
auto prepareResultMSL = prepareResult.msl.length() ? prepareResult.msl : String::fromUTF8(code);
auto library = ShaderModule::createLibrary(device.device(), prepareResultMSL, WTFMove(label));
if (!library)
return nullptr;
return ShaderModule::create(WTFMove(checkResult), WTFMove(hints), WTFMove(prepareResult.entryPoints), library, device);
}
Ref<ShaderModule> Device::createShaderModule(const WGPUShaderModuleDescriptor& descriptor)
{
if (!descriptor.nextInChain)
return ShaderModule::createInvalid(*this);
auto shaderModuleParameters = findShaderModuleParameters(descriptor);
if (!shaderModuleParameters)
return ShaderModule::createInvalid(*this);
auto checkResult = WGSL::staticCheck(fromAPI(shaderModuleParameters->wgsl.code), std::nullopt);
if (std::holds_alternative<WGSL::SuccessfulCheck>(checkResult) && shaderModuleParameters->hints && shaderModuleParameters->hints->hintsCount) {
if (auto result = earlyCompileShaderModule(*this, WTFMove(checkResult), *shaderModuleParameters->hints, fromAPI(descriptor.label), shaderModuleParameters->wgsl.code))
return result.releaseNonNull();
}
return ShaderModule::create(WTFMove(checkResult), { }, { }, nil, *this);
}
auto ShaderModule::convertCheckResult(std::variant<WGSL::SuccessfulCheck, WGSL::FailedCheck>&& checkResult) -> CheckResult
{
return WTF::switchOn(WTFMove(checkResult), [](auto&& check) -> CheckResult {
return std::forward<decltype(check)>(check);
});
}
ShaderModule::ShaderModule(std::variant<WGSL::SuccessfulCheck, WGSL::FailedCheck>&& checkResult, HashMap<String, Ref<PipelineLayout>>&& pipelineLayoutHints, HashMap<String, WGSL::Reflection::EntryPointInformation>&& entryPointInformation, id<MTLLibrary> library, Device& device)
: m_checkResult(convertCheckResult(WTFMove(checkResult)))
, m_pipelineLayoutHints(WTFMove(pipelineLayoutHints))
, m_entryPointInformation(WTFMove(entryPointInformation))
, m_library(library)
, m_device(device)
{
}
ShaderModule::ShaderModule(Device& device)
: m_checkResult(std::monostate { })
, m_device(device)
{
}
ShaderModule::~ShaderModule() = default;
struct Messages {
const Vector<WGSL::CompilationMessage>& messages;
WGPUCompilationMessageType type;
};
struct CompilationMessageData {
CompilationMessageData(Vector<WGPUCompilationMessage>&& compilationMessages, Vector<CString>&& messages)
: compilationMessages(WTFMove(compilationMessages))
, messages(WTFMove(messages))
{
}
CompilationMessageData(const CompilationMessageData&) = delete;
CompilationMessageData(CompilationMessageData&&) = default;
Vector<WGPUCompilationMessage> compilationMessages;
Vector<CString> messages;
};
static CompilationMessageData convertMessages(const Messages& messages1, const std::optional<Messages>& messages2 = std::nullopt)
{
Vector<WGPUCompilationMessage> flattenedCompilationMessages;
Vector<CString> flattenedMessages;
auto populateMessages = [&](const Messages& compilationMessages) {
for (const auto& compilationMessage : compilationMessages.messages)
flattenedMessages.append(compilationMessage.message().utf8());
};
populateMessages(messages1);
if (messages2)
populateMessages(*messages2);
auto populateCompilationMessages = [&](const Messages& compilationMessages, size_t base) {
for (size_t i = 0; i < compilationMessages.messages.size(); ++i) {
const auto& compilationMessage = compilationMessages.messages[i];
flattenedCompilationMessages.append({
nullptr,
flattenedMessages[i + base].data(),
compilationMessages.type,
compilationMessage.lineNumber(),
compilationMessage.lineOffset(),
compilationMessage.offset(),
compilationMessage.length(),
});
}
};
populateCompilationMessages(messages1, 0);
if (messages2)
populateCompilationMessages(*messages2, messages1.messages.size());
return { WTFMove(flattenedCompilationMessages), WTFMove(flattenedMessages) };
}
void ShaderModule::getCompilationInfo(CompletionHandler<void(WGPUCompilationInfoRequestStatus, const WGPUCompilationInfo&)>&& callback)
{
WTF::switchOn(m_checkResult, [&](const WGSL::SuccessfulCheck& successfulCheck) {
auto compilationMessageData(convertMessages({ successfulCheck.warnings, WGPUCompilationMessageType_Warning }));
WGPUCompilationInfo compilationInfo {
nullptr,
static_cast<uint32_t>(compilationMessageData.compilationMessages.size()),
compilationMessageData.compilationMessages.data(),
};
m_device->instance().scheduleWork([compilationInfo = WTFMove(compilationInfo), callback = WTFMove(callback)]() mutable {
callback(WGPUCompilationInfoRequestStatus_Success, compilationInfo);
});
}, [&](const WGSL::FailedCheck& failedCheck) {
auto compilationMessageData(convertMessages(
{ failedCheck.errors, WGPUCompilationMessageType_Error },
{ { failedCheck.warnings, WGPUCompilationMessageType_Warning } }));
WGPUCompilationInfo compilationInfo {
nullptr,
static_cast<uint32_t>(compilationMessageData.compilationMessages.size()),
compilationMessageData.compilationMessages.data(),
};
m_device->instance().scheduleWork([compilationInfo = WTFMove(compilationInfo), callback = WTFMove(callback)]() mutable {
callback(WGPUCompilationInfoRequestStatus_Error, compilationInfo);
});
}, [](std::monostate) {
ASSERT_NOT_REACHED();
});
}
void ShaderModule::setLabel(String&& label)
{
if (m_library)
m_library.label = label;
}
id<MTLFunction> ShaderModule::getNamedFunction(const String& name) const
{
return [m_library newFunctionWithName:name];
}
WGSL::PipelineLayout ShaderModule::convertPipelineLayout(const PipelineLayout& pipelineLayout)
{
UNUSED_PARAM(pipelineLayout);
// FIXME: Implement this
return { { } };
}
const WGSL::AST::ShaderModule* ShaderModule::ast() const
{
return WTF::switchOn(m_checkResult, [&](const WGSL::SuccessfulCheck& successfulCheck) -> const WGSL::AST::ShaderModule* {
return successfulCheck.ast.ptr();
}, [&](const WGSL::FailedCheck&) -> const WGSL::AST::ShaderModule* {
return nullptr;
}, [](std::monostate) -> const WGSL::AST::ShaderModule* {
ASSERT_NOT_REACHED();
return nullptr;
});
}
const PipelineLayout* ShaderModule::pipelineLayoutHint(const String& name) const
{
auto iterator = m_pipelineLayoutHints.find(name);
if (iterator == m_pipelineLayoutHints.end())
return nullptr;
return iterator->value.ptr();
}
const WGSL::Reflection::EntryPointInformation* ShaderModule::entryPointInformation(const String& name) const
{
auto iterator = m_entryPointInformation.find(name);
if (iterator == m_entryPointInformation.end())
return nullptr;
return &iterator->value;
}
} // namespace WebGPU
#pragma mark WGPU Stubs
void wgpuShaderModuleRelease(WGPUShaderModule shaderModule)
{
WebGPU::fromAPI(shaderModule).deref();
}
void wgpuShaderModuleGetCompilationInfo(WGPUShaderModule shaderModule, WGPUCompilationInfoCallback callback, void * userdata)
{
WebGPU::fromAPI(shaderModule).getCompilationInfo([callback, userdata](WGPUCompilationInfoRequestStatus status, const WGPUCompilationInfo& compilationInfo) {
callback(status, &compilationInfo, userdata);
});
}
void wgpuShaderModuleGetCompilationInfoWithBlock(WGPUShaderModule shaderModule, WGPUCompilationInfoBlockCallback callback)
{
WebGPU::fromAPI(shaderModule).getCompilationInfo([callback = WTFMove(callback)](WGPUCompilationInfoRequestStatus status, const WGPUCompilationInfo& compilationInfo) {
callback(status, &compilationInfo);
});
}
void wgpuShaderModuleSetLabel(WGPUShaderModule shaderModule, const char* label)
{
WebGPU::fromAPI(shaderModule).setLabel(WebGPU::fromAPI(label));
}