forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSemaDXR.cpp
More file actions
1297 lines (1125 loc) · 45.3 KB
/
SemaDXR.cpp
File metadata and controls
1297 lines (1125 loc) · 45.3 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
//===------ SemaDXR.cpp - Semantic Analysis for DXR shader -----*- C++ -*-===//
///////////////////////////////////////////////////////////////////////////////
// //
// SemaDXR.cpp //
// Copyright (C) Nvidia Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// This file defines the semantic support for DXR. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Sema/SemaHLSL.h"
#include "clang/Analysis/Analyses/Dominators.h"
#include "clang/Analysis/Analyses/ReachableCode.h"
#include "clang/Analysis/CFG.h"
#include "llvm/ADT/BitVector.h"
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilShaderModel.h"
#include "dxc/HlslIntrinsicOp.h"
using namespace clang;
using namespace sema;
using namespace hlsl;
namespace {
struct PayloadUse {
PayloadUse() = default;
PayloadUse(const Stmt *S, const CFGBlock *Parent)
: S(S), Parent(Parent), Member(nullptr) {}
PayloadUse(const Stmt *S, const CFGBlock *Parent, const MemberExpr *Member)
: S(S), Parent(Parent), Member(Member) {}
bool operator<(const PayloadUse &Other) const { return S < Other.S; }
const Stmt *S = nullptr;
const CFGBlock *Parent = nullptr;
const MemberExpr *Member = nullptr;
};
struct PayloadBuiltinCall {
PayloadBuiltinCall() = default;
PayloadBuiltinCall(const CallExpr *Call, const CFGBlock *Parent)
: Call(Call), Parent(Parent) {}
const CallExpr *Call = nullptr;
const CFGBlock *Parent = nullptr;
};
struct PayloadAccessInfo {
PayloadAccessInfo() = default;
PayloadAccessInfo(const MemberExpr *Member, const CallExpr *Call,
bool IsLValue)
: Member(Member), Call(Call), IsLValue(IsLValue) {}
const MemberExpr *Member = nullptr;
const CallExpr *Call = nullptr;
bool IsLValue = false;
};
struct DxrShaderDiagnoseInfo {
const FunctionDecl *funcDecl;
const VarDecl *Payload;
DXIL::PayloadAccessShaderStage Stage;
std::vector<PayloadBuiltinCall> PayloadBuiltinCalls;
std::map<const FieldDecl *, std::vector<PayloadUse>> WritesPerField;
std::map<const FieldDecl *, std::vector<PayloadUse>> ReadsPerField;
std::vector<PayloadUse> PayloadAsCallArg;
};
std::vector<const FieldDecl *>
DiagnosePayloadAccess(Sema &S, DxrShaderDiagnoseInfo &Info,
const std::set<const FieldDecl *> &FieldsToIgnoreRead,
const std::set<const FieldDecl *> &FieldsToIgnoreWrite,
std::set<const FunctionDecl *> VisitedFunctions);
const Stmt *IgnoreParensAndDecay(const Stmt *S);
// Transform the shader stage to string to be used in diagnostics
StringRef GetStringForShaderStage(DXIL::PayloadAccessShaderStage Stage) {
StringRef StageNames[] = {"caller", "closesthit", "miss", "anyhit"};
if (Stage != DXIL::PayloadAccessShaderStage::Invalid)
return StageNames[static_cast<unsigned>(Stage)];
return "";
}
// Returns the Qualifier for a Field and a given shader stage.
DXIL::PayloadAccessQualifier
GetPayloadQualifierForStage(FieldDecl *Field,
DXIL::PayloadAccessShaderStage Stage) {
bool hasRead = false;
bool hasWrite = false;
for (UnusualAnnotation *annotation : Field->getUnusualAnnotations()) {
if (auto *payloadAnnotation =
dyn_cast<hlsl::PayloadAccessAnnotation>(annotation)) {
for (auto &ShaderStage : payloadAnnotation->ShaderStages) {
if (ShaderStage != Stage)
continue;
hasRead |=
payloadAnnotation->qualifier == DXIL::PayloadAccessQualifier::Read;
hasWrite |=
payloadAnnotation->qualifier == DXIL::PayloadAccessQualifier::Write;
}
}
}
if (hasRead && hasWrite)
return DXIL::PayloadAccessQualifier::ReadWrite;
if (hasRead)
return DXIL::PayloadAccessQualifier::Read;
if (hasWrite)
return DXIL::PayloadAccessQualifier::Write;
return DXIL::PayloadAccessQualifier::NoAccess;
}
static int GetPayloadParamIdxForIntrinsic(const FunctionDecl *FD) {
HLSLIntrinsicAttr *IntrinAttr = FD->getAttr<HLSLIntrinsicAttr>();
if (!IntrinAttr)
return -1;
switch ((IntrinsicOp)IntrinAttr->getOpcode()) {
default:
return -1;
case IntrinsicOp::IOP_TraceRay:
case IntrinsicOp::MOP_DxHitObject_TraceRay:
case IntrinsicOp::MOP_DxHitObject_Invoke:
return FD->getNumParams() - 1;
}
}
static bool IsBuiltinWithPayload(const FunctionDecl *FD) {
return GetPayloadParamIdxForIntrinsic(FD) >= 0;
}
// Returns the declaration of the payload used in a call to TraceRay,
// HitObject::TraceRay or HitObject::Invoke.
const VarDecl *GetPayloadParameterForBuiltinCall(const CallExpr *Call) {
const Decl *Callee = Call->getCalleeDecl();
if (!Callee)
return nullptr;
if (!isa<FunctionDecl>(Callee))
return nullptr;
int PldParamIdx = GetPayloadParamIdxForIntrinsic(cast<FunctionDecl>(Callee));
if (PldParamIdx < 0)
return nullptr;
const Stmt *Param = IgnoreParensAndDecay(Call->getArg(PldParamIdx));
if (const DeclRefExpr *ParamRef = dyn_cast<DeclRefExpr>(Param))
if (const VarDecl *Decl = dyn_cast<VarDecl>(ParamRef->getDecl()))
return Decl;
return nullptr;
}
// Recursively extracts accesses to a payload struct from a Stmt
void GetPayloadAccesses(const Stmt *S, const DxrShaderDiagnoseInfo &Info,
std::vector<PayloadAccessInfo> &Accesses, bool IsLValue,
const MemberExpr *Member, const CallExpr *Call) {
for (auto C : S->children()) {
if (!C)
continue;
if (const DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(C)) {
if (Ref->getDecl() == Info.Payload) {
Accesses.push_back(PayloadAccessInfo{Member, Call, IsLValue});
}
}
if (const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(C)) {
if (Cast->getCastKind() == CK_LValueToRValue) {
IsLValue = false;
}
}
GetPayloadAccesses(C, Info, Accesses, IsLValue,
Member ? Member : dyn_cast<MemberExpr>(C),
Call ? Call : dyn_cast<CallExpr>(C));
}
}
// Collects all reads, writes and calls with participation of the payload.
void CollectReadsWritesAndCallsForPayload(const Stmt *S,
DxrShaderDiagnoseInfo &Info,
const CFGBlock *Block) {
std::vector<PayloadAccessInfo> PayloadAccesses;
GetPayloadAccesses(S, Info, PayloadAccesses, true, dyn_cast<MemberExpr>(S),
dyn_cast<CallExpr>(S));
for (auto &Access : PayloadAccesses) {
// An access to a payload member was found.
if (Access.Member) {
FieldDecl *Field = cast<FieldDecl>(Access.Member->getMemberDecl());
if (Access.IsLValue) {
Info.WritesPerField[Field].push_back(
PayloadUse{S, Block, Access.Member});
} else {
Info.ReadsPerField[Field].push_back(
PayloadUse{S, Block, Access.Member});
}
} else if (Access.Call) {
Info.PayloadAsCallArg.push_back(PayloadUse{S, Block});
}
}
}
// Collects all calls to TraceRay, HitObject::TraceRay and HitObject::Invoke.
void CollectBuiltinCallsWithPayload(const Stmt *S, DxrShaderDiagnoseInfo &Info,
const CFGBlock *Block) {
if (const CallExpr *Call = dyn_cast<CallExpr>(S)) {
const Decl *Callee = Call->getCalleeDecl();
if (!Callee || !isa<FunctionDecl>(Callee))
return;
const FunctionDecl *CalledFunction = cast<FunctionDecl>(Callee);
if (IsBuiltinWithPayload(CalledFunction))
Info.PayloadBuiltinCalls.push_back({Call, Block});
}
}
// Find the last write to the payload field in the given block.
PayloadUse GetLastWriteInBlock(CFGBlock &Block,
ArrayRef<PayloadUse> PayloadWrites) {
PayloadUse LastWrite;
for (auto &Element : Block) { // TODO: reverse iterate?
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
auto It = std::find_if(
PayloadWrites.begin(), PayloadWrites.end(),
[&](const PayloadUse &V) { return V.S == S->getStmt(); });
if (It != std::end(PayloadWrites)) {
LastWrite = *It;
LastWrite.Parent = &Block;
}
}
}
return LastWrite;
}
// Travers the CFG until every path has reached a write or the ENTRY.
void TraverseCFGUntilWrite(CFGBlock &Current, std::vector<PayloadUse> &Writes,
ArrayRef<PayloadUse> PayloadWrites,
std::set<const CFGBlock *> &Visited) {
if (Visited.count(&Current))
return;
Visited.insert(&Current);
for (auto I = Current.pred_begin(), E = Current.pred_end(); I != E; ++I) {
CFGBlock *Pred = *I;
if (!Pred)
continue;
PayloadUse WriteInPred = GetLastWriteInBlock(*Pred, PayloadWrites);
if (!WriteInPred.S)
TraverseCFGUntilWrite(*Pred, Writes, PayloadWrites, Visited);
else
Writes.push_back(WriteInPred);
}
}
// Traverse the CFG from the EXIT backwards and stop as soon as a block has a
// write to the payload field.
std::vector<PayloadUse>
GetAllWritesReachingExit(CFG &ShaderCFG, ArrayRef<PayloadUse> PayloadWrites) {
std::vector<PayloadUse> Writes;
CFGBlock &Exit = ShaderCFG.getExit();
std::set<const CFGBlock *> Visited;
TraverseCFGUntilWrite(Exit, Writes, PayloadWrites, Visited);
return Writes;
}
// Find the first read to the payload field in the given block.
PayloadUse GetFirstReadInBlock(CFGBlock &Block,
ArrayRef<PayloadUse> PayloadReads) {
PayloadUse FirstRead;
for (auto &Element : Block) {
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
auto It = std::find_if(
PayloadReads.begin(), PayloadReads.end(),
[&](const PayloadUse &V) { return V.S == S->getStmt(); });
if (It != std::end(PayloadReads)) {
FirstRead = *It;
FirstRead.Parent = &Block;
break; // We found the first read and are done with this block.
}
}
}
return FirstRead;
}
// Travers the CFG until every path has reached a read or the EXIT.
void TraverseCFGUntilRead(CFGBlock &Current, std::vector<PayloadUse> &Reads,
ArrayRef<PayloadUse> PayloadWrites,
std::set<const CFGBlock *> &Visited) {
if (Visited.count(&Current))
return;
Visited.insert(&Current);
for (auto I = Current.succ_begin(), E = Current.succ_end(); I != E; ++I) {
CFGBlock *Succ = *I;
if (!Succ)
continue;
PayloadUse ReadInSucc = GetFirstReadInBlock(*Succ, PayloadWrites);
if (!ReadInSucc.S)
TraverseCFGUntilRead(*Succ, Reads, PayloadWrites, Visited);
else
Reads.push_back(ReadInSucc);
}
}
// Traverse the CFG from the ENTRY down and stop as soon as a block has a read
// to the payload field.
std::vector<PayloadUse>
GetAllReadsReachedFromEntry(CFG &ShaderCFG, ArrayRef<PayloadUse> PayloadReads) {
std::vector<PayloadUse> Reads;
CFGBlock &Entry = ShaderCFG.getEntry();
std::set<const CFGBlock *> Visited;
TraverseCFGUntilRead(Entry, Reads, PayloadReads, Visited);
return Reads;
}
// Returns the record type of a payload declaration.
CXXRecordDecl *GetPayloadType(const VarDecl *Payload) {
auto PayloadType = Payload->getType();
if (PayloadType->isStructureOrClassType()) {
return PayloadType->getAsCXXRecordDecl();
}
return nullptr;
}
std::vector<FieldDecl *> GetAllPayloadFields(RecordDecl *PayloadType) {
std::vector<FieldDecl *> PayloadFields;
for (FieldDecl *Field : PayloadType->fields()) {
QualType FieldType = Field->getType();
if (RecordDecl *FieldRecordDecl = FieldType->getAsCXXRecordDecl()) {
// Skip nested payload types.
if (FieldRecordDecl->hasAttr<HLSLRayPayloadAttr>()) {
auto SubTypeFields = GetAllPayloadFields(FieldRecordDecl);
PayloadFields.insert(PayloadFields.end(), SubTypeFields.begin(),
SubTypeFields.end());
continue;
}
}
PayloadFields.push_back(Field);
}
return PayloadFields;
}
// Returns true if the field is writeable in an earlier shader stage.
bool IsFieldWriteableInEarlierStage(FieldDecl *Field,
DXIL::PayloadAccessShaderStage ThisStage) {
bool isWriteableInEarlierStage = false;
switch (ThisStage) {
case DXIL::PayloadAccessShaderStage::Anyhit:
case DXIL::PayloadAccessShaderStage::Closesthit:
case DXIL::PayloadAccessShaderStage::Miss: {
auto Qualifier = GetPayloadQualifierForStage(
Field, DXIL::PayloadAccessShaderStage::Caller);
isWriteableInEarlierStage =
Qualifier == DXIL::PayloadAccessQualifier::Write ||
Qualifier == DXIL::PayloadAccessQualifier::ReadWrite;
Qualifier = GetPayloadQualifierForStage(
Field, DXIL::PayloadAccessShaderStage::Anyhit);
isWriteableInEarlierStage |=
Qualifier == DXIL::PayloadAccessQualifier::Write ||
Qualifier == DXIL::PayloadAccessQualifier::ReadWrite;
} break;
default:
break;
}
return isWriteableInEarlierStage;
}
// Emit warnings on payload writes.
void DiagnosePayloadWrites(Sema &S, CFG &ShaderCFG, DominatorTree &DT,
const DxrShaderDiagnoseInfo &Info,
ArrayRef<FieldDecl *> NonWriteableFields,
RecordDecl *PayloadType) {
for (FieldDecl *Field : NonWriteableFields) {
auto WritesToField = Info.WritesPerField.find(Field);
if (WritesToField == Info.WritesPerField.end())
continue;
const auto &WritesToDiagnose =
GetAllWritesReachingExit(ShaderCFG, WritesToField->second);
for (auto &Write : WritesToDiagnose) {
FieldDecl *MemField = cast<FieldDecl>(Write.Member->getMemberDecl());
auto Qualifier = GetPayloadQualifierForStage(MemField, Info.Stage);
if (Qualifier != DXIL::PayloadAccessQualifier::Write &&
Qualifier != DXIL::PayloadAccessQualifier::ReadWrite) {
S.Diag(Write.Member->getExprLoc(),
diag::warn_hlsl_payload_access_write_loss)
<< Field->getName() << GetStringForShaderStage(Info.Stage);
}
}
}
// Check if a field is not unconditionally written and a write form an earlier
// stage will be lost.
auto PayloadFields = GetAllPayloadFields(PayloadType);
for (FieldDecl *Field : PayloadFields) {
auto Qualifier = GetPayloadQualifierForStage(Field, Info.Stage);
if (IsFieldWriteableInEarlierStage(Field, Info.Stage) &&
Qualifier == DXIL::PayloadAccessQualifier::Write) {
// The field is writeable in an earlier stage and pure write in this
// stage. Check if we find a write that dominates the exit of the
// function.
bool fieldHasDominatingWrite = false;
auto It = Info.WritesPerField.find(Field);
if (It != Info.WritesPerField.end()) {
for (auto &Write : It->second) {
fieldHasDominatingWrite =
DT.dominates(Write.Parent, &ShaderCFG.getExit());
if (fieldHasDominatingWrite)
break;
}
}
if (!fieldHasDominatingWrite) {
S.Diag(Info.Payload->getLocation(),
diag::warn_hlsl_payload_access_data_loss)
<< Field->getName() << GetStringForShaderStage(Info.Stage);
}
}
}
}
// Returns true if A is earlier than B in Parent
bool IsEarlierStatementAs(const Stmt *A, const Stmt *B,
const CFGBlock &Parent) {
for (auto Element : Parent) {
if (auto S = Element.getAs<CFGStmt>()) {
if (S->getStmt() == A)
return true;
if (S->getStmt() == B)
return false;
}
}
return true;
}
// Returns true if the write dominates payload use.
template <typename T>
bool WriteDominatesUse(const PayloadUse &Write, const T &Use,
DominatorTree &DT) {
if (Use.Parent == Write.Parent) {
// Use and write are in the same Block.
return IsEarlierStatementAs(Write.S, Use.S, *Use.Parent);
}
return DT.dominates(Write.Parent, Use.Parent);
}
// Emit warnings for payload reads.
void DiagnosePayloadReads(Sema &S, CFG &ShaderCFG, DominatorTree &DT,
const DxrShaderDiagnoseInfo &Info,
ArrayRef<FieldDecl *> NonReadableFields) {
for (FieldDecl *Field : NonReadableFields) {
auto ReadsFromField = Info.ReadsPerField.find(Field);
if (ReadsFromField == Info.ReadsPerField.end())
continue;
auto WritesToField = Info.WritesPerField.find(Field);
bool FieldHasWrites = WritesToField != Info.WritesPerField.end();
const auto &ReadsToDiagnose =
GetAllReadsReachedFromEntry(ShaderCFG, ReadsFromField->second);
for (auto &Read : ReadsToDiagnose) {
bool ReadIsDominatedByWrite = false;
if (FieldHasWrites) {
// We found a read to a field that needs diagnose.
// We do not want to warn about fields that read but are dominated by a
// write. Find writes that dominate the read. If we found one, ignore
// the read.
for (auto Write : WritesToField->second) {
ReadIsDominatedByWrite = WriteDominatesUse(Write, Read, DT);
if (ReadIsDominatedByWrite)
break;
}
}
if (ReadIsDominatedByWrite)
continue;
FieldDecl *MemField = cast<FieldDecl>(Read.Member->getMemberDecl());
auto Qualifier = GetPayloadQualifierForStage(MemField, Info.Stage);
if (Qualifier != DXIL::PayloadAccessQualifier::Read &&
Qualifier != DXIL::PayloadAccessQualifier::ReadWrite) {
S.Diag(Read.Member->getExprLoc(),
diag::warn_hlsl_payload_access_undef_read)
<< Field->getName() << GetStringForShaderStage(Info.Stage);
}
}
}
}
// Generic CFG traversal that performs PerElementAction on every Stmt in the
// CFG.
template <bool Backward, typename Action>
void TraverseCFG(const CFGBlock &Block, Action PerElementAction,
std::set<const CFGBlock *> &Visited) {
if (Visited.count(&Block))
return;
Visited.insert(&Block);
for (const auto &Element : Block) {
PerElementAction(Block, Element);
}
if (!Backward) {
for (auto I = Block.succ_begin(), E = Block.succ_end(); I != E; ++I) {
CFGBlock *Succ = *I;
if (!Succ)
continue;
TraverseCFG</*Backward=*/false>(*Succ, PerElementAction, Visited);
}
} else {
for (auto I = Block.pred_begin(), E = Block.pred_end(); I != E; ++I) {
CFGBlock *Pred = *I;
if (!Pred)
continue;
TraverseCFG<Backward>(*Pred, PerElementAction, Visited);
}
}
}
// Forward traverse the CFG and collect calls to TraceRay, HitObject::TraceRay
// and HitObject::Invoke.
void ForwardTraverseCFGAndCollectBuiltinCallsWithPayload(
const CFGBlock &Block, DxrShaderDiagnoseInfo &Info,
std::set<const CFGBlock *> &Visited) {
auto Action = [&Info](const CFGBlock &Block, const CFGElement &Element) {
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
CollectBuiltinCallsWithPayload(S->getStmt(), Info, &Block);
}
};
TraverseCFG<false>(Block, Action, Visited);
}
// Foward traverse the CFG and collect all reads and writes to the payload.
void ForwardTraverseCFGAndCollectReadsWrites(
const CFGBlock &StartBlock, DxrShaderDiagnoseInfo &Info,
std::set<const CFGBlock *> &Visited) {
auto Action = [&Info](const CFGBlock &Block, const CFGElement &Element) {
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
CollectReadsWritesAndCallsForPayload(S->getStmt(), Info, &Block);
}
};
TraverseCFG<false>(StartBlock, Action, Visited);
}
// Backward traverse the CFG and collect all reads and writes to the payload.
void BackwardTraverseCFGAndCollectReadsWrites(
const CFGBlock &StartBlock, DxrShaderDiagnoseInfo &Info,
std::set<const CFGBlock *> &Visited) {
auto Action = [&](const CFGBlock &Block, const CFGElement &Element) {
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
CollectReadsWritesAndCallsForPayload(S->getStmt(), Info, &Block);
}
};
TraverseCFG<true>(StartBlock, Action, Visited);
}
// Returns true if the Stmt uses the Payload.
bool IsPayloadArg(const Stmt *S, const Decl *Payload) {
if (const DeclRefExpr *Ref = dyn_cast<DeclRefExpr>(S)) {
const Decl *Decl = Ref->getDecl();
if (Decl == Payload)
return true;
}
for (auto C : S->children()) {
if (IsPayloadArg(C, Payload))
return true;
}
return false;
}
bool DiagnoseCallExprForExternal(Sema &S, const FunctionDecl *FD,
const CallExpr *CE,
const ParmVarDecl *Payload);
// Collects all writes that dominate a PayloadUse in a CallExpr
// and returns a set of the Fields accessed.
std::set<const FieldDecl *>
CollectDominatingWritesForCall(PayloadUse &Use, DxrShaderDiagnoseInfo &Info,
DominatorTree &DT) {
std::set<const FieldDecl *> FieldsToIgnore;
for (auto P : Info.WritesPerField) {
for (auto Write : P.second) {
bool WriteDominatesCallSite = WriteDominatesUse(Write, Use, DT);
if (WriteDominatesCallSite) {
FieldsToIgnore.insert(P.first);
break;
}
}
}
return FieldsToIgnore;
}
// Collects all reads that are reachable from a PayloadUse in a CallExpr
// and returns a set of the Fields accessed.
std::set<const FieldDecl *>
CollectReachableWritesForCall(PayloadUse &Use,
const DxrShaderDiagnoseInfo &Info) {
std::set<const FieldDecl *> FieldsToIgnore;
assert(Use.Parent);
const CFGBlock *Current = Use.Parent;
// Traverse the CFG beginning from the block of the call and collect all
// fields written to after the call. These fields must not be diagnosed with
// warnings about lost writes.
DxrShaderDiagnoseInfo TempInfo;
TempInfo.Payload = Info.Payload;
bool foundCall = false;
for (auto &Element : *Current) {
// Search for the Call in the block
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
if (S->getStmt() == Use.S) {
foundCall = true;
continue;
}
if (foundCall)
CollectReadsWritesAndCallsForPayload(S->getStmt(), TempInfo, Current);
}
}
for (auto I = Current->succ_begin(); I != Current->succ_end(); ++I) {
CFGBlock *Succ = *I;
if (!Succ)
continue;
std::set<const CFGBlock *> Visited;
ForwardTraverseCFGAndCollectReadsWrites(*Succ, TempInfo, Visited);
}
for (auto &p : TempInfo.WritesPerField)
FieldsToIgnore.insert(p.first);
return FieldsToIgnore;
}
// Emit diagnostics when the payload is used as an argument
// in a function call.
std::map<PayloadUse, std::vector<const FieldDecl *>>
DiagnosePayloadAsFunctionArg(
Sema &S, DxrShaderDiagnoseInfo &Info, DominatorTree &DT,
const std::set<const FieldDecl *> &ParentFieldsToIgnoreRead,
const std::set<const FieldDecl *> &ParentFieldsToIgnoreWrite,
std::set<const FunctionDecl *> VisitedFunctions) {
std::map<PayloadUse, std::vector<const FieldDecl *>> WrittenFieldsInCalls;
for (PayloadUse &Use : Info.PayloadAsCallArg) {
if (const CallExpr *Call = dyn_cast<CallExpr>(Use.S)) {
const Decl *Callee = Call->getCalleeDecl();
if (!Callee || !isa<FunctionDecl>(Callee))
continue;
const FunctionDecl *CalledFunction = cast<FunctionDecl>(Callee);
// Ignore trace calls here.
if (IsBuiltinWithPayload(CalledFunction)) {
Info.PayloadBuiltinCalls.push_back(
PayloadBuiltinCall{Call, Use.Parent});
continue;
}
// Handle external function calls
if (!CalledFunction->hasBody()) {
assert(isa<ParmVarDecl>(Info.Payload));
DiagnoseCallExprForExternal(S, CalledFunction, Call,
cast<ParmVarDecl>(Info.Payload));
continue;
}
if (VisitedFunctions.count(CalledFunction))
return WrittenFieldsInCalls;
VisitedFunctions.insert(CalledFunction);
DxrShaderDiagnoseInfo CalleeInfo;
for (unsigned i = 0; i < Call->getNumArgs(); ++i) {
const Expr *Arg = Call->getArg(i);
if (IsPayloadArg(Arg, Info.Payload)) {
CalleeInfo.Payload = CalledFunction->getParamDecl(i);
break;
}
}
if (CalleeInfo.Payload) {
CalleeInfo.funcDecl = CalledFunction;
CalleeInfo.Stage = Info.Stage;
auto FieldsToIgnoreRead = CollectDominatingWritesForCall(Use, Info, DT);
auto FieldsToIgnoreWrite = CollectReachableWritesForCall(Use, Info);
FieldsToIgnoreRead.insert(ParentFieldsToIgnoreRead.begin(),
ParentFieldsToIgnoreRead.end());
FieldsToIgnoreWrite.insert(ParentFieldsToIgnoreWrite.begin(),
ParentFieldsToIgnoreWrite.end());
WrittenFieldsInCalls[Use] =
DiagnosePayloadAccess(S, CalleeInfo, FieldsToIgnoreRead,
FieldsToIgnoreWrite, VisitedFunctions);
}
}
}
return WrittenFieldsInCalls;
}
// Collect all fields that cannot be accessed for the given shader stage.
// This function recurses into nested payload types.
void CollectNonAccessableFields(
RecordDecl *PayloadType, DXIL::PayloadAccessShaderStage Stage,
const std::set<const FieldDecl *> &FieldsToIgnoreRead,
const std::set<const FieldDecl *> &FieldsToIgnoreWrite,
std::vector<FieldDecl *> &NonWriteableFields,
std::vector<FieldDecl *> &NonReadableFields) {
for (FieldDecl *Field : PayloadType->fields()) {
QualType FieldType = Field->getType();
if (RecordDecl *FieldRecordDecl = FieldType->getAsCXXRecordDecl()) {
if (FieldRecordDecl->hasAttr<HLSLRayPayloadAttr>()) {
CollectNonAccessableFields(FieldRecordDecl, Stage, FieldsToIgnoreRead,
FieldsToIgnoreWrite, NonWriteableFields,
NonReadableFields);
continue;
}
}
auto Qualifier = GetPayloadQualifierForStage(Field, Stage);
// Diagnose writes only if they are not written heigher in the call-graph.
if (!FieldsToIgnoreWrite.count(Field)) {
if (Qualifier != DXIL::PayloadAccessQualifier::Write &&
Qualifier != DXIL::PayloadAccessQualifier::ReadWrite)
NonWriteableFields.push_back(Field);
}
// Diagnose reads only if they have no write heigher in the call-graph.
if (!FieldsToIgnoreRead.count(Field)) {
if (Qualifier != DXIL::PayloadAccessQualifier::Read &&
Qualifier != DXIL::PayloadAccessQualifier::ReadWrite)
NonReadableFields.push_back(Field);
}
}
}
void CollectAccessableFields(RecordDecl *PayloadType,
const std::vector<FieldDecl *> &NonWriteableFields,
const std::vector<FieldDecl *> &NonReadableFields,
std::vector<FieldDecl *> &WriteableFields,
std::vector<FieldDecl *> &ReadableFields) {
for (FieldDecl *Field : PayloadType->fields()) {
QualType FieldType = Field->getType();
if (RecordDecl *FieldRecordDecl = FieldType->getAsCXXRecordDecl()) {
// Skip nested payload types.
if (FieldRecordDecl->hasAttr<HLSLRayPayloadAttr>()) {
CollectAccessableFields(FieldRecordDecl, NonWriteableFields,
NonReadableFields, WriteableFields,
ReadableFields);
continue;
}
}
if (std::find(NonWriteableFields.begin(), NonWriteableFields.end(),
Field) == NonWriteableFields.end())
WriteableFields.push_back(Field);
if (std::find(NonReadableFields.begin(), NonReadableFields.end(), Field) ==
NonReadableFields.end())
ReadableFields.push_back(Field);
}
}
void HandlePayloadInitializer(DxrShaderDiagnoseInfo &Info) {
const VarDecl *Payload = Info.Payload;
const Expr *Init = Payload->getInit();
if (Init) {
// If the payload has an initializer, then handle all fields as
// written. Sema will check that the initializer is correct.
// We can handle all fields as written.
RecordDecl *PayloadType = GetPayloadType(Info.Payload);
for (FieldDecl *Field : PayloadType->fields()) {
Info.WritesPerField[Field].push_back(PayloadUse{Init, nullptr, nullptr});
}
}
}
// Emit diagnostics for this call to either TraceRay, HitObject::TraceRay or
// HitObject::Invoke.
void DiagnoseBuiltinCallWithPayload(Sema &S, const VarDecl *Payload,
const PayloadBuiltinCall &PldCall,
DominatorTree &DT) {
// For each call check if write(caller) fields are written.
const DXIL::PayloadAccessShaderStage CallerStage =
DXIL::PayloadAccessShaderStage::Caller;
std::vector<FieldDecl *> WriteableFields;
std::vector<FieldDecl *> NonWriteableFields;
std::vector<FieldDecl *> ReadableFields;
std::vector<FieldDecl *> NonReadableFields;
RecordDecl *PayloadType = GetPayloadType(Payload);
// Check if the payload type used for this trace call is a payload type
if (!PayloadType->hasAttr<HLSLRayPayloadAttr>()) {
S.Diag(Payload->getLocation(), diag::err_payload_requires_attribute)
<< PayloadType->getName();
return;
}
// Verify that the payload type is legal
const TypeDiagContext DiagContext = TypeDiagContext::PayloadParameters;
if (DiagnoseTypeElements(S, Payload->getLocation(), Payload->getType(),
DiagContext, DiagContext))
return;
if (!hlsl::IsHLSLCopyableAnnotatableRecord(Payload->getType())) {
S.Diag(Payload->getLocation(), diag::err_payload_attrs_must_be_udt)
<< /*payload|attributes|callable*/ 0 << /*parameter %2|type*/ 0
<< Payload;
return;
}
CollectNonAccessableFields(PayloadType, CallerStage, {}, {},
NonWriteableFields, NonReadableFields);
CollectAccessableFields(PayloadType, NonWriteableFields, NonReadableFields,
WriteableFields, ReadableFields);
// Find all writes to Payload that reaches the Trace
DxrShaderDiagnoseInfo TraceInfo;
TraceInfo.Payload = Payload;
// Handle initializers for the payload struct if any is present.
HandlePayloadInitializer(TraceInfo);
std::set<const CFGBlock *> Visited;
const CFGBlock *Parent = PldCall.Parent;
Visited.insert(Parent);
// Collect payload accesses in the same block until we reach the call
for (auto Element : *Parent) {
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
if (S->getStmt() == PldCall.Call)
break;
CollectReadsWritesAndCallsForPayload(S->getStmt(), TraceInfo, Parent);
}
}
for (auto I = Parent->pred_begin(); I != Parent->pred_end(); ++I) {
CFGBlock *Pred = *I;
if (!Pred)
continue;
BackwardTraverseCFGAndCollectReadsWrites(*Pred, TraceInfo, Visited);
}
int PldArgIdx = PldCall.Call->getNumArgs() - 1;
// Warn if a writeable field has not been written.
for (const FieldDecl *Field : WriteableFields) {
if (!TraceInfo.WritesPerField.count(Field)) {
S.Diag(PldCall.Call->getArg(PldArgIdx)->getExprLoc(),
diag::warn_hlsl_payload_access_no_write_for_trace_payload)
<< Field->getName();
}
}
// Warn if a written field is not write(caller)
for (const FieldDecl *Field : NonWriteableFields) {
if (TraceInfo.WritesPerField.count(Field)) {
S.Diag(
PldCall.Call->getArg(PldArgIdx)->getExprLoc(),
diag::warn_hlsl_payload_access_write_but_no_write_for_trace_payload)
<< Field->getName();
}
}
// After a trace call, collect all reads that are not dominated by another
// write warn if a field is not read(caller) but the value is read (undef
// read).
// Discard reads/writes from backward traversal.
TraceInfo.ReadsPerField.clear();
TraceInfo.WritesPerField.clear();
bool CallFound = false;
for (auto Element : *Parent) { // TODO: reverse iterate?
if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
if (S->getStmt() == PldCall.Call) {
CallFound = true;
continue;
}
if (CallFound)
CollectReadsWritesAndCallsForPayload(S->getStmt(), TraceInfo, Parent);
}
}
for (auto I = Parent->succ_begin(); I != Parent->succ_end(); ++I) {
CFGBlock *Pred = *I;
if (!Pred)
continue;
ForwardTraverseCFGAndCollectReadsWrites(*Pred, TraceInfo, Visited);
}
for (const FieldDecl *Field : ReadableFields) {
if (!TraceInfo.ReadsPerField.count(Field)) {
S.Diag(PldCall.Call->getArg(PldArgIdx)->getExprLoc(),
diag::warn_hlsl_payload_access_read_but_no_read_after_trace)
<< Field->getName();
}
}
for (const FieldDecl *Field : NonReadableFields) {
auto WritesToField = TraceInfo.WritesPerField.find(Field);
bool FieldHasWrites = WritesToField != TraceInfo.WritesPerField.end();
for (auto &Read : TraceInfo.ReadsPerField[Field]) {
bool ReadIsDominatedByWrite = false;
if (FieldHasWrites) {
// We found a read to a field that needs diagnose.
// We do not want to warn about fields that read but are dominated by
// a write. Find writes that dominate the read. If we found one,
// ignore the read.
for (auto Write : WritesToField->second) {
ReadIsDominatedByWrite = WriteDominatesUse(Write, Read, DT);
if (ReadIsDominatedByWrite)
break;
}
}
if (ReadIsDominatedByWrite)
continue;
S.Diag(Read.Member->getExprLoc(),
diag::warn_hlsl_payload_access_read_of_undef_after_trace)
<< Field->getName();
}
}
}
// Emit diagnostics for all calls to TraceRay, HitObject::TraceRay or
// HitObject::Invoke.
void DiagnoseBuiltinCallsWithPayload(Sema &S, CFG &ShaderCFG, DominatorTree &DT,
DxrShaderDiagnoseInfo &Info) {
// Collect calls with payload in the shader.
std::set<const CFGBlock *> Visited;
ForwardTraverseCFGAndCollectBuiltinCallsWithPayload(ShaderCFG.getEntry(),
Info, Visited);
std::set<const CallExpr *> Diagnosed;
for (const PayloadBuiltinCall &PldCall : Info.PayloadBuiltinCalls) {
if (Diagnosed.count(PldCall.Call))
continue;
Diagnosed.insert(PldCall.Call);
const VarDecl *Payload = GetPayloadParameterForBuiltinCall(PldCall.Call);
DiagnoseBuiltinCallWithPayload(S, Payload, PldCall, DT);
}
}
// Emit diagnostics for all access to the payload of a shader,
// and the input to TraceRay, HitObject::TraceRay or HitObject::Invoke calls.
std::vector<const FieldDecl *>
DiagnosePayloadAccess(Sema &S, DxrShaderDiagnoseInfo &Info,
const std::set<const FieldDecl *> &FieldsToIgnoreRead,
const std::set<const FieldDecl *> &FieldsToIgnoreWrite,
std::set<const FunctionDecl *> VisitedFunctions) {
clang::DominatorTree DT;
AnalysisDeclContextManager AnalysisManager;
AnalysisDeclContext *AnalysisContext =
AnalysisManager.getContext(Info.funcDecl);
CFG &TheCFG = *AnalysisContext->getCFG();
DT.buildDominatorTree(*AnalysisContext);
// Collect all Fields that gets written to return it back up through the
// recursion.
std::vector<const FieldDecl *> WrittenFields;
// Skip if we are in a RayGeneration shader without payload.
if (Info.Payload) {
std::vector<FieldDecl *> NonWriteableFields;
std::vector<FieldDecl *> NonReadableFields;
RecordDecl *PayloadType = GetPayloadType(Info.Payload);
if (!PayloadType)
return WrittenFields;