LLVM  15.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"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
21 #include "llvm/ADT/Statistic.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/IntrinsicsAMDGPU.h"
35 #include "llvm/IR/IntrinsicsR600.h"
37 #include "llvm/Support/KnownBits.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "si-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
46  "amdgpu-disable-loop-alignment",
47  cl::desc("Do not align and prefetch loops"),
48  cl::init(false));
49 
51  "amdgpu-use-divergent-register-indexing",
52  cl::Hidden,
53  cl::desc("Use indirect register addressing for divergent indexes"),
54  cl::init(false));
55 
56 static bool hasFP32Denormals(const MachineFunction &MF) {
58  return Info->getMode().allFP32Denormals();
59 }
60 
61 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
63  return Info->getMode().allFP64FP16Denormals();
64 }
65 
66 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
67  unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
68  for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
69  if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
70  return AMDGPU::SGPR0 + Reg;
71  }
72  }
73  llvm_unreachable("Cannot allocate sgpr");
74 }
75 
77  const GCNSubtarget &STI)
78  : AMDGPUTargetLowering(TM, STI),
79  Subtarget(&STI) {
80  addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
81  addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
82 
83  addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
84  addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
85 
86  addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
87 
88  const SIRegisterInfo *TRI = STI.getRegisterInfo();
89  const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
90 
91  addRegisterClass(MVT::f64, V64RegClass);
92  addRegisterClass(MVT::v2f32, V64RegClass);
93 
94  addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
95  addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
96 
97  addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
98  addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
99 
100  addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
101  addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
102 
103  addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
104  addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
105 
106  addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
107  addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
108 
109  addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
110  addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
111 
112  addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
113  addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
114 
115  addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
116  addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
117 
118  addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
119  addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
120 
121  addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
122  addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
123 
124  addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
125  addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
126 
127  addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
128  addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
129 
130  if (Subtarget->has16BitInsts()) {
131  addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
132  addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
133 
134  // Unless there are also VOP3P operations, not operations are really legal.
135  addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
136  addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
137  addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
138  addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
139  addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
140  addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
141  }
142 
143  addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144  addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
147 
148  // The boolean content concept here is too inflexible. Compares only ever
149  // really produce a 1-bit result. Any copy/extend from these will turn into a
150  // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151  // it's what most targets use.
154 
155  // We need to custom lower vector stores from local memory
159  MVT::v32i32},
160  Custom);
161 
165  MVT::v32i32},
166  Custom);
167 
184 
192 
194 
199 
202 
206 
210  Expand);
214  Expand);
215 
219  Custom);
220 
224 
226 
228 
230  Expand);
231 
232 #if 0
234 #endif
235 
236  // We only support LOAD/STORE and vector manipulation ops for vectors
237  // with > 4 elements.
244  for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245  switch (Op) {
246  case ISD::LOAD:
247  case ISD::STORE:
248  case ISD::BUILD_VECTOR:
249  case ISD::BITCAST:
254  break;
256  case ISD::CONCAT_VECTORS:
258  break;
259  default:
261  break;
262  }
263  }
264  }
265 
267 
268  // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269  // is expanded to avoid having two separate loops in case the index is a VGPR.
270 
271  // Most operations are naturally 32-bit vector operations. We only support
272  // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273  for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
276 
279 
282 
285  }
286 
287  for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
290 
293 
296 
299  }
300 
301  for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
304 
307 
310 
313  }
314 
315  for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
318 
321 
324 
327  }
328 
329  for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
332 
335 
338 
341  }
342 
345  Expand);
346 
348 
349  // Avoid stack access for these.
350  // TODO: Generalize to more vector types.
354  Custom);
355 
356  // Deal with vec3 vector operations when widened to vec4.
359 
360  // Deal with vec5/6/7 vector operations when widened to vec8.
364  Custom);
365 
366  // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
367  // and output demarshalling
369 
370  // We can't return success/failure, only the old value,
371  // let LLVM add the comparison
373  Expand);
374 
375  if (Subtarget->hasFlatAddressSpace())
377 
379 
380  // FIXME: This should be narrowed to i32, but that only happens if i64 is
381  // illegal.
382  // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
384 
385  // On SI this is s_memtime and s_memrealtime on VI.
388 
389  if (Subtarget->has16BitInsts()) {
392  }
393 
394  if (Subtarget->hasMadMacF32Insts())
396 
397  if (!Subtarget->hasBFI())
398  // fcopysign can be done in a single instruction with BFI.
400 
401  if (!Subtarget->hasBCNT(32))
403 
404  if (!Subtarget->hasBCNT(64))
406 
407  if (Subtarget->hasFFBH())
409 
410  if (Subtarget->hasFFBL())
412 
413  // We only really have 32-bit BFE instructions (and 16-bit on VI).
414  //
415  // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
416  // effort to match them now. We want this to be false for i64 cases when the
417  // extraction isn't restricted to the upper or lower half. Ideally we would
418  // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
419  // span the midpoint are probably relatively rare, so don't worry about them
420  // for now.
421  if (Subtarget->hasBFE())
422  setHasExtractBitsInsn(true);
423 
424  // Clamp modifier on add/sub
425  if (Subtarget->hasIntClamp())
427 
428  if (Subtarget->hasAddNoCarry())
430  Legal);
431 
433  Custom);
434 
435  // These are really only legal for ieee_mode functions. We should be avoiding
436  // them for functions that don't have ieee_mode enabled, so just say they are
437  // legal.
439  {MVT::f32, MVT::f64}, Legal);
440 
441  if (Subtarget->haveRoundOpsF64())
443  else
445  MVT::f64, Custom);
446 
448 
451 
452  if (Subtarget->has16BitInsts()) {
455  MVT::i16, Legal);
456 
458 
460  MVT::i16, Expand);
461 
465  ISD::CTPOP},
466  MVT::i16, Promote);
467 
469 
471 
476 
478 
479  // F16 - Constant Actions.
481 
482  // F16 - Load/Store Actions.
487 
488  // F16 - VOP1 Actions.
491  MVT::f16, Custom);
492 
494 
497  MVT::f16, Promote);
498 
499  // F16 - VOP2 Actions.
501 
503 
504  // F16 - VOP3 Actions.
506  if (STI.hasMadF16())
508 
510  MVT::v8f16}) {
511  for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
512  switch (Op) {
513  case ISD::LOAD:
514  case ISD::STORE:
515  case ISD::BUILD_VECTOR:
516  case ISD::BITCAST:
522  break;
523  case ISD::CONCAT_VECTORS:
525  break;
526  default:
528  break;
529  }
530  }
531  }
532 
533  // v_perm_b32 can handle either of these.
536 
537  // XXX - Do these do anything? Vector constants turn into build_vector.
539 
541 
546 
551 
558 
563 
568 
573 
578 
583 
585  MVT::v2i32, Expand);
587 
589  MVT::v4i32, Expand);
590 
592  MVT::v8i32, Expand);
593 
594  if (!Subtarget->hasVOP3PInsts())
596 
598  // This isn't really legal, but this avoids the legalizer unrolling it (and
599  // allows matching fneg (fabs x) patterns)
601 
604 
607 
609  Expand);
610 
611  for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
614  Vec16, Custom);
616  }
617  }
618 
619  if (Subtarget->hasVOP3PInsts()) {
623  MVT::v2i16, Legal);
624 
627  MVT::v2f16, Legal);
628 
630  Custom);
631 
634  Custom);
635 
636  for (MVT VT : {MVT::v4i16, MVT::v8i16})
637  // Split vector operations.
641  ISD::SSUBSAT},
642  VT, Custom);
643 
644  for (MVT VT : {MVT::v4f16, MVT::v8f16})
645  // Split vector operations.
647  VT, Custom);
648 
650  Custom);
651 
654 
655  if (Subtarget->hasPackedFP32Ops()) {
657  MVT::v2f32, Legal);
660  Custom);
661  }
662  }
663 
665 
666  if (Subtarget->has16BitInsts()) {
671  } else {
672  // Legalization hack.
674 
676  }
677 
681  Custom);
682 
684 
685  if (Subtarget->hasMad64_32())
687 
691  Custom);
692 
696  MVT::i16, MVT::i8},
697  Custom);
698 
702  MVT::i8},
703  Custom);
704 
707  ISD::SUB,
709  ISD::FADD,
710  ISD::FSUB,
711  ISD::FMINNUM,
712  ISD::FMAXNUM,
715  ISD::FMA,
716  ISD::SMIN,
717  ISD::SMAX,
718  ISD::UMIN,
719  ISD::UMAX,
720  ISD::SETCC,
721  ISD::AND,
722  ISD::OR,
723  ISD::XOR,
732 
733  // All memory operations. Some folding on the pointer operand is done to help
734  // matching the constant offsets in the addressing modes.
736  ISD::STORE,
755 
756  // FIXME: In other contexts we pretend this is a per-function property.
757  setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
758 
760 }
761 
763  return Subtarget;
764 }
765 
766 //===----------------------------------------------------------------------===//
767 // TargetLowering queries
768 //===----------------------------------------------------------------------===//
769 
770 // v_mad_mix* support a conversion from f16 to f32.
771 //
772 // There is only one special case when denormals are enabled we don't currently,
773 // where this is OK to use.
774 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
775  EVT DestVT, EVT SrcVT) const {
776  return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
777  (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
778  DestVT.getScalarType() == MVT::f32 &&
779  SrcVT.getScalarType() == MVT::f16 &&
780  // TODO: This probably only requires no input flushing?
782 }
783 
784 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
785  LLT DestTy, LLT SrcTy) const {
786  return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
787  (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
788  DestTy.getScalarSizeInBits() == 32 &&
789  SrcTy.getScalarSizeInBits() == 16 &&
790  // TODO: This probably only requires no input flushing?
791  !hasFP32Denormals(*MI.getMF());
792 }
793 
795  // SI has some legal vector types, but no legal vector operations. Say no
796  // shuffles are legal in order to prefer scalarizing some vector operations.
797  return false;
798 }
799 
801  CallingConv::ID CC,
802  EVT VT) const {
803  if (CC == CallingConv::AMDGPU_KERNEL)
805 
806  if (VT.isVector()) {
807  EVT ScalarVT = VT.getScalarType();
808  unsigned Size = ScalarVT.getSizeInBits();
809  if (Size == 16) {
810  if (Subtarget->has16BitInsts())
811  return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
812  return VT.isInteger() ? MVT::i32 : MVT::f32;
813  }
814 
815  if (Size < 16)
816  return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
817  return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
818  }
819 
820  if (VT.getSizeInBits() > 32)
821  return MVT::i32;
822 
824 }
825 
827  CallingConv::ID CC,
828  EVT VT) const {
829  if (CC == CallingConv::AMDGPU_KERNEL)
831 
832  if (VT.isVector()) {
833  unsigned NumElts = VT.getVectorNumElements();
834  EVT ScalarVT = VT.getScalarType();
835  unsigned Size = ScalarVT.getSizeInBits();
836 
837  // FIXME: Should probably promote 8-bit vectors to i16.
838  if (Size == 16 && Subtarget->has16BitInsts())
839  return (NumElts + 1) / 2;
840 
841  if (Size <= 32)
842  return NumElts;
843 
844  if (Size > 32)
845  return NumElts * ((Size + 31) / 32);
846  } else if (VT.getSizeInBits() > 32)
847  return (VT.getSizeInBits() + 31) / 32;
848 
850 }
851 
854  EVT VT, EVT &IntermediateVT,
855  unsigned &NumIntermediates, MVT &RegisterVT) const {
856  if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
857  unsigned NumElts = VT.getVectorNumElements();
858  EVT ScalarVT = VT.getScalarType();
859  unsigned Size = ScalarVT.getSizeInBits();
860  // FIXME: We should fix the ABI to be the same on targets without 16-bit
861  // support, but unless we can properly handle 3-vectors, it will be still be
862  // inconsistent.
863  if (Size == 16 && Subtarget->has16BitInsts()) {
864  RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
865  IntermediateVT = RegisterVT;
866  NumIntermediates = (NumElts + 1) / 2;
867  return NumIntermediates;
868  }
869 
870  if (Size == 32) {
871  RegisterVT = ScalarVT.getSimpleVT();
872  IntermediateVT = RegisterVT;
873  NumIntermediates = NumElts;
874  return NumIntermediates;
875  }
876 
877  if (Size < 16 && Subtarget->has16BitInsts()) {
878  // FIXME: Should probably form v2i16 pieces
879  RegisterVT = MVT::i16;
880  IntermediateVT = ScalarVT;
881  NumIntermediates = NumElts;
882  return NumIntermediates;
883  }
884 
885 
886  if (Size != 16 && Size <= 32) {
887  RegisterVT = MVT::i32;
888  IntermediateVT = ScalarVT;
889  NumIntermediates = NumElts;
890  return NumIntermediates;
891  }
892 
893  if (Size > 32) {
894  RegisterVT = MVT::i32;
895  IntermediateVT = RegisterVT;
896  NumIntermediates = NumElts * ((Size + 31) / 32);
897  return NumIntermediates;
898  }
899  }
900 
902  Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
903 }
904 
905 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
906  assert(DMaskLanes != 0);
907 
908  if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
909  unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
910  return EVT::getVectorVT(Ty->getContext(),
911  EVT::getEVT(VT->getElementType()),
912  NumElts);
913  }
914 
915  return EVT::getEVT(Ty);
916 }
917 
918 // Peek through TFE struct returns to only use the data size.
919 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
920  auto *ST = dyn_cast<StructType>(Ty);
921  if (!ST)
922  return memVTFromImageData(Ty, DMaskLanes);
923 
924  // Some intrinsics return an aggregate type - special case to work out the
925  // correct memVT.
926  //
927  // Only limited forms of aggregate type currently expected.
928  if (ST->getNumContainedTypes() != 2 ||
929  !ST->getContainedType(1)->isIntegerTy(32))
930  return EVT();
931  return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
932 }
933 
935  const CallInst &CI,
936  MachineFunction &MF,
937  unsigned IntrID) const {
939  if (CI.hasMetadata(LLVMContext::MD_invariant_load))
941 
942  if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
943  AMDGPU::lookupRsrcIntrinsic(IntrID)) {
945  (Intrinsic::ID)IntrID);
946  if (Attr.hasFnAttr(Attribute::ReadNone))
947  return false;
948 
950 
951  if (RsrcIntr->IsImage) {
952  Info.ptrVal =
954  Info.align.reset();
955  } else {
956  Info.ptrVal =
958  }
959 
961  if (Attr.hasFnAttr(Attribute::ReadOnly)) {
962  unsigned DMaskLanes = 4;
963 
964  if (RsrcIntr->IsImage) {
967  const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
968  AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
969 
970  if (!BaseOpcode->Gather4) {
971  // If this isn't a gather, we may have excess loaded elements in the
972  // IR type. Check the dmask for the real number of elements loaded.
973  unsigned DMask
974  = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
975  DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
976  }
977 
978  Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
979  } else
980  Info.memVT = EVT::getEVT(CI.getType());
981 
982  // FIXME: What does alignment mean for an image?
985  } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
987 
988  Type *DataTy = CI.getArgOperand(0)->getType();
989  if (RsrcIntr->IsImage) {
990  unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
991  unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
992  Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
993  } else
994  Info.memVT = EVT::getEVT(DataTy);
995 
997  } else {
998  // Atomic
999  Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1001  Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1002  Info.flags |= MachineMemOperand::MOLoad |
1005 
1006  // XXX - Should this be volatile without known ordering?
1008 
1009  switch (IntrID) {
1010  default:
1011  break;
1012  case Intrinsic::amdgcn_raw_buffer_load_lds:
1013  case Intrinsic::amdgcn_struct_buffer_load_lds: {
1014  unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1015  Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1016  return true;
1017  }
1018  }
1019  }
1020  return true;
1021  }
1022 
1023  switch (IntrID) {
1024  case Intrinsic::amdgcn_atomic_inc:
1025  case Intrinsic::amdgcn_atomic_dec:
1026  case Intrinsic::amdgcn_ds_ordered_add:
1027  case Intrinsic::amdgcn_ds_ordered_swap:
1028  case Intrinsic::amdgcn_ds_fadd:
1029  case Intrinsic::amdgcn_ds_fmin:
1030  case Intrinsic::amdgcn_ds_fmax: {
1032  Info.memVT = MVT::getVT(CI.getType());
1033  Info.ptrVal = CI.getOperand(0);
1034  Info.align.reset();
1036 
1037  const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1038  if (!Vol->isZero())
1040 
1041  return true;
1042  }
1043  case Intrinsic::amdgcn_buffer_atomic_fadd: {
1045 
1047  Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1048  Info.ptrVal =
1050  Info.align.reset();
1052 
1053  const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1054  if (!Vol || !Vol->isZero())
1056 
1057  return true;
1058  }
1059  case Intrinsic::amdgcn_ds_append:
1060  case Intrinsic::amdgcn_ds_consume: {
1062  Info.memVT = MVT::getVT(CI.getType());
1063  Info.ptrVal = CI.getOperand(0);
1064  Info.align.reset();
1066 
1067  const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1068  if (!Vol->isZero())
1070 
1071  return true;
1072  }
1073  case Intrinsic::amdgcn_global_atomic_csub: {
1075  Info.memVT = MVT::getVT(CI.getType());
1076  Info.ptrVal = CI.getOperand(0);
1077  Info.align.reset();
1078  Info.flags |= MachineMemOperand::MOLoad |
1081  return true;
1082  }
1083  case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1086  Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1087  Info.ptrVal =
1089  Info.align.reset();
1090  Info.flags |= MachineMemOperand::MOLoad |
1092  return true;
1093  }
1094  case Intrinsic::amdgcn_global_atomic_fadd:
1095  case Intrinsic::amdgcn_global_atomic_fmin:
1096  case Intrinsic::amdgcn_global_atomic_fmax:
1097  case Intrinsic::amdgcn_flat_atomic_fadd:
1098  case Intrinsic::amdgcn_flat_atomic_fmin:
1099  case Intrinsic::amdgcn_flat_atomic_fmax:
1100  case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1101  case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1103  Info.memVT = MVT::getVT(CI.getType());
1104  Info.ptrVal = CI.getOperand(0);
1105  Info.align.reset();
1106  Info.flags |= MachineMemOperand::MOLoad |
1110  return true;
1111  }
1112  case Intrinsic::amdgcn_ds_gws_init:
1113  case Intrinsic::amdgcn_ds_gws_barrier:
1114  case Intrinsic::amdgcn_ds_gws_sema_v:
1115  case Intrinsic::amdgcn_ds_gws_sema_br:
1116  case Intrinsic::amdgcn_ds_gws_sema_p:
1117  case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1118  Info.opc = ISD::INTRINSIC_VOID;
1119 
1121  Info.ptrVal =
1123 
1124  // This is an abstract access, but we need to specify a type and size.
1125  Info.memVT = MVT::i32;
1126  Info.size = 4;
1127  Info.align = Align(4);
1128 
1129  if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1131  else
1133  return true;
1134  }
1135  case Intrinsic::amdgcn_global_load_lds: {
1136  Info.opc = ISD::INTRINSIC_VOID;
1137  unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1138  Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1141  return true;
1142  }
1143  default:
1144  return false;
1145  }
1146 }
1147 
1150  Type *&AccessTy) const {
1151  switch (II->getIntrinsicID()) {
1152  case Intrinsic::amdgcn_atomic_inc:
1153  case Intrinsic::amdgcn_atomic_dec:
1154  case Intrinsic::amdgcn_ds_ordered_add:
1155  case Intrinsic::amdgcn_ds_ordered_swap:
1156  case Intrinsic::amdgcn_ds_append:
1157  case Intrinsic::amdgcn_ds_consume:
1158  case Intrinsic::amdgcn_ds_fadd:
1159  case Intrinsic::amdgcn_ds_fmin:
1160  case Intrinsic::amdgcn_ds_fmax:
1161  case Intrinsic::amdgcn_global_atomic_fadd:
1162  case Intrinsic::amdgcn_flat_atomic_fadd:
1163  case Intrinsic::amdgcn_flat_atomic_fmin:
1164  case Intrinsic::amdgcn_flat_atomic_fmax:
1165  case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1166  case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1167  case Intrinsic::amdgcn_global_atomic_csub: {
1168  Value *Ptr = II->getArgOperand(0);
1169  AccessTy = II->getType();
1170  Ops.push_back(Ptr);
1171  return true;
1172  }
1173  default:
1174  return false;
1175  }
1176 }
1177 
1178 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1179  if (!Subtarget->hasFlatInstOffsets()) {
1180  // Flat instructions do not have offsets, and only have the register
1181  // address.
1182  return AM.BaseOffs == 0 && AM.Scale == 0;
1183  }
1184 
1185  return AM.Scale == 0 &&
1186  (AM.BaseOffs == 0 ||
1187  Subtarget->getInstrInfo()->isLegalFLATOffset(
1189 }
1190 
1192  if (Subtarget->hasFlatGlobalInsts())
1193  return AM.Scale == 0 &&
1194  (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1197 
1198  if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1199  // Assume the we will use FLAT for all global memory accesses
1200  // on VI.
1201  // FIXME: This assumption is currently wrong. On VI we still use
1202  // MUBUF instructions for the r + i addressing mode. As currently
1203  // implemented, the MUBUF instructions only work on buffer < 4GB.
1204  // It may be possible to support > 4GB buffers with MUBUF instructions,
1205  // by setting the stride value in the resource descriptor which would
1206  // increase the size limit to (stride * 4GB). However, this is risky,
1207  // because it has never been validated.
1208  return isLegalFlatAddressingMode(AM);
1209  }
1210 
1211  return isLegalMUBUFAddressingMode(AM);
1212 }
1213 
1214 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1215  // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1216  // additionally can do r + r + i with addr64. 32-bit has more addressing
1217  // mode options. Depending on the resource constant, it can also do
1218  // (i64 r0) + (i32 r1) * (i14 i).
1219  //
1220  // Private arrays end up using a scratch buffer most of the time, so also
1221  // assume those use MUBUF instructions. Scratch loads / stores are currently
1222  // implemented as mubuf instructions with offen bit set, so slightly
1223  // different than the normal addr64.
1224  if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1225  return false;
1226 
1227  // FIXME: Since we can split immediate into soffset and immediate offset,
1228  // would it make sense to allow any immediate?
1229 
1230  switch (AM.Scale) {
1231  case 0: // r + i or just i, depending on HasBaseReg.
1232  return true;
1233  case 1:
1234  return true; // We have r + r or r + i.
1235  case 2:
1236  if (AM.HasBaseReg) {
1237  // Reject 2 * r + r.
1238  return false;
1239  }
1240 
1241  // Allow 2 * r as r + r
1242  // Or 2 * r + i is allowed as r + r + i.
1243  return true;
1244  default: // Don't allow n * r
1245  return false;
1246  }
1247 }
1248 
1250  const AddrMode &AM, Type *Ty,
1251  unsigned AS, Instruction *I) const {
1252  // No global is ever allowed as a base.
1253  if (AM.BaseGV)
1254  return false;
1255 
1256  if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1257  return isLegalGlobalAddressingMode(AM);
1258 
1259  if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1262  // If the offset isn't a multiple of 4, it probably isn't going to be
1263  // correctly aligned.
1264  // FIXME: Can we get the real alignment here?
1265  if (AM.BaseOffs % 4 != 0)
1266  return isLegalMUBUFAddressingMode(AM);
1267 
1268  // There are no SMRD extloads, so if we have to do a small type access we
1269  // will use a MUBUF load.
1270  // FIXME?: We also need to do this if unaligned, but we don't know the
1271  // alignment here.
1272  if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1273  return isLegalGlobalAddressingMode(AM);
1274 
1275  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1276  // SMRD instructions have an 8-bit, dword offset on SI.
1277  if (!isUInt<8>(AM.BaseOffs / 4))
1278  return false;
1279  } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1280  // On CI+, this can also be a 32-bit literal constant offset. If it fits
1281  // in 8-bits, it can use a smaller encoding.
1282  if (!isUInt<32>(AM.BaseOffs / 4))
1283  return false;
1284  } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1285  // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1286  if (!isUInt<20>(AM.BaseOffs))
1287  return false;
1288  } else
1289  llvm_unreachable("unhandled generation");
1290 
1291  if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1292  return true;
1293 
1294  if (AM.Scale == 1 && AM.HasBaseReg)
1295  return true;
1296 
1297  return false;
1298 
1299  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1300  return isLegalMUBUFAddressingMode(AM);
1301  } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1302  AS == AMDGPUAS::REGION_ADDRESS) {
1303  // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1304  // field.
1305  // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1306  // an 8-bit dword offset but we don't know the alignment here.
1307  if (!isUInt<16>(AM.BaseOffs))
1308  return false;
1309 
1310  if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1311  return true;
1312 
1313  if (AM.Scale == 1 && AM.HasBaseReg)
1314  return true;
1315 
1316  return false;
1317  } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1319  // For an unknown address space, this usually means that this is for some
1320  // reason being used for pure arithmetic, and not based on some addressing
1321  // computation. We don't have instructions that compute pointers with any
1322  // addressing modes, so treat them as having no offset like flat
1323  // instructions.
1324  return isLegalFlatAddressingMode(AM);
1325  }
1326 
1327  // Assume a user alias of global for unknown address spaces.
1328  return isLegalGlobalAddressingMode(AM);
1329 }
1330 
1331 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1332  const MachineFunction &MF) const {
1333  if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1334  return (MemVT.getSizeInBits() <= 4 * 32);
1335  } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1336  unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1337  return (MemVT.getSizeInBits() <= MaxPrivateBits);
1338  } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1339  return (MemVT.getSizeInBits() <= 2 * 32);
1340  }
1341  return true;
1342 }
1343 
1345  unsigned Size, unsigned AddrSpace, Align Alignment,
1346  MachineMemOperand::Flags Flags, bool *IsFast) const {
1347  if (IsFast)
1348  *IsFast = false;
1349 
1350  if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1351  AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1352  // Check if alignment requirements for ds_read/write instructions are
1353  // disabled.
1354  if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1355  return false;
1356 
1357  Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1358  if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1359  Alignment < RequiredAlignment)
1360  return false;
1361 
1362  // Either, the alignment requirements are "enabled", or there is an
1363  // unaligned LDS access related hardware bug though alignment requirements
1364  // are "disabled". In either case, we need to check for proper alignment
1365  // requirements.
1366  //
1367  switch (Size) {
1368  case 64:
1369  // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1370  // address is negative, then the instruction is incorrectly treated as
1371  // out-of-bounds even if base + offsets is in bounds. Split vectorized
1372  // loads here to avoid emitting ds_read2_b32. We may re-combine the
1373  // load later in the SILoadStoreOptimizer.
1374  if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1375  return false;
1376 
1377  // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1378  // can do a 4 byte aligned, 8 byte access in a single operation using
1379  // ds_read2/write2_b32 with adjacent offsets.
1380  RequiredAlignment = Align(4);
1381 
1382  if (Subtarget->hasUnalignedDSAccessEnabled()) {
1383  // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1384  // ds_write2_b32 depending on the alignment. In either case with either
1385  // alignment there is no faster way of doing this.
1386  if (IsFast)
1387  *IsFast = true;
1388  return true;
1389  }
1390 
1391  break;
1392  case 96:
1393  if (!Subtarget->hasDS96AndDS128())
1394  return false;
1395 
1396  // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1397  // gfx8 and older.
1398 
1399  if (Subtarget->hasUnalignedDSAccessEnabled()) {
1400  // Naturally aligned access is fastest. However, also report it is Fast
1401  // if memory is aligned less than DWORD. A narrow load or store will be
1402  // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1403  // be more of them, so overall we will pay less penalty issuing a single
1404  // instruction.
1405  if (IsFast)
1406  *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1407  return true;
1408  }
1409 
1410  break;
1411  case 128:
1412  if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1413  return false;
1414 
1415  // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1416  // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a
1417  // single operation using ds_read2/write2_b64.
1418  RequiredAlignment = Align(8);
1419 
1420  if (Subtarget->hasUnalignedDSAccessEnabled()) {
1421  // Naturally aligned access is fastest. However, also report it is Fast
1422  // if memory is aligned less than DWORD. A narrow load or store will be
1423  // be equally slow as a single ds_read_b128/ds_write_b128, but there
1424  // will be more of them, so overall we will pay less penalty issuing a
1425  // single instruction.
1426  if (IsFast)
1427  *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1428  return true;
1429  }
1430 
1431  break;
1432  default:
1433  if (Size > 32)
1434  return false;
1435 
1436  break;
1437  }
1438 
1439  if (IsFast)
1440  *IsFast = Alignment >= RequiredAlignment;
1441 
1442  return Alignment >= RequiredAlignment ||
1443  Subtarget->hasUnalignedDSAccessEnabled();
1444  }
1445 
1446  if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1447  bool AlignedBy4 = Alignment >= Align(4);
1448  if (IsFast)
1449  *IsFast = AlignedBy4;
1450 
1451  return AlignedBy4 ||
1452  Subtarget->enableFlatScratch() ||
1453  Subtarget->hasUnalignedScratchAccess();
1454  }
1455 
1456  // FIXME: We have to be conservative here and assume that flat operations
1457  // will access scratch. If we had access to the IR function, then we
1458  // could determine if any private memory was used in the function.
1459  if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1460  !Subtarget->hasUnalignedScratchAccess()) {
1461  bool AlignedBy4 = Alignment >= Align(4);
1462  if (IsFast)
1463  *IsFast = AlignedBy4;
1464 
1465  return AlignedBy4;
1466  }
1467 
1468  if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1469  // If we have a uniform constant load, it still requires using a slow
1470  // buffer instruction if unaligned.
1471  if (IsFast) {
1472  // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1473  // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1474  *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1475  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1476  Alignment >= Align(4) : Alignment != Align(2);
1477  }
1478 
1479  return true;
1480  }
1481 
1482  // Smaller than dword value must be aligned.
1483  if (Size < 32)
1484  return false;
1485 
1486  // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1487  // byte-address are ignored, thus forcing Dword alignment.
1488  // This applies to private, global, and constant memory.
1489  if (IsFast)
1490  *IsFast = true;
1491 
1492  return Size >= 32 && Alignment >= Align(4);
1493 }
1494 
1496  EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1497  bool *IsFast) const {
1499  Alignment, Flags, IsFast);
1500 
1501  if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1502  (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1503  AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1504  // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1505  // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1506  // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1507  // which would be equally misaligned.
1508  // This is only used by the common passes, selection always calls the
1509  // allowsMisalignedMemoryAccessesImpl version.
1510  *IsFast = true;
1511  }
1512 
1513  return Allow;
1514 }
1515 
1517  const MemOp &Op, const AttributeList &FuncAttributes) const {
1518  // FIXME: Should account for address space here.
1519 
1520  // The default fallback uses the private pointer size as a guess for a type to
1521  // use. Make sure we switch these to 64-bit accesses.
1522 
1523  if (Op.size() >= 16 &&
1524  Op.isDstAligned(Align(4))) // XXX: Should only do for global
1525  return MVT::v4i32;
1526 
1527  if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1528  return MVT::v2i32;
1529 
1530  // Use the default.
1531  return MVT::Other;
1532 }
1533 
1535  const MemSDNode *MemNode = cast<MemSDNode>(N);
1536  return MemNode->getMemOperand()->getFlags() & MONoClobber;
1537 }
1538 
1540  return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1542 }
1543 
1545  unsigned DestAS) const {
1546  // Flat -> private/local is a simple truncate.
1547  // Flat -> global is no-op
1548  if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1549  return true;
1550 
1551  const GCNTargetMachine &TM =
1552  static_cast<const GCNTargetMachine &>(getTargetMachine());
1553  return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1554 }
1555 
1557  const MemSDNode *MemNode = cast<MemSDNode>(N);
1558 
1559  return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1560 }
1561 
1564  if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1568 }
1569 
1571  Type *Ty) const {
1572  // FIXME: Could be smarter if called for vector constants.
1573  return true;
1574 }
1575 
1577  if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1578  switch (Op) {
1579  case ISD::LOAD:
1580  case ISD::STORE:
1581 
1582  // These operations are done with 32-bit instructions anyway.
1583  case ISD::AND:
1584  case ISD::OR:
1585  case ISD::XOR:
1586  case ISD::SELECT:
1587  // TODO: Extensions?
1588  return true;
1589  default:
1590  return false;
1591  }
1592  }
1593 
1594  // SimplifySetCC uses this function to determine whether or not it should
1595  // create setcc with i1 operands. We don't have instructions for i1 setcc.
1596  if (VT == MVT::i1 && Op == ISD::SETCC)
1597  return false;
1598 
1600 }
1601 
1602 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1603  const SDLoc &SL,
1604  SDValue Chain,
1605  uint64_t Offset) const {
1606  const DataLayout &DL = DAG.getDataLayout();
1607  MachineFunction &MF = DAG.getMachineFunction();
1609 
1610  const ArgDescriptor *InputPtrReg;
1611  const TargetRegisterClass *RC;
1612  LLT ArgTy;
1614 
1615  std::tie(InputPtrReg, RC, ArgTy) =
1617 
1618  // We may not have the kernarg segment argument if we have no kernel
1619  // arguments.
1620  if (!InputPtrReg)
1621  return DAG.getConstant(0, SL, PtrVT);
1622 
1624  SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1625  MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1626 
1627  return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1628 }
1629 
1630 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1631  const SDLoc &SL) const {
1633  FIRST_IMPLICIT);
1634  return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1635 }
1636 
1637 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1638  const SDLoc &SL, SDValue Val,
1639  bool Signed,
1640  const ISD::InputArg *Arg) const {
1641  // First, if it is a widened vector, narrow it.
1642  if (VT.isVector() &&
1643  VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1644  EVT NarrowedVT =
1646  VT.getVectorNumElements());
1647  Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1648  DAG.getConstant(0, SL, MVT::i32));
1649  }
1650 
1651  // Then convert the vector elements or scalar value.
1652  if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1653  VT.bitsLT(MemVT)) {
1654  unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1655  Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1656  }
1657 
1658  if (MemVT.isFloatingPoint())
1659  Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1660  else if (Signed)
1661  Val = DAG.getSExtOrTrunc(Val, SL, VT);
1662  else
1663  Val = DAG.getZExtOrTrunc(Val, SL, VT);
1664 
1665  return Val;
1666 }
1667 
1668 SDValue SITargetLowering::lowerKernargMemParameter(
1669  SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1670  uint64_t Offset, Align Alignment, bool Signed,
1671  const ISD::InputArg *Arg) const {
1673 
1674  // Try to avoid using an extload by loading earlier than the argument address,
1675  // and extracting the relevant bits. The load should hopefully be merged with
1676  // the previous argument.
1677  if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1678  // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1679  int64_t AlignDownOffset = alignDown(Offset, 4);
1680  int64_t OffsetDiff = Offset - AlignDownOffset;
1681 
1682  EVT IntVT = MemVT.changeTypeToInteger();
1683 
1684  // TODO: If we passed in the base kernel offset we could have a better
1685  // alignment than 4, but we don't really need it.
1686  SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1687  SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1690 
1691  SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1692  SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1693 
1694  SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1695  ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1696  ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1697 
1698 
1699  return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1700  }
1701 
1702  SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1703  SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1706 
1707  SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1708  return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1709 }
1710 
1711 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1712  const SDLoc &SL, SDValue Chain,
1713  const ISD::InputArg &Arg) const {
1714  MachineFunction &MF = DAG.getMachineFunction();
1715  MachineFrameInfo &MFI = MF.getFrameInfo();
1716 
1717  if (Arg.Flags.isByVal()) {
1718  unsigned Size = Arg.Flags.getByValSize();
1719  int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1720  return DAG.getFrameIndex(FrameIdx, MVT::i32);
1721  }
1722 
1723  unsigned ArgOffset = VA.getLocMemOffset();
1724  unsigned ArgSize = VA.getValVT().getStoreSize();
1725 
1726  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1727 
1728  // Create load nodes to retrieve arguments from the stack.
1729  SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1730  SDValue ArgValue;
1731 
1732  // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1734  MVT MemVT = VA.getValVT();
1735 
1736  switch (VA.getLocInfo()) {
1737  default:
1738  break;
1739  case CCValAssign::BCvt:
1740  MemVT = VA.getLocVT();
1741  break;
1742  case CCValAssign::SExt:
1743  ExtType = ISD::SEXTLOAD;
1744  break;
1745  case CCValAssign::ZExt:
1746  ExtType = ISD::ZEXTLOAD;
1747  break;
1748  case CCValAssign::AExt:
1749  ExtType = ISD::EXTLOAD;
1750  break;
1751  }
1752 
1753  ArgValue = DAG.getExtLoad(
1754  ExtType, SL, VA.getLocVT(), Chain, FIN,
1756  MemVT);
1757  return ArgValue;
1758 }
1759 
1760 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1761  const SIMachineFunctionInfo &MFI,
1762  EVT VT,
1764  const ArgDescriptor *Reg;
1765  const TargetRegisterClass *RC;
1766  LLT Ty;
1767 
1768  std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1769  if (!Reg) {
1770  if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1771  // It's possible for a kernarg intrinsic call to appear in a kernel with
1772  // no allocated segment, in which case we do not add the user sgpr
1773  // argument, so just return null.
1774  return DAG.getConstant(0, SDLoc(), VT);
1775  }
1776 
1777  // It's undefined behavior if a function marked with the amdgpu-no-*
1778  // attributes uses the corresponding intrinsic.
1779  return DAG.getUNDEF(VT);
1780  }
1781 
1782  return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1783 }
1784 
1786  CallingConv::ID CallConv,
1788  FunctionType *FType,
1790  for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1791  const ISD::InputArg *Arg = &Ins[I];
1792 
1793  assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1794  "vector type argument should have been split");
1795 
1796  // First check if it's a PS input addr.
1797  if (CallConv == CallingConv::AMDGPU_PS &&
1798  !Arg->Flags.isInReg() && PSInputNum <= 15) {
1799  bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1800 
1801  // Inconveniently only the first part of the split is marked as isSplit,
1802  // so skip to the end. We only want to increment PSInputNum once for the
1803  // entire split argument.
1804  if (Arg->Flags.isSplit()) {
1805  while (!Arg->Flags.isSplitEnd()) {
1806  assert((!Arg->VT.isVector() ||
1807  Arg->VT.getScalarSizeInBits() == 16) &&
1808  "unexpected vector split in ps argument type");
1809  if (!SkipArg)
1810  Splits.push_back(*Arg);
1811  Arg = &Ins[++I];
1812  }
1813  }
1814 
1815  if (SkipArg) {
1816  // We can safely skip PS inputs.
1817  Skipped.set(Arg->getOrigArgIndex());
1818  ++PSInputNum;
1819  continue;
1820  }
1821 
1822  Info->markPSInputAllocated(PSInputNum);
1823  if (Arg->Used)
1824  Info->markPSInputEnabled(PSInputNum);
1825 
1826  ++PSInputNum;
1827  }
1828 
1829  Splits.push_back(*Arg);
1830  }
1831 }
1832 
1833 // Allocate special inputs passed in VGPRs.
1835  MachineFunction &MF,
1836  const SIRegisterInfo &TRI,
1837  SIMachineFunctionInfo &Info) const {
1838  const LLT S32 = LLT::scalar(32);
1840 
1841  if (Info.hasWorkItemIDX()) {
1842  Register Reg = AMDGPU::VGPR0;
1843  MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1844 
1845  CCInfo.AllocateReg(Reg);
1846  unsigned Mask = (Subtarget->hasPackedTID() &&
1847  Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1848  Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1849  }
1850 
1851  if (Info.hasWorkItemIDY()) {
1852  assert(Info.hasWorkItemIDX());
1853  if (Subtarget->hasPackedTID()) {
1854  Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1855  0x3ff << 10));
1856  } else {
1857  unsigned Reg = AMDGPU::VGPR1;
1858  MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1859 
1860  CCInfo.AllocateReg(Reg);
1861  Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1862  }
1863  }
1864 
1865  if (Info.hasWorkItemIDZ()) {
1866  assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1867  if (Subtarget->hasPackedTID()) {
1868  Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1869  0x3ff << 20));
1870  } else {
1871  unsigned Reg = AMDGPU::VGPR2;
1872  MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1873 
1874  CCInfo.AllocateReg(Reg);
1875  Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1876  }
1877  }
1878 }
1879 
1880 // Try to allocate a VGPR at the end of the argument list, or if no argument
1881 // VGPRs are left allocating a stack slot.
1882 // If \p Mask is is given it indicates bitfield position in the register.
1883 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1884 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1886  if (Arg.isSet())
1888 
1889  ArrayRef<MCPhysReg> ArgVGPRs
1890  = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1891  unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1892  if (RegIdx == ArgVGPRs.size()) {
1893  // Spill to stack required.
1894  int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1895 
1896  return ArgDescriptor::createStack(Offset, Mask);
1897  }
1898 
1899  unsigned Reg = ArgVGPRs[RegIdx];
1900  Reg = CCInfo.AllocateReg(Reg);
1901  assert(Reg != AMDGPU::NoRegister);
1902 
1903  MachineFunction &MF = CCInfo.getMachineFunction();
1904  Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1905  MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1907 }
1908 
1910  const TargetRegisterClass *RC,
1911  unsigned NumArgRegs) {
1912  ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1913  unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1914  if (RegIdx == ArgSGPRs.size())
1915  report_fatal_error("ran out of SGPRs for arguments");
1916 
1917  unsigned Reg = ArgSGPRs[RegIdx];
1918  Reg = CCInfo.AllocateReg(Reg);
1919  assert(Reg != AMDGPU::NoRegister);
1920 
1921  MachineFunction &MF = CCInfo.getMachineFunction();
1922  MF.addLiveIn(Reg, RC);
1924 }
1925 
1926 // If this has a fixed position, we still should allocate the register in the
1927 // CCInfo state. Technically we could get away with this for values passed
1928 // outside of the normal argument range.
1930  const TargetRegisterClass *RC,
1931  MCRegister Reg) {
1932  Reg = CCInfo.AllocateReg(Reg);
1933  assert(Reg != AMDGPU::NoRegister);
1934  MachineFunction &MF = CCInfo.getMachineFunction();
1935  MF.addLiveIn(Reg, RC);
1936 }
1937 
1939  if (Arg) {
1940  allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1941  Arg.getRegister());
1942  } else
1943  Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1944 }
1945 
1947  if (Arg) {
1948  allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1949  Arg.getRegister());
1950  } else
1951  Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1952 }
1953 
1954 /// Allocate implicit function VGPR arguments at the end of allocated user
1955 /// arguments.
1957  CCState &CCInfo, MachineFunction &MF,
1958  const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1959  const unsigned Mask = 0x3ff;
1961 
1962  if (Info.hasWorkItemIDX()) {
1963  Arg = allocateVGPR32Input(CCInfo, Mask);
1964  Info.setWorkItemIDX(Arg);
1965  }
1966 
1967  if (Info.hasWorkItemIDY()) {
1968  Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1969  Info.setWorkItemIDY(Arg);
1970  }
1971 
1972  if (Info.hasWorkItemIDZ())
1973  Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1974 }
1975 
1976 /// Allocate implicit function VGPR arguments in fixed registers.
1978  CCState &CCInfo, MachineFunction &MF,
1979  const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1980  Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1981  if (!Reg)
1982  report_fatal_error("failed to allocated VGPR for implicit arguments");
1983 
1984  const unsigned Mask = 0x3ff;
1985  Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1986  Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1987  Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1988 }
1989 
1991  CCState &CCInfo,
1992  MachineFunction &MF,
1993  const SIRegisterInfo &TRI,
1994  SIMachineFunctionInfo &Info) const {
1995  auto &ArgInfo = Info.getArgInfo();
1996 
1997  // TODO: Unify handling with private memory pointers.
1998  if (Info.hasDispatchPtr())
1999  allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2000 
2001  if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2002  allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2003 
2004  // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2005  // constant offset from the kernarg segment.
2006  if (Info.hasImplicitArgPtr())
2007  allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2008 
2009  if (Info.hasDispatchID())
2010  allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2011 
2012  // flat_scratch_init is not applicable for non-kernel functions.
2013 
2014  if (Info.hasWorkGroupIDX())
2015  allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2016 
2017  if (Info.hasWorkGroupIDY())
2018  allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2019 
2020  if (Info.hasWorkGroupIDZ())
2021  allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2022 }
2023 
2024 // Allocate special inputs passed in user SGPRs.
2026  MachineFunction &MF,
2027  const SIRegisterInfo &TRI,
2028  SIMachineFunctionInfo &Info) const {
2029  if (Info.hasImplicitBufferPtr()) {
2030  Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2031  MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2032  CCInfo.AllocateReg(ImplicitBufferPtrReg);
2033  }
2034 
2035  // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2036  if (Info.hasPrivateSegmentBuffer()) {
2037  Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2038  MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2039  CCInfo.AllocateReg(PrivateSegmentBufferReg);
2040  }
2041 
2042  if (Info.hasDispatchPtr()) {
2043  Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2044  MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2045  CCInfo.AllocateReg(DispatchPtrReg);
2046  }
2047 
2048  if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2049  Register QueuePtrReg = Info.addQueuePtr(TRI);
2050  MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2051  CCInfo.AllocateReg(QueuePtrReg);
2052  }
2053 
2054  if (Info.hasKernargSegmentPtr()) {
2056  Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2057  CCInfo.AllocateReg(InputPtrReg);
2058 
2059  Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2061  }
2062 
2063  if (Info.hasDispatchID()) {
2064  Register DispatchIDReg = Info.addDispatchID(TRI);
2065  MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2066  CCInfo.AllocateReg(DispatchIDReg);
2067  }
2068 
2069  if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2070  Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2071  MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2072  CCInfo.AllocateReg(FlatScratchInitReg);
2073  }
2074 
2075  // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2076  // these from the dispatch pointer.
2077 }
2078 
2079 // Allocate special input registers that are initialized per-wave.
2081  MachineFunction &MF,
2083  CallingConv::ID CallConv,
2084  bool IsShader) const {
2085  if (Info.hasWorkGroupIDX()) {
2086  Register Reg = Info.addWorkGroupIDX();
2087  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2088  CCInfo.AllocateReg(Reg);
2089  }
2090 
2091  if (Info.hasWorkGroupIDY()) {
2092  Register Reg = Info.addWorkGroupIDY();
2093  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2094  CCInfo.AllocateReg(Reg);
2095  }
2096 
2097  if (Info.hasWorkGroupIDZ()) {
2098  Register Reg = Info.addWorkGroupIDZ();
2099  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2100  CCInfo.AllocateReg(Reg);
2101  }
2102 
2103  if (Info.hasWorkGroupInfo()) {
2104  Register Reg = Info.addWorkGroupInfo();
2105  MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2106  CCInfo.AllocateReg(Reg);
2107  }
2108 
2109  if (Info.hasPrivateSegmentWaveByteOffset()) {
2110  // Scratch wave offset passed in system SGPR.
2111  unsigned PrivateSegmentWaveByteOffsetReg;
2112 
2113  if (IsShader) {
2114  PrivateSegmentWaveByteOffsetReg =
2115  Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2116 
2117  // This is true if the scratch wave byte offset doesn't have a fixed
2118  // location.
2119  if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2120  PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2121  Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2122  }
2123  } else
2124  PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2125 
2126  MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2127  CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2128  }
2129 }
2130 
2132  MachineFunction &MF,
2133  const SIRegisterInfo &TRI,
2135  // Now that we've figured out where the scratch register inputs are, see if
2136  // should reserve the arguments and use them directly.
2137  MachineFrameInfo &MFI = MF.getFrameInfo();
2138  bool HasStackObjects = MFI.hasStackObjects();
2139  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2140 
2141  // Record that we know we have non-spill stack objects so we don't need to
2142  // check all stack objects later.
2143  if (HasStackObjects)
2144  Info.setHasNonSpillStackObjects(true);
2145 
2146  // Everything live out of a block is spilled with fast regalloc, so it's
2147  // almost certain that spilling will be required.
2148  if (TM.getOptLevel() == CodeGenOpt::None)
2149  HasStackObjects = true;
2150 
2151  // For now assume stack access is needed in any callee functions, so we need
2152  // the scratch registers to pass in.
2153  bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2154 
2155  if (!ST.enableFlatScratch()) {
2156  if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2157  // If we have stack objects, we unquestionably need the private buffer
2158  // resource. For the Code Object V2 ABI, this will be the first 4 user
2159  // SGPR inputs. We can reserve those and use them directly.
2160 
2161  Register PrivateSegmentBufferReg =
2163  Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2164  } else {
2165  unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2166  // We tentatively reserve the last registers (skipping the last registers
2167  // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2168  // we'll replace these with the ones immediately after those which were
2169  // really allocated. In the prologue copies will be inserted from the
2170  // argument to these reserved registers.
2171 
2172  // Without HSA, relocations are used for the scratch pointer and the
2173  // buffer resource setup is always inserted in the prologue. Scratch wave
2174  // offset is still in an input SGPR.
2175  Info.setScratchRSrcReg(ReservedBufferReg);
2176  }
2177  }
2178 
2180 
2181  // For entry functions we have to set up the stack pointer if we use it,
2182  // whereas non-entry functions get this "for free". This means there is no
2183  // intrinsic advantage to using S32 over S34 in cases where we do not have
2184  // calls but do need a frame pointer (i.e. if we are requested to have one
2185  // because frame pointer elimination is disabled). To keep things simple we
2186  // only ever use S32 as the call ABI stack pointer, and so using it does not
2187  // imply we need a separate frame pointer.
2188  //
2189  // Try to use s32 as the SP, but move it if it would interfere with input
2190  // arguments. This won't work with calls though.
2191  //
2192  // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2193  // registers.
2194  if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2195  Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2196  } else {
2198 
2199  if (MFI.hasCalls())
2200  report_fatal_error("call in graphics shader with too many input SGPRs");
2201 
2202  for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2203  if (!MRI.isLiveIn(Reg)) {
2204  Info.setStackPtrOffsetReg(Reg);
2205  break;
2206  }
2207  }
2208 
2209  if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2210  report_fatal_error("failed to find register for SP");
2211  }
2212 
2213  // hasFP should be accurate for entry functions even before the frame is
2214  // finalized, because it does not rely on the known stack size, only
2215  // properties like whether variable sized objects are present.
2216  if (ST.getFrameLowering()->hasFP(MF)) {
2217  Info.setFrameOffsetReg(AMDGPU::SGPR33);
2218  }
2219 }
2220 
2223  return !Info->isEntryFunction();
2224 }
2225 
2227 
2228 }
2229 
2231  MachineBasicBlock *Entry,
2232  const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2234 
2235  const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2236  if (!IStart)
2237  return;
2238 
2239  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2240  MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2241  MachineBasicBlock::iterator MBBI = Entry->begin();
2242  for (const MCPhysReg *I = IStart; *I; ++I) {
2243  const TargetRegisterClass *RC = nullptr;
2244  if (AMDGPU::SReg_64RegClass.contains(*I))
2245  RC = &AMDGPU::SGPR_64RegClass;
2246  else if (AMDGPU::SReg_32RegClass.contains(*I))
2247  RC = &AMDGPU::SGPR_32RegClass;
2248  else
2249  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2250 
2251  Register NewVR = MRI->createVirtualRegister(RC);
2252  // Create copy from CSR to a virtual register.
2253  Entry->addLiveIn(*I);
2254  BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2255  .addReg(*I);
2256 
2257  // Insert the copy-back instructions right before the terminator.
2258  for (auto *Exit : Exits)
2259  BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2260  TII->get(TargetOpcode::COPY), *I)
2261  .addReg(NewVR);
2262  }
2263 }
2264 
2266  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2267  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2268  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2270 
2271  MachineFunction &MF = DAG.getMachineFunction();
2272  const Function &Fn = MF.getFunction();
2273  FunctionType *FType = MF.getFunction().getFunctionType();
2275 
2276  if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2277  DiagnosticInfoUnsupported NoGraphicsHSA(
2278  Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2279  DAG.getContext()->diagnose(NoGraphicsHSA);
2280  return DAG.getEntryNode();
2281  }
2282 
2283  Info->allocateModuleLDSGlobal(Fn);
2284 
2287  BitVector Skipped(Ins.size());
2288  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2289  *DAG.getContext());
2290 
2291  bool IsGraphics = AMDGPU::isGraphics(CallConv);
2292  bool IsKernel = AMDGPU::isKernel(CallConv);
2293  bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2294 
2295  if (IsGraphics) {
2296  assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2297  (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2298  !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2299  !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2300  !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2301  !Info->hasWorkItemIDZ());
2302  }
2303 
2304  if (CallConv == CallingConv::AMDGPU_PS) {
2305  processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2306 
2307  // At least one interpolation mode must be enabled or else the GPU will
2308  // hang.
2309  //
2310  // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2311  // set PSInputAddr, the user wants to enable some bits after the compilation
2312  // based on run-time states. Since we can't know what the final PSInputEna
2313  // will look like, so we shouldn't do anything here and the user should take
2314  // responsibility for the correct programming.
2315  //
2316  // Otherwise, the following restrictions apply:
2317  // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2318  // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2319  // enabled too.
2320  if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2321  ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2322  CCInfo.AllocateReg(AMDGPU::VGPR0);
2323  CCInfo.AllocateReg(AMDGPU::VGPR1);
2324  Info->markPSInputAllocated(0);
2325  Info->markPSInputEnabled(0);
2326  }
2327  if (Subtarget->isAmdPalOS()) {
2328  // For isAmdPalOS, the user does not enable some bits after compilation
2329  // based on run-time states; the register values being generated here are
2330  // the final ones set in hardware. Therefore we need to apply the
2331  // workaround to PSInputAddr and PSInputEnable together. (The case where
2332  // a bit is set in PSInputAddr but not PSInputEnable is where the
2333  // frontend set up an input arg for a particular interpolation mode, but
2334  // nothing uses that input arg. Really we should have an earlier pass
2335  // that removes such an arg.)
2336  unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2337  if ((PsInputBits & 0x7F) == 0 ||
2338  ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2339  Info->markPSInputEnabled(
2340  countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2341  }
2342  } else if (IsKernel) {
2343  assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2344  } else {
2345  Splits.append(Ins.begin(), Ins.end());
2346  }
2347 
2348  if (IsEntryFunc) {
2349  allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2350  allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2351  } else if (!IsGraphics) {
2352  // For the fixed ABI, pass workitem IDs in the last argument register.
2353  allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2354  }
2355 
2356  if (IsKernel) {
2358  } else {
2359  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2360  CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2361  }
2362 
2363  SmallVector<SDValue, 16> Chains;
2364 
2365  // FIXME: This is the minimum kernel argument alignment. We should improve
2366  // this to the maximum alignment of the arguments.
2367  //
2368  // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2369  // kern arg offset.
2370  const Align KernelArgBaseAlign = Align(16);
2371 
2372  for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2373  const ISD::InputArg &Arg = Ins[i];
2374  if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2375  InVals.push_back(DAG.getUNDEF(Arg.VT));
2376  continue;
2377  }
2378 
2379  CCValAssign &VA = ArgLocs[ArgIdx++];
2380  MVT VT = VA.getLocVT();
2381 
2382  if (IsEntryFunc && VA.isMemLoc()) {
2383  VT = Ins[i].VT;
2384  EVT MemVT = VA.getLocVT();
2385 
2386  const uint64_t Offset = VA.getLocMemOffset();
2387  Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2388 
2389  if (Arg.Flags.isByRef()) {
2390  SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2391 
2392  const GCNTargetMachine &TM =
2393  static_cast<const GCNTargetMachine &>(getTargetMachine());
2394  if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2395  Arg.Flags.getPointerAddrSpace())) {
2396  Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2397  Arg.Flags.getPointerAddrSpace());
2398  }
2399 
2400  InVals.push_back(Ptr);
2401  continue;
2402  }
2403 
2404  SDValue Arg = lowerKernargMemParameter(
2405  DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2406  Chains.push_back(Arg.getValue(1));
2407 
2408  auto *ParamTy =
2409  dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2410  if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2411  ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2412  ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2413  // On SI local pointers are just offsets into LDS, so they are always
2414  // less than 16-bits. On CI and newer they could potentially be
2415  // real pointers, so we can't guarantee their size.
2416  Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2417  DAG.getValueType(MVT::i16));
2418  }
2419 
2420  InVals.push_back(Arg);
2421  continue;
2422  } else if (!IsEntryFunc && VA.isMemLoc()) {
2423  SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2424  InVals.push_back(Val);
2425  if (!Arg.Flags.isByVal())
2426  Chains.push_back(Val.getValue(1));
2427  continue;
2428  }
2429 
2430  assert(VA.isRegLoc() && "Parameter must be in a register!");
2431 
2432  Register Reg = VA.getLocReg();
2433  const TargetRegisterClass *RC = nullptr;
2434  if (AMDGPU::VGPR_32RegClass.contains(Reg))
2435  RC = &AMDGPU::VGPR_32RegClass;
2436  else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2437  RC = &AMDGPU::SGPR_32RegClass;
2438  else
2439  llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2440  EVT ValVT = VA.getValVT();
2441 
2442  Reg = MF.addLiveIn(Reg, RC);
2443  SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2444 
2445  if (Arg.Flags.isSRet()) {
2446  // The return object should be reasonably addressable.
2447 
2448  // FIXME: This helps when the return is a real sret. If it is a
2449  // automatically inserted sret (i.e. CanLowerReturn returns false), an
2450  // extra copy is inserted in SelectionDAGBuilder which obscures this.
2451  unsigned NumBits
2453  Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2454  DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2455  }
2456 
2457  // If this is an 8 or 16-bit value, it is really passed promoted
2458  // to 32 bits. Insert an assert[sz]ext to capture this, then
2459  // truncate to the right size.
2460  switch (VA.getLocInfo()) {
2461  case CCValAssign::Full:
2462  break;
2463  case CCValAssign::BCvt:
2464  Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2465  break;
2466  case CCValAssign::SExt:
2467  Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2468  DAG.getValueType(ValVT));
2469  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2470  break;
2471  case CCValAssign::ZExt:
2472  Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2473  DAG.getValueType(ValVT));
2474  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2475  break;
2476  case CCValAssign::AExt:
2477  Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2478  break;
2479  default:
2480  llvm_unreachable("Unknown loc info!");
2481  }
2482 
2483  InVals.push_back(Val);
2484  }
2485 
2486  // Start adding system SGPRs.
2487  if (IsEntryFunc) {
2488  allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2489  } else {
2490  CCInfo.AllocateReg(Info->getScratchRSrcReg());
2491  if (!IsGraphics)
2492  allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2493  }
2494 
2495  auto &ArgUsageInfo =
2497  ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2498 
2499  unsigned StackArgSize = CCInfo.getNextStackOffset();
2500  Info->setBytesInStackArgArea(StackArgSize);
2501 
2502  return Chains.empty() ? Chain :
2503  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2504 }
2505 
2506 // TODO: If return values can't fit in registers, we should return as many as
2507 // possible in registers before passing on stack.
2509  CallingConv::ID CallConv,
2510  MachineFunction &MF, bool IsVarArg,
2511  const SmallVectorImpl<ISD::OutputArg> &Outs,
2512  LLVMContext &Context) const {
2513  // Replacing returns with sret/stack usage doesn't make sense for shaders.
2514  // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2515  // for shaders. Vector types should be explicitly handled by CC.
2516  if (AMDGPU::isEntryFunctionCC(CallConv))
2517  return true;
2518 
2520  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2521  return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2522 }
2523 
2524 SDValue
2526  bool isVarArg,
2527  const SmallVectorImpl<ISD::OutputArg> &Outs,
2528  const SmallVectorImpl<SDValue> &OutVals,
2529  const SDLoc &DL, SelectionDAG &DAG) const {
2530  MachineFunction &MF = DAG.getMachineFunction();
2532 
2533  if (AMDGPU::isKernel(CallConv)) {
2534  return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2535  OutVals, DL, DAG);
2536  }
2537 
2538  bool IsShader = AMDGPU::isShader(CallConv);
2539 
2540  Info->setIfReturnsVoid(Outs.empty());
2541  bool IsWaveEnd = Info->returnsVoid() && IsShader;
2542 
2543  // CCValAssign - represent the assignment of the return value to a location.
2546 
2547  // CCState - Info about the registers and stack slots.
2548  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2549  *DAG.getContext());
2550 
2551  // Analyze outgoing return values.
2552  CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2553 
2554  SDValue Flag;
2555  SmallVector<SDValue, 48> RetOps;
2556  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2557 
2558  // Copy the result values into the output registers.
2559  for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2560  ++I, ++RealRVLocIdx) {
2561  CCValAssign &VA = RVLocs[I];
2562  assert(VA.isRegLoc() && "Can only return in registers!");
2563  // TODO: Partially return in registers if return values don't fit.
2564  SDValue Arg = OutVals[RealRVLocIdx];
2565 
2566  // Copied from other backends.
2567  switch (VA.getLocInfo()) {
2568  case CCValAssign::Full:
2569  break;
2570  case CCValAssign::BCvt:
2571  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2572  break;
2573  case CCValAssign::SExt:
2574  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2575  break;
2576  case CCValAssign::ZExt:
2577  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2578  break;
2579  case CCValAssign::AExt:
2580  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2581  break;
2582  default:
2583  llvm_unreachable("Unknown loc info!");
2584  }
2585 
2586  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2587  Flag = Chain.getValue(1);
2588  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2589  }
2590 
2591  // FIXME: Does sret work properly?
2592  if (!Info->isEntryFunction()) {
2593  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2594  const MCPhysReg *I =
2595  TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2596  if (I) {
2597  for (; *I; ++I) {
2598  if (AMDGPU::SReg_64RegClass.contains(*I))
2599  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2600  else if (AMDGPU::SReg_32RegClass.contains(*I))
2601  RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2602  else
2603  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2604  }
2605  }
2606  }
2607 
2608  // Update chain and glue.
2609  RetOps[0] = Chain;
2610  if (Flag.getNode())
2611  RetOps.push_back(Flag);
2612 
2613  unsigned Opc = AMDGPUISD::ENDPGM;
2614  if (!IsWaveEnd)
2616  return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2617 }
2618 
2620  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2621  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2622  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2623  SDValue ThisVal) const {
2624  CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2625 
2626  // Assign locations to each value returned by this call.
2628  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2629  *DAG.getContext());
2630  CCInfo.AnalyzeCallResult(Ins, RetCC);
2631 
2632  // Copy all of the result registers out of their specified physreg.
2633  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2634  CCValAssign VA = RVLocs[i];
2635  SDValue Val;
2636 
2637  if (VA.isRegLoc()) {
2638  Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2639  Chain = Val.getValue(1);
2640  InFlag = Val.getValue(2);
2641  } else if (VA.isMemLoc()) {
2642  report_fatal_error("TODO: return values in memory");
2643  } else
2644  llvm_unreachable("unknown argument location type");
2645 
2646  switch (VA.getLocInfo()) {
2647  case CCValAssign::Full:
2648  break;
2649  case CCValAssign::BCvt:
2650  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2651  break;
2652  case CCValAssign::ZExt:
2653  Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2654  DAG.getValueType(VA.getValVT()));
2655  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2656  break;
2657  case CCValAssign::SExt:
2658  Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2659  DAG.getValueType(VA.getValVT()));
2660  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2661  break;
2662  case CCValAssign::AExt:
2663  Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2664  break;
2665  default:
2666  llvm_unreachable("Unknown loc info!");
2667  }
2668 
2669  InVals.push_back(Val);
2670  }
2671 
2672  return Chain;
2673 }
2674 
2675 // Add code to pass special inputs required depending on used features separate
2676 // from the explicit user arguments present in the IR.
2678  CallLoweringInfo &CLI,
2679  CCState &CCInfo,
2680  const SIMachineFunctionInfo &Info,
2681  SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2682  SmallVectorImpl<SDValue> &MemOpChains,
2683  SDValue Chain) const {
2684  // If we don't have a call site, this was a call inserted by
2685  // legalization. These can never use special inputs.
2686  if (!CLI.CB)
2687  return;
2688 
2689  SelectionDAG &DAG = CLI.DAG;
2690  const SDLoc &DL = CLI.DL;
2691  const Function &F = DAG.getMachineFunction().getFunction();
2692 
2693  const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2694  const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2695 
2696  const AMDGPUFunctionArgInfo *CalleeArgInfo
2698  if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2699  auto &ArgUsageInfo =
2701  CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2702  }
2703 
2704  // TODO: Unify with private memory register handling. This is complicated by
2705  // the fact that at least in kernels, the input argument is not necessarily
2706  // in the same location as the input.
2707  static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2709  {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2710  {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2711  {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2712  {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2713  {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2714  {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2715  {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2716  };
2717 
2718  for (auto Attr : ImplicitAttrs) {
2719  const ArgDescriptor *OutgoingArg;
2720  const TargetRegisterClass *ArgRC;
2721  LLT ArgTy;
2722 
2723  AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2724 
2725  // If the callee does not use the attribute value, skip copying the value.
2726  if (CLI.CB->hasFnAttr(Attr.second))
2727  continue;
2728 
2729  std::tie(OutgoingArg, ArgRC, ArgTy) =
2730  CalleeArgInfo->getPreloadedValue(InputID);
2731  if (!OutgoingArg)
2732  continue;
2733 
2734  const ArgDescriptor *IncomingArg;
2735  const TargetRegisterClass *IncomingArgRC;
2736  LLT Ty;
2737  std::tie(IncomingArg, IncomingArgRC, Ty) =
2738  CallerArgInfo.getPreloadedValue(InputID);
2739  assert(IncomingArgRC == ArgRC);
2740 
2741  // All special arguments are ints for now.
2742  EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2743  SDValue InputReg;
2744 
2745  if (IncomingArg) {
2746  InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2747  } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2748  // The implicit arg ptr is special because it doesn't have a corresponding
2749  // input for kernels, and is computed from the kernarg segment pointer.
2750  InputReg = getImplicitArgPtr(DAG, DL);
2751  } else {
2752  // We may have proven the input wasn't needed, although the ABI is
2753  // requiring it. We just need to allocate the register appropriately.
2754  InputReg = DAG.getUNDEF(ArgVT);
2755  }
2756 
2757  if (OutgoingArg->isRegister()) {
2758  RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2759  if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2760  report_fatal_error("failed to allocate implicit input argument");
2761  } else {
2762  unsigned SpecialArgOffset =
2763  CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2764  SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2765  SpecialArgOffset);
2766  MemOpChains.push_back(ArgStore);
2767  }
2768  }
2769 
2770  // Pack workitem IDs into a single register or pass it as is if already
2771  // packed.
2772  const ArgDescriptor *OutgoingArg;
2773  const TargetRegisterClass *ArgRC;
2774  LLT Ty;
2775 
2776  std::tie(OutgoingArg, ArgRC, Ty) =
2778  if (!OutgoingArg)
2779  std::tie(OutgoingArg, ArgRC, Ty) =
2781  if (!OutgoingArg)
2782  std::tie(OutgoingArg, ArgRC, Ty) =
2784  if (!OutgoingArg)
2785  return;
2786 
2787  const ArgDescriptor *IncomingArgX = std::get<0>(
2789  const ArgDescriptor *IncomingArgY = std::get<0>(
2791  const ArgDescriptor *IncomingArgZ = std::get<0>(
2793 
2794  SDValue InputReg;
2795  SDLoc SL;
2796 
2797  const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2798  const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2799  const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2800 
2801  // If incoming ids are not packed we need to pack them.
2802  if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2803  NeedWorkItemIDX) {
2804  if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2805  InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2806  } else {
2807  InputReg = DAG.getConstant(0, DL, MVT::i32);
2808  }
2809  }
2810 
2811  if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2812  NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2813  SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2814  Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2815  DAG.getShiftAmountConstant(10, MVT::i32, SL));
2816  InputReg = InputReg.getNode() ?
2817  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2818  }
2819 
2820  if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2821  NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2822  SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2823  Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2824  DAG.getShiftAmountConstant(20, MVT::i32, SL));
2825  InputReg = InputReg.getNode() ?
2826  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2827  }
2828 
2829  if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2830  if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2831  // We're in a situation where the outgoing function requires the workitem
2832  // ID, but the calling function does not have it (e.g a graphics function
2833  // calling a C calling convention function). This is illegal, but we need
2834  // to produce something.
2835  InputReg = DAG.getUNDEF(MVT::i32);
2836  } else {
2837  // Workitem ids are already packed, any of present incoming arguments
2838  // will carry all required fields.
2840  IncomingArgX ? *IncomingArgX :
2841  IncomingArgY ? *IncomingArgY :
2842  *IncomingArgZ, ~0u);
2843  InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2844  }
2845  }
2846 
2847  if (OutgoingArg->isRegister()) {
2848  if (InputReg)
2849  RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2850 
2851  CCInfo.AllocateReg(OutgoingArg->getRegister());
2852  } else {
2853  unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2854  if (InputReg) {
2855  SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2856  SpecialArgOffset);
2857  MemOpChains.push_back(ArgStore);
2858  }
2859  }
2860 }
2861 
2863  return CC == CallingConv::Fast;
2864 }
2865 
2866 /// Return true if we might ever do TCO for calls with this calling convention.
2868  switch (CC) {
2869  case CallingConv::C:
2871  return true;
2872  default:
2873  return canGuaranteeTCO(CC);
2874  }
2875 }
2876 
2878  SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2879  const SmallVectorImpl<ISD::OutputArg> &Outs,
2880  const SmallVectorImpl<SDValue> &OutVals,
2881  const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2882  if (!mayTailCallThisCC(CalleeCC))
2883  return false;
2884 
2885  // For a divergent call target, we need to do a waterfall loop over the
2886  // possible callees which precludes us from using a simple jump.
2887  if (Callee->isDivergent())
2888  return false;
2889 
2890  MachineFunction &MF = DAG.getMachineFunction();
2891  const Function &CallerF = MF.getFunction();
2892  CallingConv::ID CallerCC = CallerF.getCallingConv();
2894  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2895 
2896  // Kernels aren't callable, and don't have a live in return address so it
2897  // doesn't make sense to do a tail call with entry functions.
2898  if (!CallerPreserved)
2899  return false;
2900 
2901  bool CCMatch = CallerCC == CalleeCC;
2902 
2904  if (canGuaranteeTCO(CalleeCC) && CCMatch)
2905  return true;
2906  return false;
2907  }
2908 
2909  // TODO: Can we handle var args?
2910  if (IsVarArg)
2911  return false;
2912 
2913  for (const Argument &Arg : CallerF.args()) {
2914  if (Arg.hasByValAttr())
2915  return false;
2916  }
2917 
2918  LLVMContext &Ctx = *DAG.getContext();
2919 
2920  // Check that the call results are passed in the same way.
2921  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2922  CCAssignFnForCall(CalleeCC, IsVarArg),
2923  CCAssignFnForCall(CallerCC, IsVarArg)))
2924  return false;
2925 
2926  // The callee has to preserve all registers the caller needs to preserve.
2927  if (!CCMatch) {
2928  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2929  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2930  return false;
2931  }
2932 
2933  // Nothing more to check if the callee is taking no arguments.
2934  if (Outs.empty())
2935  return true;
2936 
2938  CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2939 
2940  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2941 
2942  const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2943  // If the stack arguments for this call do not fit into our own save area then
2944  // the call cannot be made tail.
2945  // TODO: Is this really necessary?
2946  if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2947  return false;
2948 
2949  const MachineRegisterInfo &MRI = MF.getRegInfo();
2950  return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2951 }
2952 
2954  if (!CI->isTailCall())
2955  return false;
2956 
2957  const Function *ParentFn = CI->getParent()->getParent();
2958  if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2959  return false;
2960  return true;
2961 }
2962 
2963 // The wave scratch offset register is used as the global base pointer.
2965  SmallVectorImpl<SDValue> &InVals) const {
2966  SelectionDAG &DAG = CLI.DAG;
2967  const SDLoc &DL = CLI.DL;
2969  SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2971  SDValue Chain = CLI.Chain;
2972  SDValue Callee = CLI.Callee;
2973  bool &IsTailCall = CLI.IsTailCall;
2974  CallingConv::ID CallConv = CLI.CallConv;
2975  bool IsVarArg = CLI.IsVarArg;
2976  bool IsSibCall = false;
2977  bool IsThisReturn = false;
2978  MachineFunction &MF = DAG.getMachineFunction();
2979 
2980  if (Callee.isUndef() || isNullConstant(Callee)) {
2981  if (!CLI.IsTailCall) {
2982  for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2983  InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2984  }
2985 
2986  return Chain;
2987  }
2988 
2989  if (IsVarArg) {
2990  return lowerUnhandledCall(CLI, InVals,
2991  "unsupported call to variadic function ");
2992  }
2993 
2994  if (!CLI.CB)
2995  report_fatal_error("unsupported libcall legalization");
2996 
2997  if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2998  return lowerUnhandledCall(CLI, InVals,
2999  "unsupported required tail call to function ");
3000  }
3001 
3002  if (AMDGPU::isShader(CallConv)) {
3003  // Note the issue is with the CC of the called function, not of the call
3004  // itself.
3005  return lowerUnhandledCall(CLI, InVals,
3006  "unsupported call to a shader function ");
3007  }
3008 
3010  CallConv != CallingConv::AMDGPU_Gfx) {
3011  // Only allow calls with specific calling conventions.
3012  return lowerUnhandledCall(CLI, InVals,
3013  "unsupported calling convention for call from "
3014  "graphics shader of function ");
3015  }
3016 
3017  if (IsTailCall) {
3018  IsTailCall = isEligibleForTailCallOptimization(
3019  Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3020  if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3021  report_fatal_error("failed to perform tail call elimination on a call "
3022  "site marked musttail");
3023  }
3024 
3025  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3026 
3027  // A sibling call is one where we're under the usual C ABI and not planning
3028  // to change that but can still do a tail call:
3029  if (!TailCallOpt && IsTailCall)
3030  IsSibCall = true;
3031 
3032  if (IsTailCall)
3033  ++NumTailCalls;
3034  }
3035 
3038  SmallVector<SDValue, 8> MemOpChains;
3039 
3040  // Analyze operands of the call, assigning locations to each operand.
3042  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3043  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3044 
3045  if (CallConv != CallingConv::AMDGPU_Gfx) {
3046  // With a fixed ABI, allocate fixed registers before user arguments.
3047  passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3048  }
3049 
3050  CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3051 
3052  // Get a count of how many bytes are to be pushed on the stack.
3053  unsigned NumBytes = CCInfo.getNextStackOffset();
3054 
3055  if (IsSibCall) {
3056  // Since we're not changing the ABI to make this a tail call, the memory
3057  // operands are already available in the caller's incoming argument space.
3058  NumBytes = 0;
3059  }
3060 
3061  // FPDiff is the byte offset of the call's argument area from the callee's.
3062  // Stores to callee stack arguments will be placed in FixedStackSlots offset
3063  // by this amount for a tail call. In a sibling call it must be 0 because the
3064  // caller will deallocate the entire stack and the callee still expects its
3065  // arguments to begin at SP+0. Completely unused for non-tail calls.
3066  int32_t FPDiff = 0;
3067  MachineFrameInfo &MFI = MF.getFrameInfo();
3068 
3069  // Adjust the stack pointer for the new arguments...
3070  // These operations are automatically eliminated by the prolog/epilog pass
3071  if (!IsSibCall) {
3072  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3073 
3074  if (!Subtarget->enableFlatScratch()) {
3075  SmallVector<SDValue, 4> CopyFromChains;
3076 
3077  // In the HSA case, this should be an identity copy.
3078  SDValue ScratchRSrcReg
3079  = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3080  RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3081  CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3082  Chain = DAG.getTokenFactor(DL, CopyFromChains);
3083  }
3084  }
3085 
3086  MVT PtrVT = MVT::i32;
3087 
3088  // Walk the register/memloc assignments, inserting copies/loads.
3089  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3090  CCValAssign &VA = ArgLocs[i];
3091  SDValue Arg = OutVals[i];
3092 
3093  // Promote the value if needed.
3094  switch (VA.getLocInfo()) {
3095  case CCValAssign::Full:
3096  break;
3097  case CCValAssign::BCvt:
3098  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3099  break;
3100  case CCValAssign::ZExt:
3101  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3102  break;
3103  case CCValAssign::SExt:
3104  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3105  break;
3106  case CCValAssign::AExt:
3107  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3108  break;
3109  case CCValAssign::FPExt:
3110  Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3111  break;
3112  default:
3113  llvm_unreachable("Unknown loc info!");
3114  }
3115 
3116  if (VA.isRegLoc()) {
3117  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3118  } else {
3119  assert(VA.isMemLoc());
3120 
3121  SDValue DstAddr;
3122  MachinePointerInfo DstInfo;
3123 
3124  unsigned LocMemOffset = VA.getLocMemOffset();
3125  int32_t Offset = LocMemOffset;
3126 
3127  SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3128  MaybeAlign Alignment;
3129 
3130  if (IsTailCall) {
3131  ISD::ArgFlagsTy Flags = Outs[i].Flags;
3132  unsigned OpSize = Flags.isByVal() ?
3133  Flags.getByValSize() : VA.getValVT().getStoreSize();
3134 
3135  // FIXME: We can have better than the minimum byval required alignment.
3136  Alignment =
3137  Flags.isByVal()
3138  ? Flags.getNonZeroByValAlign()
3139  : commonAlignment(Subtarget->getStackAlignment(), Offset);
3140 
3141  Offset = Offset + FPDiff;
3142  int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3143 
3144  DstAddr = DAG.getFrameIndex(FI, PtrVT);
3145  DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3146 
3147  // Make sure any stack arguments overlapping with where we're storing
3148  // are loaded before this eventual operation. Otherwise they'll be
3149  // clobbered.
3150 
3151  // FIXME: Why is this really necessary? This seems to just result in a
3152  // lot of code to copy the stack and write them back to the same
3153  // locations, which are supposed to be immutable?
3154  Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3155  } else {
3156  // Stores to the argument stack area are relative to the stack pointer.
3157  SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3158  MVT::i32);
3159  DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3160  DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3161  Alignment =
3162  commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3163  }
3164 
3165  if (Outs[i].Flags.isByVal()) {
3166  SDValue SizeNode =
3167  DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3168  SDValue Cpy =
3169  DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3170  Outs[i].Flags.getNonZeroByValAlign(),
3171  /*isVol = */ false, /*AlwaysInline = */ true,
3172  /*isTailCall = */ false, DstInfo,
3174 
3175  MemOpChains.push_back(Cpy);
3176  } else {
3177  SDValue Store =
3178  DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3179  MemOpChains.push_back(Store);
3180  }
3181  }
3182  }
3183 
3184  if (!MemOpChains.empty())
3185  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3186 
3187  // Build a sequence of copy-to-reg nodes chained together with token chain
3188  // and flag operands which copy the outgoing args into the appropriate regs.
3189  SDValue InFlag;
3190  for (auto &RegToPass : RegsToPass) {
3191  Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3192  RegToPass.second, InFlag);
3193  InFlag = Chain.getValue(1);
3194  }
3195 
3196 
3197  // We don't usually want to end the call-sequence here because we would tidy
3198  // the frame up *after* the call, however in the ABI-changing tail-call case
3199  // we've carefully laid out the parameters so that when sp is reset they'll be
3200  // in the correct location.
3201  if (IsTailCall && !IsSibCall) {
3202  Chain = DAG.getCALLSEQ_END(Chain,
3203  DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3204  DAG.getTargetConstant(0, DL, MVT::i32),
3205  InFlag, DL);
3206  InFlag = Chain.getValue(1);
3207  }
3208 
3209  std::vector<SDValue> Ops;
3210  Ops.push_back(Chain);
3211  Ops.push_back(Callee);
3212  // Add a redundant copy of the callee global which will not be legalized, as
3213  // we need direct access to the callee later.
3214  if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3215  const GlobalValue *GV = GSD->getGlobal();
3216  Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3217  } else {
3218  Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3219  }
3220 
3221  if (IsTailCall) {
3222  // Each tail call may have to adjust the stack by a different amount, so
3223  // this information must travel along with the operation for eventual
3224  // consumption by emitEpilogue.
3225  Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3226  }
3227 
3228  // Add argument registers to the end of the list so that they are known live
3229  // into the call.
3230  for (auto &RegToPass : RegsToPass) {
3231  Ops.push_back(DAG.getRegister(RegToPass.first,
3232  RegToPass.second.getValueType()));
3233  }
3234 
3235  // Add a register mask operand representing the call-preserved registers.
3236 
3237  auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3238  const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3239  assert(Mask && "Missing call preserved mask for calling convention");
3240  Ops.push_back(DAG.getRegisterMask(Mask));
3241 
3242  if (InFlag.getNode())
3243  Ops.push_back(InFlag);
3244 
3245  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3246 
3247  // If we're doing a tall call, use a TC_RETURN here rather than an
3248  // actual call instruction.
3249  if (IsTailCall) {
3250  MFI.setHasTailCall();
3251  return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3252  }
3253 
3254  // Returns a chain and a flag for retval copy to use.
3255  SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3256  Chain = Call.getValue(0);
3257  InFlag = Call.getValue(1);
3258 
3259  uint64_t CalleePopBytes = NumBytes;
3260  Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3261  DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3262  InFlag, DL);
3263  if (!Ins.empty())
3264  InFlag = Chain.getValue(1);
3265 
3266  // Handle result values, copying them out of physregs into vregs that we
3267  // return.
3268  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3269  InVals, IsThisReturn,
3270  IsThisReturn ? OutVals[0] : SDValue());
3271 }
3272 
3273 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3274 // except for applying the wave size scale to the increment amount.
3276  SDValue Op, SelectionDAG &DAG) const {
3277  const MachineFunction &MF = DAG.getMachineFunction();
3279 
3280  SDLoc dl(Op);
3281  EVT VT = Op.getValueType();
3282  SDValue Tmp1 = Op;
3283  SDValue Tmp2 = Op.getValue(1);
3284  SDValue Tmp3 = Op.getOperand(2);
3285  SDValue Chain = Tmp1.getOperand(0);
3286 
3287  Register SPReg = Info->getStackPtrOffsetReg();
3288 
3289  // Chain the dynamic stack allocation so that it doesn't modify the stack
3290  // pointer when other instructions are using the stack.
3291  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3292 
3293  SDValue Size = Tmp2.getOperand(1);
3294  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3295  Chain = SP.getValue(1);
3296  MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3297  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3298  const TargetFrameLowering *TFL = ST.getFrameLowering();
3299  unsigned Opc =
3300  TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3301  ISD::ADD : ISD::SUB;
3302 
3303  SDValue ScaledSize = DAG.getNode(
3304  ISD::SHL, dl, VT, Size,
3305  DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3306 
3307  Align StackAlign = TFL->getStackAlign();
3308  Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3309  if (Alignment && *Alignment > StackAlign) {
3310  Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3311  DAG.getConstant(-(uint64_t)Alignment->value()
3312  << ST.getWavefrontSizeLog2(),
3313  dl, VT));
3314  }
3315 
3316  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
3317  Tmp2 = DAG.getCALLSEQ_END(
3318  Chain, DAG.getIntPtrConstant(0, dl, true),
3319  DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3320 
3321  return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3322 }
3323 
3325  SelectionDAG &DAG) const {
3326  // We only handle constant sizes here to allow non-entry block, static sized
3327  // allocas. A truly dynamic value is more difficult to support because we
3328  // don't know if the size value is uniform or not. If the size isn't uniform,
3329  // we would need to do a wave reduction to get the maximum size to know how
3330  // much to increment the uniform stack pointer.
3331  SDValue Size = Op.getOperand(1);
3332  if (isa<ConstantSDNode>(Size))
3333  return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3334 
3336 }
3337 
3339  const MachineFunction &MF) const {
3341  .Case("m0", AMDGPU::M0)
3342  .Case("exec", AMDGPU::EXEC)
3343  .Case("exec_lo", AMDGPU::EXEC_LO)
3344  .Case("exec_hi", AMDGPU::EXEC_HI)
3345  .Case("flat_scratch", AMDGPU::FLAT_SCR)
3346  .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3347  .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3348  .Default(Register());
3349 
3350  if (Reg == AMDGPU::NoRegister) {
3351  report_fatal_error(Twine("invalid register name \""
3352  + StringRef(RegName) + "\"."));
3353 
3354  }
3355 
3356  if (!Subtarget->hasFlatScrRegister() &&
3357  Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3358  report_fatal_error(Twine("invalid register \""
3359  + StringRef(RegName) + "\" for subtarget."));
3360  }
3361 
3362  switch (Reg) {
3363  case AMDGPU::M0:
3364  case AMDGPU::EXEC_LO:
3365  case AMDGPU::EXEC_HI:
3366  case AMDGPU::FLAT_SCR_LO:
3367  case AMDGPU::FLAT_SCR_HI:
3368  if (VT.getSizeInBits() == 32)
3369  return Reg;
3370  break;
3371  case AMDGPU::EXEC:
3372  case AMDGPU::FLAT_SCR:
3373  if (VT.getSizeInBits() == 64)
3374  return Reg;
3375  break;
3376  default:
3377  llvm_unreachable("missing register type checking");
3378  }
3379 
3380  report_fatal_error(Twine("invalid type for register \""
3381  + StringRef(RegName) + "\"."));
3382 }
3383 
3384 // If kill is not the last instruction, split the block so kill is always a
3385 // proper terminator.
3388  MachineBasicBlock *BB) const {
3389  MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3390  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3391  MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3392  return SplitBB;
3393 }
3394 
3395 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3396 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3397 // be the first instruction in the remainder block.
3398 //
3399 /// \returns { LoopBody, Remainder }
3400 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3402  MachineFunction *MF = MBB.getParent();
3404 
3405  // To insert the loop we need to split the block. Move everything after this
3406  // point to a new block, and insert a new empty block between the two.
3408  MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3410  ++MBBI;
3411 
3412  MF->insert(MBBI, LoopBB);
3413  MF->insert(MBBI, RemainderBB);
3414 
3415  LoopBB->addSuccessor(LoopBB);
3416  LoopBB->addSuccessor(RemainderBB);
3417 
3418  // Move the rest of the block into a new block.
3419  RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3420 
3421  if (InstInLoop) {
3422  auto Next = std::next(I);
3423 
3424  // Move instruction to loop body.
3425  LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3426 
3427  // Move the rest of the block.
3428  RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3429  } else {
3430  RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3431  }
3432 
3433  MBB.addSuccessor(LoopBB);
3434 
3435  return std::make_pair(LoopBB, RemainderBB);
3436 }
3437 
3438 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3440  MachineBasicBlock *MBB = MI.getParent();
3441  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3442  auto I = MI.getIterator();
3443  auto E = std::next(I);
3444 
3445  BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3446  .addImm(0);
3447 
3448  MIBundleBuilder Bundler(*MBB, I, E);
3449  finalizeBundle(*MBB, Bundler.begin());
3450 }
3451 
3454  MachineBasicBlock *BB) const {
3455  const DebugLoc &DL = MI.getDebugLoc();
3456 
3457  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3458 
3459  MachineBasicBlock *LoopBB;
3460  MachineBasicBlock *RemainderBB;
3461  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3462 
3463  // Apparently kill flags are only valid if the def is in the same block?
3464  if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3465  Src->setIsKill(false);
3466 
3467  std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3468 
3469  MachineBasicBlock::iterator I = LoopBB->end();
3470 
3471  const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3473 
3474  // Clear TRAP_STS.MEM_VIOL
3475  BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3476  .addImm(0)
3477  .addImm(EncodedReg);
3478 
3480 
3481  Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3482 
3483  // Load and check TRAP_STS.MEM_VIOL
3484  BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3485  .addImm(EncodedReg);
3486 
3487  // FIXME: Do we need to use an isel pseudo that may clobber scc?
3488  BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3490  .addImm(0);
3491  BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3492  .addMBB(LoopBB);
3493 
3494  return RemainderBB;
3495 }
3496 
3497 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3498 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3499 // will only do one iteration. In the worst case, this will loop 64 times.
3500 //
3501 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3504  MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3505  const DebugLoc &DL, const MachineOperand &Idx,
3506  unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3507  unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3508  Register &SGPRIdxReg) {
3509 
3510  MachineFunction *MF = OrigBB.getParent();
3511  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3512  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3513  MachineBasicBlock::iterator I = LoopBB.begin();
3514 
3515  const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3516  Register PhiExec = MRI.createVirtualRegister(BoolRC);
3517  Register NewExec = MRI.createVirtualRegister(BoolRC);
3518  Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3519  Register CondReg = MRI.createVirtualRegister(BoolRC);
3520 
3521  BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3522  .addReg(InitReg)
3523  .addMBB(&OrigBB)
3524  .addReg(ResultReg)
3525  .addMBB(&LoopBB);
3526 
3527  BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3528  .addReg(InitSaveExecReg)
3529  .addMBB(&OrigBB)
3530  .addReg(NewExec)
3531  .addMBB(&LoopBB);
3532 
3533  // Read the next variant <- also loop target.
3534  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3535  .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3536 
3537  // Compare the just read M0 value to all possible Idx values.
3538  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3539  .addReg(CurrentIdxReg)
3540  .addReg(Idx.getReg(), 0, Idx.getSubReg());
3541 
3542  // Update EXEC, save the original EXEC value to VCC.
3543  BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3544  : AMDGPU::S_AND_SAVEEXEC_B64),
3545  NewExec)
3546  .addReg(CondReg, RegState::Kill);
3547 
3548  MRI.setSimpleHint(NewExec, CondReg);
3549 
3550  if (UseGPRIdxMode) {
3551  if (Offset == 0) {
3552  SGPRIdxReg = CurrentIdxReg;
3553  } else {
3554  SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3555  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3556  .addReg(CurrentIdxReg, RegState::Kill)
3557  .addImm(Offset);
3558  }
3559  } else {
3560  // Move index from VCC into M0
3561  if (Offset == 0) {
3562  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3563  .addReg(CurrentIdxReg, RegState::Kill);
3564  } else {
3565  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3566  .addReg(CurrentIdxReg, RegState::Kill)
3567  .addImm(Offset);
3568  }
3569  }
3570 
3571  // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3572  unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3573  MachineInstr *InsertPt =
3574  BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3575  : AMDGPU::S_XOR_B64_term), Exec)
3576  .addReg(Exec)
3577  .addReg(NewExec);
3578 
3579  // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3580  // s_cbranch_scc0?
3581 
3582  // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3583  BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3584  .addMBB(&LoopBB);
3585 
3586  return InsertPt->getIterator();
3587 }
3588 
3589 // This has slightly sub-optimal regalloc when the source vector is killed by
3590 // the read. The register allocator does not understand that the kill is
3591 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3592 // subregister from it, using 1 more VGPR than necessary. This was saved when
3593 // this was expanded after register allocation.
3596  unsigned InitResultReg, unsigned PhiReg, int Offset,
3597  bool UseGPRIdxMode, Register &SGPRIdxReg) {
3598  MachineFunction *MF = MBB.getParent();
3599  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3600  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3602  const DebugLoc &DL = MI.getDebugLoc();
3604 
3605  const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3606  Register DstReg = MI.getOperand(0).getReg();
3607  Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3608  Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3609  unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3610  unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3611 
3612  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3613 
3614  // Save the EXEC mask
3615  BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3616  .addReg(Exec);
3617 
3618  MachineBasicBlock *LoopBB;
3619  MachineBasicBlock *RemainderBB;
3620  std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3621 
3622  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3623 
3624  auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3625  InitResultReg, DstReg, PhiReg, TmpExec,
3626  Offset, UseGPRIdxMode, SGPRIdxReg);
3627 
3628  MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3630  ++MBBI;
3631  MF->insert(MBBI, LandingPad);
3632  LoopBB->removeSuccessor(RemainderBB);
3633  LandingPad->addSuccessor(RemainderBB);
3634  LoopBB->addSuccessor(LandingPad);
3635  MachineBasicBlock::iterator First = LandingPad->begin();
3636  BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3637  .addReg(SaveExec);
3638 
3639  return InsPt;
3640 }
3641 
3642 // Returns subreg index, offset
3643 static std::pair<unsigned, int>
3645  const TargetRegisterClass *SuperRC,
3646  unsigned VecReg,
3647  int Offset) {
3648  int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3649 
3650  // Skip out of bounds offsets, or else we would end up using an undefined
3651  // register.
3652  if (Offset >= NumElts || Offset < 0)
3653  return std::make_pair(AMDGPU::sub0, Offset);
3654 
3655  return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3656 }
3657 
3660  int Offset) {
3661  MachineBasicBlock *MBB = MI.getParent();
3662  const DebugLoc &DL = MI.getDebugLoc();
3664 
3665  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3666 
3667  assert(Idx->getReg() != AMDGPU::NoRegister);
3668 
3669  if (Offset == 0) {
3670  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3671  } else {
3672  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3673  .add(*Idx)
3674  .addImm(Offset);
3675  }
3676 }
3677 
3680  int Offset) {
3681  MachineBasicBlock *MBB = MI.getParent();
3682  const DebugLoc &DL = MI.getDebugLoc();
3684 
3685  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3686 
3687  if (Offset == 0)
3688  return Idx->getReg();
3689 
3690  Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3691  BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3692  .add(*Idx)
3693  .addImm(Offset);
3694  return Tmp;
3695 }
3696 
3699  const GCNSubtarget &ST) {
3700  const SIInstrInfo *TII = ST.getInstrInfo();
3701  const SIRegisterInfo &TRI = TII->getRegisterInfo();
3702  MachineFunction *MF = MBB.getParent();
3704 
3705  Register Dst = MI.getOperand(0).getReg();
3706  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3707  Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3708  int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3709 
3710  const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3711  const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3712 
3713  unsigned SubReg;
3714  std::tie(SubReg, Offset)
3715  = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3716 
3717  const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3718 
3719  // Check for a SGPR index.
3720  if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3722  const DebugLoc &DL = MI.getDebugLoc();
3723 
3724  if (UseGPRIdxMode) {
3725  // TODO: Look at the uses to avoid the copy. This may require rescheduling
3726  // to avoid interfering with other uses, so probably requires a new
3727  // optimization pass.
3728  Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3729 
3730  const MCInstrDesc &GPRIDXDesc =
3731  TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3732  BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3733  .addReg(SrcReg)
3734  .addReg(Idx)
3735  .addImm(SubReg);
3736  } else {
3737  setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3738 
3739  BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3740  .addReg(SrcReg, 0, SubReg)
3741  .addReg(SrcReg, RegState::Implicit);
3742  }
3743 
3744  MI.eraseFromParent();
3745 
3746  return &MBB;
3747  }
3748 
3749  // Control flow needs to be inserted if indexing with a VGPR.
3750  const DebugLoc &DL = MI.getDebugLoc();
3752 
3753  Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3754  Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3755 
3756  BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3757 
3758  Register SGPRIdxReg;
3759  auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3760  UseGPRIdxMode, SGPRIdxReg);
3761 
3762  MachineBasicBlock *LoopBB = InsPt->getParent();
3763 
3764  if (UseGPRIdxMode) {
3765  const MCInstrDesc &GPRIDXDesc =
3766  TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3767 
3768  BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3769  .addReg(SrcReg)
3770  .addReg(SGPRIdxReg)
3771  .addImm(SubReg);
3772  } else {
3773  BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3774  .addReg(SrcReg, 0, SubReg)
3775  .addReg(SrcReg, RegState::Implicit);
3776  }
3777 
3778  MI.eraseFromParent();
3779 
3780  return LoopBB;
3781 }
3782 
3785  const GCNSubtarget &ST) {
3786  const SIInstrInfo *TII = ST.getInstrInfo();
3787  const SIRegisterInfo &TRI = TII->getRegisterInfo();
3788  MachineFunction *MF = MBB.getParent();
3790 
3791  Register Dst = MI.getOperand(0).getReg();
3792  const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3793  const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3794  const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3795  int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3796  const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3797  const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3798 
3799  // This can be an immediate, but will be folded later.
3800  assert(Val->getReg());
3801 
3802  unsigned SubReg;
3803  std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3804  SrcVec->getReg(),
3805  Offset);
3806  const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3807 
3808  if (Idx->getReg() == AMDGPU::NoRegister) {
3810  const DebugLoc &DL = MI.getDebugLoc();
3811 
3812  assert(Offset == 0);
3813 
3814  BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3815  .add(*SrcVec)
3816  .add(*Val)
3817  .addImm(SubReg);
3818 
3819  MI.eraseFromParent();
3820  return &MBB;
3821  }
3822 
3823  // Check for a SGPR index.
3824  if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3826  const DebugLoc &DL = MI.getDebugLoc();
3827 
3828  if (UseGPRIdxMode) {
3829  Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3830 
3831  const MCInstrDesc &GPRIDXDesc =
3832  TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3833  BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3834  .addReg(SrcVec->getReg())
3835  .add(*Val)
3836  .addReg(Idx)
3837  .addImm(SubReg);
3838  } else {
3839  setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3840 
3841  const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3842  TRI.getRegSizeInBits(*VecRC), 32, false);
3843  BuildMI(MBB, I, DL, MovRelDesc, Dst)
3844  .addReg(SrcVec->getReg())
3845  .add(*Val)
3846  .addImm(SubReg);
3847  }
3848  MI.eraseFromParent();
3849  return &MBB;
3850  }
3851 
3852  // Control flow needs to be inserted if indexing with a VGPR.
3853  if (Val->isReg())
3854  MRI.clearKillFlags(Val->getReg());
3855 
3856  const DebugLoc &DL = MI.getDebugLoc();
3857 
3858  Register PhiReg = MRI.createVirtualRegister(VecRC);
3859 
3860  Register SGPRIdxReg;
3861  auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3862  UseGPRIdxMode, SGPRIdxReg);
3863  MachineBasicBlock *LoopBB = InsPt->getParent();
3864 
3865  if (UseGPRIdxMode) {
3866  const MCInstrDesc &GPRIDXDesc =
3867  TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3868 
3869  BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3870  .addReg(PhiReg)
3871  .add(*Val)
3872  .addReg(SGPRIdxReg)
3873  .addImm(AMDGPU::sub0);
3874  } else {
3875  const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3876  TRI.getRegSizeInBits(*VecRC), 32, false);
3877  BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3878  .addReg(PhiReg)
3879  .add(*Val)
3880  .addImm(AMDGPU::sub0);
3881  }
3882 
3883  MI.eraseFromParent();
3884  return LoopBB;
3885 }
3886 
3888  MachineInstr &MI, MachineBasicBlock *BB) const {
3889 
3890  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3891  MachineFunction *MF = BB->getParent();
3893 
3894  switch (MI.getOpcode()) {
3895  case AMDGPU::S_UADDO_PSEUDO:
3896  case AMDGPU::S_USUBO_PSEUDO: {
3897  const DebugLoc &DL = MI.getDebugLoc();
3898  MachineOperand &Dest0 = MI.getOperand(0);
3899  MachineOperand &Dest1 = MI.getOperand(1);
3900  MachineOperand &Src0 = MI.getOperand(2);
3901  MachineOperand &Src1 = MI.getOperand(3);
3902 
3903  unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3904  ? AMDGPU::S_ADD_I32
3905  : AMDGPU::S_SUB_I32;
3906  BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3907 
3908  BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3909  .addImm(1)
3910  .addImm(0);
3911 
3912  MI.eraseFromParent();
3913  return BB;
3914  }
3915  case AMDGPU::S_ADD_U64_PSEUDO:
3916  case AMDGPU::S_SUB_U64_PSEUDO: {
3917  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3918  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3919  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3920  const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3921  const DebugLoc &DL = MI.getDebugLoc();
3922 
3923  MachineOperand &Dest = MI.getOperand(0);
3924  MachineOperand &Src0 = MI.getOperand(1);
3925  MachineOperand &Src1 = MI.getOperand(2);
3926 
3927  Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3928  Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3929 
3930  MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3931  MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3932  MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3933  MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3934 
3935  MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3936  MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3937  MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3938  MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3939 
3940  bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3941 
3942  unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3943  unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3944  BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3945  BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3946  BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3947  .addReg(DestSub0)
3948  .addImm(AMDGPU::sub0)
3949  .addReg(DestSub1)
3950  .addImm(AMDGPU::sub1);
3951  MI.eraseFromParent();
3952  return BB;
3953  }
3954  case AMDGPU::V_ADD_U64_PSEUDO:
3955  case AMDGPU::V_SUB_U64_PSEUDO: {
3956  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3957  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3958  const SIRegisterInfo *TRI = ST.getRegisterInfo();
3959  const DebugLoc &DL = MI.getDebugLoc();
3960 
3961  bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3962 
3963  MachineOperand &Dest = MI.getOperand(0);
3964  MachineOperand &Src0 = MI.getOperand(1);
3965  MachineOperand &Src1 = MI.getOperand(2);
3966 
3967  if (IsAdd && ST.hasLshlAddB64()) {
3968  auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
3969  Dest.getReg())
3970  .add(Src0)
3971  .addImm(0)
3972  .add(Src1);
3973  TII->legalizeOperands(*Add);
3974  MI.eraseFromParent();
3975  return BB;
3976  }
3977 
3978  const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3979 
3980  Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3981  Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3982 
3983  Register CarryReg = MRI.createVirtualRegister(CarryRC);
3984  Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3985 
3986  const TargetRegisterClass *Src0RC = Src0.isReg()
3987  ? MRI.getRegClass(Src0.getReg())
3988  : &AMDGPU::VReg_64RegClass;
3989  const TargetRegisterClass *Src1RC = Src1.isReg()
3990  ? MRI.getRegClass(Src1.getReg())
3991  : &AMDGPU::VReg_64RegClass;
3992 
3993  const TargetRegisterClass *Src0SubRC =
3994  TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3995  const TargetRegisterClass *Src1SubRC =
3996  TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3997 
3998  MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3999  MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4000  MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4001  MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4002 
4003  MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4004  MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4005  MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4006  MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4007 
4008  unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4009  MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4010  .addReg(CarryReg, RegState::Define)
4011  .add(SrcReg0Sub0)
4012  .add(SrcReg1Sub0)
4013  .addImm(0); // clamp bit
4014 
4015  unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4016  MachineInstr *HiHalf =
4017  BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4018  .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4019  .add(SrcReg0Sub1)
4020  .add(SrcReg1Sub1)
4021  .addReg(CarryReg, RegState::Kill)
4022  .addImm(0); // clamp bit
4023 
4024  BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4025  .addReg(DestSub0)
4026  .addImm(AMDGPU::sub0)
4027  .addReg(DestSub1)
4028  .addImm(AMDGPU::sub1);
4029  TII->legalizeOperands(*LoHalf);
4030  TII->legalizeOperands(*HiHalf);
4031  MI.eraseFromParent();
4032  return BB;
4033  }
4034  case AMDGPU::S_ADD_CO_PSEUDO:
4035  case AMDGPU::S_SUB_CO_PSEUDO: {
4036  // This pseudo has a chance to be selected
4037  // only from uniform add/subcarry node. All the VGPR operands
4038  // therefore assumed to be splat vectors.
4039  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4040  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4041  const SIRegisterInfo *TRI = ST.getRegisterInfo();
4043  const DebugLoc &DL = MI.getDebugLoc();
4044  MachineOperand &Dest = MI.getOperand(0);
4045  MachineOperand &CarryDest = MI.getOperand(1);
4046  MachineOperand &Src0 = MI.getOperand(2);
4047  MachineOperand &Src1 = MI.getOperand(3);
4048  MachineOperand &Src2 = MI.getOperand(4);
4049  unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4050  ? AMDGPU::S_ADDC_U32
4051  : AMDGPU::S_SUBB_U32;
4052  if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4053  Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4054  BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4055  .addReg(Src0.getReg());
4056  Src0.setReg(RegOp0);
4057  }
4058  if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4059  Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4060  BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4061  .addReg(Src1.getReg());
4062  Src1.setReg(RegOp1);
4063  }
4064  Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4065  if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4066  BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4067  .addReg(Src2.getReg());
4068  Src2.setReg(RegOp2);
4069  }
4070 
4071  const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4072  unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4073  assert(WaveSize == 64 || WaveSize == 32);
4074 
4075  if (WaveSize == 64) {
4076  if (ST.hasScalarCompareEq64()) {
4077  BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4078  .addReg(Src2.getReg())
4079  .addImm(0);
4080  } else {
4081  const TargetRegisterClass *SubRC =
4082  TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4083  MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4084  MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4085  MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4086  MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4087  Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4088 
4089  BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4090  .add(Src2Sub0)
4091  .add(Src2Sub1);
4092 
4093  BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4094  .addReg(Src2_32, RegState::Kill)
4095  .addImm(0);
4096  }
4097  } else {
4098  BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4099  .addReg(Src2.getReg())
4100  .addImm(0);
4101  }
4102 
4103  BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4104 
4105  unsigned SelOpc =
4106  (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4107 
4108  BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4109  .addImm(-1)
4110  .addImm(0);
4111 
4112  MI.eraseFromParent();
4113  return BB;
4114  }
4115  case AMDGPU::SI_INIT_M0: {
4116  BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4117  TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4118  .add(MI.getOperand(0));
4119  MI.eraseFromParent();
4120  return BB;
4121  }
4122  case AMDGPU::GET_GROUPSTATICSIZE: {
4123  assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4124  getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4125  DebugLoc DL = MI.getDebugLoc();
4126  BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4127  .add(MI.getOperand(0))
4128  .addImm(MFI->getLDSSize());
4129  MI.eraseFromParent();
4130  return BB;
4131  }
4132  case AMDGPU::SI_INDIRECT_SRC_V1:
4133  case AMDGPU::SI_INDIRECT_SRC_V2:
4134  case AMDGPU::SI_INDIRECT_SRC_V4:
4135  case AMDGPU::SI_INDIRECT_SRC_V8:
4136  case AMDGPU::SI_INDIRECT_SRC_V16:
4137  case AMDGPU::SI_INDIRECT_SRC_V32:
4138  return emitIndirectSrc(MI, *BB, *getSubtarget());
4139  case AMDGPU::SI_INDIRECT_DST_V1:
4140  case AMDGPU::SI_INDIRECT_DST_V2:
4141  case AMDGPU::SI_INDIRECT_DST_V4:
4142  case AMDGPU::SI_INDIRECT_DST_V8:
4143  case AMDGPU::SI_INDIRECT_DST_V16:
4144  case AMDGPU::SI_INDIRECT_DST_V32:
4145  return emitIndirectDst(MI, *BB, *getSubtarget());
4146  case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4147  case AMDGPU::SI_KILL_I1_PSEUDO:
4148  return splitKillBlock(MI, BB);
4149  case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4150  MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4151  const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4152  const SIRegisterInfo *TRI = ST.getRegisterInfo();
4153 
4154  Register Dst = MI.getOperand(0).getReg();
4155  Register Src0 = MI.getOperand(1).getReg();
4156  Register Src1 = MI.getOperand(2).getReg();
4157  const DebugLoc &DL = MI.getDebugLoc();
4158  Register SrcCond = MI.getOperand(3).getReg();
4159 
4160  Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4161  Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4162  const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4163  Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4164 
4165  BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4166  .addReg(SrcCond);
4167  BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4168  .addImm(0)
4169  .addReg(Src0, 0, AMDGPU::sub0)
4170  .addImm(0)
4171  .addReg(Src1, 0, AMDGPU::sub0)
4172  .addReg(SrcCondCopy);
4173  BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4174  .addImm(0)
4175  .addReg(Src0, 0, AMDGPU::sub1)
4176  .addImm(0)
4177  .addReg(Src1, 0, AMDGPU::sub1)
4178  .addReg(SrcCondCopy);
4179 
4180  BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4181  .addReg(DstLo)
4182  .addImm(AMDGPU::sub0)
4183  .addReg(DstHi)
4184  .addImm(AMDGPU::sub1);
4185  MI.eraseFromParent();
4186  return BB;
4187  }
4188  case AMDGPU::SI_BR_UNDEF: {
4189  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4190  const DebugLoc &DL = MI.getDebugLoc();
4191  MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4192  .add(MI.getOperand(0));
4193  Br->getOperand(1).setIsUndef(true); // read undef SCC
4194  MI.eraseFromParent();
4195  return BB;
4196  }
4197  case AMDGPU::ADJCALLSTACKUP:
4198  case AMDGPU::ADJCALLSTACKDOWN: {
4200  MachineInstrBuilder MIB(*MF, &MI);
4201  MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4202  .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4203  return BB;
4204  }
4205  case AMDGPU::SI_CALL_ISEL: {
4206  const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4207  const DebugLoc &DL = MI.getDebugLoc();
4208 
4209  unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4210 
4211  MachineInstrBuilder MIB;
4212  MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4213 
4214  for (const MachineOperand &MO : MI.operands())
4215  MIB.add(MO);