1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
|
#include "slang-ir-legalize-matrix-types.h"
#include "slang-compiler.h"
#include "slang-ir-insts-enum.h"
#include "slang-ir-insts.h"
#include "slang-ir-util.h"
#include "slang-ir.h"
namespace Slang
{
struct MatrixTypeLoweringContext
{
TargetProgram* targetProgram;
IRModule* module;
DiagnosticSink* sink;
InstWorkList workList;
InstHashSet workListSet;
Dictionary<IRInst*, IRInst*> replacements;
MatrixTypeLoweringContext(TargetProgram* targetProgram, IRModule* module)
: targetProgram(targetProgram), module(module), workList(module), workListSet(module)
{
}
void addToWorkList(IRInst* inst)
{
for (auto ii = inst->getParent(); ii; ii = ii->getParent())
{
if (as<IRGeneric>(ii))
return;
}
if (workListSet.contains(inst))
return;
workList.add(inst);
workListSet.add(inst);
}
bool shouldLowerTarget()
{
auto target = targetProgram->getTargetReq()->getTarget();
switch (target)
{
case CodeGenTarget::SPIRV:
case CodeGenTarget::SPIRVAssembly:
case CodeGenTarget::GLSL:
case CodeGenTarget::WGSL:
case CodeGenTarget::WGSLSPIRV:
case CodeGenTarget::WGSLSPIRVAssembly:
case CodeGenTarget::Metal:
case CodeGenTarget::MetalLib:
case CodeGenTarget::MetalLibAssembly:
return true;
default:
return false;
}
}
bool shouldLowerMatrixType(IRMatrixType* matrixType)
{
if (!shouldLowerTarget())
return false;
auto elementType = matrixType->getElementType();
return as<IRBoolType>(elementType) || as<IRUIntType>(elementType) ||
as<IRIntType>(elementType);
}
IRInst* legalizeMatrixTypeDeclaration(IRInst* inst)
{
auto matrixType = as<IRMatrixType>(inst);
if (shouldLowerMatrixType(matrixType))
{
// Lower matrix<T, R, C> to T[R][C] (array of R vectors of length C)
auto elementType = matrixType->getElementType();
auto rowCount = matrixType->getRowCount();
auto columnCount = matrixType->getColumnCount();
IRBuilder builder(matrixType);
builder.setInsertBefore(matrixType);
// Create vector type for columns: vector<T, C>
auto vectorType = builder.getVectorType(elementType, columnCount);
// Create array type for rows: vector<T, C>[R]
auto arrayType = builder.getArrayType(vectorType, rowCount);
return arrayType;
}
return inst;
}
IRInst* legalizeMakeMatrix(IRInst* inst)
{
auto makeMatrix = as<IRMakeMatrix>(inst);
auto matrixType = as<IRMatrixType>(makeMatrix->getDataType());
SLANG_ASSERT(matrixType && "Matrix type is expected");
SLANG_ASSERT(
shouldLowerMatrixType(matrixType) && "Matrix type is expected to need legalization");
// Lower makeMatrix to makeArray of makeVectors
auto elementType = matrixType->getElementType();
auto rowCount = as<IRIntLit>(matrixType->getRowCount());
auto columnCount = as<IRIntLit>(matrixType->getColumnCount());
SLANG_ASSERT(
rowCount && columnCount &&
"Matrix dimensions must be compile-time constants for lowering");
IRBuilder builder(makeMatrix);
builder.setInsertBefore(makeMatrix);
// Create vector type for rows: vector<T, C>
auto vectorType = builder.getVectorType(elementType, columnCount);
// Create array type: vector<T, C>[R]
auto arrayType = builder.getArrayType(vectorType, rowCount);
// Group operands into rows and create vectors
List<IRInst*> rowVectors;
UInt operandIndex = 0;
// Assert that we have the expected number of operands
if (makeMatrix->getOperandCount() == UInt(rowCount->getValue() * columnCount->getValue()))
{
// Each operand is a matrix element
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
List<IRInst*> rowElements;
for (IRIntegerValue col = 0; col < columnCount->getValue(); col++)
{
SLANG_ASSERT(
operandIndex < makeMatrix->getOperandCount() &&
"Operand index out of bounds");
rowElements.add(getReplacement(makeMatrix->getOperand(operandIndex)));
operandIndex++;
}
SLANG_ASSERT(
rowElements.getCount() == columnCount->getValue() &&
"Row elements count must match column count");
auto rowVector = builder.emitMakeVector(vectorType, rowElements);
rowVectors.add(rowVector);
}
}
else if (makeMatrix->getOperandCount() == UInt(rowCount->getValue()))
{
// Each operand is a vector with width columnCount->getValue().
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
auto rowVector = getReplacement(makeMatrix->getOperand(row));
auto vecType = as<IRVectorType>(rowVector->getDataType());
SLANG_ASSERT(
getIntVal(vecType->getElementCount()) == columnCount->getValue() &&
"Row elements count must match column count");
rowVectors.add(rowVector);
}
}
else
SLANG_ASSERT_FAILURE("makeMatrix operand count must match matrix dimensions");
SLANG_ASSERT(
rowVectors.getCount() == rowCount->getValue() &&
"Row vectors count must match matrix row count");
return builder.emitMakeArray(arrayType, rowVectors.getCount(), rowVectors.getBuffer());
}
IRInst* legalizeMakeMatrixFromScalar(IRInst* inst)
{
auto matrixType = as<IRMatrixType>(inst->getDataType());
SLANG_ASSERT(matrixType && "Matrix type is expected");
SLANG_ASSERT(
shouldLowerMatrixType(matrixType) && "Matrix type is expected to need legalization");
// Lower makeMatrixFromScalar to makeArray of makeVectors from scalar
auto elementType = matrixType->getElementType();
auto rowCount = as<IRIntLit>(matrixType->getRowCount());
auto columnCount = as<IRIntLit>(matrixType->getColumnCount());
SLANG_ASSERT(
rowCount && columnCount &&
"Matrix dimensions must be compile-time constants for lowering");
SLANG_ASSERT(
inst->getOperandCount() == 1 && "makeMatrixFromScalar should have exactly one operand");
IRBuilder builder(inst);
builder.setInsertBefore(inst);
// Get the scalar operand
auto scalarOperand = getReplacement(inst->getOperand(0));
// Create vector type for rows: vector<T, C>
auto vectorType = builder.getVectorType(elementType, columnCount);
// Create array type: vector<T, C>[R]
auto arrayType = builder.getArrayType(vectorType, rowCount);
// Create a vector from the scalar (replicated C times)
List<IRInst*> vectorElements;
for (IRIntegerValue col = 0; col < columnCount->getValue(); col++)
{
vectorElements.add(scalarOperand);
}
auto rowVector = builder.emitMakeVector(vectorType, vectorElements);
// Create array with R copies of the same vector
List<IRInst*> rowVectors;
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
rowVectors.add(rowVector);
}
SLANG_ASSERT(
rowVectors.getCount() == rowCount->getValue() &&
"Row vectors count must match matrix row count");
return builder.emitMakeArray(arrayType, rowVectors.getCount(), rowVectors.getBuffer());
}
IRInst* legalizeMatrixMatrixBinaryOperation(
IRBuilder& builder,
IRInst* legalizedA,
IRInst* legalizedB,
IRMatrixType* resultMatrixType,
IROp binaryOp)
{
auto elementType = resultMatrixType->getElementType();
auto rowCount = as<IRIntLit>(resultMatrixType->getRowCount());
auto columnCount = as<IRIntLit>(resultMatrixType->getColumnCount());
SLANG_ASSERT(
rowCount && columnCount &&
"Matrix dimensions must be compile-time constants for lowering");
// Create vector type for rows: vector<T, C>
auto vectorType = builder.getVectorType(elementType, columnCount);
// Create array type: vector<T, C>[R]
auto arrayType = builder.getArrayType(vectorType, rowCount);
// Extract vectors from both arrays and apply binary operation
List<IRInst*> resultVectors;
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
// Extract the row vector from each operand array
auto rowIndexInst = builder.getIntValue(builder.getIntType(), row);
auto vectorA = builder.emitElementExtract(legalizedA, rowIndexInst);
auto vectorB = builder.emitElementExtract(legalizedB, rowIndexInst);
// Apply the binary operation to the vectors
IRInst* args[] = {vectorA, vectorB};
auto resultVector = builder.emitIntrinsicInst(vectorType, binaryOp, 2, args);
resultVectors.add(resultVector);
}
// Create the result array from the vectors
return builder.emitMakeArray(
arrayType,
resultVectors.getCount(),
resultVectors.getBuffer());
}
template<bool matrixIsFirst>
IRInst* legalizeMatrixMixedBinaryOperation(
IRBuilder& builder,
IRInst* legalizedMatrix,
IRInst* legalizedOther,
IRMatrixType* resultMatrixType,
IROp binaryOp)
{
// Verify that the other operand is either a vector or scalar type
auto otherType = legalizedOther->getDataType();
auto otherVectorType = as<IRVectorType>(otherType);
auto otherBasicType = as<IRBasicType>(otherType);
SLANG_ASSERT(
(otherVectorType || otherBasicType) && "Other operand must be vector or scalar type");
auto elementType = resultMatrixType->getElementType();
auto rowCount = as<IRIntLit>(resultMatrixType->getRowCount());
auto columnCount = as<IRIntLit>(resultMatrixType->getColumnCount());
SLANG_ASSERT(
rowCount && columnCount &&
"Matrix dimensions must be compile-time constants for lowering");
// Create vector type for rows: vector<T, C>
auto vectorType = builder.getVectorType(elementType, columnCount);
// Create array type: vector<T, C>[R]
auto arrayType = builder.getArrayType(vectorType, rowCount);
// Extract vectors from matrix array and apply binary operation with other operand
List<IRInst*> resultVectors;
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
// Extract the row vector from matrix array
auto rowIndexInst = builder.getIntValue(builder.getIntType(), row);
auto matrixRowVector = builder.emitElementExtract(legalizedMatrix, rowIndexInst);
// Apply the binary operation between matrix row vector and other operand
IRInst* args[2];
if constexpr (matrixIsFirst)
{
args[0] = matrixRowVector;
args[1] = legalizedOther;
}
else
{
args[0] = legalizedOther;
args[1] = matrixRowVector;
}
auto resultVector = builder.emitIntrinsicInst(vectorType, binaryOp, 2, args);
resultVectors.add(resultVector);
}
// Create the result array from the vectors
return builder.emitMakeArray(
arrayType,
resultVectors.getCount(),
resultVectors.getBuffer());
}
IRInst* legalizeBinaryOperation(IRInst* inst, IROp binaryOp)
{
IRInst* opdA = inst->getOperand(0);
IRInst* opdB = inst->getOperand(1);
// Check what types we're dealing with
auto typeA = opdA->getDataType();
auto typeB = opdB->getDataType();
auto matrixTypeA = as<IRMatrixType>(typeA);
auto matrixTypeB = as<IRMatrixType>(typeB);
bool shouldLowerA = matrixTypeA && shouldLowerMatrixType(matrixTypeA);
bool shouldLowerB = matrixTypeB && shouldLowerMatrixType(matrixTypeB);
// Get the result matrix type to determine dimensions
auto resultMatrixType = as<IRMatrixType>(inst->getDataType());
SLANG_ASSERT(resultMatrixType && "Binary operation should have matrix result type");
SLANG_ASSERT(
shouldLowerMatrixType(resultMatrixType) &&
"Result matrix type should need legalization");
// Create IRBuilder at the top level
IRBuilder builder(inst);
builder.setInsertBefore(inst);
// Get legalized operands once
IRInst* legalizedA = getReplacement(opdA);
IRInst* legalizedB = getReplacement(opdB);
if (shouldLowerA && shouldLowerB)
{
return legalizeMatrixMatrixBinaryOperation(
builder,
legalizedA,
legalizedB,
resultMatrixType,
binaryOp);
}
else if (shouldLowerA && !shouldLowerB)
{
return legalizeMatrixMixedBinaryOperation<true>(
builder,
legalizedA,
legalizedB,
resultMatrixType,
binaryOp);
}
else if (!shouldLowerA && shouldLowerB)
{
return legalizeMatrixMixedBinaryOperation<false>(
builder,
legalizedB,
legalizedA,
resultMatrixType,
binaryOp);
}
// Neither operand is a matrix that needs lowering, shouldn't reach here
SLANG_UNREACHABLE("legalizeBinaryOperation called but no matrix operand needs lowering");
}
IRInst* legalizeComparisonOperation(IRInst* inst, IROp comparisonOp)
{
IRInst* opdA = inst->getOperand(0);
IRInst* opdB = inst->getOperand(1);
// Check what types we're dealing with
auto typeA = opdA->getDataType();
auto typeB = opdB->getDataType();
auto matrixTypeA = as<IRMatrixType>(typeA);
auto matrixTypeB = as<IRMatrixType>(typeB);
bool shouldLowerA = matrixTypeA && shouldLowerMatrixType(matrixTypeA);
bool shouldLowerB = matrixTypeB && shouldLowerMatrixType(matrixTypeB);
// Only matrix-matrix comparisons are supported
SLANG_ASSERT(
shouldLowerA && shouldLowerB &&
"Comparison operations only supported between matrices that need lowering");
// Create IRBuilder at the top level
IRBuilder builder(inst);
builder.setInsertBefore(inst);
// Get legalized operands
IRInst* legalizedA = getReplacement(opdA);
IRInst* legalizedB = getReplacement(opdB);
auto rowCount = as<IRIntLit>(matrixTypeA->getRowCount());
auto columnCount = as<IRIntLit>(matrixTypeA->getColumnCount());
SLANG_ASSERT(
rowCount && columnCount &&
"Matrix dimensions must be compile-time constants for lowering");
// Create boolean vector type for rows: vector<bool, C>
auto boolType = builder.getBoolType();
auto boolVectorType = builder.getVectorType(boolType, columnCount);
// Create array type: vector<bool, C>[R]
auto boolArrayType = builder.getArrayType(boolVectorType, rowCount);
// Extract vectors from both arrays and apply comparison operation
List<IRInst*> resultVectors;
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
// Extract the row vector from each operand array
auto rowIndexInst = builder.getIntValue(builder.getIntType(), row);
auto vectorA = builder.emitElementExtract(legalizedA, rowIndexInst);
auto vectorB = builder.emitElementExtract(legalizedB, rowIndexInst);
// Apply the comparison operation to the vectors
IRInst* args[] = {vectorA, vectorB};
auto resultVector = builder.emitIntrinsicInst(boolVectorType, comparisonOp, 2, args);
resultVectors.add(resultVector);
}
// Create the result array from the vectors
return builder.emitMakeArray(
boolArrayType,
resultVectors.getCount(),
resultVectors.getBuffer());
}
IRInst* legalizeUnaryOperation(IRInst* inst, IROp unaryOp)
{
IRInst* operand = inst->getOperand(0);
// Get the legalized operand (should be an array of vectors)
IRInst* legalizedOperand = getReplacement(operand);
// Get the result matrix type to determine dimensions
auto resultMatrixType = as<IRMatrixType>(inst->getDataType());
SLANG_ASSERT(resultMatrixType && "Unary operation should have matrix result type");
SLANG_ASSERT(
shouldLowerMatrixType(resultMatrixType) &&
"Result matrix type should need legalization");
auto elementType = resultMatrixType->getElementType();
auto rowCount = as<IRIntLit>(resultMatrixType->getRowCount());
auto columnCount = as<IRIntLit>(resultMatrixType->getColumnCount());
SLANG_ASSERT(
rowCount && columnCount &&
"Matrix dimensions must be compile-time constants for lowering");
IRBuilder builder(inst);
builder.setInsertBefore(inst);
// Create vector type for rows: vector<T, C>
auto vectorType = builder.getVectorType(elementType, columnCount);
// Create array type: vector<T, C>[R]
auto arrayType = builder.getArrayType(vectorType, rowCount);
// Extract vectors from array and apply unary operation
List<IRInst*> resultVectors;
for (IRIntegerValue row = 0; row < rowCount->getValue(); row++)
{
// Extract the row vector from operand array
auto rowIndexInst = builder.getIntValue(builder.getIntType(), row);
auto vector = builder.emitElementExtract(legalizedOperand, rowIndexInst);
// Apply the unary operation to the vector
IRInst* args[] = {vector};
auto resultVector = builder.emitIntrinsicInst(vectorType, unaryOp, 1, args);
resultVectors.add(resultVector);
}
// Create the result array from the vectors
return builder.emitMakeArray(
arrayType,
resultVectors.getCount(),
resultVectors.getBuffer());
}
IRInst* legalizeMatrixProducingInstruction(IRInst* inst)
{
switch (inst->getOp())
{
case kIROp_MakeMatrix:
return legalizeMakeMatrix(inst);
case kIROp_MakeMatrixFromScalar:
return legalizeMakeMatrixFromScalar(inst);
case kIROp_Add:
case kIROp_Sub:
case kIROp_Mul:
case kIROp_Div:
case kIROp_IRem:
case kIROp_FRem:
case kIROp_Lsh:
case kIROp_Rsh:
case kIROp_And:
case kIROp_Or:
case kIROp_BitAnd:
case kIROp_BitOr:
case kIROp_BitXor:
return legalizeBinaryOperation(inst, inst->getOp());
case kIROp_Eql:
case kIROp_Neq:
case kIROp_Greater:
case kIROp_Less:
case kIROp_Geq:
case kIROp_Leq:
return legalizeComparisonOperation(inst, inst->getOp());
case kIROp_Not:
case kIROp_BitNot:
case kIROp_Neg:
case kIROp_IntCast:
case kIROp_FloatCast:
case kIROp_CastIntToFloat:
case kIROp_CastFloatToInt:
return legalizeUnaryOperation(inst, inst->getOp());
default:
break;
}
return inst;
}
IRInst* getReplacement(IRInst* inst)
{
if (auto replacement = replacements.tryGetValue(inst))
return *replacement;
IRInst* newInst = inst;
if (as<IRMatrixType>(inst))
newInst = legalizeMatrixTypeDeclaration(inst);
IRType* resultType = inst->getDataType();
if (auto matrixType = as<IRMatrixType>(resultType))
{
if (shouldLowerMatrixType(matrixType))
newInst = legalizeMatrixProducingInstruction(inst);
}
replacements[inst] = newInst;
return newInst;
}
void processModule()
{
addToWorkList(module->getModuleInst());
while (workList.getCount() != 0)
{
IRInst* inst = workList.getLast();
workList.removeLast();
workListSet.remove(inst);
// Run this inst through the replacer
getReplacement(inst);
for (auto child = inst->getLastChild(); child; child = child->getPrevInst())
{
addToWorkList(child);
}
}
// Apply all replacements
for (const auto& [old, replacement] : replacements)
{
if (old != replacement)
{
old->replaceUsesWith(replacement);
old->removeAndDeallocate();
}
}
}
};
void legalizeMatrixTypes(TargetProgram* targetProgram, IRModule* module, DiagnosticSink* sink)
{
MatrixTypeLoweringContext context(targetProgram, module);
context.sink = sink;
context.processModule();
}
} // namespace Slang
|