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