-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
EntryPointRewriter.cpp
310 lines (275 loc) · 10.4 KB
/
EntryPointRewriter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
* Copyright (c) 2023 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.
*/
#include "config.h"
#include "EntryPointRewriter.h"
#include "AST.h"
#include "ASTVisitor.h"
#include "CallGraph.h"
#include "TypeStore.h"
#include "Types.h"
#include "WGSL.h"
#include "WGSLShaderModule.h"
namespace WGSL {
class EntryPointRewriter {
public:
EntryPointRewriter(ShaderModule&, const AST::Function&, AST::StageAttribute::Stage);
void rewrite();
Reflection::EntryPointInformation takeEntryPointInformation();
private:
struct MemberOrParameter {
AST::Identifier name;
AST::TypeName::Ref type;
AST::Attribute::List attributes;
};
enum class IsBuiltin {
No = 0,
Yes = 1,
};
void collectParameters();
void checkReturnType();
void constructInputStruct();
void materialize(Vector<String>& path, MemberOrParameter&, IsBuiltin);
void visit(Vector<String>& path, MemberOrParameter&&);
void appendBuiltins();
AST::StageAttribute::Stage m_stage;
ShaderModule& m_shaderModule;
const AST::Function& m_function;
Vector<MemberOrParameter> m_builtins;
Vector<MemberOrParameter> m_parameters;
AST::Statement::List m_materializations;
Type* m_structType;
String m_structTypeName;
String m_structParameterName;
Reflection::EntryPointInformation m_information;
};
EntryPointRewriter::EntryPointRewriter(ShaderModule& shaderModule, const AST::Function& function, AST::StageAttribute::Stage stage)
: m_stage(stage)
, m_shaderModule(shaderModule)
, m_function(function)
{
switch (m_stage) {
case AST::StageAttribute::Stage::Compute:
m_information.typedEntryPoint = Reflection::Compute { 1, 1, 1 };
break;
case AST::StageAttribute::Stage::Vertex:
m_information.typedEntryPoint = Reflection::Vertex { false };
break;
case AST::StageAttribute::Stage::Fragment:
m_information.typedEntryPoint = Reflection::Fragment { };
break;
}
}
void EntryPointRewriter::rewrite()
{
m_structTypeName = makeString("__", m_function.name(), "_inT");
m_structParameterName = makeString("__", m_function.name(), "_in");
collectParameters();
checkReturnType();
// nothing to rewrite
if (m_parameters.isEmpty()) {
appendBuiltins();
return;
}
constructInputStruct();
appendBuiltins();
// add parameter to builtins: ${structName} : ${structType}
auto type = adoptRef(*new AST::NamedTypeName(SourceSpan::empty(), AST::Identifier::make(m_structTypeName)));
type->m_resolvedType = m_structType;
auto parameter = adoptRef(*new AST::Parameter(
SourceSpan::empty(),
AST::Identifier::make(m_structParameterName),
type,
AST::Attribute::List { },
AST::ParameterRole::StageIn
));
m_shaderModule.append(m_function.parameters(), WTFMove(parameter));
while (m_materializations.size())
m_shaderModule.insert(m_function.body().statements(), 0, m_materializations.takeLast());
}
Reflection::EntryPointInformation EntryPointRewriter::takeEntryPointInformation()
{
return WTFMove(m_information);
}
void EntryPointRewriter::collectParameters()
{
while (m_function.parameters().size()) {
auto parameter = m_shaderModule.takeLast(m_function.parameters());
Vector<String> path;
visit(path, MemberOrParameter { parameter->name(), parameter->typeName(), parameter->attributes() });
}
}
void EntryPointRewriter::checkReturnType()
{
if (m_stage != AST::StageAttribute::Stage::Vertex)
return;
// FIXME: we might have to duplicate this struct if it has other uses
if (auto* maybeReturnType = m_function.maybeReturnType()) {
if (auto* structType = std::get_if<Types::Struct>(maybeReturnType->resolvedType())) {
ASSERT(structType->structure.role() == AST::StructureRole::UserDefined);
m_shaderModule.replace(&structType->structure.role(), AST::StructureRole::VertexOutput);
}
}
}
void EntryPointRewriter::constructInputStruct()
{
// insert `var ${parameter.name()} = ${structName}.${parameter.name()}`
AST::StructureMember::List structMembers;
for (auto& parameter : m_parameters) {
structMembers.append(m_shaderModule.astBuilder().construct<AST::StructureMember>(
SourceSpan::empty(),
WTFMove(parameter.name),
WTFMove(parameter.type),
WTFMove(parameter.attributes)
));
}
AST::StructureRole role;
switch (m_stage) {
case AST::StageAttribute::Stage::Compute:
role = AST::StructureRole::ComputeInput;
break;
case AST::StageAttribute::Stage::Vertex:
role = AST::StructureRole::VertexInput;
break;
case AST::StageAttribute::Stage::Fragment:
role = AST::StructureRole::FragmentInput;
break;
}
m_shaderModule.append(m_shaderModule.structures(), makeUniqueRef<AST::Structure>(
SourceSpan::empty(),
AST::Identifier::make(m_structTypeName),
WTFMove(structMembers),
AST::Attribute::List { },
role
));
m_structType = m_shaderModule.types().structType(m_shaderModule.structures().last());
}
void EntryPointRewriter::materialize(Vector<String>& path, MemberOrParameter& data, IsBuiltin isBuiltin)
{
std::unique_ptr<AST::Expression> rhs;
if (isBuiltin == IsBuiltin::Yes)
rhs = makeUnique<AST::IdentifierExpression>(SourceSpan::empty(), AST::Identifier::make(data.name));
else {
rhs = makeUnique<AST::FieldAccessExpression>(
SourceSpan::empty(),
makeUniqueRef<AST::IdentifierExpression>(SourceSpan::empty(), AST::Identifier::make(m_structParameterName)),
AST::Identifier::make(data.name)
);
}
if (!path.size()) {
m_materializations.append(makeUniqueRef<AST::VariableStatement>(
SourceSpan::empty(),
makeUniqueRef<AST::Variable>(
SourceSpan::empty(),
AST::VariableFlavor::Var,
AST::Identifier::make(data.name),
nullptr, // TODO: do we need a VariableQualifier?
data.type.copyRef(),
WTFMove(rhs),
AST::Attribute::List { }
)
));
return;
}
path.append(data.name);
unsigned i = 0;
UniqueRef<AST::Expression> lhs = makeUniqueRef<AST::IdentifierExpression>(SourceSpan::empty(), AST::Identifier::make(path[i++]));
while (i < path.size()) {
lhs = makeUniqueRef<AST::FieldAccessExpression>(
SourceSpan::empty(),
WTFMove(lhs),
AST::Identifier::make(path[i++])
);
}
path.removeLast();
m_materializations.append(makeUniqueRef<AST::AssignmentStatement>(
SourceSpan::empty(),
WTFMove(lhs),
makeUniqueRefFromNonNullUniquePtr(WTFMove(rhs))
));
}
void EntryPointRewriter::visit(Vector<String>& path, MemberOrParameter&& data)
{
if (auto* structType = std::get_if<Types::Struct>(data.type->resolvedType())) {
m_materializations.append(makeUniqueRef<AST::VariableStatement>(
SourceSpan::empty(),
makeUniqueRef<AST::Variable>(
SourceSpan::empty(),
AST::VariableFlavor::Var,
AST::Identifier::make(data.name),
nullptr,
data.type.copyRef(),
nullptr,
AST::Attribute::List { }
)
));
path.append(data.name);
for (AST::StructureMember& member : structType->structure.members())
visit(path, MemberOrParameter { member.name(), member.type(), member.attributes() });
path.removeLast();
return;
}
bool isBuiltin = false;
for (auto& attribute : data.attributes) {
if (is<AST::BuiltinAttribute>(attribute)) {
isBuiltin = true;
break;
}
}
if (isBuiltin) {
// if path is empty, then it was already a parameter and there's nothing to do
if (!path.isEmpty())
materialize(path, data, IsBuiltin::Yes);
// builtin was hoisted from a struct into a parameter, we need to reconstruct the struct
// ${path}.${data.name} = ${data.name}
m_builtins.append(WTFMove(data));
return;
}
// parameter was moved into a struct, so we need to reload it
// ${path}.${data.name} = ${struct}.${data.name}
materialize(path, data, IsBuiltin::No);
m_parameters.append(WTFMove(data));
}
void EntryPointRewriter::appendBuiltins()
{
for (auto& data : m_builtins) {
m_shaderModule.append(m_function.parameters(), adoptRef(*new AST::Parameter(
SourceSpan::empty(),
AST::Identifier::make(data.name),
WTFMove(data.type),
WTFMove(data.attributes),
AST::ParameterRole::UserDefined
)));
}
}
void rewriteEntryPoints(CallGraph& callGraph, PrepareResult& result)
{
for (auto& entryPoint : callGraph.entrypoints()) {
EntryPointRewriter rewriter(callGraph.ast(), entryPoint.function, entryPoint.stage);
rewriter.rewrite();
auto addResult = result.entryPoints.add(entryPoint.function.name().id(), rewriter.takeEntryPointInformation());
ASSERT_UNUSED(addResult, addResult.isNewEntry);
}
}
} // namespace WGSL