forked from microsoft/DirectXShaderCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScalarReplAggregatesHLSL.cpp
More file actions
6732 lines (6096 loc) · 248 KB
/
ScalarReplAggregatesHLSL.cpp
File metadata and controls
6732 lines (6096 loc) · 248 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
//===- ScalarReplAggregatesHLSL.cpp - Scalar Replacement of Aggregates ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// Based on ScalarReplAggregates.cpp. The difference is HLSL version will keep
// array so it can break up all structure.
//
//===----------------------------------------------------------------------===//
#include "dxc/DXIL/DxilConstants.h"
#include "dxc/DXIL/DxilModule.h"
#include "dxc/DXIL/DxilOperations.h"
#include "dxc/DXIL/DxilTypeSystem.h"
#include "dxc/DXIL/DxilUtil.h"
#include "dxc/HLSL/HLLowerUDT.h"
#include "dxc/HLSL/HLMatrixLowerHelper.h"
#include "dxc/HLSL/HLMatrixType.h"
#include "dxc/HLSL/HLModule.h"
#include "dxc/HLSL/HLOperations.h"
#include "dxc/HLSL/HLUtil.h"
#include "dxc/HlslIntrinsicOp.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include <deque>
#include <queue>
#include <unordered_map>
#include <unordered_set>
using namespace llvm;
using namespace hlsl;
#define DEBUG_TYPE "scalarreplhlsl"
STATISTIC(NumReplaced, "Number of allocas broken up");
namespace {
class SROA_Helper {
public:
// Split V into AllocaInsts with Builder and save the new AllocaInsts into
// Elts. Then do SROA on V.
static bool DoScalarReplacement(Value *V, std::vector<Value *> &Elts,
Type *&BrokenUpTy, uint64_t &NumInstances,
IRBuilder<> &Builder, bool bFlatVector,
bool hasPrecise, DxilTypeSystem &typeSys,
const DataLayout &DL,
SmallVector<Value *, 32> &DeadInsts,
DominatorTree *DT);
static bool
DoScalarReplacement(GlobalVariable *GV, std::vector<Value *> &Elts,
IRBuilder<> &Builder, bool bFlatVector, bool hasPrecise,
DxilTypeSystem &typeSys, const DataLayout &DL,
SmallVector<Value *, 32> &DeadInsts, DominatorTree *DT);
static unsigned GetEltAlign(unsigned ValueAlign, const DataLayout &DL,
Type *EltTy, unsigned Offset);
// Lower memcpy related to V.
static bool LowerMemcpy(Value *V, DxilFieldAnnotation *annotation,
DxilTypeSystem &typeSys, const DataLayout &DL,
DominatorTree *DT, bool bAllowReplace);
static void MarkEmptyStructUsers(Value *V,
SmallVector<Value *, 32> &DeadInsts);
static bool IsEmptyStructType(Type *Ty, DxilTypeSystem &typeSys);
private:
SROA_Helper(Value *V, ArrayRef<Value *> Elts,
SmallVector<Value *, 32> &DeadInsts, DxilTypeSystem &ts,
const DataLayout &dl, DominatorTree *dt)
: OldVal(V), NewElts(Elts), DeadInsts(DeadInsts), typeSys(ts), DL(dl),
DT(dt) {}
void RewriteForScalarRepl(Value *V, IRBuilder<> &Builder);
private:
// Must be a pointer type val.
Value *OldVal;
// Flattened elements for OldVal.
ArrayRef<Value *> NewElts;
SmallVector<Value *, 32> &DeadInsts;
DxilTypeSystem &typeSys;
const DataLayout &DL;
DominatorTree *DT;
void RewriteForConstExpr(ConstantExpr *user, IRBuilder<> &Builder);
void RewriteForGEP(GEPOperator *GEP, IRBuilder<> &Builder);
void RewriteForAddrSpaceCast(Value *user, IRBuilder<> &Builder);
void RewriteForLoad(LoadInst *loadInst);
void RewriteForStore(StoreInst *storeInst);
void RewriteMemIntrin(MemIntrinsic *MI, Value *OldV);
void RewriteCall(CallInst *CI);
void RewriteBitCast(BitCastInst *BCI);
void RewriteCallArg(CallInst *CI, unsigned ArgIdx, bool bIn, bool bOut);
};
} // namespace
static unsigned getNestedLevelInStruct(const Type *ty) {
unsigned lvl = 0;
while (ty->isStructTy()) {
if (ty->getStructNumElements() != 1)
break;
ty = ty->getStructElementType(0);
lvl++;
}
return lvl;
}
// After SROA'ing a given value into a series of elements,
// creates the debug info for the storage of the individual elements.
static void addDebugInfoForElements(Value *ParentVal, Type *BrokenUpTy,
uint64_t NumInstances,
ArrayRef<Value *> Elems,
const DataLayout &DatLayout,
DIBuilder *DbgBuilder) {
// Extract the data we need from the parent value,
// depending on whether it is an alloca, argument or global variable.
if (isa<GlobalVariable>(ParentVal)) {
llvm_unreachable(
"Not implemented: sroa debug info propagation for global vars.");
} else {
Type *ParentTy = nullptr;
if (AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal))
ParentTy = ParentAlloca->getAllocatedType();
else
ParentTy = cast<Argument>(ParentVal)->getType();
SmallVector<DbgDeclareInst *, 4> Declares;
llvm::FindAllocaDbgDeclare(ParentVal, Declares);
for (DbgDeclareInst *ParentDbgDeclare : Declares) {
unsigned ParentBitPieceOffset = 0;
DIVariable *ParentDbgVariable = nullptr;
DIExpression *ParentDbgExpr = nullptr;
DILocation *ParentDbgLocation = nullptr;
Instruction *DbgDeclareInsertPt = nullptr;
std::vector<DxilDIArrayDim> DIArrayDims;
// Get the bit piece offset
if ((ParentDbgExpr = ParentDbgDeclare->getExpression())) {
if (ParentDbgExpr->isBitPiece()) {
ParentBitPieceOffset = ParentDbgExpr->getBitPieceOffset();
}
}
ParentDbgVariable = ParentDbgDeclare->getVariable();
ParentDbgLocation = ParentDbgDeclare->getDebugLoc();
DbgDeclareInsertPt = ParentDbgDeclare;
// Read the extra layout metadata, if any
unsigned ParentBitPieceOffsetFromMD = 0;
if (DxilMDHelper::GetVariableDebugLayout(
ParentDbgDeclare, ParentBitPieceOffsetFromMD, DIArrayDims)) {
// The offset is redundant for local variables and only necessary for
// global variables.
DXASSERT(ParentBitPieceOffsetFromMD == ParentBitPieceOffset,
"Bit piece offset mismatch between llvm.dbg.declare and DXIL "
"metadata.");
}
// If the type that was broken up is nested in arrays,
// then each element will also be an array,
// but the continuity between successive elements of the original
// aggregate will have been broken, such that we must store the stride to
// rebuild it. For example: [2 x {i32, float}] => [2 x i32], [2 x float],
// each with stride 64 bits
if (NumInstances > 1 && Elems.size() > 1) {
// Existing dimensions already account for part of the stride
uint64_t NewDimNumElements = NumInstances;
for (const DxilDIArrayDim &ArrayDim : DIArrayDims) {
DXASSERT(NewDimNumElements % ArrayDim.NumElements == 0,
"Debug array stride is inconsistent with the number of "
"elements.");
NewDimNumElements /= ArrayDim.NumElements;
}
// Add a stride dimension
DxilDIArrayDim NewDIArrayDim = {};
NewDIArrayDim.StrideInBits =
(unsigned)DatLayout.getTypeAllocSizeInBits(BrokenUpTy);
NewDIArrayDim.NumElements = (unsigned)NewDimNumElements;
DIArrayDims.emplace_back(NewDIArrayDim);
} else {
DIArrayDims.clear();
}
// Create the debug info for each element
for (unsigned ElemIdx = 0; ElemIdx < Elems.size(); ++ElemIdx) {
// Figure out the offset of the element in the broken up type
unsigned ElemBitPieceOffset = ParentBitPieceOffset;
if (StructType *ParentStructTy = dyn_cast<StructType>(BrokenUpTy)) {
DXASSERT_NOMSG(Elems.size() == ParentStructTy->getNumElements());
ElemBitPieceOffset +=
(unsigned)DatLayout.getStructLayout(ParentStructTy)
->getElementOffsetInBits(ElemIdx);
} else if (VectorType *ParentVecTy = dyn_cast<VectorType>(BrokenUpTy)) {
DXASSERT_NOMSG(Elems.size() == ParentVecTy->getNumElements());
ElemBitPieceOffset += (unsigned)DatLayout.getTypeStoreSizeInBits(
ParentVecTy->getElementType()) *
ElemIdx;
} else if (ArrayType *ParentArrayTy = dyn_cast<ArrayType>(BrokenUpTy)) {
DXASSERT_NOMSG(Elems.size() == ParentArrayTy->getNumElements());
ElemBitPieceOffset += (unsigned)DatLayout.getTypeStoreSizeInBits(
ParentArrayTy->getElementType()) *
ElemIdx;
}
// The bit_piece can only represent the leading contiguous bytes.
// If strides are involved, we'll need additional metadata.
Type *ElemTy = Elems[ElemIdx]->getType()->getPointerElementType();
unsigned ElemBitPieceSize =
(unsigned)DatLayout.getTypeStoreSizeInBits(ElemTy);
for (const DxilDIArrayDim &ArrayDim : DIArrayDims)
ElemBitPieceSize /= ArrayDim.NumElements;
if (AllocaInst *ElemAlloca = dyn_cast<AllocaInst>(Elems[ElemIdx])) {
// Local variables get an @llvm.dbg.declare plus optional metadata for
// layout stride information.
DIExpression *ElemDbgExpr = nullptr;
if (ElemBitPieceOffset == 0 &&
DatLayout.getTypeAllocSizeInBits(ParentTy) == ElemBitPieceSize) {
ElemDbgExpr = DbgBuilder->createExpression();
} else {
ElemDbgExpr = DbgBuilder->createBitPieceExpression(
ElemBitPieceOffset, ElemBitPieceSize);
}
DXASSERT_NOMSG(DbgBuilder != nullptr);
DbgDeclareInst *EltDDI =
cast<DbgDeclareInst>(DbgBuilder->insertDeclare(
ElemAlloca, cast<DILocalVariable>(ParentDbgVariable),
ElemDbgExpr, ParentDbgLocation, DbgDeclareInsertPt));
if (!DIArrayDims.empty())
DxilMDHelper::SetVariableDebugLayout(EltDDI, ElemBitPieceOffset,
DIArrayDims);
} else {
llvm_unreachable("Non-AllocaInst SROA'd elements.");
}
}
}
}
}
/// Returns first GEP index that indexes a struct member, or 0 otherwise.
/// Ignores initial ptr index.
static unsigned FindFirstStructMemberIdxInGEP(GEPOperator *GEP) {
StructType *ST = dyn_cast<StructType>(
GEP->getPointerOperandType()->getPointerElementType());
int index = 1;
for (auto it = gep_type_begin(GEP), E = gep_type_end(GEP); it != E;
++it, ++index) {
if (ST) {
DXASSERT(!HLMatrixType::isa(ST) && !dxilutil::IsHLSLObjectType(ST),
"otherwise, indexing into hlsl object");
return index;
}
ST = dyn_cast<StructType>(it->getPointerElementType());
}
return 0;
}
/// Return true when ptr should not be SROA'd or copied, but used directly
/// by a function in its lowered form. Also collect uses for translation.
/// What is meant by directly here:
/// Possibly accessed through GEP array index or address space cast, but
/// not under another struct member (always allow SROA of outer struct).
typedef SmallMapVector<CallInst *, unsigned, 4> FunctionUseMap;
static unsigned IsPtrUsedByLoweredFn(Value *V, FunctionUseMap &CollectedUses) {
bool bFound = false;
for (Use &U : V->uses()) {
User *user = U.getUser();
if (CallInst *CI = dyn_cast<CallInst>(user)) {
unsigned foundIdx = (unsigned)-1;
Function *F = CI->getCalledFunction();
Type *Ty = V->getType();
if (F->isDeclaration() && !F->isIntrinsic() && Ty->isPointerTy()) {
HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(F);
if (group == HLOpcodeGroup::HLIntrinsic) {
unsigned opIdx = U.getOperandNo();
switch ((IntrinsicOp)hlsl::GetHLOpcode(CI)) {
// TODO: Lower these as well, along with function parameter types
// case IntrinsicOp::IOP_TraceRay:
// if (opIdx != HLOperandIndex::kTraceRayPayLoadOpIdx)
// continue;
// break;
// case IntrinsicOp::IOP_ReportHit:
// if (opIdx != HLOperandIndex::kReportIntersectionAttributeOpIdx)
// continue;
// break;
// case IntrinsicOp::IOP_CallShader:
// if (opIdx != HLOperandIndex::kCallShaderPayloadOpIdx)
// continue;
// break;
case IntrinsicOp::IOP_DispatchMesh:
if (opIdx != HLOperandIndex::kDispatchMeshOpPayload)
continue;
break;
default:
continue;
}
foundIdx = opIdx;
// TODO: Lower these as well, along with function parameter types
//} else if (group == HLOpcodeGroup::NotHL) {
// foundIdx = U.getOperandNo();
}
}
if (foundIdx != (unsigned)-1) {
bFound = true;
auto insRes = CollectedUses.insert(std::make_pair(CI, foundIdx));
DXASSERT_LOCALVAR(insRes, insRes.second,
"otherwise, multiple uses in single call");
}
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(user)) {
// Not what we are looking for if GEP result is not [array of] struct.
// If use is under struct member, we can still SROA the outer struct.
if (!dxilutil::StripArrayTypes(GEP->getType()->getPointerElementType())
->isStructTy() ||
FindFirstStructMemberIdxInGEP(GEP))
continue;
if (IsPtrUsedByLoweredFn(user, CollectedUses))
bFound = true;
} else if (isa<AddrSpaceCastInst>(user)) {
if (IsPtrUsedByLoweredFn(user, CollectedUses))
bFound = true;
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(user)) {
unsigned opcode = CE->getOpcode();
if (opcode == Instruction::AddrSpaceCast)
if (IsPtrUsedByLoweredFn(user, CollectedUses))
bFound = true;
}
}
return bFound;
}
/// Rewrite call to natively use an argument with addrspace cast/bitcast
static CallInst *RewriteIntrinsicCallForCastedArg(CallInst *CI,
unsigned argIdx) {
Function *F = CI->getCalledFunction();
HLOpcodeGroup group = GetHLOpcodeGroupByName(F);
DXASSERT_NOMSG(group == HLOpcodeGroup::HLIntrinsic);
unsigned opcode = GetHLOpcode(CI);
SmallVector<Type *, 8> newArgTypes(CI->getFunctionType()->param_begin(),
CI->getFunctionType()->param_end());
SmallVector<Value *, 8> newArgs(CI->arg_operands());
Value *newArg = CI->getOperand(argIdx)->stripPointerCasts();
newArgTypes[argIdx] = newArg->getType();
newArgs[argIdx] = newArg;
FunctionType *newFuncTy =
FunctionType::get(CI->getType(), newArgTypes, false);
Function *newF =
GetOrCreateHLFunction(*F->getParent(), newFuncTy, group, opcode,
F->getAttributes().getFnAttributes());
IRBuilder<> Builder(CI);
return Builder.CreateCall(newF, newArgs);
}
/// Translate pointer for cases where intrinsics use UDT pointers directly
/// Return existing or new ptr if needs preserving,
/// otherwise nullptr to proceed with existing checks and SROA.
static Value *TranslatePtrIfUsedByLoweredFn(Value *Ptr,
DxilTypeSystem &TypeSys) {
if (!Ptr->getType()->isPointerTy())
return nullptr;
Type *Ty = Ptr->getType()->getPointerElementType();
SmallVector<unsigned, 4> outerToInnerLengths;
Ty = dxilutil::StripArrayTypes(Ty, &outerToInnerLengths);
if (!Ty->isStructTy())
return nullptr;
if (HLMatrixType::isa(Ty) || dxilutil::IsHLSLObjectType(Ty))
return nullptr;
unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
FunctionUseMap FunctionUses;
if (!IsPtrUsedByLoweredFn(Ptr, FunctionUses))
return nullptr;
// Translate vectors to arrays in type, but don't SROA
Type *NewTy = GetLoweredUDT(cast<StructType>(Ty), &TypeSys);
// No work to do here, but prevent SROA.
if (Ty == NewTy && AddrSpace != DXIL::kTGSMAddrSpace)
return Ptr;
// If type changed, replace value, otherwise casting may still
// require a rewrite of the calls.
Value *NewPtr = Ptr;
if (Ty != NewTy) {
NewTy = dxilutil::WrapInArrayTypes(NewTy, outerToInnerLengths);
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Module &M = *GV->getParent();
// Rewrite init expression for arrays instead of vectors
Constant *Init = GV->hasInitializer() ? GV->getInitializer()
: UndefValue::get(Ptr->getType());
Constant *NewInit = TranslateInitForLoweredUDT(Init, NewTy, &TypeSys);
// Replace with new GV, and rewrite vector load/store users
GlobalVariable *NewGV = new GlobalVariable(
M, NewTy, GV->isConstant(), GV->getLinkage(), NewInit, GV->getName(),
/*InsertBefore*/ GV, GV->getThreadLocalMode(), AddrSpace);
NewPtr = NewGV;
} else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
IRBuilder<> Builder(AI);
AllocaInst *NewAI = Builder.CreateAlloca(NewTy, nullptr, AI->getName());
NewPtr = NewAI;
} else {
DXASSERT(false, "Ptr must be global or alloca");
}
// This will rewrite vector load/store users
// and insert bitcasts for CallInst users
ReplaceUsesForLoweredUDT(Ptr, NewPtr);
}
// Rewrite the HLIntrinsic calls
for (auto it : FunctionUses) {
CallInst *CI = it.first;
HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
if (group == HLOpcodeGroup::NotHL)
continue;
CallInst *newCI = RewriteIntrinsicCallForCastedArg(CI, it.second);
CI->replaceAllUsesWith(newCI);
CI->eraseFromParent();
}
return NewPtr;
}
/// isHomogeneousAggregate - Check if type T is a struct or array containing
/// elements of the same type (which is always true for arrays). If so,
/// return true with NumElts and EltTy set to the number of elements and the
/// element type, respectively.
static bool isHomogeneousAggregate(Type *T, unsigned &NumElts, Type *&EltTy) {
if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
NumElts = AT->getNumElements();
EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
return true;
}
if (StructType *ST = dyn_cast<StructType>(T)) {
NumElts = ST->getNumContainedTypes();
EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
for (unsigned n = 1; n < NumElts; ++n) {
if (ST->getContainedType(n) != EltTy)
return false;
}
return true;
}
return false;
}
/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
/// "homogeneous" aggregates with the same element type and number of elements.
static bool isCompatibleAggregate(Type *T1, Type *T2) {
if (T1 == T2)
return true;
unsigned NumElts1, NumElts2;
Type *EltTy1, *EltTy2;
if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
isHomogeneousAggregate(T2, NumElts2, EltTy2) && NumElts1 == NumElts2 &&
EltTy1 == EltTy2)
return true;
return false;
}
/// LoadVectorArray - Load vector array like [2 x <4 x float>] from
/// arrays like 4 [2 x float] or struct array like
/// [2 x { <4 x float>, < 4 x uint> }]
/// from arrays like [ 2 x <4 x float> ], [ 2 x <4 x uint> ].
static Value *LoadVectorOrStructArray(ArrayType *AT, ArrayRef<Value *> NewElts,
SmallVector<Value *, 8> &idxList,
IRBuilder<> &Builder) {
Type *EltTy = AT->getElementType();
Value *retVal = llvm::UndefValue::get(AT);
Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
uint32_t arraySize = AT->getNumElements();
for (uint32_t i = 0; i < arraySize; i++) {
Constant *idx = ConstantInt::get(i32Ty, i);
idxList.emplace_back(idx);
if (ArrayType *EltAT = dyn_cast<ArrayType>(EltTy)) {
Value *EltVal = LoadVectorOrStructArray(EltAT, NewElts, idxList, Builder);
retVal = Builder.CreateInsertValue(retVal, EltVal, i);
} else {
assert((EltTy->isVectorTy() || EltTy->isStructTy()) &&
"must be a vector or struct type");
bool isVectorTy = EltTy->isVectorTy();
Value *retVec = llvm::UndefValue::get(EltTy);
if (isVectorTy) {
for (uint32_t c = 0; c < EltTy->getVectorNumElements(); c++) {
Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
Value *elt = Builder.CreateLoad(GEP);
retVec = Builder.CreateInsertElement(retVec, elt, c);
}
} else {
for (uint32_t c = 0; c < EltTy->getStructNumElements(); c++) {
Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
Value *elt = Builder.CreateLoad(GEP);
retVec = Builder.CreateInsertValue(retVec, elt, c);
}
}
retVal = Builder.CreateInsertValue(retVal, retVec, i);
}
idxList.pop_back();
}
return retVal;
}
/// LoadVectorArray - Store vector array like [2 x <4 x float>] to
/// arrays like 4 [2 x float] or struct array like
/// [2 x { <4 x float>, < 4 x uint> }]
/// from arrays like [ 2 x <4 x float> ], [ 2 x <4 x uint> ].
static void StoreVectorOrStructArray(ArrayType *AT, Value *val,
ArrayRef<Value *> NewElts,
SmallVector<Value *, 8> &idxList,
IRBuilder<> &Builder) {
Type *EltTy = AT->getElementType();
Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
uint32_t arraySize = AT->getNumElements();
for (uint32_t i = 0; i < arraySize; i++) {
Value *elt = Builder.CreateExtractValue(val, i);
Constant *idx = ConstantInt::get(i32Ty, i);
idxList.emplace_back(idx);
if (ArrayType *EltAT = dyn_cast<ArrayType>(EltTy)) {
StoreVectorOrStructArray(EltAT, elt, NewElts, idxList, Builder);
} else {
assert((EltTy->isVectorTy() || EltTy->isStructTy()) &&
"must be a vector or struct type");
bool isVectorTy = EltTy->isVectorTy();
if (isVectorTy) {
for (uint32_t c = 0; c < EltTy->getVectorNumElements(); c++) {
Value *component = Builder.CreateExtractElement(elt, c);
Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
Builder.CreateStore(component, GEP);
}
} else {
for (uint32_t c = 0; c < EltTy->getStructNumElements(); c++) {
Value *field = Builder.CreateExtractValue(elt, c);
Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
Builder.CreateStore(field, GEP);
}
}
}
idxList.pop_back();
}
}
namespace {
// Simple struct to split memcpy into ld/st
struct MemcpySplitter {
llvm::LLVMContext &m_context;
DxilTypeSystem &m_typeSys;
public:
MemcpySplitter(llvm::LLVMContext &context, DxilTypeSystem &typeSys)
: m_context(context), m_typeSys(typeSys) {}
void Split(llvm::Function &F);
static void PatchMemCpyWithZeroIdxGEP(Module &M);
static void PatchMemCpyWithZeroIdxGEP(MemCpyInst *MI, const DataLayout &DL);
static void SplitMemCpy(MemCpyInst *MI, const DataLayout &DL,
DxilFieldAnnotation *fieldAnnotation,
DxilTypeSystem &typeSys,
const bool bEltMemCpy = true);
};
// Copy data from srcPtr to destPtr.
void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
llvm::SmallVector<llvm::Value *, 16> &idxList,
IRBuilder<> &Builder) {
if (idxList.size() > 1) {
DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
}
llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
Builder.CreateStore(ld, DestPtr);
}
// Copy srcVal to destPtr.
void SimpleValCopy(Value *DestPtr, Value *SrcVal,
llvm::SmallVector<llvm::Value *, 16> &idxList,
IRBuilder<> &Builder) {
Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
Value *Val = SrcVal;
// Skip beginning pointer type.
for (unsigned i = 1; i < idxList.size(); i++) {
ConstantInt *idx = cast<ConstantInt>(idxList[i]);
Type *Ty = Val->getType();
if (Ty->isAggregateType()) {
Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
}
}
Builder.CreateStore(Val, DestGEP);
}
void SimpleCopy(Value *Dest, Value *Src,
llvm::SmallVector<llvm::Value *, 16> &idxList,
IRBuilder<> &Builder) {
if (Src->getType()->isPointerTy())
SimplePtrCopy(Dest, Src, idxList, Builder);
else
SimpleValCopy(Dest, Src, idxList, Builder);
}
Value *CreateMergedGEP(Value *Ptr, SmallVector<Value *, 16> &idxList,
IRBuilder<> &Builder) {
if (GEPOperator *GEPPtr = dyn_cast<GEPOperator>(Ptr)) {
SmallVector<Value *, 2> IdxList(GEPPtr->idx_begin(), GEPPtr->idx_end());
// skip idxLIst.begin() because it is included in GEPPtr idx.
IdxList.append(idxList.begin() + 1, idxList.end());
return Builder.CreateInBoundsGEP(GEPPtr->getPointerOperand(), IdxList);
} else {
return Builder.CreateInBoundsGEP(Ptr, idxList);
}
}
void EltMemCpy(Type *Ty, Value *Dest, Value *Src,
SmallVector<Value *, 16> &idxList, IRBuilder<> &Builder,
const DataLayout &DL) {
Value *DestGEP = CreateMergedGEP(Dest, idxList, Builder);
Value *SrcGEP = CreateMergedGEP(Src, idxList, Builder);
unsigned size = DL.getTypeAllocSize(Ty);
Builder.CreateMemCpy(DestGEP, SrcGEP, size, /* Align */ 1);
}
bool IsMemCpyTy(Type *Ty, DxilTypeSystem &typeSys) {
if (!Ty->isAggregateType())
return false;
if (HLMatrixType::isa(Ty))
return false;
if (dxilutil::IsHLSLObjectType(Ty))
return false;
if (StructType *ST = dyn_cast<StructType>(Ty)) {
DxilStructAnnotation *STA = typeSys.GetStructAnnotation(ST);
DXASSERT(STA, "require annotation here");
if (STA->IsEmptyStruct())
return false;
// Skip 1 element struct which the element is basic type.
// Because create memcpy will create gep on the struct, memcpy the basic
// type only.
if (ST->getNumElements() == 1)
return IsMemCpyTy(ST->getElementType(0), typeSys);
}
return true;
}
// Split copy into ld/st.
void SplitCpy(Type *Ty, Value *Dest, Value *Src,
SmallVector<Value *, 16> &idxList, IRBuilder<> &Builder,
const DataLayout &DL, DxilTypeSystem &typeSys,
const DxilFieldAnnotation *fieldAnnotation,
const bool bEltMemCpy = true) {
if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
Constant *idx = Constant::getIntegerValue(
IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
idxList.emplace_back(idx);
SplitCpy(PT->getElementType(), Dest, Src, idxList, Builder, DL, typeSys,
fieldAnnotation, bEltMemCpy);
idxList.pop_back();
} else if (HLMatrixType::isa(Ty)) {
// If no fieldAnnotation, use row major as default.
// Only load then store immediately should be fine.
bool bRowMajor = true;
if (fieldAnnotation) {
DXASSERT(fieldAnnotation->HasMatrixAnnotation(),
"must has matrix annotation");
bRowMajor = fieldAnnotation->GetMatrixAnnotation().Orientation ==
MatrixOrientation::RowMajor;
}
Module *M = Builder.GetInsertPoint()->getModule();
Value *DestMatPtr;
Value *SrcMatPtr;
if (idxList.size() == 1 &&
idxList[0] == ConstantInt::get(IntegerType::get(Ty->getContext(), 32),
APInt(32, 0))) {
// Avoid creating GEP(0)
DestMatPtr = Dest;
SrcMatPtr = Src;
} else {
DestMatPtr = Builder.CreateInBoundsGEP(Dest, idxList);
SrcMatPtr = Builder.CreateInBoundsGEP(Src, idxList);
}
HLMatLoadStoreOpcode loadOp = bRowMajor ? HLMatLoadStoreOpcode::RowMatLoad
: HLMatLoadStoreOpcode::ColMatLoad;
HLMatLoadStoreOpcode storeOp = bRowMajor
? HLMatLoadStoreOpcode::RowMatStore
: HLMatLoadStoreOpcode::ColMatStore;
Value *Load = HLModule::EmitHLOperationCall(
Builder, HLOpcodeGroup::HLMatLoadStore, static_cast<unsigned>(loadOp),
Ty, {SrcMatPtr}, *M);
HLModule::EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
static_cast<unsigned>(storeOp), Ty,
{DestMatPtr, Load}, *M);
} else if (StructType *ST = dyn_cast<StructType>(Ty)) {
if (dxilutil::IsHLSLObjectType(ST)) {
// Avoid split HLSL object.
SimpleCopy(Dest, Src, idxList, Builder);
return;
}
// Built-in structs have no type annotation
DxilStructAnnotation *STA = typeSys.GetStructAnnotation(ST);
if (STA && STA->IsEmptyStruct())
return;
for (uint32_t i = 0; i < ST->getNumElements(); i++) {
llvm::Type *ET = ST->getElementType(i);
Constant *idx = llvm::Constant::getIntegerValue(
IntegerType::get(Ty->getContext(), 32), APInt(32, i));
idxList.emplace_back(idx);
if (bEltMemCpy && IsMemCpyTy(ET, typeSys)) {
EltMemCpy(ET, Dest, Src, idxList, Builder, DL);
} else {
DxilFieldAnnotation *EltAnnotation =
STA ? &STA->GetFieldAnnotation(i) : nullptr;
SplitCpy(ET, Dest, Src, idxList, Builder, DL, typeSys, EltAnnotation,
bEltMemCpy);
}
idxList.pop_back();
}
} else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Type *ET = AT->getElementType();
for (uint32_t i = 0; i < AT->getNumElements(); i++) {
Constant *idx = Constant::getIntegerValue(
IntegerType::get(Ty->getContext(), 32), APInt(32, i));
idxList.emplace_back(idx);
if (bEltMemCpy && IsMemCpyTy(ET, typeSys)) {
EltMemCpy(ET, Dest, Src, idxList, Builder, DL);
} else {
SplitCpy(ET, Dest, Src, idxList, Builder, DL, typeSys, fieldAnnotation,
bEltMemCpy);
}
idxList.pop_back();
}
} else {
SimpleCopy(Dest, Src, idxList, Builder);
}
}
// Given a pointer to a value, produces a list of pointers to
// all scalar elements of that value and their field annotations, at any nesting
// level.
void SplitPtr(
Value *Ptr, // The root value pointer
SmallVectorImpl<Value *> &IdxList, // GEP indices stack during recursion
Type *Ty, // Type at the current GEP indirection level
const DxilFieldAnnotation
&Annotation, // Annotation at the current GEP indirection level
SmallVectorImpl<Value *>
&EltPtrList, // Accumulates pointers to each element found
SmallVectorImpl<const DxilFieldAnnotation *>
&EltAnnotationList, // Accumulates field annotations for each element
// found
DxilTypeSystem &TypeSys, IRBuilder<> &Builder) {
if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
Constant *idx = Constant::getIntegerValue(
IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
IdxList.emplace_back(idx);
SplitPtr(Ptr, IdxList, PT->getElementType(), Annotation, EltPtrList,
EltAnnotationList, TypeSys, Builder);
IdxList.pop_back();
return;
}
if (StructType *ST = dyn_cast<StructType>(Ty)) {
if (!HLMatrixType::isa(Ty) && !dxilutil::IsHLSLObjectType(ST)) {
const DxilStructAnnotation *SA = TypeSys.GetStructAnnotation(ST);
for (uint32_t i = 0; i < ST->getNumElements(); i++) {
llvm::Type *EltTy = ST->getElementType(i);
Constant *idx = llvm::Constant::getIntegerValue(
IntegerType::get(Ty->getContext(), 32), APInt(32, i));
IdxList.emplace_back(idx);
SplitPtr(Ptr, IdxList, EltTy, SA->GetFieldAnnotation(i), EltPtrList,
EltAnnotationList, TypeSys, Builder);
IdxList.pop_back();
}
return;
}
}
if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
if (AT->getArrayNumElements() == 0) {
// Skip cases like [0 x %struct], nothing to copy
return;
}
Type *ElTy = AT->getElementType();
SmallVector<ArrayType *, 4> nestArrayTys;
nestArrayTys.emplace_back(AT);
// support multi level of array
while (ElTy->isArrayTy()) {
ArrayType *ElAT = cast<ArrayType>(ElTy);
nestArrayTys.emplace_back(ElAT);
ElTy = ElAT->getElementType();
}
if (ElTy->isStructTy() && !HLMatrixType::isa(ElTy)) {
DXASSERT(0, "Not support array of struct when split pointers.");
return;
}
}
// Return a pointer to the current element and its annotation
Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
EltPtrList.emplace_back(GEP);
EltAnnotationList.emplace_back(&Annotation);
}
// Support case when bitcast (gep ptr, 0,0) is transformed into bitcast ptr.
unsigned MatchSizeByCheckElementType(Type *Ty, const DataLayout &DL,
unsigned size, unsigned level) {
unsigned ptrSize = DL.getTypeAllocSize(Ty);
// Size match, return current level.
if (ptrSize == size) {
// Do not go deeper for matrix or object.
if (HLMatrixType::isa(Ty) || dxilutil::IsHLSLObjectType(Ty))
return level;
// For struct, go deeper if size not change.
// This will leave memcpy to deeper level when flatten.
if (StructType *ST = dyn_cast<StructType>(Ty)) {
if (ST->getNumElements() == 1) {
return MatchSizeByCheckElementType(ST->getElementType(0), DL, size,
level + 1);
}
}
// Don't do this for array.
// Array will be flattened as struct of array.
return level;
}
// Add ZeroIdx cannot make ptrSize bigger.
if (ptrSize < size)
return 0;
// ptrSize > size.
// Try to use element type to make size match.
if (StructType *ST = dyn_cast<StructType>(Ty)) {
return MatchSizeByCheckElementType(ST->getElementType(0), DL, size,
level + 1);
} else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
return MatchSizeByCheckElementType(AT->getElementType(), DL, size,
level + 1);
} else {
return 0;
}
}
void PatchZeroIdxGEP(Value *Ptr, Value *RawPtr, MemCpyInst *MI, unsigned level,
IRBuilder<> &Builder) {
Value *zeroIdx = Builder.getInt32(0);
Value *GEP = nullptr;
if (GEPOperator *GEPPtr = dyn_cast<GEPOperator>(Ptr)) {
SmallVector<Value *, 2> IdxList(GEPPtr->idx_begin(), GEPPtr->idx_end());
// level not + 1 because it is included in GEPPtr idx.
IdxList.append(level, zeroIdx);
GEP = Builder.CreateInBoundsGEP(GEPPtr->getPointerOperand(), IdxList);
} else {
SmallVector<Value *, 2> IdxList(level + 1, zeroIdx);
GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
}
// Use BitCastInst::Create to prevent idxList from being optimized.
CastInst *Cast =
BitCastInst::Create(Instruction::BitCast, GEP, RawPtr->getType());
Builder.Insert(Cast);
MI->replaceUsesOfWith(RawPtr, Cast);
// Remove RawPtr if possible.
if (RawPtr->user_empty()) {
if (Instruction *I = dyn_cast<Instruction>(RawPtr)) {
I->eraseFromParent();
}
}
}
void MemcpySplitter::PatchMemCpyWithZeroIdxGEP(MemCpyInst *MI,
const DataLayout &DL) {
Value *Dest = MI->getRawDest();
Value *Src = MI->getRawSource();
// Only remove one level bitcast generated from inline.
if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
Dest = BC->getOperand(0);
if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
Src = BC->getOperand(0);
IRBuilder<> Builder(MI);
ConstantInt *zero = Builder.getInt32(0);
Type *DestTy = Dest->getType()->getPointerElementType();
Type *SrcTy = Src->getType()->getPointerElementType();
// Support case when bitcast (gep ptr, 0,0) is transformed into
// bitcast ptr.
// Also replace (gep ptr, 0) with ptr.
ConstantInt *Length = cast<ConstantInt>(MI->getLength());
unsigned size = Length->getLimitedValue();
if (unsigned level = MatchSizeByCheckElementType(DestTy, DL, size, 0)) {
PatchZeroIdxGEP(Dest, MI->getRawDest(), MI, level, Builder);
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Dest)) {
if (GEP->getNumIndices() == 1) {
Value *idx = *GEP->idx_begin();
if (idx == zero) {
GEP->replaceAllUsesWith(GEP->getPointerOperand());
}
}
}
if (unsigned level = MatchSizeByCheckElementType(SrcTy, DL, size, 0)) {
PatchZeroIdxGEP(Src, MI->getRawSource(), MI, level, Builder);
} else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
if (GEP->getNumIndices() == 1) {
Value *idx = *GEP->idx_begin();
if (idx == zero) {
GEP->replaceAllUsesWith(GEP->getPointerOperand());
}
}
}
}
void MemcpySplitter::PatchMemCpyWithZeroIdxGEP(Module &M) {
const DataLayout &DL = M.getDataLayout();
for (Function &F : M.functions()) {
for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
// Avoid invalidating the iterator.
Instruction *I = BI++;
if (MemCpyInst *MI = dyn_cast<MemCpyInst>(I)) {
PatchMemCpyWithZeroIdxGEP(MI, DL);
}
}
}
}
}
void DeleteMemcpy(MemCpyInst *MI) {
Value *Op0 = MI->getOperand(0);
Value *Op1 = MI->getOperand(1);
// delete memcpy