forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpirvBuilder.cpp
More file actions
2017 lines (1766 loc) · 80.2 KB
/
SpirvBuilder.cpp
File metadata and controls
2017 lines (1766 loc) · 80.2 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- SpirvBuilder.cpp - SPIR-V Builder Implementation --------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/SPIRV/SpirvBuilder.h"
#include "CapabilityVisitor.h"
#include "DebugTypeVisitor.h"
#include "EmitVisitor.h"
#include "LiteralTypeVisitor.h"
#include "LowerTypeVisitor.h"
#include "NonUniformVisitor.h"
#include "PervertexInputVisitor.h"
#include "PreciseVisitor.h"
#include "RelaxedPrecisionVisitor.h"
#include "RemoveBufferBlockVisitor.h"
#include "SortDebugInfoVisitor.h"
#include "clang/SPIRV/AstTypeProbe.h"
#include "clang/SPIRV/String.h"
namespace clang {
namespace spirv {
SpirvBuilder::SpirvBuilder(ASTContext &ac, SpirvContext &ctx,
const SpirvCodeGenOptions &opt,
FeatureManager &featureMgr)
: astContext(ac), context(ctx), featureManager(featureMgr),
mod(llvm::make_unique<SpirvModule>()), function(nullptr),
moduleInit(nullptr), moduleInitInsertPoint(nullptr), spirvOptions(opt),
builtinVars(), debugNone(nullptr), nullDebugExpr(nullptr),
stringLiterals(), emptyString(nullptr) {}
SpirvFunction *SpirvBuilder::createSpirvFunction(QualType returnType,
SourceLocation loc,
llvm::StringRef name,
bool isPrecise,
bool isNoInline) {
auto *fn =
new (context) SpirvFunction(returnType, loc, name, isPrecise, isNoInline);
mod->addFunction(fn);
return fn;
}
SpirvFunction *SpirvBuilder::beginFunction(QualType returnType,
SourceLocation loc,
llvm::StringRef funcName,
bool isPrecise, bool isNoInline,
SpirvFunction *func) {
assert(!function && "found nested function");
if (func) {
function = func;
function->setAstReturnType(returnType);
function->setSourceLocation(loc);
function->setFunctionName(funcName);
function->setPrecise(isPrecise);
function->setNoInline(isNoInline);
} else {
function =
createSpirvFunction(returnType, loc, funcName, isPrecise, isNoInline);
}
return function;
}
SpirvFunctionParameter *
SpirvBuilder::addFnParam(QualType ptrType, bool isPrecise, bool isNointerp,
SourceLocation loc, llvm::StringRef name) {
assert(function && "found detached parameter");
SpirvFunctionParameter *param = nullptr;
if (isBindlessOpaqueArray(ptrType)) {
// If it is a bindless array of an opaque type, we have to use
// a pointer to a pointer of the runtime array.
param = new (context) SpirvFunctionParameter(
context.getPointerType(ptrType, spv::StorageClass::UniformConstant),
isPrecise, isNointerp, loc);
} else {
param = new (context)
SpirvFunctionParameter(ptrType, isPrecise, isNointerp, loc);
}
param->setStorageClass(spv::StorageClass::Function);
param->setDebugName(name);
function->addParameter(param);
return param;
}
SpirvVariable *SpirvBuilder::addFnVar(QualType valueType, SourceLocation loc,
llvm::StringRef name, bool isPrecise,
bool isNointerp, SpirvInstruction *init) {
assert(function && "found detached local variable");
SpirvVariable *var = nullptr;
if (isBindlessOpaqueArray(valueType)) {
// If it is a bindless array of an opaque type, we have to use
// a pointer to a pointer of the runtime array.
var = new (context) SpirvVariable(
context.getPointerType(valueType, spv::StorageClass::UniformConstant),
loc, spv::StorageClass::Function, isPrecise, isNointerp, init);
} else {
var =
new (context) SpirvVariable(valueType, loc, spv::StorageClass::Function,
isPrecise, isNointerp, init);
}
var->setDebugName(name);
function->addVariable(var);
return var;
}
void SpirvBuilder::endFunction() {
assert(function && "no active function");
mod->addFunctionToListOfSortedModuleFunctions(function);
function = nullptr;
insertPoint = nullptr;
}
SpirvBasicBlock *SpirvBuilder::createBasicBlock(llvm::StringRef name) {
assert(function && "found detached basic block");
auto *bb = new (context) SpirvBasicBlock(name);
function->addBasicBlock(bb);
if (auto *scope = context.getCurrentLexicalScope())
bb->setDebugScope(new (context) SpirvDebugScope(scope));
return bb;
}
SpirvDebugScope *SpirvBuilder::createDebugScope(SpirvDebugInstruction *scope) {
assert(insertPoint && "null insert point");
auto *dbgScope = new (context) SpirvDebugScope(scope);
insertPoint->addInstruction(dbgScope);
return dbgScope;
}
void SpirvBuilder::addSuccessor(SpirvBasicBlock *successorBB) {
assert(insertPoint && "null insert point");
insertPoint->addSuccessor(successorBB);
}
void SpirvBuilder::setMergeTarget(SpirvBasicBlock *mergeLabel) {
assert(insertPoint && "null insert point");
insertPoint->setMergeTarget(mergeLabel);
}
void SpirvBuilder::setContinueTarget(SpirvBasicBlock *continueLabel) {
assert(insertPoint && "null insert point");
insertPoint->setContinueTarget(continueLabel);
}
SpirvCompositeConstruct *SpirvBuilder::createCompositeConstruct(
QualType resultType, llvm::ArrayRef<SpirvInstruction *> constituents,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvCompositeConstruct(resultType, loc, constituents, range);
insertPoint->addInstruction(instruction);
if (!constituents.empty()) {
instruction->setLayoutRule(constituents[0]->getLayoutRule());
}
return instruction;
}
SpirvCompositeExtract *SpirvBuilder::createCompositeExtract(
QualType resultType, SpirvInstruction *composite,
llvm::ArrayRef<uint32_t> indexes, SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvCompositeExtract(resultType, loc, composite, indexes, range);
instruction->setRValue();
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvCompositeInsert *SpirvBuilder::createCompositeInsert(
QualType resultType, SpirvInstruction *composite,
llvm::ArrayRef<uint32_t> indices, SpirvInstruction *object,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvCompositeInsert(resultType, loc, composite, object, indices, range);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvVectorShuffle *SpirvBuilder::createVectorShuffle(
QualType resultType, SpirvInstruction *vector1, SpirvInstruction *vector2,
llvm::ArrayRef<uint32_t> selectors, SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvVectorShuffle(resultType, loc, vector1, vector2, selectors, range);
instruction->setRValue();
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvInstruction *SpirvBuilder::createLoad(QualType resultType,
SpirvInstruction *pointer,
SourceLocation loc,
SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction = new (context) SpirvLoad(resultType, loc, pointer, range);
instruction->setStorageClass(pointer->getStorageClass());
instruction->setLayoutRule(pointer->getLayoutRule());
instruction->setRValue(true);
if (pointer->getStorageClass() == spv::StorageClass::PhysicalStorageBuffer) {
AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
uint32_t align, size, stride;
std::tie(align, size) = alignmentCalc.getAlignmentAndSize(
resultType, pointer->getLayoutRule(), llvm::None, &stride);
instruction->setAlignment(align);
}
if (pointer->containsAliasComponent() &&
isAKindOfStructuredOrByteBuffer(resultType)) {
instruction->setStorageClass(spv::StorageClass::Uniform);
// Now it is a pointer to the global resource, which is lvalue.
instruction->setRValue(false);
// Set to false to indicate that we've performed dereference over the
// pointer-to-pointer and now should fallback to the normal path
instruction->setContainsAliasComponent(false);
}
if (pointer->isRasterizerOrdered()) {
createBeginInvocationInterlockEXT(loc, range);
}
insertPoint->addInstruction(instruction);
if (pointer->isRasterizerOrdered()) {
createEndInvocationInterlockEXT(loc, range);
}
const auto &bitfieldInfo = pointer->getBitfieldInfo();
if (!bitfieldInfo.hasValue())
return instruction;
return createBitFieldExtract(resultType, instruction,
bitfieldInfo->offsetInBits,
bitfieldInfo->sizeInBits, loc, range);
}
SpirvCopyObject *SpirvBuilder::createCopyObject(QualType resultType,
SpirvInstruction *pointer,
SourceLocation loc) {
assert(insertPoint && "null insert point");
auto *instruction = new (context) SpirvCopyObject(resultType, loc, pointer);
instruction->setStorageClass(pointer->getStorageClass());
instruction->setLayoutRule(pointer->getLayoutRule());
// The result of OpCopyObject is always an rvalue.
instruction->setRValue(true);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvLoad *SpirvBuilder::createLoad(const SpirvType *resultType,
SpirvInstruction *pointer,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvLoad(/*QualType*/ {}, loc, pointer, range);
instruction->setResultType(resultType);
instruction->setStorageClass(pointer->getStorageClass());
// Special case for legalization. We could have point-to-pointer types.
// For example:
//
// %var = OpVariable %_ptr_Private__ptr_Uniform_type_X Private
// %1 = OpLoad %_ptr_Uniform_type_X %var
//
// Loading from %var should result in Uniform storage class, not Private.
if (const auto *ptrType = dyn_cast<SpirvPointerType>(resultType)) {
instruction->setStorageClass(ptrType->getStorageClass());
}
instruction->setLayoutRule(pointer->getLayoutRule());
instruction->setRValue(true);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvStore *SpirvBuilder::createStore(SpirvInstruction *address,
SpirvInstruction *value,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
// Safeguard. If this happens, it means we leak non-extracted bitfields.
assert(false == value->getBitfieldInfo().hasValue());
if (address->isRasterizerOrdered()) {
createBeginInvocationInterlockEXT(loc, range);
}
SpirvInstruction *source = value;
const auto &bitfieldInfo = address->getBitfieldInfo();
if (bitfieldInfo.hasValue()) {
// Generate SPIR-V type for value. This is required to know the final
// layout.
LowerTypeVisitor lowerTypeVisitor(astContext, context, spirvOptions, *this);
lowerTypeVisitor.visitInstruction(value);
context.addToInstructionsWithLoweredType(value);
auto *base = createLoad(value->getResultType(), address, loc, range);
source = createBitFieldInsert(/*QualType*/ {}, base, value,
bitfieldInfo->offsetInBits,
bitfieldInfo->sizeInBits, loc, range);
source->setResultType(value->getResultType());
}
auto *instruction =
new (context) SpirvStore(loc, address, source, llvm::None, range);
insertPoint->addInstruction(instruction);
if (address->getStorageClass() == spv::StorageClass::PhysicalStorageBuffer &&
address->getAstResultType() != QualType()) { // exclude raw buffer
AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
uint32_t align, size, stride;
std::tie(align, size) = alignmentCalc.getAlignmentAndSize(
address->getAstResultType(), address->getLayoutRule(), llvm::None,
&stride);
instruction->setAlignment(align);
}
if (address->isRasterizerOrdered()) {
createEndInvocationInterlockEXT(loc, range);
}
if (isa<SpirvLoad>(value) && isa<SpirvVariable>(address)) {
auto paramPtr = dyn_cast<SpirvLoad>(value)->getPointer();
while (isa<SpirvAccessChain>(paramPtr)) {
paramPtr = dyn_cast<SpirvAccessChain>(paramPtr)->getBase();
}
if (isa<SpirvFunctionParameter>(paramPtr))
function->addFuncParamVarEntry(address,
dyn_cast<SpirvLoad>(value)->getPointer());
}
return instruction;
}
SpirvFunctionCall *
SpirvBuilder::createFunctionCall(QualType returnType, SpirvFunction *func,
llvm::ArrayRef<SpirvInstruction *> params,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvFunctionCall(returnType, loc, func, params, range);
instruction->setRValue(func->isRValue());
instruction->setContainsAliasComponent(func->constainsAliasComponent());
if (func->constainsAliasComponent() &&
isAKindOfStructuredOrByteBuffer(returnType)) {
instruction->setStorageClass(spv::StorageClass::Uniform);
// Now it is a pointer to the global resource, which is lvalue.
instruction->setRValue(false);
// Set to false to indicate that we've performed dereference over the
// pointer-to-pointer and now should fallback to the normal path
instruction->setContainsAliasComponent(false);
}
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvAccessChain *SpirvBuilder::createAccessChain(
const SpirvType *resultType, SpirvInstruction *base,
llvm::ArrayRef<SpirvInstruction *> indexes, SourceLocation loc) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvAccessChain(/*QualType*/ {}, loc, base, indexes);
instruction->setResultType(resultType);
instruction->setStorageClass(base->getStorageClass());
instruction->setLayoutRule(base->getLayoutRule());
instruction->setContainsAliasComponent(base->containsAliasComponent());
// If doing an access chain into a structured or byte address buffer, make
// sure the layout rule is sBufferLayoutRule.
if (base->hasAstResultType() &&
isAKindOfStructuredOrByteBuffer(base->getAstResultType()))
instruction->setLayoutRule(spirvOptions.sBufferLayoutRule);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvAccessChain *
SpirvBuilder::createAccessChain(QualType resultType, SpirvInstruction *base,
llvm::ArrayRef<SpirvInstruction *> indexes,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvAccessChain(resultType, loc, base, indexes, range);
instruction->setStorageClass(base->getStorageClass());
instruction->setLayoutRule(base->getLayoutRule());
instruction->setContainsAliasComponent(base->containsAliasComponent());
// If doing an access chain into a structured or byte address buffer, make
// sure the layout rule is sBufferLayoutRule.
if (base->hasAstResultType() &&
isAKindOfStructuredOrByteBuffer(base->getAstResultType()))
instruction->setLayoutRule(spirvOptions.sBufferLayoutRule);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvUnaryOp *SpirvBuilder::createUnaryOp(spv::Op op, QualType resultType,
SpirvInstruction *operand,
SourceLocation loc,
SourceRange range) {
if (!operand)
return nullptr;
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvUnaryOp(op, resultType, loc, operand, range);
insertPoint->addInstruction(instruction);
instruction->setLayoutRule(operand->getLayoutRule());
return instruction;
}
SpirvUnaryOp *SpirvBuilder::createUnaryOp(spv::Op op,
const SpirvType *resultType,
SpirvInstruction *operand,
SourceLocation loc) {
if (!operand)
return nullptr;
assert(insertPoint && "null insert point");
auto *instruction = new (context) SpirvUnaryOp(op, resultType, loc, operand);
instruction->setLayoutRule(operand->getLayoutRule());
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvBinaryOp *SpirvBuilder::createBinaryOp(spv::Op op, QualType resultType,
SpirvInstruction *lhs,
SpirvInstruction *rhs,
SourceLocation loc,
SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvBinaryOp(op, resultType, loc, lhs, rhs, range);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvSpecConstantBinaryOp *SpirvBuilder::createSpecConstantBinaryOp(
spv::Op op, QualType resultType, SpirvInstruction *lhs,
SpirvInstruction *rhs, SourceLocation loc) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvSpecConstantBinaryOp(op, resultType, loc, lhs, rhs);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvGroupNonUniformOp *SpirvBuilder::createGroupNonUniformOp(
spv::Op op, QualType resultType, llvm::Optional<spv::Scope> execScope,
llvm::ArrayRef<SpirvInstruction *> operands, SourceLocation loc,
llvm::Optional<spv::GroupOperation> groupOp) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvGroupNonUniformOp(op, resultType, execScope, operands, loc, groupOp);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvAtomic *SpirvBuilder::createAtomicOp(
spv::Op opcode, QualType resultType, SpirvInstruction *originalValuePtr,
spv::Scope scope, spv::MemorySemanticsMask memorySemantics,
SpirvInstruction *valueToOp, SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction =
new (context) SpirvAtomic(opcode, resultType, loc, originalValuePtr,
scope, memorySemantics, valueToOp, range);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvAtomic *SpirvBuilder::createAtomicCompareExchange(
QualType resultType, SpirvInstruction *originalValuePtr, spv::Scope scope,
spv::MemorySemanticsMask equalMemorySemantics,
spv::MemorySemanticsMask unequalMemorySemantics,
SpirvInstruction *valueToOp, SpirvInstruction *comparator,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvAtomic(spv::Op::OpAtomicCompareExchange, resultType, loc,
originalValuePtr, scope, equalMemorySemantics,
unequalMemorySemantics, valueToOp, comparator, range);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvSampledImage *SpirvBuilder::createSampledImage(QualType imageType,
SpirvInstruction *image,
SpirvInstruction *sampler,
SourceLocation loc,
SourceRange range) {
assert(insertPoint && "null insert point");
auto *sampledImage =
new (context) SpirvSampledImage(imageType, loc, image, sampler, range);
insertPoint->addInstruction(sampledImage);
return sampledImage;
}
SpirvImageTexelPointer *SpirvBuilder::createImageTexelPointer(
QualType resultType, SpirvInstruction *image, SpirvInstruction *coordinate,
SpirvInstruction *sample, SourceLocation loc) {
assert(insertPoint && "null insert point");
auto *instruction = new (context)
SpirvImageTexelPointer(resultType, loc, image, coordinate, sample);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvConvertPtrToU *SpirvBuilder::createConvertPtrToU(SpirvInstruction *ptr,
QualType type) {
auto *instruction = new (context) SpirvConvertPtrToU(ptr, type);
instruction->setRValue(true);
insertPoint->addInstruction(instruction);
return instruction;
}
SpirvConvertUToPtr *SpirvBuilder::createConvertUToPtr(SpirvInstruction *val,
QualType type) {
auto *instruction = new (context) SpirvConvertUToPtr(val, type);
instruction->setRValue(false);
insertPoint->addInstruction(instruction);
return instruction;
}
spv::ImageOperandsMask SpirvBuilder::composeImageOperandsMask(
SpirvInstruction *bias, SpirvInstruction *lod,
const std::pair<SpirvInstruction *, SpirvInstruction *> &grad,
SpirvInstruction *constOffset, SpirvInstruction *varOffset,
SpirvInstruction *constOffsets, SpirvInstruction *sample,
SpirvInstruction *minLod) {
using spv::ImageOperandsMask;
// SPIR-V Image Operands from least significant bit to most significant bit
// Bias, Lod, Grad, ConstOffset, Offset, ConstOffsets, Sample, MinLod
auto mask = ImageOperandsMask::MaskNone;
if (bias) {
mask = mask | ImageOperandsMask::Bias;
}
if (lod) {
mask = mask | ImageOperandsMask::Lod;
}
if (grad.first && grad.second) {
mask = mask | ImageOperandsMask::Grad;
}
if (constOffset) {
mask = mask | ImageOperandsMask::ConstOffset;
}
if (varOffset) {
mask = mask | ImageOperandsMask::Offset;
}
if (constOffsets) {
mask = mask | ImageOperandsMask::ConstOffsets;
}
if (sample) {
mask = mask | ImageOperandsMask::Sample;
}
if (minLod) {
mask = mask | ImageOperandsMask::MinLod;
}
return mask;
}
SpirvInstruction *SpirvBuilder::createImageSample(
QualType texelType, QualType imageType, SpirvInstruction *image,
SpirvInstruction *sampler, SpirvInstruction *coordinate,
SpirvInstruction *compareVal, SpirvInstruction *bias, SpirvInstruction *lod,
std::pair<SpirvInstruction *, SpirvInstruction *> grad,
SpirvInstruction *constOffset, SpirvInstruction *varOffset,
SpirvInstruction *constOffsets, SpirvInstruction *sample,
SpirvInstruction *minLod, SpirvInstruction *residencyCode,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
// The Lod and Grad image operands requires explicit-lod instructions.
// Otherwise we use implicit-lod instructions.
const bool isExplicit = lod || (grad.first && grad.second);
const bool isSparse = (residencyCode != nullptr);
spv::Op op = spv::Op::Max;
if (compareVal) {
op = isExplicit ? (isSparse ? spv::Op::OpImageSparseSampleDrefExplicitLod
: spv::Op::OpImageSampleDrefExplicitLod)
: (isSparse ? spv::Op::OpImageSparseSampleDrefImplicitLod
: spv::Op::OpImageSampleDrefImplicitLod);
} else {
op = isExplicit ? (isSparse ? spv::Op::OpImageSparseSampleExplicitLod
: spv::Op::OpImageSampleExplicitLod)
: (isSparse ? spv::Op::OpImageSparseSampleImplicitLod
: spv::Op::OpImageSampleImplicitLod);
}
// minLod is only valid with Implicit instructions and Grad instructions.
// This means that we cannot have Lod and minLod together because Lod requires
// explicit insturctions. So either lod or minLod or both must be zero.
assert(lod == nullptr || minLod == nullptr);
// An OpSampledImage is required to do the image sampling.
auto *sampledImage =
createSampledImage(imageType, image, sampler, loc, range);
const auto mask = composeImageOperandsMask(
bias, lod, grad, constOffset, varOffset, constOffsets, sample, minLod);
auto *imageSampleInst = new (context) SpirvImageOp(
op, texelType, loc, sampledImage, coordinate, mask, compareVal, bias, lod,
grad.first, grad.second, constOffset, varOffset, constOffsets, sample,
minLod, nullptr, nullptr, range);
insertPoint->addInstruction(imageSampleInst);
if (isSparse) {
// Write the Residency Code
const auto status = createCompositeExtract(
astContext.UnsignedIntTy, imageSampleInst, {0}, loc, range);
createStore(residencyCode, status, loc, range);
// Extract the real result from the struct
return createCompositeExtract(texelType, imageSampleInst, {1}, loc, range);
}
return imageSampleInst;
}
SpirvInstruction *SpirvBuilder::createImageFetchOrRead(
bool doImageFetch, QualType texelType, QualType imageType,
SpirvInstruction *image, SpirvInstruction *coordinate,
SpirvInstruction *lod, SpirvInstruction *constOffset,
SpirvInstruction *constOffsets, SpirvInstruction *sample,
SpirvInstruction *residencyCode, SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
const auto mask = composeImageOperandsMask(
/*bias*/ nullptr, lod, std::make_pair(nullptr, nullptr), constOffset,
/*varOffset*/ nullptr, constOffsets, sample, /*minLod*/ nullptr);
const bool isSparse = (residencyCode != nullptr);
spv::Op op =
doImageFetch
? (isSparse ? spv::Op::OpImageSparseFetch : spv::Op::OpImageFetch)
: (isSparse ? spv::Op::OpImageSparseRead : spv::Op::OpImageRead);
auto *fetchOrReadInst = new (context)
SpirvImageOp(op, texelType, loc, image, coordinate, mask,
/*dref*/ nullptr, /*bias*/ nullptr, lod, /*gradDx*/ nullptr,
/*gradDy*/ nullptr, constOffset, /*varOffset*/ nullptr,
constOffsets, sample, nullptr, nullptr, nullptr, range);
insertPoint->addInstruction(fetchOrReadInst);
if (isSparse) {
// Write the Residency Code
const auto status = createCompositeExtract(
astContext.UnsignedIntTy, fetchOrReadInst, {0}, loc, range);
createStore(residencyCode, status, loc, range);
// Extract the real result from the struct
return createCompositeExtract(texelType, fetchOrReadInst, {1}, loc, range);
}
return fetchOrReadInst;
}
void SpirvBuilder::createImageWrite(QualType imageType, SpirvInstruction *image,
SpirvInstruction *coord,
SpirvInstruction *texel, SourceLocation loc,
SourceRange range) {
assert(insertPoint && "null insert point");
auto *writeInst = new (context) SpirvImageOp(
spv::Op::OpImageWrite, imageType, loc, image, coord,
spv::ImageOperandsMask::MaskNone,
/*dref*/ nullptr, /*bias*/ nullptr, /*lod*/ nullptr, /*gradDx*/ nullptr,
/*gradDy*/ nullptr, /*constOffset*/ nullptr, /*varOffset*/ nullptr,
/*constOffsets*/ nullptr, /*sample*/ nullptr, /*minLod*/ nullptr,
/*component*/ nullptr, texel, range);
insertPoint->addInstruction(writeInst);
}
SpirvInstruction *SpirvBuilder::createImageGather(
QualType texelType, QualType imageType, SpirvInstruction *image,
SpirvInstruction *sampler, SpirvInstruction *coordinate,
SpirvInstruction *component, SpirvInstruction *compareVal,
SpirvInstruction *constOffset, SpirvInstruction *varOffset,
SpirvInstruction *constOffsets, SpirvInstruction *sample,
SpirvInstruction *residencyCode, SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
// An OpSampledImage is required to do the image sampling.
auto *sampledImage =
createSampledImage(imageType, image, sampler, loc, range);
// TODO: Update ImageGather to accept minLod if necessary.
const auto mask = composeImageOperandsMask(
/*bias*/ nullptr, /*lod*/ nullptr, std::make_pair(nullptr, nullptr),
constOffset, varOffset, constOffsets, sample, /*minLod*/ nullptr);
spv::Op op = compareVal ? (residencyCode ? spv::Op::OpImageSparseDrefGather
: spv::Op::OpImageDrefGather)
: (residencyCode ? spv::Op::OpImageSparseGather
: spv::Op::OpImageGather);
// Note: OpImageSparseDrefGather and OpImageDrefGather do not take the
// component parameter.
if (compareVal)
component = nullptr;
auto *imageInstruction = new (context) SpirvImageOp(
op, texelType, loc, sampledImage, coordinate, mask, compareVal,
/*bias*/ nullptr, /*lod*/ nullptr, /*gradDx*/ nullptr,
/*gradDy*/ nullptr, constOffset, varOffset, constOffsets, sample,
/*minLod*/ nullptr, component, nullptr, range);
insertPoint->addInstruction(imageInstruction);
if (residencyCode) {
// Write the Residency Code
const auto status = createCompositeExtract(astContext.UnsignedIntTy,
imageInstruction, {0}, loc);
createStore(residencyCode, status, loc);
// Extract the real result from the struct
return createCompositeExtract(texelType, imageInstruction, {1}, loc);
}
return imageInstruction;
}
SpirvImageSparseTexelsResident *SpirvBuilder::createImageSparseTexelsResident(
SpirvInstruction *residentCode, SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *inst = new (context) SpirvImageSparseTexelsResident(
astContext.BoolTy, loc, residentCode, range);
insertPoint->addInstruction(inst);
return inst;
}
SpirvImageQuery *
SpirvBuilder::createImageQuery(spv::Op opcode, QualType resultType,
SourceLocation loc, SpirvInstruction *image,
SpirvInstruction *lod, SourceRange range) {
assert(insertPoint && "null insert point");
SpirvInstruction *lodParam = nullptr;
SpirvInstruction *coordinateParam = nullptr;
if (opcode == spv::Op::OpImageQuerySizeLod)
lodParam = lod;
if (opcode == spv::Op::OpImageQueryLod)
coordinateParam = lod;
auto *inst = new (context) SpirvImageQuery(opcode, resultType, loc, image,
lodParam, coordinateParam, range);
insertPoint->addInstruction(inst);
return inst;
}
SpirvSelect *SpirvBuilder::createSelect(QualType resultType,
SpirvInstruction *condition,
SpirvInstruction *trueValue,
SpirvInstruction *falseValue,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *inst = new (context)
SpirvSelect(resultType, loc, condition, trueValue, falseValue, range);
insertPoint->addInstruction(inst);
return inst;
}
void SpirvBuilder::createSwitch(
SpirvBasicBlock *mergeLabel, SpirvInstruction *selector,
SpirvBasicBlock *defaultLabel,
llvm::ArrayRef<std::pair<llvm::APInt, SpirvBasicBlock *>> target,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
// Create the OpSelectioMerege.
auto *selectionMerge = new (context) SpirvSelectionMerge(
loc, mergeLabel, spv::SelectionControlMask::MaskNone, range);
insertPoint->addInstruction(selectionMerge);
// Create the OpSwitch.
auto *switchInst =
new (context) SpirvSwitch(loc, selector, defaultLabel, target);
insertPoint->addInstruction(switchInst);
}
void SpirvBuilder::createKill(SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *kill = new (context) SpirvKill(loc, range);
insertPoint->addInstruction(kill);
}
void SpirvBuilder::createBranch(SpirvBasicBlock *targetLabel,
SourceLocation loc, SpirvBasicBlock *mergeBB,
SpirvBasicBlock *continueBB,
spv::LoopControlMask loopControl,
SourceRange range) {
assert(insertPoint && "null insert point");
if (mergeBB && continueBB) {
auto *loopMerge = new (context)
SpirvLoopMerge(loc, mergeBB, continueBB, loopControl, range);
insertPoint->addInstruction(loopMerge);
}
auto *branch = new (context) SpirvBranch(loc, targetLabel, range);
insertPoint->addInstruction(branch);
}
void SpirvBuilder::createConditionalBranch(
SpirvInstruction *condition, SpirvBasicBlock *trueLabel,
SpirvBasicBlock *falseLabel, SourceLocation loc,
SpirvBasicBlock *mergeLabel, SpirvBasicBlock *continueLabel,
spv::SelectionControlMask selectionControl,
spv::LoopControlMask loopControl, SourceRange range) {
assert(insertPoint && "null insert point");
if (mergeLabel) {
if (continueLabel) {
auto *loopMerge = new (context)
SpirvLoopMerge(loc, mergeLabel, continueLabel, loopControl, range);
insertPoint->addInstruction(loopMerge);
} else {
auto *selectionMerge = new (context)
SpirvSelectionMerge(loc, mergeLabel, selectionControl, range);
insertPoint->addInstruction(selectionMerge);
}
}
auto *branchConditional = new (context)
SpirvBranchConditional(loc, condition, trueLabel, falseLabel);
insertPoint->addInstruction(branchConditional);
}
void SpirvBuilder::createReturn(SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
insertPoint->addInstruction(new (context) SpirvReturn(loc, nullptr, range));
}
void SpirvBuilder::createReturnValue(SpirvInstruction *value,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
insertPoint->addInstruction(new (context) SpirvReturn(loc, value, range));
}
SpirvInstruction *
SpirvBuilder::createGLSLExtInst(QualType resultType, GLSLstd450 inst,
llvm::ArrayRef<SpirvInstruction *> operands,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *extInst = new (context) SpirvExtInst(
resultType, loc, getExtInstSet("GLSL.std.450"), inst, operands, range);
insertPoint->addInstruction(extInst);
return extInst;
}
SpirvInstruction *
SpirvBuilder::createGLSLExtInst(const SpirvType *resultType, GLSLstd450 inst,
llvm::ArrayRef<SpirvInstruction *> operands,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
auto *extInst = new (context) SpirvExtInst(
/*QualType*/ {}, loc, getExtInstSet("GLSL.std.450"), inst, operands,
range);
extInst->setResultType(resultType);
insertPoint->addInstruction(extInst);
return extInst;
}
SpirvInstruction *SpirvBuilder::createNonSemanticDebugPrintfExtInst(
QualType resultType, NonSemanticDebugPrintfInstructions instId,
llvm::ArrayRef<SpirvInstruction *> operands, SourceLocation loc) {
assert(insertPoint && "null insert point");
auto *extInst = new (context)
SpirvExtInst(resultType, loc, getExtInstSet("NonSemantic.DebugPrintf"),
instId, operands);
insertPoint->addInstruction(extInst);
return extInst;
}
void SpirvBuilder::createBarrier(spv::Scope memoryScope,
spv::MemorySemanticsMask memorySemantics,
llvm::Optional<spv::Scope> exec,
SourceLocation loc, SourceRange range) {
assert(insertPoint && "null insert point");
SpirvBarrier *barrier = new (context)
SpirvBarrier(loc, memoryScope, memorySemantics, exec, range);
insertPoint->addInstruction(barrier);
}
SpirvInstruction *SpirvBuilder::createEmulatedBitFieldInsert(
QualType resultType, uint32_t baseTypeBitwidth, SpirvInstruction *base,
SpirvInstruction *insert, unsigned bitOffset, unsigned bitCount,
SourceLocation loc, SourceRange range) {
// The destination is a raw struct field, which can contain several bitfields:
// raw field: AAAABBBBCCCCCCCCDDDD
// To insert a new value for the field BBBB, we need to clear the B bits in
// the field, and insert the new values.
// Create a mask to clear B from the raw field.
// mask = (1 << bitCount) - 1
// raw field: AAAABBBBCCCCCCCCDDDD
// mask: 00000000000000001111
// cast mask to the an unsigned with the same bitwidth.
// mask = (unsigned dstType)mask
// Move the mask to B's position in the raw type.
// mask = mask << bitOffset
// raw field: AAAABBBBCCCCCCCCDDDD
// mask: 00001111000000000000
// Generate inverted mask to clear other bits in *insert*.
// notMask = ~mask
// raw field: AAAABBBBCCCCCCCCDDDD
// mask: 11110000111111111111
assert(bitCount <= 64 &&
"Bitfield insertion emulation can only insert at most 64 bits.");
auto maskTy =
astContext.getIntTypeForBitwidth(baseTypeBitwidth, /* signed= */ 0);
const uint64_t maskValue = ((1ull << bitCount) - 1ull) << bitOffset;
const uint64_t notMaskValue = ~maskValue;
auto *mask = getConstantInt(maskTy, llvm::APInt(baseTypeBitwidth, maskValue));
auto *notMask =
getConstantInt(maskTy, llvm::APInt(baseTypeBitwidth, notMaskValue));
auto *shiftOffset =
getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, bitOffset));
// base = base & MASK // Clear bits at B's position.
// input: AAAABBBBCCCCCCCCDDDD
// output: AAAA----CCCCCCCCDDDD
auto *clearedDst = createBinaryOp(spv::Op::OpBitwiseAnd, resultType, base,
notMask, loc, range);
// input: SSSSSSSSSSSSSSSSBBBB
// tmp = (dstType)SRC // Convert SRC to the base type.
// tmp = tmp << bitOffset // Move the SRC value to the correct bit offset.
// output: SSSSBBBB------------
// tmp = tmp & ~MASK // Clear any sign extension bits.
// output: ----BBBB------------
auto *castedSrc =
createUnaryOp(spv::Op::OpBitcast, resultType, insert, loc, range);
auto *shiftedSrc = createBinaryOp(spv::Op::OpShiftLeftLogical, resultType,
castedSrc, shiftOffset, loc, range);
auto *maskedSrc = createBinaryOp(spv::Op::OpBitwiseAnd, resultType,
shiftedSrc, mask, loc, range);
// base = base | tmp; // Insert B in the raw field.
// tmp: ----BBBB------------
// base: AAAA----CCCCCCCCDDDD
// output: AAAABBBBCCCCCCCCDDDD
auto *result = createBinaryOp(spv::Op::OpBitwiseOr, resultType, clearedDst,
maskedSrc, loc, range);
if (base->getResultType()) {
auto *dstTy = dyn_cast<IntegerType>(base->getResultType());
clearedDst->setResultType(dstTy);
shiftedSrc->setResultType(dstTy);
maskedSrc->setResultType(dstTy);
castedSrc->setResultType(dstTy);
result->setResultType(dstTy);
}
return result;
}
SpirvInstruction *
SpirvBuilder::createBitFieldInsert(QualType resultType, SpirvInstruction *base,
SpirvInstruction *insert, unsigned bitOffset,
unsigned bitCount, SourceLocation loc,
SourceRange range) {
assert(insertPoint && "null insert point");
uint32_t bitwidth = 0;
if (resultType == QualType({})) {
assert(base->hasResultType() && "No type information for bitfield.");
bitwidth = dyn_cast<IntegerType>(base->getResultType())->getBitwidth();
} else {
bitwidth = getElementSpirvBitwidth(astContext, resultType,
spirvOptions.enable16BitTypes);
}
if (bitwidth != 32)
return createEmulatedBitFieldInsert(resultType, bitwidth, base, insert,
bitOffset, bitCount, loc, range);
auto *insertOffset =
getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, bitOffset));
auto *insertCount =
getConstantInt(astContext.UnsignedIntTy, llvm::APInt(32, bitCount));
auto *inst = new (context) SpirvBitFieldInsert(resultType, loc, base, insert,
insertOffset, insertCount);
insertPoint->addInstruction(inst);
inst->setRValue(true);
return inst;
}
SpirvInstruction *SpirvBuilder::createEmulatedBitFieldExtract(
QualType resultType, uint32_t baseTypeBitwidth, SpirvInstruction *base,
unsigned bitOffset, unsigned bitCount, SourceLocation loc,
SourceRange range) {
assert(bitCount <= 64 &&
"Bitfield extraction emulation can only extract at most 64 bits.");
// The base is a raw struct field, which can contain several bitfields:
// raw field: AAAABBBBCCCCCCCCDDDD
// Extracting B means shifting it right until B's LSB is the basetype LSB.
// But first, we need to left shift until B's MSB becomes the basetype MSB: