LLVM 17.0.0git
SIISelLowering.cpp
Go to the documentation of this file.
1//===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Custom DAG lowering for SI
11//
12//===----------------------------------------------------------------------===//
13
14#include "SIISelLowering.h"
15#include "AMDGPU.h"
16#include "AMDGPUInstrInfo.h"
17#include "AMDGPUTargetMachine.h"
19#include "SIRegisterInfo.h"
21#include "llvm/ADT/Statistic.h"
33#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/IntrinsicsAMDGPU.h"
36#include "llvm/IR/IntrinsicsR600.h"
38#include "llvm/Support/ModRef.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "si-lower"
44
45STATISTIC(NumTailCalls, "Number of tail calls");
46
48 "amdgpu-disable-loop-alignment",
49 cl::desc("Do not align and prefetch loops"),
50 cl::init(false));
51
53 "amdgpu-use-divergent-register-indexing",
55 cl::desc("Use indirect register addressing for divergent indexes"),
56 cl::init(false));
57
58static bool hasFP32Denormals(const MachineFunction &MF) {
60 return Info->getMode().allFP32Denormals();
61}
62
63static bool hasFP64FP16Denormals(const MachineFunction &MF) {
65 return Info->getMode().allFP64FP16Denormals();
66}
67
68static unsigned findFirstFreeSGPR(CCState &CCInfo) {
69 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
70 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
71 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
72 return AMDGPU::SGPR0 + Reg;
73 }
74 }
75 llvm_unreachable("Cannot allocate sgpr");
76}
77
79 const GCNSubtarget &STI)
81 Subtarget(&STI) {
82 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
83 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
84
85 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
86 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
87
88 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
89
90 const SIRegisterInfo *TRI = STI.getRegisterInfo();
91 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
92
93 addRegisterClass(MVT::f64, V64RegClass);
94 addRegisterClass(MVT::v2f32, V64RegClass);
95
96 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
97 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
98
99 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
100 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
101
102 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
103 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
104
105 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
106 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
107
108 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
109 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
110
111 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
112 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
113
114 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
115 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
116
117 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
118 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
119
120 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
121 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
122
123 addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
124 addRegisterClass(MVT::v9f32, TRI->getVGPRClassForBitWidth(288));
125
126 addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
127 addRegisterClass(MVT::v10f32, TRI->getVGPRClassForBitWidth(320));
128
129 addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
130 addRegisterClass(MVT::v11f32, TRI->getVGPRClassForBitWidth(352));
131
132 addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
133 addRegisterClass(MVT::v12f32, TRI->getVGPRClassForBitWidth(384));
134
135 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
136 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
137
138 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
139 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
140
141 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
142 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
143
144 if (Subtarget->has16BitInsts()) {
145 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
146 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
147
148 // Unless there are also VOP3P operations, not operations are really legal.
149 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
150 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
151 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
152 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
153 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
154 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
155 addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
156 addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
157 }
158
159 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
160 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
161
163
164 // The boolean content concept here is too inflexible. Compares only ever
165 // really produce a 1-bit result. Any copy/extend from these will turn into a
166 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
167 // it's what most targets use.
170
171 // We need to custom lower vector stores from local memory
177 Custom);
178
184 Custom);
185
202
210
212
217
220
224
229 Expand);
234 Expand);
235
239 Custom);
240
244
246
248
250 Expand);
251
252#if 0
254#endif
255
256 // We only support LOAD/STORE and vector manipulation ops for vectors
257 // with > 4 elements.
258 for (MVT VT :
266 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
267 switch (Op) {
268 case ISD::LOAD:
269 case ISD::STORE:
271 case ISD::BITCAST:
272 case ISD::UNDEF:
277 case ISD::IS_FPCLASS:
278 break;
281 setOperationAction(Op, VT, Custom);
282 break;
283 default:
284 setOperationAction(Op, VT, Expand);
285 break;
286 }
287 }
288 }
289
291
292 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
293 // is expanded to avoid having two separate loops in case the index is a VGPR.
294
295 // Most operations are naturally 32-bit vector operations. We only support
296 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
297 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
300
303
306
309 }
310
311 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
314
317
320
323 }
324
325 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
328
331
334
337 }
338
339 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
342
345
348
351 }
352
353 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
356
359
362
365 }
366
369 Expand);
370
372
373 // Avoid stack access for these.
374 // TODO: Generalize to more vector types.
378 Custom);
379
380 // Deal with vec3 vector operations when widened to vec4.
383
384 // Deal with vec5/6/7 vector operations when widened to vec8.
390 Custom);
391
392 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
393 // and output demarshalling
395
396 // We can't return success/failure, only the old value,
397 // let LLVM add the comparison
399 Expand);
400
402
404
405 // FIXME: This should be narrowed to i32, but that only happens if i64 is
406 // illegal.
407 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
409
410 // On SI this is s_memtime and s_memrealtime on VI.
413
414 if (Subtarget->has16BitInsts()) {
417 }
418
419 if (Subtarget->hasMadMacF32Insts())
421
422 if (!Subtarget->hasBFI())
423 // fcopysign can be done in a single instruction with BFI.
425
426 if (!Subtarget->hasBCNT(32))
428
429 if (!Subtarget->hasBCNT(64))
431
432 if (Subtarget->hasFFBH())
434
435 if (Subtarget->hasFFBL())
437
438 // We only really have 32-bit BFE instructions (and 16-bit on VI).
439 //
440 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
441 // effort to match them now. We want this to be false for i64 cases when the
442 // extraction isn't restricted to the upper or lower half. Ideally we would
443 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
444 // span the midpoint are probably relatively rare, so don't worry about them
445 // for now.
446 if (Subtarget->hasBFE())
448
449 // Clamp modifier on add/sub
450 if (Subtarget->hasIntClamp())
452
453 if (Subtarget->hasAddNoCarry())
455 Legal);
456
458 Custom);
459
460 // These are really only legal for ieee_mode functions. We should be avoiding
461 // them for functions that don't have ieee_mode enabled, so just say they are
462 // legal.
465
466 if (Subtarget->haveRoundOpsF64())
468 else
471
473
476
479
480 if (Subtarget->has16BitInsts()) {
483 MVT::i16, Legal);
484
486
489
493 ISD::CTPOP},
495
497
499
504
506
507 // F16 - Constant Actions.
509
510 // F16 - Load/Store Actions.
515
516 // F16 - VOP1 Actions.
520
522
526
527 // F16 - VOP2 Actions.
529
531
532 // F16 - VOP3 Actions.
534 if (STI.hasMadF16())
536
539 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
540 switch (Op) {
541 case ISD::LOAD:
542 case ISD::STORE:
544 case ISD::BITCAST:
545 case ISD::UNDEF:
551 case ISD::IS_FPCLASS:
552 break;
554 setOperationAction(Op, VT, Custom);
555 break;
556 default:
557 setOperationAction(Op, VT, Expand);
558 break;
559 }
560 }
561 }
562
563 // v_perm_b32 can handle either of these.
566
567 // XXX - Do these do anything? Vector constants turn into build_vector.
569
571
576
581
588
593
598
603
608
613
618
623
627
630
633
634 if (!Subtarget->hasVOP3PInsts())
636
638 // This isn't really legal, but this avoids the legalizer unrolling it (and
639 // allows matching fneg (fabs x) patterns)
641
644
647
650
651 for (MVT Vec16 : {MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
654 Vec16, Custom);
656 }
657 }
658
659 if (Subtarget->hasVOP3PInsts()) {
664
668
670 Custom);
671
675 Custom);
676
677 for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16})
678 // Split vector operations.
683 VT, Custom);
684
685 for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16})
686 // Split vector operations.
688 VT, Custom);
689
691 Custom);
692
695
696 if (Subtarget->hasPackedFP32Ops()) {
701 Custom);
702 }
703 }
704
706
707 if (Subtarget->has16BitInsts()) {
712 } else {
713 // Legalization hack.
715
717 }
718
722 Custom);
723
725
726 if (Subtarget->hasMad64_32())
728
732 Custom);
733
738 Custom);
739
743 MVT::i8},
744 Custom);
745
748 ISD::SUB,
750 ISD::FADD,
751 ISD::FSUB,
756 ISD::FMA,
757 ISD::SMIN,
758 ISD::SMAX,
759 ISD::UMIN,
760 ISD::UMAX,
762 ISD::AND,
763 ISD::OR,
764 ISD::XOR,
773
774 // All memory operations. Some folding on the pointer operand is done to help
775 // matching the constant offsets in the addressing modes.
798
799 // FIXME: In other contexts we pretend this is a per-function property.
801
803}
804
806 return Subtarget;
807}
808
809//===----------------------------------------------------------------------===//
810// TargetLowering queries
811//===----------------------------------------------------------------------===//
812
813// v_mad_mix* support a conversion from f16 to f32.
814//
815// There is only one special case when denormals are enabled we don't currently,
816// where this is OK to use.
817bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
818 EVT DestVT, EVT SrcVT) const {
819 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
820 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
821 DestVT.getScalarType() == MVT::f32 &&
822 SrcVT.getScalarType() == MVT::f16 &&
823 // TODO: This probably only requires no input flushing?
825}
826
828 LLT DestTy, LLT SrcTy) const {
829 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
830 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
831 DestTy.getScalarSizeInBits() == 32 &&
832 SrcTy.getScalarSizeInBits() == 16 &&
833 // TODO: This probably only requires no input flushing?
834 !hasFP32Denormals(*MI.getMF());
835}
836
838 // SI has some legal vector types, but no legal vector operations. Say no
839 // shuffles are legal in order to prefer scalarizing some vector operations.
840 return false;
841}
842
845 EVT VT) const {
848
849 if (VT.isVector()) {
850 EVT ScalarVT = VT.getScalarType();
851 unsigned Size = ScalarVT.getSizeInBits();
852 if (Size == 16) {
853 if (Subtarget->has16BitInsts()) {
854 if (VT.isInteger())
855 return MVT::v2i16;
856 return (ScalarVT == MVT::bf16 ? MVT::i32 : MVT::v2f16);
857 }
858 return VT.isInteger() ? MVT::i32 : MVT::f32;
859 }
860
861 if (Size < 16)
862 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
863 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
864 }
865
866 if (VT.getSizeInBits() > 32)
867 return MVT::i32;
868
870}
871
874 EVT VT) const {
877
878 if (VT.isVector()) {
879 unsigned NumElts = VT.getVectorNumElements();
880 EVT ScalarVT = VT.getScalarType();
881 unsigned Size = ScalarVT.getSizeInBits();
882
883 // FIXME: Should probably promote 8-bit vectors to i16.
884 if (Size == 16 && Subtarget->has16BitInsts())
885 return (NumElts + 1) / 2;
886
887 if (Size <= 32)
888 return NumElts;
889
890 if (Size > 32)
891 return NumElts * ((Size + 31) / 32);
892 } else if (VT.getSizeInBits() > 32)
893 return (VT.getSizeInBits() + 31) / 32;
894
896}
897
900 EVT VT, EVT &IntermediateVT,
901 unsigned &NumIntermediates, MVT &RegisterVT) const {
902 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
903 unsigned NumElts = VT.getVectorNumElements();
904 EVT ScalarVT = VT.getScalarType();
905 unsigned Size = ScalarVT.getSizeInBits();
906 // FIXME: We should fix the ABI to be the same on targets without 16-bit
907 // support, but unless we can properly handle 3-vectors, it will be still be
908 // inconsistent.
909 if (Size == 16 && Subtarget->has16BitInsts()) {
910 if (ScalarVT == MVT::bf16) {
911 RegisterVT = MVT::i32;
912 IntermediateVT = MVT::v2bf16;
913 } else {
914 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
915 IntermediateVT = RegisterVT;
916 }
917 NumIntermediates = (NumElts + 1) / 2;
918 return NumIntermediates;
919 }
920
921 if (Size == 32) {
922 RegisterVT = ScalarVT.getSimpleVT();
923 IntermediateVT = RegisterVT;
924 NumIntermediates = NumElts;
925 return NumIntermediates;
926 }
927
928 if (Size < 16 && Subtarget->has16BitInsts()) {
929 // FIXME: Should probably form v2i16 pieces
930 RegisterVT = MVT::i16;
931 IntermediateVT = ScalarVT;
932 NumIntermediates = NumElts;
933 return NumIntermediates;
934 }
935
936
937 if (Size != 16 && Size <= 32) {
938 RegisterVT = MVT::i32;
939 IntermediateVT = ScalarVT;
940 NumIntermediates = NumElts;
941 return NumIntermediates;
942 }
943
944 if (Size > 32) {
945 RegisterVT = MVT::i32;
946 IntermediateVT = RegisterVT;
947 NumIntermediates = NumElts * ((Size + 31) / 32);
948 return NumIntermediates;
949 }
950 }
951
953 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
954}
955
956static EVT memVTFromLoadIntrData(Type *Ty, unsigned MaxNumLanes) {
957 assert(MaxNumLanes != 0);
958
959 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
960 unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
961 return EVT::getVectorVT(Ty->getContext(),
962 EVT::getEVT(VT->getElementType()),
963 NumElts);
964 }
965
966 return EVT::getEVT(Ty);
967}
968
969// Peek through TFE struct returns to only use the data size.
970static EVT memVTFromLoadIntrReturn(Type *Ty, unsigned MaxNumLanes) {
971 auto *ST = dyn_cast<StructType>(Ty);
972 if (!ST)
973 return memVTFromLoadIntrData(Ty, MaxNumLanes);
974
975 // TFE intrinsics return an aggregate type.
976 assert(ST->getNumContainedTypes() == 2 &&
977 ST->getContainedType(1)->isIntegerTy(32));
978 return memVTFromLoadIntrData(ST->getContainedType(0), MaxNumLanes);
979}
980
982 const CallInst &CI,
983 MachineFunction &MF,
984 unsigned IntrID) const {
986 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
988
989 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
992 (Intrinsic::ID)IntrID);
994 if (ME.doesNotAccessMemory())
995 return false;
996
997 // TODO: Should images get their own address space?
998 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_FAT_POINTER;
999
1000 if (RsrcIntr->IsImage)
1001 Info.align.reset();
1002
1004 if (ME.onlyReadsMemory()) {
1005 unsigned MaxNumLanes = 4;
1006
1007 if (RsrcIntr->IsImage) {
1010 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1012
1013 if (!BaseOpcode->Gather4) {
1014 // If this isn't a gather, we may have excess loaded elements in the
1015 // IR type. Check the dmask for the real number of elements loaded.
1016 unsigned DMask
1017 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1018 MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1019 }
1020 }
1021
1022 Info.memVT = memVTFromLoadIntrReturn(CI.getType(), MaxNumLanes);
1023
1024 // FIXME: What does alignment mean for an image?
1027 } else if (ME.onlyWritesMemory()) {
1029
1030 Type *DataTy = CI.getArgOperand(0)->getType();
1031 if (RsrcIntr->IsImage) {
1032 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1033 unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1034 Info.memVT = memVTFromLoadIntrData(DataTy, DMaskLanes);
1035 } else
1036 Info.memVT = EVT::getEVT(DataTy);
1037
1039 } else {
1040 // Atomic
1041 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1043 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1047
1048 // XXX - Should this be volatile without known ordering?
1050
1051 switch (IntrID) {
1052 default:
1053 break;
1054 case Intrinsic::amdgcn_raw_buffer_load_lds:
1055 case Intrinsic::amdgcn_struct_buffer_load_lds: {
1056 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1057 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1058 return true;
1059 }
1060 }
1061 }
1062 return true;
1063 }
1064
1065 switch (IntrID) {
1066 case Intrinsic::amdgcn_atomic_inc:
1067 case Intrinsic::amdgcn_atomic_dec:
1068 case Intrinsic::amdgcn_ds_ordered_add:
1069 case Intrinsic::amdgcn_ds_ordered_swap:
1070 case Intrinsic::amdgcn_ds_fadd:
1071 case Intrinsic::amdgcn_ds_fmin:
1072 case Intrinsic::amdgcn_ds_fmax: {
1074 Info.memVT = MVT::getVT(CI.getType());
1075 Info.ptrVal = CI.getOperand(0);
1076 Info.align.reset();
1078
1079 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1080 if (!Vol->isZero())
1082
1083 return true;
1084 }
1085 case Intrinsic::amdgcn_buffer_atomic_fadd: {
1087 Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1088 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_FAT_POINTER;
1089 Info.align.reset();
1091
1092 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1093 if (!Vol || !Vol->isZero())
1095
1096 return true;
1097 }
1098 case Intrinsic::amdgcn_ds_append:
1099 case Intrinsic::amdgcn_ds_consume: {
1101 Info.memVT = MVT::getVT(CI.getType());
1102 Info.ptrVal = CI.getOperand(0);
1103 Info.align.reset();
1105
1106 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1107 if (!Vol->isZero())
1109
1110 return true;
1111 }
1112 case Intrinsic::amdgcn_global_atomic_csub: {
1114 Info.memVT = MVT::getVT(CI.getType());
1115 Info.ptrVal = CI.getOperand(0);
1116 Info.align.reset();
1120 return true;
1121 }
1122 case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1124 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1125
1126 Info.fallbackAddressSpace = AMDGPUAS::BUFFER_FAT_POINTER;
1127 Info.align.reset();
1130 return true;
1131 }
1132 case Intrinsic::amdgcn_global_atomic_fadd:
1133 case Intrinsic::amdgcn_global_atomic_fmin:
1134 case Intrinsic::amdgcn_global_atomic_fmax:
1135 case Intrinsic::amdgcn_flat_atomic_fadd:
1136 case Intrinsic::amdgcn_flat_atomic_fmin:
1137 case Intrinsic::amdgcn_flat_atomic_fmax:
1138 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1139 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1141 Info.memVT = MVT::getVT(CI.getType());
1142 Info.ptrVal = CI.getOperand(0);
1143 Info.align.reset();
1148 return true;
1149 }
1150 case Intrinsic::amdgcn_ds_gws_init:
1151 case Intrinsic::amdgcn_ds_gws_barrier:
1152 case Intrinsic::amdgcn_ds_gws_sema_v:
1153 case Intrinsic::amdgcn_ds_gws_sema_br:
1154 case Intrinsic::amdgcn_ds_gws_sema_p:
1155 case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1157
1158 const GCNTargetMachine &TM =
1159 static_cast<const GCNTargetMachine &>(getTargetMachine());
1160
1162 Info.ptrVal = MFI->getGWSPSV(TM);
1163
1164 // This is an abstract access, but we need to specify a type and size.
1165 Info.memVT = MVT::i32;
1166 Info.size = 4;
1167 Info.align = Align(4);
1168
1169 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1171 else
1173 return true;
1174 }
1175 case Intrinsic::amdgcn_global_load_lds: {
1177 unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1178 Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1181 return true;
1182 }
1183 case Intrinsic::amdgcn_ds_bvh_stack_rtn: {
1185
1186 const GCNTargetMachine &TM =
1187 static_cast<const GCNTargetMachine &>(getTargetMachine());
1188
1190 Info.ptrVal = MFI->getGWSPSV(TM);
1191
1192 // This is an abstract access, but we need to specify a type and size.
1193 Info.memVT = MVT::i32;
1194 Info.size = 4;
1195 Info.align = Align(4);
1196
1198 return true;
1199 }
1200 default:
1201 return false;
1202 }
1203}
1204
1207 Type *&AccessTy) const {
1208 switch (II->getIntrinsicID()) {
1209 case Intrinsic::amdgcn_atomic_inc:
1210 case Intrinsic::amdgcn_atomic_dec:
1211 case Intrinsic::amdgcn_ds_ordered_add:
1212 case Intrinsic::amdgcn_ds_ordered_swap:
1213 case Intrinsic::amdgcn_ds_append:
1214 case Intrinsic::amdgcn_ds_consume:
1215 case Intrinsic::amdgcn_ds_fadd:
1216 case Intrinsic::amdgcn_ds_fmin:
1217 case Intrinsic::amdgcn_ds_fmax:
1218 case Intrinsic::amdgcn_global_atomic_fadd:
1219 case Intrinsic::amdgcn_flat_atomic_fadd:
1220 case Intrinsic::amdgcn_flat_atomic_fmin:
1221 case Intrinsic::amdgcn_flat_atomic_fmax:
1222 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1223 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1224 case Intrinsic::amdgcn_global_atomic_csub: {
1225 Value *Ptr = II->getArgOperand(0);
1226 AccessTy = II->getType();
1227 Ops.push_back(Ptr);
1228 return true;
1229 }
1230 default:
1231 return false;
1232 }
1233}
1234
1235bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1236 if (!Subtarget->hasFlatInstOffsets()) {
1237 // Flat instructions do not have offsets, and only have the register
1238 // address.
1239 return AM.BaseOffs == 0 && AM.Scale == 0;
1240 }
1241
1242 return AM.Scale == 0 &&
1243 (AM.BaseOffs == 0 ||
1244 Subtarget->getInstrInfo()->isLegalFLATOffset(
1246}
1247
1249 if (Subtarget->hasFlatGlobalInsts())
1250 return AM.Scale == 0 &&
1251 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1254
1255 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1256 // Assume the we will use FLAT for all global memory accesses
1257 // on VI.
1258 // FIXME: This assumption is currently wrong. On VI we still use
1259 // MUBUF instructions for the r + i addressing mode. As currently
1260 // implemented, the MUBUF instructions only work on buffer < 4GB.
1261 // It may be possible to support > 4GB buffers with MUBUF instructions,
1262 // by setting the stride value in the resource descriptor which would
1263 // increase the size limit to (stride * 4GB). However, this is risky,
1264 // because it has never been validated.
1265 return isLegalFlatAddressingMode(AM);
1266 }
1267
1268 return isLegalMUBUFAddressingMode(AM);
1269}
1270
1271bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1272 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1273 // additionally can do r + r + i with addr64. 32-bit has more addressing
1274 // mode options. Depending on the resource constant, it can also do
1275 // (i64 r0) + (i32 r1) * (i14 i).
1276 //
1277 // Private arrays end up using a scratch buffer most of the time, so also
1278 // assume those use MUBUF instructions. Scratch loads / stores are currently
1279 // implemented as mubuf instructions with offen bit set, so slightly
1280 // different than the normal addr64.
1281 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1282 return false;
1283
1284 // FIXME: Since we can split immediate into soffset and immediate offset,
1285 // would it make sense to allow any immediate?
1286
1287 switch (AM.Scale) {
1288 case 0: // r + i or just i, depending on HasBaseReg.
1289 return true;
1290 case 1:
1291 return true; // We have r + r or r + i.
1292 case 2:
1293 if (AM.HasBaseReg) {
1294 // Reject 2 * r + r.
1295 return false;
1296 }
1297
1298 // Allow 2 * r as r + r
1299 // Or 2 * r + i is allowed as r + r + i.
1300 return true;
1301 default: // Don't allow n * r
1302 return false;
1303 }
1304}
1305
1307 const AddrMode &AM, Type *Ty,
1308 unsigned AS, Instruction *I) const {
1309 // No global is ever allowed as a base.
1310 if (AM.BaseGV)
1311 return false;
1312
1313 if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1314 return isLegalGlobalAddressingMode(AM);
1315
1316 if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1319 // If the offset isn't a multiple of 4, it probably isn't going to be
1320 // correctly aligned.
1321 // FIXME: Can we get the real alignment here?
1322 if (AM.BaseOffs % 4 != 0)
1323 return isLegalMUBUFAddressingMode(AM);
1324
1325 // There are no SMRD extloads, so if we have to do a small type access we
1326 // will use a MUBUF load.
1327 // FIXME?: We also need to do this if unaligned, but we don't know the
1328 // alignment here.
1329 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1330 return isLegalGlobalAddressingMode(AM);
1331
1333 // SMRD instructions have an 8-bit, dword offset on SI.
1334 if (!isUInt<8>(AM.BaseOffs / 4))
1335 return false;
1336 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1337 // On CI+, this can also be a 32-bit literal constant offset. If it fits
1338 // in 8-bits, it can use a smaller encoding.
1339 if (!isUInt<32>(AM.BaseOffs / 4))
1340 return false;
1341 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1342 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1343 if (!isUInt<20>(AM.BaseOffs))
1344 return false;
1345 } else
1346 llvm_unreachable("unhandled generation");
1347
1348 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1349 return true;
1350
1351 if (AM.Scale == 1 && AM.HasBaseReg)
1352 return true;
1353
1354 return false;
1355
1356 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1357 return isLegalMUBUFAddressingMode(AM);
1358 } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1360 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1361 // field.
1362 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1363 // an 8-bit dword offset but we don't know the alignment here.
1364 if (!isUInt<16>(AM.BaseOffs))
1365 return false;
1366
1367 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1368 return true;
1369
1370 if (AM.Scale == 1 && AM.HasBaseReg)
1371 return true;
1372
1373 return false;
1374 } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1376 // For an unknown address space, this usually means that this is for some
1377 // reason being used for pure arithmetic, and not based on some addressing
1378 // computation. We don't have instructions that compute pointers with any
1379 // addressing modes, so treat them as having no offset like flat
1380 // instructions.
1381 return isLegalFlatAddressingMode(AM);
1382 }
1383
1384 // Assume a user alias of global for unknown address spaces.
1385 return isLegalGlobalAddressingMode(AM);
1386}
1387
1389 const MachineFunction &MF) const {
1391 return (MemVT.getSizeInBits() <= 4 * 32);
1392 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1393 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1394 return (MemVT.getSizeInBits() <= MaxPrivateBits);
1395 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1396 return (MemVT.getSizeInBits() <= 2 * 32);
1397 }
1398 return true;
1399}
1400
1402 unsigned Size, unsigned AddrSpace, Align Alignment,
1403 MachineMemOperand::Flags Flags, unsigned *IsFast) const {
1404 if (IsFast)
1405 *IsFast = 0;
1406
1407 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1408 AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1409 // Check if alignment requirements for ds_read/write instructions are
1410 // disabled.
1411 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1412 return false;
1413
1414 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1415 if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1416 Alignment < RequiredAlignment)
1417 return false;
1418
1419 // Either, the alignment requirements are "enabled", or there is an
1420 // unaligned LDS access related hardware bug though alignment requirements
1421 // are "disabled". In either case, we need to check for proper alignment
1422 // requirements.
1423 //
1424 switch (Size) {
1425 case 64:
1426 // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1427 // address is negative, then the instruction is incorrectly treated as
1428 // out-of-bounds even if base + offsets is in bounds. Split vectorized
1429 // loads here to avoid emitting ds_read2_b32. We may re-combine the
1430 // load later in the SILoadStoreOptimizer.
1431 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1432 return false;
1433
1434 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1435 // can do a 4 byte aligned, 8 byte access in a single operation using
1436 // ds_read2/write2_b32 with adjacent offsets.
1437 RequiredAlignment = Align(4);
1438
1439 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1440 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1441 // ds_write2_b32 depending on the alignment. In either case with either
1442 // alignment there is no faster way of doing this.
1443
1444 // The numbers returned here and below are not additive, it is a 'speed
1445 // rank'. They are just meant to be compared to decide if a certain way
1446 // of lowering an operation is faster than another. For that purpose
1447 // naturally aligned operation gets it bitsize to indicate that "it
1448 // operates with a speed comparable to N-bit wide load". With the full
1449 // alignment ds128 is slower than ds96 for example. If underaligned it
1450 // is comparable to a speed of a single dword access, which would then
1451 // mean 32 < 128 and it is faster to issue a wide load regardless.
1452 // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
1453 // wider load which will not be aligned anymore the latter is slower.
1454 if (IsFast)
1455 *IsFast = (Alignment >= RequiredAlignment) ? 64
1456 : (Alignment < Align(4)) ? 32
1457 : 1;
1458 return true;
1459 }
1460
1461 break;
1462 case 96:
1463 if (!Subtarget->hasDS96AndDS128())
1464 return false;
1465
1466 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1467 // gfx8 and older.
1468
1469 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1470 // Naturally aligned access is fastest. However, also report it is Fast
1471 // if memory is aligned less than DWORD. A narrow load or store will be
1472 // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1473 // be more of them, so overall we will pay less penalty issuing a single
1474 // instruction.
1475
1476 // See comment on the values above.
1477 if (IsFast)
1478 *IsFast = (Alignment >= RequiredAlignment) ? 96
1479 : (Alignment < Align(4)) ? 32
1480 : 1;
1481 return true;
1482 }
1483
1484 break;
1485 case 128:
1486 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1487 return false;
1488
1489 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1490 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
1491 // single operation using ds_read2/write2_b64.
1492 RequiredAlignment = Align(8);
1493
1494 if (Subtarget->hasUnalignedDSAccessEnabled()) {
1495 // Naturally aligned access is fastest. However, also report it is Fast
1496 // if memory is aligned less than DWORD. A narrow load or store will be
1497 // be equally slow as a single ds_read_b128/ds_write_b128, but there
1498 // will be more of them, so overall we will pay less penalty issuing a
1499 // single instruction.
1500
1501 // See comment on the values above.
1502 if (IsFast)
1503 *IsFast = (Alignment >= RequiredAlignment) ? 128
1504 : (Alignment < Align(4)) ? 32
1505 : 1;
1506 return true;
1507 }
1508
1509 break;
1510 default:
1511 if (Size > 32)
1512 return false;
1513
1514 break;
1515 }
1516
1517 // See comment on the values above.
1518 // Note that we have a single-dword or sub-dword here, so if underaligned
1519 // it is a slowest possible access, hence returned value is 0.
1520 if (IsFast)
1521 *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
1522
1523 return Alignment >= RequiredAlignment ||
1524 Subtarget->hasUnalignedDSAccessEnabled();
1525 }
1526
1527 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1528 bool AlignedBy4 = Alignment >= Align(4);
1529 if (IsFast)
1530 *IsFast = AlignedBy4;
1531
1532 return AlignedBy4 ||
1533 Subtarget->enableFlatScratch() ||
1534 Subtarget->hasUnalignedScratchAccess();
1535 }
1536
1537 // FIXME: We have to be conservative here and assume that flat operations
1538 // will access scratch. If we had access to the IR function, then we
1539 // could determine if any private memory was used in the function.
1540 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1541 !Subtarget->hasUnalignedScratchAccess()) {
1542 bool AlignedBy4 = Alignment >= Align(4);
1543 if (IsFast)
1544 *IsFast = AlignedBy4;
1545
1546 return AlignedBy4;
1547 }
1548
1549 if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1550 // If we have a uniform constant load, it still requires using a slow
1551 // buffer instruction if unaligned.
1552 if (IsFast) {
1553 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1554 // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1555 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1556 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1557 Alignment >= Align(4) : Alignment != Align(2);
1558 }
1559
1560 return true;
1561 }
1562
1563 // Smaller than dword value must be aligned.
1564 if (Size < 32)
1565 return false;
1566
1567 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1568 // byte-address are ignored, thus forcing Dword alignment.
1569 // This applies to private, global, and constant memory.
1570 if (IsFast)
1571 *IsFast = 1;
1572
1573 return Size >= 32 && Alignment >= Align(4);
1574}
1575
1577 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1578 unsigned *IsFast) const {
1580 Alignment, Flags, IsFast);
1581}
1582
1584 const MemOp &Op, const AttributeList &FuncAttributes) const {
1585 // FIXME: Should account for address space here.
1586
1587 // The default fallback uses the private pointer size as a guess for a type to
1588 // use. Make sure we switch these to 64-bit accesses.
1589
1590 if (Op.size() >= 16 &&
1591 Op.isDstAligned(Align(4))) // XXX: Should only do for global
1592 return MVT::v4i32;
1593
1594 if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1595 return MVT::v2i32;
1596
1597 // Use the default.
1598 return MVT::Other;
1599}
1600
1602 const MemSDNode *MemNode = cast<MemSDNode>(N);
1603 return MemNode->getMemOperand()->getFlags() & MONoClobber;
1604}
1605
1607 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1609}
1610
1612 unsigned DestAS) const {
1613 // Flat -> private/local is a simple truncate.
1614 // Flat -> global is no-op
1615 if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1616 return true;
1617
1618 const GCNTargetMachine &TM =
1619 static_cast<const GCNTargetMachine &>(getTargetMachine());
1620 return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1621}
1622
1624 const MemSDNode *MemNode = cast<MemSDNode>(N);
1625
1627}
1628
1631 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1635}
1636
1638 Type *Ty) const {
1639 // FIXME: Could be smarter if called for vector constants.
1640 return true;
1641}
1642
1644 unsigned Index) const {
1646 return false;
1647
1648 // TODO: Add more cases that are cheap.
1649 return Index == 0;
1650}
1651
1652bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1653 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1654 switch (Op) {
1655 case ISD::LOAD:
1656 case ISD::STORE:
1657
1658 // These operations are done with 32-bit instructions anyway.
1659 case ISD::AND:
1660 case ISD::OR:
1661 case ISD::XOR:
1662 case ISD::SELECT:
1663 // TODO: Extensions?
1664 return true;
1665 default:
1666 return false;
1667 }
1668 }
1669
1670 // SimplifySetCC uses this function to determine whether or not it should
1671 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1672 if (VT == MVT::i1 && Op == ISD::SETCC)
1673 return false;
1674
1676}
1677
1678SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1679 const SDLoc &SL,
1680 SDValue Chain,
1681 uint64_t Offset) const {
1682 const DataLayout &DL = DAG.getDataLayout();
1685
1686 const ArgDescriptor *InputPtrReg;
1687 const TargetRegisterClass *RC;
1688 LLT ArgTy;
1690
1691 std::tie(InputPtrReg, RC, ArgTy) =
1693
1694 // We may not have the kernarg segment argument if we have no kernel
1695 // arguments.
1696 if (!InputPtrReg)
1697 return DAG.getConstant(0, SL, PtrVT);
1698
1700 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1701 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1702
1703 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1704}
1705
1706SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1707 const SDLoc &SL) const {
1710 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1711}
1712
1713SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
1714 const SDLoc &SL) const {
1715
1717 std::optional<uint32_t> KnownSize =
1719 if (KnownSize.has_value())
1720 return DAG.getConstant(*KnownSize, SL, MVT::i32);
1721 return SDValue();
1722}
1723
1724SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1725 const SDLoc &SL, SDValue Val,
1726 bool Signed,
1727 const ISD::InputArg *Arg) const {
1728 // First, if it is a widened vector, narrow it.
1729 if (VT.isVector() &&
1731 EVT NarrowedVT =
1734 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1735 DAG.getConstant(0, SL, MVT::i32));
1736 }
1737
1738 // Then convert the vector elements or scalar value.
1739 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1740 VT.bitsLT(MemVT)) {
1741 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1742 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1743 }
1744
1745 if (MemVT.isFloatingPoint())
1746 Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1747 else if (Signed)
1748 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1749 else
1750 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1751
1752 return Val;
1753}
1754
1755SDValue SITargetLowering::lowerKernargMemParameter(
1756 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1757 uint64_t Offset, Align Alignment, bool Signed,
1758 const ISD::InputArg *Arg) const {
1760
1761 // Try to avoid using an extload by loading earlier than the argument address,
1762 // and extracting the relevant bits. The load should hopefully be merged with
1763 // the previous argument.
1764 if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1765 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1766 int64_t AlignDownOffset = alignDown(Offset, 4);
1767 int64_t OffsetDiff = Offset - AlignDownOffset;
1768
1769 EVT IntVT = MemVT.changeTypeToInteger();
1770
1771 // TODO: If we passed in the base kernel offset we could have a better
1772 // alignment than 4, but we don't really need it.
1773 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1774 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1777
1778 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1779 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1780
1781 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1782 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1783 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1784
1785
1786 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1787 }
1788
1789 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1790 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1793
1794 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1795 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1796}
1797
1798SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1799 const SDLoc &SL, SDValue Chain,
1800 const ISD::InputArg &Arg) const {
1802 MachineFrameInfo &MFI = MF.getFrameInfo();
1803
1804 if (Arg.Flags.isByVal()) {
1805 unsigned Size = Arg.Flags.getByValSize();
1806 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1807 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1808 }
1809
1810 unsigned ArgOffset = VA.getLocMemOffset();
1811 unsigned ArgSize = VA.getValVT().getStoreSize();
1812
1813 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1814
1815 // Create load nodes to retrieve arguments from the stack.
1816 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1817 SDValue ArgValue;
1818
1819 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1821 MVT MemVT = VA.getValVT();
1822
1823 switch (VA.getLocInfo()) {
1824 default:
1825 break;
1826 case CCValAssign::BCvt:
1827 MemVT = VA.getLocVT();
1828 break;
1829 case CCValAssign::SExt:
1830 ExtType = ISD::SEXTLOAD;
1831 break;
1832 case CCValAssign::ZExt:
1833 ExtType = ISD::ZEXTLOAD;
1834 break;
1835 case CCValAssign::AExt:
1836 ExtType = ISD::EXTLOAD;
1837 break;
1838 }
1839
1840 ArgValue = DAG.getExtLoad(
1841 ExtType, SL, VA.getLocVT(), Chain, FIN,
1843 MemVT);
1844 return ArgValue;
1845}
1846
1847SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1848 const SIMachineFunctionInfo &MFI,
1849 EVT VT,
1851 const ArgDescriptor *Reg;
1852 const TargetRegisterClass *RC;
1853 LLT Ty;
1854
1855 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1856 if (!Reg) {
1858 // It's possible for a kernarg intrinsic call to appear in a kernel with
1859 // no allocated segment, in which case we do not add the user sgpr
1860 // argument, so just return null.
1861 return DAG.getConstant(0, SDLoc(), VT);
1862 }
1863
1864 // It's undefined behavior if a function marked with the amdgpu-no-*
1865 // attributes uses the corresponding intrinsic.
1866 return DAG.getUNDEF(VT);
1867 }
1868
1869 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1870}
1871
1873 CallingConv::ID CallConv,
1874 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1875 FunctionType *FType,
1876 SIMachineFunctionInfo *Info) {
1877 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1878 const ISD::InputArg *Arg = &Ins[I];
1879
1880 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1881 "vector type argument should have been split");
1882
1883 // First check if it's a PS input addr.
1884 if (CallConv == CallingConv::AMDGPU_PS &&
1885 !Arg->Flags.isInReg() && PSInputNum <= 15) {
1886 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1887
1888 // Inconveniently only the first part of the split is marked as isSplit,
1889 // so skip to the end. We only want to increment PSInputNum once for the
1890 // entire split argument.
1891 if (Arg->Flags.isSplit()) {
1892 while (!Arg->Flags.isSplitEnd()) {
1893 assert((!Arg->VT.isVector() ||
1894 Arg->VT.getScalarSizeInBits() == 16) &&
1895 "unexpected vector split in ps argument type");
1896 if (!SkipArg)
1897 Splits.push_back(*Arg);
1898 Arg = &Ins[++I];
1899 }
1900 }
1901
1902 if (SkipArg) {
1903 // We can safely skip PS inputs.
1904 Skipped.set(Arg->getOrigArgIndex());
1905 ++PSInputNum;
1906 continue;
1907 }
1908
1909 Info->markPSInputAllocated(PSInputNum);
1910 if (Arg->Used)
1911 Info->markPSInputEnabled(PSInputNum);
1912
1913 ++PSInputNum;
1914 }
1915
1916 Splits.push_back(*Arg);
1917 }
1918}
1919
1920// Allocate special inputs passed in VGPRs.
1922 MachineFunction &MF,
1923 const SIRegisterInfo &TRI,
1924 SIMachineFunctionInfo &Info) const {
1925 const LLT S32 = LLT::scalar(32);
1927
1928 if (Info.hasWorkItemIDX()) {
1929 Register Reg = AMDGPU::VGPR0;
1930 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1931
1932 CCInfo.AllocateReg(Reg);
1933 unsigned Mask = (Subtarget->hasPackedTID() &&
1934 Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1935 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1936 }
1937
1938 if (Info.hasWorkItemIDY()) {
1939 assert(Info.hasWorkItemIDX());
1940 if (Subtarget->hasPackedTID()) {
1941 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1942 0x3ff << 10));
1943 } else {
1944 unsigned Reg = AMDGPU::VGPR1;
1945 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1946
1947 CCInfo.AllocateReg(Reg);
1948 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1949 }
1950 }
1951
1952 if (Info.hasWorkItemIDZ()) {
1953 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1954 if (Subtarget->hasPackedTID()) {
1955 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1956 0x3ff << 20));
1957 } else {
1958 unsigned Reg = AMDGPU::VGPR2;
1959 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1960
1961 CCInfo.AllocateReg(Reg);
1962 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1963 }
1964 }
1965}
1966
1967// Try to allocate a VGPR at the end of the argument list, or if no argument
1968// VGPRs are left allocating a stack slot.
1969// If \p Mask is is given it indicates bitfield position in the register.
1970// If \p Arg is given use it with new ]p Mask instead of allocating new.
1971static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1973 if (Arg.isSet())
1974 return ArgDescriptor::createArg(Arg, Mask);
1975
1976 ArrayRef<MCPhysReg> ArgVGPRs = ArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1977 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1978 if (RegIdx == ArgVGPRs.size()) {
1979 // Spill to stack required.
1980 int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1981
1982 return ArgDescriptor::createStack(Offset, Mask);
1983 }
1984
1985 unsigned Reg = ArgVGPRs[RegIdx];
1986 Reg = CCInfo.AllocateReg(Reg);
1987 assert(Reg != AMDGPU::NoRegister);
1988
1989 MachineFunction &MF = CCInfo.getMachineFunction();
1990 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1991 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1992 return ArgDescriptor::createRegister(Reg, Mask);
1993}
1994
1996 const TargetRegisterClass *RC,
1997 unsigned NumArgRegs) {
1998 ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
1999 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2000 if (RegIdx == ArgSGPRs.size())
2001 report_fatal_error("ran out of SGPRs for arguments");
2002
2003 unsigned Reg = ArgSGPRs[RegIdx];
2004 Reg = CCInfo.AllocateReg(Reg);
2005 assert(Reg != AMDGPU::NoRegister);
2006
2007 MachineFunction &MF = CCInfo.getMachineFunction();
2008 MF.addLiveIn(Reg, RC);
2010}
2011
2012// If this has a fixed position, we still should allocate the register in the
2013// CCInfo state. Technically we could get away with this for values passed
2014// outside of the normal argument range.
2016 const TargetRegisterClass *RC,
2017 MCRegister Reg) {
2018 Reg = CCInfo.AllocateReg(Reg);
2019 assert(Reg != AMDGPU::NoRegister);
2020 MachineFunction &MF = CCInfo.getMachineFunction();
2021 MF.addLiveIn(Reg, RC);
2022}
2023
2025 if (Arg) {
2026 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2027 Arg.getRegister());
2028 } else
2029 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2030}
2031
2033 if (Arg) {
2034 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2035 Arg.getRegister());
2036 } else
2037 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2038}
2039
2040/// Allocate implicit function VGPR arguments at the end of allocated user
2041/// arguments.
2043 CCState &CCInfo, MachineFunction &MF,
2044 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2045 const unsigned Mask = 0x3ff;
2047
2048 if (Info.hasWorkItemIDX()) {
2049 Arg = allocateVGPR32Input(CCInfo, Mask);
2050 Info.setWorkItemIDX(Arg);
2051 }
2052
2053 if (Info.hasWorkItemIDY()) {
2054 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2055 Info.setWorkItemIDY(Arg);
2056 }
2057
2058 if (Info.hasWorkItemIDZ())
2059 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2060}
2061
2062/// Allocate implicit function VGPR arguments in fixed registers.
2064 CCState &CCInfo, MachineFunction &MF,
2065 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2066 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2067 if (!Reg)
2068 report_fatal_error("failed to allocated VGPR for implicit arguments");
2069
2070 const unsigned Mask = 0x3ff;
2071 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2072 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2073 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2074}
2075
2077 CCState &CCInfo,
2078 MachineFunction &MF,
2079 const SIRegisterInfo &TRI,
2080 SIMachineFunctionInfo &Info) const {
2081 auto &ArgInfo = Info.getArgInfo();
2082
2083 // TODO: Unify handling with private memory pointers.
2084 if (Info.hasDispatchPtr())
2085 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2086
2087 const Module *M = MF.getFunction().getParent();
2088 if (Info.hasQueuePtr() && AMDGPU::getCodeObjectVersion(*M) < 5)
2089 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2090
2091 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2092 // constant offset from the kernarg segment.
2093 if (Info.hasImplicitArgPtr())
2094 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2095
2096 if (Info.hasDispatchID())
2097 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2098
2099 // flat_scratch_init is not applicable for non-kernel functions.
2100
2101 if (Info.hasWorkGroupIDX())
2102 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2103
2104 if (Info.hasWorkGroupIDY())
2105 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2106
2107 if (Info.hasWorkGroupIDZ())
2108 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2109
2110 if (Info.hasLDSKernelId())
2111 allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
2112}
2113
2114// Allocate special inputs passed in user SGPRs.
2116 MachineFunction &MF,
2117 const SIRegisterInfo &TRI,
2118 SIMachineFunctionInfo &Info) const {
2119 if (Info.hasImplicitBufferPtr()) {
2120 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2121 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2122 CCInfo.AllocateReg(ImplicitBufferPtrReg);
2123 }
2124
2125 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2126 if (Info.hasPrivateSegmentBuffer()) {
2127 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2128 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2129 CCInfo.AllocateReg(PrivateSegmentBufferReg);
2130 }
2131
2132 if (Info.hasDispatchPtr()) {
2133 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2134 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2135 CCInfo.AllocateReg(DispatchPtrReg);
2136 }
2137
2138 const Module *M = MF.getFunction().getParent();
2139 if (Info.hasQueuePtr() && AMDGPU::getCodeObjectVersion(*M) < 5) {
2140 Register QueuePtrReg = Info.addQueuePtr(TRI);
2141 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2142 CCInfo.AllocateReg(QueuePtrReg);
2143 }
2144
2145 if (Info.hasKernargSegmentPtr()) {
2147 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2148 CCInfo.AllocateReg(InputPtrReg);
2149
2150 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2151 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2152 }
2153
2154 if (Info.hasDispatchID()) {
2155 Register DispatchIDReg = Info.addDispatchID(TRI);
2156 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2157 CCInfo.AllocateReg(DispatchIDReg);
2158 }
2159
2160 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2161 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2162 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2163 CCInfo.AllocateReg(FlatScratchInitReg);
2164 }
2165
2166 if (Info.hasLDSKernelId()) {
2167 Register Reg = Info.addLDSKernelId();
2168 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2169 CCInfo.AllocateReg(Reg);
2170 }
2171
2172 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2173 // these from the dispatch pointer.
2174}
2175
2176// Allocate special input registers that are initialized per-wave.
2178 MachineFunction &MF,
2180 CallingConv::ID CallConv,
2181 bool IsShader) const {
2182 if (Subtarget->hasUserSGPRInit16Bug() && !IsShader) {
2183 // Note: user SGPRs are handled by the front-end for graphics shaders
2184 // Pad up the used user SGPRs with dead inputs.
2185 unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
2186
2187 // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
2188 // rely on it to reach 16 since if we end up having no stack usage, it will
2189 // not really be added.
2190 unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() +
2191 Info.hasWorkGroupIDY() +
2192 Info.hasWorkGroupIDZ() +
2193 Info.hasWorkGroupInfo();
2194 for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
2195 Register Reg = Info.addReservedUserSGPR();
2196 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2197 CCInfo.AllocateReg(Reg);
2198 }
2199 }
2200
2201 if (Info.hasWorkGroupIDX()) {
2202 Register Reg = Info.addWorkGroupIDX();
2203 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2204 CCInfo.AllocateReg(Reg);
2205 }
2206
2207 if (Info.hasWorkGroupIDY()) {
2208 Register Reg = Info.addWorkGroupIDY();
2209 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2210 CCInfo.AllocateReg(Reg);
2211 }
2212
2213 if (Info.hasWorkGroupIDZ()) {
2214 Register Reg = Info.addWorkGroupIDZ();
2215 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2216 CCInfo.AllocateReg(Reg);
2217 }
2218
2219 if (Info.hasWorkGroupInfo()) {
2220 Register Reg = Info.addWorkGroupInfo();
2221 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2222 CCInfo.AllocateReg(Reg);
2223 }
2224
2225 if (Info.hasPrivateSegmentWaveByteOffset()) {
2226 // Scratch wave offset passed in system SGPR.
2227 unsigned PrivateSegmentWaveByteOffsetReg;
2228
2229 if (IsShader) {
2230 PrivateSegmentWaveByteOffsetReg =
2231 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2232
2233 // This is true if the scratch wave byte offset doesn't have a fixed
2234 // location.
2235 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2236 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2237 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2238 }
2239 } else
2240 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2241
2242 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2243 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2244 }
2245
2246 assert(!Subtarget->hasUserSGPRInit16Bug() || IsShader ||
2247 Info.getNumPreloadedSGPRs() >= 16);
2248}
2249
2251 MachineFunction &MF,
2252 const SIRegisterInfo &TRI,
2253 SIMachineFunctionInfo &Info) {
2254 // Now that we've figured out where the scratch register inputs are, see if
2255 // should reserve the arguments and use them directly.
2256 MachineFrameInfo &MFI = MF.getFrameInfo();
2257 bool HasStackObjects = MFI.hasStackObjects();
2258 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2259
2260 // Record that we know we have non-spill stack objects so we don't need to
2261 // check all stack objects later.
2262 if (HasStackObjects)
2263 Info.setHasNonSpillStackObjects(true);
2264
2265 // Everything live out of a block is spilled with fast regalloc, so it's
2266 // almost certain that spilling will be required.
2267 if (TM.getOptLevel() == CodeGenOpt::None)
2268 HasStackObjects = true;
2269
2270 // For now assume stack access is needed in any callee functions, so we need
2271 // the scratch registers to pass in.
2272 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2273
2274 if (!ST.enableFlatScratch()) {
2275 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2276 // If we have stack objects, we unquestionably need the private buffer
2277 // resource. For the Code Object V2 ABI, this will be the first 4 user
2278 // SGPR inputs. We can reserve those and use them directly.
2279
2280 Register PrivateSegmentBufferReg =
2282 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2283 } else {
2284 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2285 // We tentatively reserve the last registers (skipping the last registers
2286 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2287 // we'll replace these with the ones immediately after those which were
2288 // really allocated. In the prologue copies will be inserted from the
2289 // argument to these reserved registers.
2290
2291 // Without HSA, relocations are used for the scratch pointer and the
2292 // buffer resource setup is always inserted in the prologue. Scratch wave
2293 // offset is still in an input SGPR.
2294 Info.setScratchRSrcReg(ReservedBufferReg);
2295 }
2296 }
2297
2299
2300 // For entry functions we have to set up the stack pointer if we use it,
2301 // whereas non-entry functions get this "for free". This means there is no
2302 // intrinsic advantage to using S32 over S34 in cases where we do not have
2303 // calls but do need a frame pointer (i.e. if we are requested to have one
2304 // because frame pointer elimination is disabled). To keep things simple we
2305 // only ever use S32 as the call ABI stack pointer, and so using it does not
2306 // imply we need a separate frame pointer.
2307 //
2308 // Try to use s32 as the SP, but move it if it would interfere with input
2309 // arguments. This won't work with calls though.
2310 //
2311 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2312 // registers.
2313 if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2314 Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2315 } else {
2317
2318 if (MFI.hasCalls())
2319 report_fatal_error("call in graphics shader with too many input SGPRs");
2320
2321 for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2322 if (!MRI.isLiveIn(Reg)) {
2323 Info.setStackPtrOffsetReg(Reg);
2324 break;
2325 }
2326 }
2327
2328 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2329 report_fatal_error("failed to find register for SP");
2330 }
2331
2332 // hasFP should be accurate for entry functions even before the frame is
2333 // finalized, because it does not rely on the known stack size, only
2334 // properties like whether variable sized objects are present.
2335 if (ST.getFrameLowering()->hasFP(MF)) {
2336 Info.setFrameOffsetReg(AMDGPU::SGPR33);
2337 }
2338}
2339
2342 return !Info->isEntryFunction();
2343}
2344
2346
2347}
2348
2350 MachineBasicBlock *Entry,
2351 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2353
2354 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2355 if (!IStart)
2356 return;
2357
2358 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2359 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2360 MachineBasicBlock::iterator MBBI = Entry->begin();
2361 for (const MCPhysReg *I = IStart; *I; ++I) {
2362 const TargetRegisterClass *RC = nullptr;
2363 if (AMDGPU::SReg_64RegClass.contains(*I))
2364 RC = &AMDGPU::SGPR_64RegClass;
2365 else if (AMDGPU::SReg_32RegClass.contains(*I))
2366 RC = &AMDGPU::SGPR_32RegClass;
2367 else
2368 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2369
2370 Register NewVR = MRI->createVirtualRegister(RC);
2371 // Create copy from CSR to a virtual register.
2372 Entry->addLiveIn(*I);
2373 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2374 .addReg(*I);
2375
2376 // Insert the copy-back instructions right before the terminator.
2377 for (auto *Exit : Exits)
2378 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2379 TII->get(TargetOpcode::COPY), *I)
2380 .addReg(NewVR);
2381 }
2382}
2383
2385 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2386 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2387 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2389
2391 const Function &Fn = MF.getFunction();
2394
2395 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2396 DiagnosticInfoUnsupported NoGraphicsHSA(
2397 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2398 DAG.getContext()->diagnose(NoGraphicsHSA);
2399 return DAG.getEntryNode();
2400 }
2401
2402 Info->allocateKnownAddressLDSGlobal(Fn);
2403
2406 BitVector Skipped(Ins.size());
2407 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2408 *DAG.getContext());
2409
2410 bool IsGraphics = AMDGPU::isGraphics(CallConv);
2411 bool IsKernel = AMDGPU::isKernel(CallConv);
2412 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2413
2414 if (IsGraphics) {
2415 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2416 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2417 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2418 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2419 !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
2420 !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
2421 }
2422
2423 if (CallConv == CallingConv::AMDGPU_PS) {
2424 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2425
2426 // At least one interpolation mode must be enabled or else the GPU will
2427 // hang.
2428 //
2429 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2430 // set PSInputAddr, the user wants to enable some bits after the compilation
2431 // based on run-time states. Since we can't know what the final PSInputEna
2432 // will look like, so we shouldn't do anything here and the user should take
2433 // responsibility for the correct programming.
2434 //
2435 // Otherwise, the following restrictions apply:
2436 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2437 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2438 // enabled too.
2439 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2440 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2441 CCInfo.AllocateReg(AMDGPU::VGPR0);
2442 CCInfo.AllocateReg(AMDGPU::VGPR1);
2443 Info->markPSInputAllocated(0);
2444 Info->markPSInputEnabled(0);
2445 }
2446 if (Subtarget->isAmdPalOS()) {
2447 // For isAmdPalOS, the user does not enable some bits after compilation
2448 // based on run-time states; the register values being generated here are
2449 // the final ones set in hardware. Therefore we need to apply the
2450 // workaround to PSInputAddr and PSInputEnable together. (The case where
2451 // a bit is set in PSInputAddr but not PSInputEnable is where the
2452 // frontend set up an input arg for a particular interpolation mode, but
2453 // nothing uses that input arg. Really we should have an earlier pass
2454 // that removes such an arg.)
2455 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2456 if ((PsInputBits & 0x7F) == 0 ||
2457 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2458 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
2459 }
2460 } else if (IsKernel) {
2461 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2462 } else {
2463 Splits.append(Ins.begin(), Ins.end());
2464 }
2465
2466 if (IsEntryFunc) {
2467 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2468 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2469 } else if (!IsGraphics) {
2470 // For the fixed ABI, pass workitem IDs in the last argument register.
2471 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2472 }
2473
2474 if (IsKernel) {
2475 analyzeFormalArgumentsCompute(CCInfo, Ins);
2476 } else {
2477 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2478 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2479 }
2480
2482
2483 // FIXME: This is the minimum kernel argument alignment. We should improve
2484 // this to the maximum alignment of the arguments.
2485 //
2486 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2487 // kern arg offset.
2488 const Align KernelArgBaseAlign = Align(16);
2489
2490 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2491 const ISD::InputArg &Arg = Ins[i];
2492 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2493 InVals.push_back(DAG.getUNDEF(Arg.VT));
2494 continue;
2495 }
2496
2497 CCValAssign &VA = ArgLocs[ArgIdx++];
2498 MVT VT = VA.getLocVT();
2499
2500 if (IsEntryFunc && VA.isMemLoc()) {
2501 VT = Ins[i].VT;
2502 EVT MemVT = VA.getLocVT();
2503
2504 const uint64_t Offset = VA.getLocMemOffset();
2505 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2506
2507 if (Arg.Flags.isByRef()) {
2508 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2509
2510 const GCNTargetMachine &TM =
2511 static_cast<const GCNTargetMachine &>(getTargetMachine());
2512 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2513 Arg.Flags.getPointerAddrSpace())) {
2515 Arg.Flags.getPointerAddrSpace());
2516 }
2517
2518 InVals.push_back(Ptr);
2519 continue;
2520 }
2521
2522 SDValue Arg = lowerKernargMemParameter(
2523 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2524 Chains.push_back(Arg.getValue(1));
2525
2526 auto *ParamTy =
2527 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2529 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2530 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2531 // On SI local pointers are just offsets into LDS, so they are always
2532 // less than 16-bits. On CI and newer they could potentially be
2533 // real pointers, so we can't guarantee their size.
2534 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2535 DAG.getValueType(MVT::i16));
2536 }
2537
2538 InVals.push_back(Arg);
2539 continue;
2540 } else if (!IsEntryFunc && VA.isMemLoc()) {
2541 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2542 InVals.push_back(Val);
2543 if (!Arg.Flags.isByVal())
2544 Chains.push_back(Val.getValue(1));
2545 continue;
2546 }
2547
2548 assert(VA.isRegLoc() && "Parameter must be in a register!");
2549
2550 Register Reg = VA.getLocReg();
2551 const TargetRegisterClass *RC = nullptr;
2552 if (AMDGPU::VGPR_32RegClass.contains(Reg))
2553 RC = &AMDGPU::VGPR_32RegClass;
2554 else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2555 RC = &AMDGPU::SGPR_32RegClass;
2556 else
2557 llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2558 EVT ValVT = VA.getValVT();
2559
2560 Reg = MF.addLiveIn(Reg, RC);
2561 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2562
2563 if (Arg.Flags.isSRet()) {
2564 // The return object should be reasonably addressable.
2565
2566 // FIXME: This helps when the return is a real sret. If it is a
2567 // automatically inserted sret (i.e. CanLowerReturn returns false), an
2568 // extra copy is inserted in SelectionDAGBuilder which obscures this.
2569 unsigned NumBits
2571 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2572 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2573 }
2574
2575 // If this is an 8 or 16-bit value, it is really passed promoted
2576 // to 32 bits. Insert an assert[sz]ext to capture this, then
2577 // truncate to the right size.
2578 switch (VA.getLocInfo()) {
2579 case CCValAssign::Full:
2580 break;
2581 case CCValAssign::BCvt:
2582 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2583 break;
2584 case CCValAssign::SExt:
2585 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2586 DAG.getValueType(ValVT));
2587 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2588 break;
2589 case CCValAssign::ZExt:
2590 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2591 DAG.getValueType(ValVT));
2592 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2593 break;
2594 case CCValAssign::AExt:
2595 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2596 break;
2597 default:
2598 llvm_unreachable("Unknown loc info!");
2599 }
2600
2601 InVals.push_back(Val);
2602 }
2603
2604 // Start adding system SGPRs.
2605 if (IsEntryFunc) {
2606 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2607 } else {
2608 CCInfo.AllocateReg(Info->getScratchRSrcReg());
2609 if (!IsGraphics)
2610 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2611 }
2612
2613 auto &ArgUsageInfo =
2615 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2616
2617 unsigned StackArgSize = CCInfo.getNextStackOffset();
2618 Info->setBytesInStackArgArea(StackArgSize);
2619
2620 return Chains.empty() ? Chain :
2621 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2622}
2623
2624// TODO: If return values can't fit in registers, we should return as many as
2625// possible in registers before passing on stack.
2627 CallingConv::ID CallConv,
2628 MachineFunction &MF, bool IsVarArg,
2630 LLVMContext &Context) const {
2631 // Replacing returns with sret/stack usage doesn't make sense for shaders.
2632 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2633 // for shaders. Vector types should be explicitly handled by CC.
2634 if (AMDGPU::isEntryFunctionCC(CallConv))
2635 return true;
2636
2638 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2639 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2640}
2641
2642SDValue
2644 bool isVarArg,
2646 const SmallVectorImpl<SDValue> &OutVals,
2647 const SDLoc &DL, SelectionDAG &DAG) const {
2650
2651 if (AMDGPU::isKernel(CallConv)) {
2652 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2653 OutVals, DL, DAG);
2654 }
2655
2656 bool IsShader = AMDGPU::isShader(CallConv);
2657
2658 Info->setIfReturnsVoid(Outs.empty());
2659 bool IsWaveEnd = Info->returnsVoid() && IsShader;
2660
2661 // CCValAssign - represent the assignment of the return value to a location.
2664
2665 // CCState - Info about the registers and stack slots.
2666 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2667 *DAG.getContext());
2668
2669 // Analyze outgoing return values.
2670 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2671
2672 SDValue Flag;
2674 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2675
2676 // Copy the result values into the output registers.
2677 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2678 ++I, ++RealRVLocIdx) {
2679 CCValAssign &VA = RVLocs[I];
2680 assert(VA.isRegLoc() && "Can only return in registers!");
2681 // TODO: Partially return in registers if return values don't fit.
2682 SDValue Arg = OutVals[RealRVLocIdx];
2683
2684 // Copied from other backends.
2685 switch (VA.getLocInfo()) {
2686 case CCValAssign::Full:
2687 break;
2688 case CCValAssign::BCvt:
2689 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2690 break;
2691 case CCValAssign::SExt:
2692 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2693 break;
2694 case CCValAssign::ZExt:
2695 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2696 break;
2697 case CCValAssign::AExt:
2698 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2699 break;
2700 default:
2701 llvm_unreachable("Unknown loc info!");
2702 }
2703
2704 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2705 Flag = Chain.getValue(1);
2706 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2707 }
2708
2709 // FIXME: Does sret work properly?
2710 if (!Info->isEntryFunction()) {
2711 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2712 const MCPhysReg *I =
2713 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2714 if (I) {
2715 for (; *I; ++I) {
2716 if (AMDGPU::SReg_64RegClass.contains(*I))
2717 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2718 else if (AMDGPU::SReg_32RegClass.contains(*I))
2719 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2720 else
2721 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2722 }
2723 }
2724 }
2725
2726 // Update chain and glue.
2727 RetOps[0] = Chain;
2728 if (Flag.getNode())
2729 RetOps.push_back(Flag);
2730
2731 unsigned Opc = AMDGPUISD::ENDPGM;
2732 if (!IsWaveEnd)
2734 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2735}
2736
2738 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2739 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2740 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2741 SDValue ThisVal) const {
2742 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2743
2744 // Assign locations to each value returned by this call.
2746 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2747 *DAG.getContext());
2748 CCInfo.AnalyzeCallResult(Ins, RetCC);
2749
2750 // Copy all of the result registers out of their specified physreg.
2751 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2752 CCValAssign VA = RVLocs[i];
2753 SDValue Val;
2754
2755 if (VA.isRegLoc()) {
2756 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2757 Chain = Val.getValue(1);
2758 InFlag = Val.getValue(2);
2759 } else if (VA.isMemLoc()) {
2760 report_fatal_error("TODO: return values in memory");
2761 } else
2762 llvm_unreachable("unknown argument location type");
2763
2764 switch (VA.getLocInfo()) {
2765 case CCValAssign::Full:
2766 break;
2767 case CCValAssign::BCvt:
2768 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2769 break;
2770 case CCValAssign::ZExt:
2771 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2772 DAG.getValueType(VA.getValVT()));
2773 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2774 break;
2775 case CCValAssign::SExt:
2776 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2777 DAG.getValueType(VA.getValVT()));
2778 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2779 break;
2780 case CCValAssign::AExt:
2781 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2782 break;
2783 default:
2784 llvm_unreachable("Unknown loc info!");
2785 }
2786
2787 InVals.push_back(Val);
2788 }
2789
2790 return Chain;
2791}
2792
2793// Add code to pass special inputs required depending on used features separate
2794// from the explicit user arguments present in the IR.
2796 CallLoweringInfo &CLI,
2797 CCState &CCInfo,
2798 const SIMachineFunctionInfo &Info,
2799 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2800 SmallVectorImpl<SDValue> &MemOpChains,
2801 SDValue Chain) const {
2802 // If we don't have a call site, this was a call inserted by
2803 // legalization. These can never use special inputs.
2804 if (!CLI.CB)
2805 return;
2806
2807 SelectionDAG &DAG = CLI.DAG;
2808 const SDLoc &DL = CLI.DL;
2809 const Function &F = DAG.getMachineFunction().getFunction();
2810
2811 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2812 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2813
2814 const AMDGPUFunctionArgInfo *CalleeArgInfo
2816 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2817 auto &ArgUsageInfo =
2819 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2820 }
2821
2822 // TODO: Unify with private memory register handling. This is complicated by
2823 // the fact that at least in kernels, the input argument is not necessarily
2824 // in the same location as the input.
2825 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2827 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2828 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2829 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2830 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2831 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2832 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2833 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"},
2834 {AMDGPUFunctionArgInfo::LDS_KERNEL_ID,"amdgpu-no-lds-kernel-id"},
2835 };
2836
2837 for (auto Attr : ImplicitAttrs) {
2838 const ArgDescriptor *OutgoingArg;
2839 const TargetRegisterClass *ArgRC;
2840 LLT ArgTy;
2841
2842 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2843
2844 // If the callee does not use the attribute value, skip copying the value.
2845 if (CLI.CB->hasFnAttr(Attr.second))
2846 continue;
2847
2848 std::tie(OutgoingArg, ArgRC, ArgTy) =
2849 CalleeArgInfo->getPreloadedValue(InputID);
2850 if (!OutgoingArg)
2851 continue;
2852
2853 const ArgDescriptor *IncomingArg;
2854 const TargetRegisterClass *IncomingArgRC;
2855 LLT Ty;
2856 std::tie(IncomingArg, IncomingArgRC, Ty) =
2857 CallerArgInfo.getPreloadedValue(InputID);
2858 assert(IncomingArgRC == ArgRC);
2859
2860 // All special arguments are ints for now.
2861 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2862 SDValue InputReg;
2863
2864 if (IncomingArg) {
2865 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2866 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2867 // The implicit arg ptr is special because it doesn't have a corresponding
2868 // input for kernels, and is computed from the kernarg segment pointer.
2869 InputReg = getImplicitArgPtr(DAG, DL);
2870 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
2871 std::optional<uint32_t> Id =
2873 if (Id.has_value()) {
2874 InputReg = DAG.getConstant(*Id, DL, ArgVT);
2875 } else {
2876 InputReg = DAG.getUNDEF(ArgVT);
2877 }
2878 } else {
2879 // We may have proven the input wasn't needed, although the ABI is
2880 // requiring it. We just need to allocate the register appropriately.
2881 InputReg = DAG.getUNDEF(ArgVT);
2882 }
2883
2884 if (OutgoingArg->isRegister()) {
2885 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2886 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2887 report_fatal_error("failed to allocate implicit input argument");
2888 } else {
2889 unsigned SpecialArgOffset =
2890 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2891 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2892 SpecialArgOffset);
2893 MemOpChains.push_back(ArgStore);
2894 }
2895 }
2896
2897 // Pack workitem IDs into a single register or pass it as is if already
2898 // packed.
2899 const ArgDescriptor *OutgoingArg;
2900 const TargetRegisterClass *ArgRC;
2901 LLT Ty;
2902
2903 std::tie(OutgoingArg, ArgRC, Ty) =
2905 if (!OutgoingArg)
2906 std::tie(OutgoingArg, ArgRC, Ty) =
2908 if (!OutgoingArg)
2909 std::tie(OutgoingArg, ArgRC, Ty) =
2911 if (!OutgoingArg)
2912 return;
2913
2914 const ArgDescriptor *IncomingArgX = std::get<0>(
2916 const ArgDescriptor *IncomingArgY = std::get<0>(
2918 const ArgDescriptor *IncomingArgZ = std::get<0>(
2920
2921 SDValue InputReg;
2922 SDLoc SL;
2923
2924 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2925 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2926 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2927
2928 // If incoming ids are not packed we need to pack them.
2929 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2930 NeedWorkItemIDX) {
2931 if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2932 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2933 } else {
2934 InputReg = DAG.getConstant(0, DL, MVT::i32);
2935 }
2936 }
2937
2938 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2939 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2940 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2941 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2942 DAG.getShiftAmountConstant(10, MVT::i32, SL));
2943 InputReg = InputReg.getNode() ?
2944 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2945 }
2946
2947 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2948 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2949 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2950 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2951 DAG.getShiftAmountConstant(20, MVT::i32, SL));
2952 InputReg = InputReg.getNode() ?
2953 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2954 }
2955
2956 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2957 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2958 // We're in a situation where the outgoing function requires the workitem
2959 // ID, but the calling function does not have it (e.g a graphics function
2960 // calling a C calling convention function). This is illegal, but we need
2961 // to produce something.
2962 InputReg = DAG.getUNDEF(MVT::i32);
2963 } else {
2964 // Workitem ids are already packed, any of present incoming arguments
2965 // will carry all required fields.
2967 IncomingArgX ? *IncomingArgX :
2968 IncomingArgY ? *IncomingArgY :
2969 *IncomingArgZ, ~0u);
2970 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2971 }
2972 }
2973
2974 if (OutgoingArg->isRegister()) {
2975 if (InputReg)
2976 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2977
2978 CCInfo.AllocateReg(OutgoingArg->getRegister());
2979 } else {
2980 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2981 if (InputReg) {
2982 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2983 SpecialArgOffset);
2984 MemOpChains.push_back(ArgStore);
2985 }
2986 }
2987}
2988
2990 return CC == CallingConv::Fast;
2991}
2992
2993/// Return true if we might ever do TCO for calls with this calling convention.
2995 switch (CC) {
2996 case CallingConv::C:
2998 return true;
2999 default:
3000 return canGuaranteeTCO(CC);
3001 }
3002}
3003
3005 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3007 const SmallVectorImpl<SDValue> &OutVals,
3008 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3009 if (!mayTailCallThisCC(CalleeCC))
3010 return false;
3011
3012 // For a divergent call target, we need to do a waterfall loop over the
3013 // possible callees which precludes us from using a simple jump.
3014 if (Callee->isDivergent())
3015 return false;
3016
3018 const Function &CallerF = MF.getFunction();
3019 CallingConv::ID CallerCC = CallerF.getCallingConv();
3021 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3022
3023 // Kernels aren't callable, and don't have a live in return address so it
3024 // doesn't make sense to do a tail call with entry functions.
3025 if (!CallerPreserved)
3026 return false;
3027
3028 bool CCMatch = CallerCC == CalleeCC;
3029
3031 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3032 return true;
3033 return false;
3034 }
3035
3036 // TODO: Can we handle var args?
3037 if (IsVarArg)
3038 return false;
3039
3040 for (const Argument &Arg : CallerF.args()) {
3041 if (Arg.hasByValAttr())
3042 return false;
3043 }
3044
3045 LLVMContext &Ctx = *DAG.getContext();
3046
3047 // Check that the call results are passed in the same way.
3048 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3049 CCAssignFnForCall(CalleeCC, IsVarArg),
3050 CCAssignFnForCall(CallerCC, IsVarArg)))
3051 return false;
3052
3053 // The callee has to preserve all registers the caller needs to preserve.
3054 if (!CCMatch) {
3055 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3056 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3057 return false;
3058 }
3059
3060 // Nothing more to check if the callee is taking no arguments.
3061 if (Outs.empty())
3062 return true;
3063
3065 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3066
3067 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3068
3069 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3070 // If the stack arguments for this call do not fit into our own save area then
3071 // the call cannot be made tail.
3072 // TODO: Is this really necessary?
3073 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3074 return false;
3075
3076 const MachineRegisterInfo &MRI = MF.getRegInfo();
3077 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3078}
3079
3081 if (!CI->isTailCall())
3082 return false;
3083
3084 const Function *ParentFn = CI->getParent()->getParent();
3086 return false;
3087 return true;
3088}
3089
3090// The wave scratch offset register is used as the global base pointer.
3092 SmallVectorImpl<SDValue> &InVals) const {
3093 SelectionDAG &DAG = CLI.DAG;
3094 const SDLoc &DL = CLI.DL;
3096 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3098 SDValue Chain = CLI.Chain;
3099 SDValue Callee = CLI.Callee;
3100 bool &IsTailCall = CLI.IsTailCall;
3101 CallingConv::ID CallConv = CLI.CallConv;
3102 bool IsVarArg = CLI.IsVarArg;
3103 bool IsSibCall = false;
3104 bool IsThisReturn = false;
3106
3107 if (Callee.isUndef() || isNullConstant(Callee)) {
3108 if (!CLI.IsTailCall) {
3109 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3110 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3111 }
3112
3113 return Chain;
3114 }
3115
3116 if (IsVarArg) {
3117 return lowerUnhandledCall(CLI, InVals,
3118 "unsupported call to variadic function ");
3119 }
3120
3121 if (!CLI.CB)
3122 report_fatal_error("unsupported libcall legalization");
3123
3124 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3125 return lowerUnhandledCall(CLI, InVals,
3126 "unsupported required tail call to function ");
3127 }
3128
3129 if (AMDGPU::isShader(CallConv)) {
3130 // Note the issue is with the CC of the called function, not of the call
3131 // itself.
3132 return lowerUnhandledCall(CLI, InVals,
3133 "unsupported call to a shader function ");
3134 }
3135
3137 CallConv != CallingConv::AMDGPU_Gfx) {
3138 // Only allow calls with specific calling conventions.
3139 return lowerUnhandledCall(CLI, InVals,
3140 "unsupported calling convention for call from "
3141 "graphics shader of function ");
3142 }
3143
3144 if (IsTailCall) {
3146 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3147 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3148 report_fatal_error("failed to perform tail call elimination on a call "
3149 "site marked musttail");
3150 }
3151
3152 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3153
3154 // A sibling call is one where we're under the usual C ABI and not planning
3155 // to change that but can still do a tail call:
3156 if (!TailCallOpt && IsTailCall)
3157 IsSibCall = true;
3158
3159 if (IsTailCall)
3160 ++NumTailCalls;
3161 }
3162
3165 SmallVector<SDValue, 8> MemOpChains;
3166
3167 // Analyze operands of the call, assigning locations to each operand.
3169 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3170 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3171
3172 if (CallConv != CallingConv::AMDGPU_Gfx) {
3173 // With a fixed ABI, allocate fixed registers before user arguments.
3174 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3175 }
3176
3177 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3178
3179 // Get a count of how many bytes are to be pushed on the stack.
3180 unsigned NumBytes = CCInfo.getNextStackOffset();
3181
3182 if (IsSibCall) {
3183 // Since we're not changing the ABI to make this a tail call, the memory
3184 // operands are already available in the caller's incoming argument space.
3185 NumBytes = 0;
3186 }
3187
3188 // FPDiff is the byte offset of the call's argument area from the callee's.
3189 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3190 // by this amount for a tail call. In a sibling call it must be 0 because the
3191 // caller will deallocate the entire stack and the callee still expects its
3192 // arguments to begin at SP+0. Completely unused for non-tail calls.
3193 int32_t FPDiff = 0;
3194 MachineFrameInfo &MFI = MF.getFrameInfo();
3195
3196 // Adjust the stack pointer for the new arguments...
3197 // These operations are automatically eliminated by the prolog/epilog pass
3198 if (!IsSibCall) {
3199 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3200
3201 if (!Subtarget->enableFlatScratch()) {
3202 SmallVector<SDValue, 4> CopyFromChains;
3203
3204 // In the HSA case, this should be an identity copy.
3205 SDValue ScratchRSrcReg
3206 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3207 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3208 CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3209 Chain = DAG.getTokenFactor(DL, CopyFromChains);
3210 }
3211 }
3212
3213 MVT PtrVT = MVT::i32;
3214
3215 // Walk the register/memloc assignments, inserting copies/loads.
3216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3217 CCValAssign &VA = ArgLocs[i];
3218 SDValue Arg = OutVals[i];
3219
3220 // Promote the value if needed.
3221 switch (VA.getLocInfo()) {
3222 case CCValAssign::Full:
3223 break;
3224 case CCValAssign::BCvt:
3225 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3226 break;
3227 case CCValAssign::ZExt:
3228 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3229 break;
3230 case CCValAssign::SExt:
3231 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3232 break;
3233 case CCValAssign::AExt:
3234 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3235 break;
3236 case CCValAssign::FPExt:
3237 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3238 break;
3239 default:
3240 llvm_unreachable("Unknown loc info!");
3241 }
3242
3243 if (VA.isRegLoc()) {
3244 RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
3245 } else {
3246 assert(VA.isMemLoc());
3247
3248 SDValue DstAddr;
3249 MachinePointerInfo DstInfo;
3250
3251 unsigned LocMemOffset = VA.getLocMemOffset();
3252 int32_t Offset = LocMemOffset;
3253
3254 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3255 MaybeAlign Alignment;
3256
3257 if (IsTailCall) {
3258 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3259 unsigned OpSize = Flags.isByVal() ?
3260 Flags.getByValSize() : VA.getValVT().getStoreSize();
3261
3262 // FIXME: We can have better than the minimum byval required alignment.
3263 Alignment =
3264 Flags.isByVal()
3265 ? Flags.getNonZeroByValAlign()
3266 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3267
3268 Offset = Offset + FPDiff;
3269 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3270
3271 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3272 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3273
3274 // Make sure any stack arguments overlapping with where we're storing
3275 // are loaded before this eventual operation. Otherwise they'll be
3276 // clobbered.
3277
3278 // FIXME: Why is this really necessary? This seems to just result in a
3279 // lot of code to copy the stack and write them back to the same
3280 // locations, which are supposed to be immutable?
3281 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3282 } else {
3283 // Stores to the argument stack area are relative to the stack pointer.
3284 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3285 MVT::i32);
3286 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3287 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3288 Alignment =
3289 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3290 }
3291
3292 if (Outs[i].Flags.isByVal()) {
3293 SDValue SizeNode =
3294 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3295 SDValue Cpy =
3296 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3297 Outs[i].Flags.getNonZeroByValAlign(),
3298 /*isVol = */ false, /*AlwaysInline = */ true,
3299 /*isTailCall = */ false, DstInfo,
3301
3302 MemOpChains.push_back(Cpy);
3303 } else {
3304 SDValue Store =
3305 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3306 MemOpChains.push_back(Store);
3307 }
3308 }
3309 }
3310
3311 if (!MemOpChains.empty())
3312 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3313
3314 // Build a sequence of copy-to-reg nodes chained together with token chain
3315 // and flag operands which copy the outgoing args into the appropriate regs.
3316 SDValue InFlag;
3317 for (auto &RegToPass : RegsToPass) {
3318 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3319 RegToPass.second, InFlag);
3320 InFlag = Chain.getValue(1);
3321 }
3322
3323
3324 // We don't usually want to end the call-sequence here because we would tidy
3325 // the frame up *after* the call, however in the ABI-changing tail-call case
3326 // we've carefully laid out the parameters so that when sp is reset they'll be
3327 // in the correct location.
3328 if (IsTailCall && !IsSibCall) {
3329 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InFlag, DL);
3330 InFlag = Chain.getValue(1);
3331 }
3332
3333 std::vector<SDValue> Ops;
3334 Ops.push_back(Chain);
3335 Ops.push_back(Callee);
3336 // Add a redundant copy of the callee global which will not be legalized, as
3337 // we need direct access to the callee later.
3338 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3339 const GlobalValue *GV = GSD->getGlobal();
3340 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3341 } else {
3342 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3343 }
3344
3345 if (IsTailCall) {
3346 // Each tail call may have to adjust the stack by a different amount, so
3347 // this information must travel along with the operation for eventual
3348 // consumption by emitEpilogue.
3349 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3350 }
3351
3352 // Add argument registers to the end of the list so that they are known live
3353 // into the call.
3354 for (auto &RegToPass : RegsToPass) {
3355 Ops.push_back(DAG.getRegister(RegToPass.first,
3356 RegToPass.second.getValueType()));
3357 }
3358
3359 // Add a register mask operand representing the call-preserved registers.
3360
3361 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3362 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3363 assert(Mask && "Missing call preserved mask for calling convention");
3364 Ops.push_back(DAG.getRegisterMask(Mask));
3365
3366 if (InFlag.getNode())
3367 Ops.push_back(InFlag);
3368
3369 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3370
3371 // If we're doing a tall call, use a TC_RETURN here rather than an
3372 // actual call instruction.
3373 if (IsTailCall) {
3374 MFI.setHasTailCall();
3375 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3376 }
3377
3378 // Returns a chain and a flag for retval copy to use.
3379 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3380 Chain = Call.getValue(0);
3381 InFlag = Call.getValue(1);
3382
3383 uint64_t CalleePopBytes = NumBytes;
3384 Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InFlag, DL);
3385 if (!Ins.empty())
3386 InFlag = Chain.getValue(1);
3387
3388 // Handle result values, copying them out of physregs into vregs that we
3389 // return.
3390 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3391 InVals, IsThisReturn,
3392 IsThisReturn ? OutVals[0] : SDValue());
3393}
3394
3395// This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3396// except for applying the wave size scale to the increment amount.
3398 SDValue Op, SelectionDAG &DAG) const {
3399 const MachineFunction &MF = DAG.getMachineFunction();
3401
3402 SDLoc dl(Op);
3403 EVT VT = Op.getValueType();
3404 SDValue Tmp1 = Op;
3405 SDValue Tmp2 = Op.getValue(1);
3406 SDValue Tmp3 = Op.getOperand(2);
3407 SDValue Chain = Tmp1.getOperand(0);
3408
3409 Register SPReg = Info->getStackPtrOffsetReg();
3410
3411 // Chain the dynamic stack allocation so that it doesn't modify the stack
3412 // pointer when other instructions are using the stack.
3413 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3414
3415 SDValue Size = Tmp2.getOperand(1);
3416 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3417 Chain = SP.getValue(1);
3418 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3419 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3420 const TargetFrameLowering *TFL = ST.getFrameLowering();
3421 unsigned Opc =
3422 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3424
3425 SDValue ScaledSize = DAG.getNode(
3426 ISD::SHL, dl, VT, Size,
3427 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3428
3429 Align StackAlign = TFL->getStackAlign();
3430 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3431 if (Alignment && *Alignment > StackAlign) {
3432 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3433 DAG.getConstant(-(uint64_t)Alignment->value()
3434 << ST.getWavefrontSizeLog2(),
3435 dl, VT));
3436 }
3437
3438 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
3439 Tmp2 = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
3440
3441 return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3442}
3443
3445 SelectionDAG &DAG) const {
3446 // We only handle constant sizes here to allow non-entry block, static sized
3447 // allocas. A truly dynamic value is more difficult to support because we
3448 // don't know if the size value is uniform or not. If the size isn't uniform,
3449 // we would need to do a wave reduction to get the maximum size to know how
3450 // much to increment the uniform stack pointer.
3451 SDValue Size = Op.getOperand(1);
3452 if (isa<ConstantSDNode>(Size))
3453 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3454
3456}
3457
3459 const MachineFunction &MF) const {
3461 .Case("m0", AMDGPU::M0)
3462 .Case("exec", AMDGPU::EXEC)
3463 .Case("exec_lo", AMDGPU::EXEC_LO)
3464 .Case("exec_hi", AMDGPU::EXEC_HI)
3465 .Case("flat_scratch", AMDGPU::FLAT_SCR)
3466 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3467 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3468 .Default(Register());
3469
3470 if (Reg == AMDGPU::NoRegister) {
3471 report_fatal_error(Twine("invalid register name \""
3472 + StringRef(RegName) + "\"."));
3473
3474 }
3475
3476 if (!Subtarget->hasFlatScrRegister() &&
3477 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3478 report_fatal_error(Twine("invalid register \""
3479 + StringRef(RegName) + "\" for subtarget."));
3480 }
3481
3482 switch (Reg) {
3483 case AMDGPU::M0:
3484 case AMDGPU::EXEC_LO:
3485 case AMDGPU::EXEC_HI:
3486 case AMDGPU::FLAT_SCR_LO:
3487 case AMDGPU::FLAT_SCR_HI:
3488 if (VT.getSizeInBits() == 32)
3489 return Reg;
3490 break;
3491 case AMDGPU::EXEC:
3492 case AMDGPU::FLAT_SCR:
3493 if (VT.getSizeInBits() == 64)
3494 return Reg;
3495 break;
3496 default:
3497 llvm_unreachable("missing register type checking");
3498 }
3499
3500 report_fatal_error(Twine("invalid type for register \""
3501 + StringRef(RegName) + "\"."));
3502}
3503
3504// If kill is not the last instruction, split the block so kill is always a
3505// proper terminator.
3508 MachineBasicBlock *BB) const {
3509 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3511 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3512 return SplitBB;
3513}
3514
3515// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3516// \p MI will be the only instruction in the loop body block. Otherwise, it will
3517// be the first instruction in the remainder block.
3518//
3519/// \returns { LoopBody, Remainder }
3520static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3524
3525 // To insert the loop we need to split the block. Move everything after this
3526 // point to a new block, and insert a new empty block between the two.
3528 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3530 ++MBBI;
3531
3532 MF->insert(MBBI, LoopBB);
3533 MF->insert(MBBI, RemainderBB);
3534
3535 LoopBB->addSuccessor(LoopBB);
3536 LoopBB->addSuccessor(RemainderBB);
3537
3538 // Move the rest of the block into a new block.
3539 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3540
3541 if (InstInLoop) {
3542 auto Next = std::next(I);
3543
3544 // Move instruction to loop body.
3545 LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3546
3547 // Move the rest of the block.
3548 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3549 } else {
3550 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3551 }
3552
3553 MBB.addSuccessor(LoopBB);
3554
3555 return std::pair(LoopBB, RemainderBB);
3556}
3557
3558/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3560 MachineBasicBlock *MBB = MI.getParent();
3562 auto I = MI.getIterator();
3563 auto E = std::next(I);
3564
3565 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3566 .addImm(0);
3567
3568 MIBundleBuilder Bundler(*MBB, I, E);
3569 finalizeBundle(*MBB, Bundler.begin());
3570}
3571
3574 MachineBasicBlock *BB) const {
3575 const DebugLoc &DL = MI.getDebugLoc();
3576
3578
3579 MachineBasicBlock *LoopBB;
3580 MachineBasicBlock *RemainderBB;
3582
3583 // Apparently kill flags are only valid if the def is in the same block?
3584 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3585 Src->setIsKill(false);
3586
3587 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3588
3589 MachineBasicBlock::iterator I = LoopBB->end();
3590
3591 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3593
3594 // Clear TRAP_STS.MEM_VIOL
3595 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3596 .addImm(0)
3597 .addImm(EncodedReg);
3598
3600
3601 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3602
3603 // Load and check TRAP_STS.MEM_VIOL
3604 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3605 .addImm(EncodedReg);
3606
3607 // FIXME: Do we need to use an isel pseudo that may clobber scc?
3608 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3609 .addReg(Reg, RegState::Kill)
3610 .addImm(0);
3611 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3612 .addMBB(LoopBB);
3613
3614 return RemainderBB;
3615}
3616
3617// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3618// wavefront. If the value is uniform and just happens to be in a VGPR, this
3619// will only do one iteration. In the worst case, this will loop 64 times.
3620//
3621// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3624 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3625 const DebugLoc &DL, const MachineOperand &Idx,
3626 unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3627 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3628 Register &SGPRIdxReg) {
3629
3630 MachineFunction *MF = OrigBB.getParent();
3631 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3632 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3634
3635 const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3636 Register PhiExec = MRI.createVirtualRegister(BoolRC);
3637 Register NewExec = MRI.createVirtualRegister(BoolRC);
3638 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3639 Register CondReg = MRI.createVirtualRegister(BoolRC);
3640
3641 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3642 .addReg(InitReg)
3643 .addMBB(&OrigBB)
3644 .addReg(ResultReg)
3645 .addMBB(&LoopBB);
3646
3647 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3648 .addReg(InitSaveExecReg)
3649 .addMBB(&OrigBB)
3650 .addReg(NewExec)
3651 .addMBB(&LoopBB);
3652
3653 // Read the next variant <- also loop target.
3654 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3655 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3656
3657 // Compare the just read M0 value to all possible Idx values.
3658 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3659 .addReg(CurrentIdxReg)
3660 .addReg(Idx.getReg(), 0, Idx.getSubReg());
3661
3662 // Update EXEC, save the original EXEC value to VCC.
3663 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3664 : AMDGPU::S_AND_SAVEEXEC_B64),
3665 NewExec)
3666 .addReg(CondReg, RegState::Kill);
3667
3668 MRI.setSimpleHint(NewExec, CondReg);
3669
3670 if (UseGPRIdxMode) {
3671 if (Offset == 0) {
3672 SGPRIdxReg = CurrentIdxReg;
3673 } else {
3674 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3675 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3676 .addReg(CurrentIdxReg, RegState::Kill)
3677 .addImm(Offset);
3678 }
3679 } else {
3680 // Move index from VCC into M0
3681 if (Offset == 0) {
3682 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3683 .addReg(CurrentIdxReg, RegState::Kill);
3684 } else {
3685 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3686 .addReg(CurrentIdxReg, RegState::Kill)
3687 .addImm(Offset);
3688 }
3689 }
3690
3691 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3692 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3693 MachineInstr *InsertPt =
3694 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3695 : AMDGPU::S_XOR_B64_term), Exec)
3696 .addReg(Exec)
3697 .addReg(NewExec);
3698
3699 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3700 // s_cbranch_scc0?
3701
3702 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3703 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3704 .addMBB(&LoopBB);
3705
3706 return InsertPt->getIterator();
3707}
3708
3709// This has slightly sub-optimal regalloc when the source vector is killed by
3710// the read. The register allocator does not understand that the kill is
3711// per-workitem, so is kept alive for the whole loop so we end up not re-using a
3712// subregister from it, using 1 more VGPR than necessary. This was saved when
3713// this was expanded after register allocation.
3716 unsigned InitResultReg, unsigned PhiReg, int Offset,
3717 bool UseGPRIdxMode, Register &SGPRIdxReg) {
3719 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3720 const SIRegisterInfo *TRI = ST.getRegisterInfo();
3722 const DebugLoc &DL = MI.getDebugLoc();
3724
3725 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3726 Register DstReg = MI.getOperand(0).getReg();
3727 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3728 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3729 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3730 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3731
3732 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3733
3734 // Save the EXEC mask
3735 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3736 .addReg(Exec);
3737
3738 MachineBasicBlock *LoopBB;
3739 MachineBasicBlock *RemainderBB;
3740 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3741
3742 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3743
3744 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3745 InitResultReg, DstReg, PhiReg, TmpExec,
3746 Offset, UseGPRIdxMode, SGPRIdxReg);
3747
3748 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3750 ++MBBI;
3751 MF->insert(MBBI, LandingPad);
3752 LoopBB->removeSuccessor(RemainderBB);
3753 LandingPad->addSuccessor(RemainderBB);
3754 LoopBB->addSuccessor(LandingPad);
3755 MachineBasicBlock::iterator First = LandingPad->begin();
3756 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3757 .addReg(SaveExec);
3758
3759 return InsPt;
3760}
3761
3762// Returns subreg index, offset
3763static std::pair<unsigned, int>
3765 const TargetRegisterClass *SuperRC,
3766 unsigned VecReg,
3767 int Offset) {
3768 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3769
3770 // Skip out of bounds offsets, or else we would end up using an undefined
3771 // register.
3772 if (Offset >= NumElts || Offset < 0)
3773 return std::pair(AMDGPU::sub0, Offset);
3774
3775 return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3776}
3777
3780 int Offset) {
3781 MachineBasicBlock *MBB = MI.getParent();
3782 const DebugLoc &DL = MI.getDebugLoc();
3784
3785 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3786
3787 assert(Idx->getReg() != AMDGPU::NoRegister);
3788
3789 if (Offset == 0) {
3790 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3791 } else {
3792 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3793 .add(*Idx)
3794 .addImm(Offset);
3795 }
3796}
3797
3800 int Offset) {
3801 MachineBasicBlock *MBB = MI.getParent();
3802 const DebugLoc &DL = MI.getDebugLoc();
3804
3805 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3806
3807 if (Offset == 0)
3808 return Idx->getReg();
3809
3810 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3811 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3812 .add(*Idx)
3813 .addImm(Offset);
3814 return Tmp;
3815}
3816
3819 const GCNSubtarget &ST) {
3820 const SIInstrInfo *TII = ST.getInstrInfo();
3821 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3824
3825 Register Dst = MI.getOperand(0).getReg();
3826 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3827 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3828 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3829
3830 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3831 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3832
3833 unsigned SubReg;
3834 std::tie(SubReg, Offset)
3835 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3836
3837 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3838
3839 // Check for a SGPR index.
3840 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3842 const DebugLoc &DL = MI.getDebugLoc();
3843
3844 if (UseGPRIdxMode) {
3845 // TODO: Look at the uses to avoid the copy. This may require rescheduling
3846 // to avoid interfering with other uses, so probably requires a new
3847 // optimization pass.
3849
3850 const MCInstrDesc &GPRIDXDesc =
3851 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3852 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3853 .addReg(SrcReg)
3854 .addReg(Idx)
3855 .addImm(SubReg);
3856 } else {
3858
3859 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3860 .addReg(SrcReg, 0, SubReg)
3861 .addReg(SrcReg, RegState::Implicit);
3862 }
3863
3864 MI.eraseFromParent();
3865
3866 return &MBB;
3867 }
3868
3869 // Control flow needs to be inserted if indexing with a VGPR.
3870 const DebugLoc &DL = MI.getDebugLoc();
3872
3873 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3874 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3875
3876 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3877
3878 Register SGPRIdxReg;
3879 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3880 UseGPRIdxMode, SGPRIdxReg);
3881
3882 MachineBasicBlock *LoopBB = InsPt->getParent();
3883
3884 if (UseGPRIdxMode) {
3885 const MCInstrDesc &GPRIDXDesc =
3886 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3887
3888 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3889 .addReg(SrcReg)
3890 .addReg(SGPRIdxReg)
3891 .addImm(SubReg);
3892 } else {
3893 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3894 .addReg(SrcReg, 0, SubReg)
3895 .addReg(SrcReg, RegState::Implicit);
3896 }
3897
3898 MI.eraseFromParent();
3899
3900 return LoopBB;
3901}
3902
3905 const GCNSubtarget &ST) {
3906 const SIInstrInfo *TII = ST.getInstrInfo();
3907 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3910
3911 Register Dst = MI.getOperand(0).getReg();
3912 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3913 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3914 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3915 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3916 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3917 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3918
3919 // This can be an immediate, but will be folded later.
3920 assert(Val->getReg());
3921
3922 unsigned SubReg;
3923 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3924 SrcVec->getReg(),
3925 Offset);
3926 const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3927
3928 if (Idx->getReg() == AMDGPU::NoRegister) {
3930 const DebugLoc &DL = MI.getDebugLoc();
3931
3932 assert(Offset == 0);
3933
3934 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3935 .add(*SrcVec)
3936 .add(*Val)
3937 .addImm(SubReg);
3938
3939 MI.eraseFromParent();
3940 return &MBB;
3941 }
3942
3943 // Check for a SGPR index.
3944 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3946 const DebugLoc &DL = MI.getDebugLoc();
3947
3948 if (UseGPRIdxMode) {
3950
3951 const MCInstrDesc &GPRIDXDesc =
3952 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3953 BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3954 .addReg(SrcVec->getReg())
3955 .add(*Val)
3956 .addReg(Idx)
3957 .addImm(SubReg);
3958 } else {
3960
3961 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3962 TRI.getRegSizeInBits(*VecRC), 32, false);
3963 BuildMI(MBB, I, DL, MovRelDesc, Dst)
3964 .addReg(SrcVec->getReg())
3965 .add(*Val)
3966 .addImm(SubReg);
3967 }
3968 MI.eraseFromParent();
3969 return &MBB;
3970 }
3971
3972 // Control flow needs to be inserted if indexing with a VGPR.
3973 if (Val->isReg())
3974 MRI.clearKillFlags(Val->getReg());
3975
3976 const DebugLoc &DL = MI.getDebugLoc();
3977
3978 Register PhiReg = MRI.createVirtualRegister(VecRC);
3979
3980 Register SGPRIdxReg;
3981 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,