LLVM  7.0.0svn
AMDGPUISelLowering.cpp
Go to the documentation of this file.
1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This is the parent TargetLowering class for hardware code gen
12 /// targets.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #define AMDGPU_LOG2E_F 1.44269504088896340735992468100189214f
17 #define AMDGPU_LN2_F 0.693147180559945309417232121458176568f
18 #define AMDGPU_LN10_F 2.30258509299404568401799145468436421f
19 
20 #include "AMDGPUISelLowering.h"
21 #include "AMDGPU.h"
22 #include "AMDGPUCallLowering.h"
23 #include "AMDGPUFrameLowering.h"
24 #include "AMDGPUIntrinsicInfo.h"
25 #include "AMDGPURegisterInfo.h"
26 #include "AMDGPUSubtarget.h"
27 #include "AMDGPUTargetMachine.h"
28 #include "Utils/AMDGPUBaseInfo.h"
30 #include "SIInstrInfo.h"
31 #include "SIMachineFunctionInfo.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DiagnosticInfo.h"
40 #include "llvm/Support/KnownBits.h"
41 using namespace llvm;
42 
43 static bool allocateKernArg(unsigned ValNo, MVT ValVT, MVT LocVT,
44  CCValAssign::LocInfo LocInfo,
45  ISD::ArgFlagsTy ArgFlags, CCState &State) {
46  MachineFunction &MF = State.getMachineFunction();
48 
49  uint64_t Offset = MFI->allocateKernArg(LocVT.getStoreSize(),
50  ArgFlags.getOrigAlign());
51  State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
52  return true;
53 }
54 
55 static bool allocateCCRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
56  CCValAssign::LocInfo LocInfo,
57  ISD::ArgFlagsTy ArgFlags, CCState &State,
58  const TargetRegisterClass *RC,
59  unsigned NumRegs) {
60  ArrayRef<MCPhysReg> RegList = makeArrayRef(RC->begin(), NumRegs);
61  unsigned RegResult = State.AllocateReg(RegList);
62  if (RegResult == AMDGPU::NoRegister)
63  return false;
64 
65  State.addLoc(CCValAssign::getReg(ValNo, ValVT, RegResult, LocVT, LocInfo));
66  return true;
67 }
68 
69 static bool allocateSGPRTuple(unsigned ValNo, MVT ValVT, MVT LocVT,
70  CCValAssign::LocInfo LocInfo,
71  ISD::ArgFlagsTy ArgFlags, CCState &State) {
72  switch (LocVT.SimpleTy) {
73  case MVT::i64:
74  case MVT::f64:
75  case MVT::v2i32:
76  case MVT::v2f32:
77  case MVT::v4i16:
78  case MVT::v4f16: {
79  // Up to SGPR0-SGPR39
80  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
81  &AMDGPU::SGPR_64RegClass, 20);
82  }
83  default:
84  return false;
85  }
86 }
87 
88 // Allocate up to VGPR31.
89 //
90 // TODO: Since there are no VGPR alignent requirements would it be better to
91 // split into individual scalar registers?
92 static bool allocateVGPRTuple(unsigned ValNo, MVT ValVT, MVT LocVT,
93  CCValAssign::LocInfo LocInfo,
94  ISD::ArgFlagsTy ArgFlags, CCState &State) {
95  switch (LocVT.SimpleTy) {
96  case MVT::i64:
97  case MVT::f64:
98  case MVT::v2i32:
99  case MVT::v2f32:
100  case MVT::v4i16:
101  case MVT::v4f16: {
102  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
103  &AMDGPU::VReg_64RegClass, 31);
104  }
105  case MVT::v4i32:
106  case MVT::v4f32:
107  case MVT::v2i64:
108  case MVT::v2f64: {
109  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
110  &AMDGPU::VReg_128RegClass, 29);
111  }
112  case MVT::v8i32:
113  case MVT::v8f32: {
114  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
115  &AMDGPU::VReg_256RegClass, 25);
116 
117  }
118  case MVT::v16i32:
119  case MVT::v16f32: {
120  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
121  &AMDGPU::VReg_512RegClass, 17);
122 
123  }
124  default:
125  return false;
126  }
127 }
128 
129 #include "AMDGPUGenCallingConv.inc"
130 
131 // Find a larger type to do a load / store of a vector with.
133  unsigned StoreSize = VT.getStoreSizeInBits();
134  if (StoreSize <= 32)
135  return EVT::getIntegerVT(Ctx, StoreSize);
136 
137  assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
138  return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
139 }
140 
142  KnownBits Known;
143  EVT VT = Op.getValueType();
144  DAG.computeKnownBits(Op, Known);
145 
146  return VT.getSizeInBits() - Known.countMinLeadingZeros();
147 }
148 
150  EVT VT = Op.getValueType();
151 
152  // In order for this to be a signed 24-bit value, bit 23, must
153  // be a sign bit.
154  return VT.getSizeInBits() - DAG.ComputeNumSignBits(Op);
155 }
156 
158  const AMDGPUSubtarget &STI)
159  : TargetLowering(TM), Subtarget(&STI) {
161  // Lower floating point store/load to integer store/load to reduce the number
162  // of patterns in tablegen.
165 
168 
171 
174 
177 
180 
183 
186 
189 
190  // There are no 64-bit extloads. These should be done as a 32-bit extload and
191  // an extension to 64-bit.
192  for (MVT VT : MVT::integer_valuetypes()) {
196  }
197 
198  for (MVT VT : MVT::integer_valuetypes()) {
199  if (VT == MVT::i64)
200  continue;
201 
206 
211 
216  }
217 
218  for (MVT VT : MVT::integer_vector_valuetypes()) {
231  }
232 
237 
242 
247 
250 
253 
256 
259 
262 
265 
268 
271 
274 
279 
284 
289 
292 
295 
298 
301 
302 
307 
310 
311  // This is totally unsupported, just custom lower to produce an error.
313 
314  // Library functions. These default to Expand, but we have instructions
315  // for them.
326 
329 
332 
333  if (Subtarget->has16BitInsts()) {
336  }
337 
340 
343 
344  // v_mad_f32 does not support denormals according to some sources.
345  if (!Subtarget->hasFP32Denormals())
347 
348  // Expand to fneg + fadd.
350 
361 
367  }
368 
369  if (!Subtarget->hasBFI()) {
370  // fcopysign can be done in a single instruction with BFI.
373  }
374 
378 
379  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
380  for (MVT VT : ScalarIntVTs) {
381  // These should use [SU]DIVREM, so set them to expand
386 
387  // GPU does not have divrem function for signed or unsigned.
390 
391  // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
394 
398 
399  // AMDGPU uses ADDC/SUBC/ADDE/SUBE
404  }
405 
406  if (!Subtarget->hasBCNT(32))
408 
409  if (!Subtarget->hasBCNT(64))
411 
412  // The hardware supports 32-bit ROTR, but not ROTL.
414  setOperationAction(ISD::ROTL, MVT::i64, Expand);
415  setOperationAction(ISD::ROTR, MVT::i64, Expand);
416 
417  setOperationAction(ISD::MUL, MVT::i64, Expand);
425 
430 
431  if (Subtarget->hasFFBH())
433 
434  if (Subtarget->hasFFBL())
436 
437  setOperationAction(ISD::CTTZ, MVT::i64, Custom);
439  setOperationAction(ISD::CTLZ, MVT::i64, Custom);
441 
442  // We only really have 32-bit BFE instructions (and 16-bit on VI).
443  //
444  // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
445  // effort to match them now. We want this to be false for i64 cases when the
446  // extraction isn't restricted to the upper or lower half. Ideally we would
447  // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
448  // span the midpoint are probably relatively rare, so don't worry about them
449  // for now.
450  if (Subtarget->hasBFE())
451  setHasExtractBitsInsn(true);
452 
453  static const MVT::SimpleValueType VectorIntTypes[] = {
455  };
456 
457  for (MVT VT : VectorIntTypes) {
458  // Expand the following operations for the current type by default.
493  }
494 
495  static const MVT::SimpleValueType FloatVectorTypes[] = {
497  };
498 
499  for (MVT VT : FloatVectorTypes) {
528  }
529 
530  // This causes using an unrolled select operation rather than expansion with
531  // bit operations. This is in general better, but the alternative using BFI
532  // instructions may be better if the select sources are SGPRs.
535 
536  setOperationAction(ISD::SELECT, MVT::v4f32, Promote);
537  AddPromotedToType(ISD::SELECT, MVT::v4f32, MVT::v4i32);
538 
539  // There are no libcalls of any kind.
540  for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
541  setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
542 
545 
547  setJumpIsExpensive(true);
548 
549  // FIXME: This is only partially true. If we have to do vector compares, any
550  // SGPR pair can be a condition register. If we have a uniform condition, we
551  // are better off doing SALU operations, where there is only one SCC. For now,
552  // we don't have a way of knowing during instruction selection if a condition
553  // will be uniform and we always use vector compares. Assume we are using
554  // vector compares until that is fixed.
556 
557  // SI at least has hardware support for floating point exceptions, but no way
558  // of using or handling them is implemented. They are also optional in OpenCL
559  // (Section 7.3)
561 
563 
564  // We want to find all load dependencies for long chains of stores to enable
565  // merging into very wide vectors. The problem is with vectors with > 4
566  // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
567  // vectors are a legal type, even though we have to split the loads
568  // usually. When we can more precisely specify load legality per address
569  // space, we should be able to make FindBetterChain/MergeConsecutiveStores
570  // smarter so that they can figure out what to do in 2 iterations without all
571  // N > 4 stores on the same chain.
573 
574  // memcpy/memmove/memset are expanded in the IR, so we shouldn't need to worry
575  // about these during lowering.
576  MaxStoresPerMemcpy = 0xffffffff;
577  MaxStoresPerMemmove = 0xffffffff;
578  MaxStoresPerMemset = 0xffffffff;
579 
597 }
598 
599 //===----------------------------------------------------------------------===//
600 // Target Information
601 //===----------------------------------------------------------------------===//
602 
604 static bool fnegFoldsIntoOp(unsigned Opc) {
605  switch (Opc) {
606  case ISD::FADD:
607  case ISD::FSUB:
608  case ISD::FMUL:
609  case ISD::FMA:
610  case ISD::FMAD:
611  case ISD::FMINNUM:
612  case ISD::FMAXNUM:
613  case ISD::FSIN:
614  case ISD::FTRUNC:
615  case ISD::FRINT:
616  case ISD::FNEARBYINT:
617  case AMDGPUISD::RCP:
619  case AMDGPUISD::SIN_HW:
623  return true;
624  default:
625  return false;
626  }
627 }
628 
629 /// \p returns true if the operation will definitely need to use a 64-bit
630 /// encoding, and thus will use a VOP3 encoding regardless of the source
631 /// modifiers.
633 static bool opMustUseVOP3Encoding(const SDNode *N, MVT VT) {
634  return N->getNumOperands() > 2 || VT == MVT::f64;
635 }
636 
637 // Most FP instructions support source modifiers, but this could be refined
638 // slightly.
640 static bool hasSourceMods(const SDNode *N) {
641  if (isa<MemSDNode>(N))
642  return false;
643 
644  switch (N->getOpcode()) {
645  case ISD::CopyToReg:
646  case ISD::SELECT:
647  case ISD::FDIV:
648  case ISD::FREM:
649  case ISD::INLINEASM:
653 
654  // TODO: Should really be looking at the users of the bitcast. These are
655  // problematic because bitcasts are used to legalize all stores to integer
656  // types.
657  case ISD::BITCAST:
658  return false;
659  default:
660  return true;
661  }
662 }
663 
665  unsigned CostThreshold) {
666  // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus
667  // it is truly free to use a source modifier in all cases. If there are
668  // multiple users but for each one will necessitate using VOP3, there will be
669  // a code size increase. Try to avoid increasing code size unless we know it
670  // will save on the instruction count.
671  unsigned NumMayIncreaseSize = 0;
672  MVT VT = N->getValueType(0).getScalarType().getSimpleVT();
673 
674  // XXX - Should this limit number of uses to check?
675  for (const SDNode *U : N->uses()) {
676  if (!hasSourceMods(U))
677  return false;
678 
679  if (!opMustUseVOP3Encoding(U, VT)) {
680  if (++NumMayIncreaseSize > CostThreshold)
681  return false;
682  }
683  }
684 
685  return true;
686 }
687 
689  return MVT::i32;
690 }
691 
693  return true;
694 }
695 
696 // The backend supports 32 and 64 bit floating point immediates.
697 // FIXME: Why are we reporting vectors of FP immediates as legal?
698 bool AMDGPUTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
699  EVT ScalarVT = VT.getScalarType();
700  return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
701  (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
702 }
703 
704 // We don't want to shrink f64 / f32 constants.
706  EVT ScalarVT = VT.getScalarType();
707  return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
708 }
709 
712  EVT NewVT) const {
713 
714  unsigned NewSize = NewVT.getStoreSizeInBits();
715 
716  // If we are reducing to a 32-bit load, this is always better.
717  if (NewSize == 32)
718  return true;
719 
720  EVT OldVT = N->getValueType(0);
721  unsigned OldSize = OldVT.getStoreSizeInBits();
722 
723  // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
724  // extloads, so doing one requires using a buffer_load. In cases where we
725  // still couldn't use a scalar load, using the wider load shouldn't really
726  // hurt anything.
727 
728  // If the old size already had to be an extload, there's no harm in continuing
729  // to reduce the width.
730  return (OldSize < 32);
731 }
732 
734  EVT CastTy) const {
735 
736  assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
737 
738  if (LoadTy.getScalarType() == MVT::i32)
739  return false;
740 
741  unsigned LScalarSize = LoadTy.getScalarSizeInBits();
742  unsigned CastScalarSize = CastTy.getScalarSizeInBits();
743 
744  return (LScalarSize < CastScalarSize) ||
745  (CastScalarSize >= 32);
746 }
747 
748 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
749 // profitable with the expansion for 64-bit since it's generally good to
750 // speculate things.
751 // FIXME: These should really have the size as a parameter.
753  return true;
754 }
755 
757  return true;
758 }
759 
761  switch (N->getOpcode()) {
762  default:
763  return false;
764  case ISD::EntryToken:
765  case ISD::TokenFactor:
766  return true;
768  {
769  unsigned IntrID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
770  switch (IntrID) {
771  default:
772  return false;
773  case Intrinsic::amdgcn_readfirstlane:
774  case Intrinsic::amdgcn_readlane:
775  return true;
776  }
777  }
778  break;
779  case ISD::LOAD:
780  {
781  const LoadSDNode * L = dyn_cast<LoadSDNode>(N);
782  if (L->getMemOperand()->getAddrSpace()
784  return true;
785  return false;
786  }
787  break;
788  }
789 }
790 
791 //===---------------------------------------------------------------------===//
792 // Target Properties
793 //===---------------------------------------------------------------------===//
794 
796  assert(VT.isFloatingPoint());
797 
798  // Packed operations do not have a fabs modifier.
799  return VT == MVT::f32 || VT == MVT::f64 ||
800  (Subtarget->has16BitInsts() && VT == MVT::f16);
801 }
802 
804  assert(VT.isFloatingPoint());
805  return VT == MVT::f32 || VT == MVT::f64 ||
806  (Subtarget->has16BitInsts() && VT == MVT::f16) ||
807  (Subtarget->hasVOP3PInsts() && VT == MVT::v2f16);
808 }
809 
811  unsigned NumElem,
812  unsigned AS) const {
813  return true;
814 }
815 
817  // There are few operations which truly have vector input operands. Any vector
818  // operation is going to involve operations on each component, and a
819  // build_vector will be a copy per element, so it always makes sense to use a
820  // build_vector input in place of the extracted element to avoid a copy into a
821  // super register.
822  //
823  // We should probably only do this if all users are extracts only, but this
824  // should be the common case.
825  return true;
826 }
827 
829  // Truncate is just accessing a subregister.
830 
831  unsigned SrcSize = Source.getSizeInBits();
832  unsigned DestSize = Dest.getSizeInBits();
833 
834  return DestSize < SrcSize && DestSize % 32 == 0 ;
835 }
836 
838  // Truncate is just accessing a subregister.
839 
840  unsigned SrcSize = Source->getScalarSizeInBits();
841  unsigned DestSize = Dest->getScalarSizeInBits();
842 
843  if (DestSize== 16 && Subtarget->has16BitInsts())
844  return SrcSize >= 32;
845 
846  return DestSize < SrcSize && DestSize % 32 == 0;
847 }
848 
849 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
850  unsigned SrcSize = Src->getScalarSizeInBits();
851  unsigned DestSize = Dest->getScalarSizeInBits();
852 
853  if (SrcSize == 16 && Subtarget->has16BitInsts())
854  return DestSize >= 32;
855 
856  return SrcSize == 32 && DestSize == 64;
857 }
858 
859 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
860  // Any register load of a 64-bit value really requires 2 32-bit moves. For all
861  // practical purposes, the extra mov 0 to load a 64-bit is free. As used,
862  // this will enable reducing 64-bit operations the 32-bit, which is always
863  // good.
864 
865  if (Src == MVT::i16)
866  return Dest == MVT::i32 ||Dest == MVT::i64 ;
867 
868  return Src == MVT::i32 && Dest == MVT::i64;
869 }
870 
872  return isZExtFree(Val.getValueType(), VT2);
873 }
874 
876  // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
877  // limited number of native 64-bit operations. Shrinking an operation to fit
878  // in a single 32-bit register should always be helpful. As currently used,
879  // this is much less general than the name suggests, and is only used in
880  // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
881  // not profitable, and may actually be harmful.
882  return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
883 }
884 
885 //===---------------------------------------------------------------------===//
886 // TargetLowering Callbacks
887 //===---------------------------------------------------------------------===//
888 
890  bool IsVarArg) {
891  switch (CC) {
894  return CC_AMDGPU_Kernel;
902  return CC_AMDGPU;
903  case CallingConv::C:
904  case CallingConv::Fast:
905  case CallingConv::Cold:
906  return CC_AMDGPU_Func;
907  default:
908  report_fatal_error("Unsupported calling convention.");
909  }
910 }
911 
913  bool IsVarArg) {
914  switch (CC) {
917  return CC_AMDGPU_Kernel;
925  return RetCC_SI_Shader;
926  case CallingConv::C:
927  case CallingConv::Fast:
928  case CallingConv::Cold:
929  return RetCC_AMDGPU_Func;
930  default:
931  report_fatal_error("Unsupported calling convention.");
932  }
933 }
934 
935 /// The SelectionDAGBuilder will automatically promote function arguments
936 /// with illegal types. However, this does not work for the AMDGPU targets
937 /// since the function arguments are stored in memory as these illegal types.
938 /// In order to handle this properly we need to get the original types sizes
939 /// from the LLVM IR Function and fixup the ISD:InputArg values before
940 /// passing them to AnalyzeFormalArguments()
941 
942 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
943 /// input values across multiple registers. Each item in the Ins array
944 /// represents a single value that will be stored in registers. Ins[x].VT is
945 /// the value type of the value that will be stored in the register, so
946 /// whatever SDNode we lower the argument to needs to be this type.
947 ///
948 /// In order to correctly lower the arguments we need to know the size of each
949 /// argument. Since Ins[x].VT gives us the size of the register that will
950 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
951 /// for the orignal function argument so that we can deduce the correct memory
952 /// type to use for Ins[x]. In most cases the correct memory type will be
953 /// Ins[x].ArgVT. However, this will not always be the case. If, for example,
954 /// we have a kernel argument of type v8i8, this argument will be split into
955 /// 8 parts and each part will be represented by its own item in the Ins array.
956 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
957 /// the argument before it was split. From this, we deduce that the memory type
958 /// for each individual part is i8. We pass the memory type as LocVT to the
959 /// calling convention analysis function and the register type (Ins[x].VT) as
960 /// the ValVT.
962  const SmallVectorImpl<ISD::InputArg> &Ins) const {
963  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
964  const ISD::InputArg &In = Ins[i];
965  EVT MemVT;
966 
967  unsigned NumRegs = getNumRegisters(State.getContext(), In.ArgVT);
968 
969  if (!Subtarget->isAmdHsaOS() &&
970  (In.ArgVT == MVT::i16 || In.ArgVT == MVT::i8 || In.ArgVT == MVT::f16)) {
971  // The ABI says the caller will extend these values to 32-bits.
972  MemVT = In.ArgVT.isInteger() ? MVT::i32 : MVT::f32;
973  } else if (NumRegs == 1) {
974  // This argument is not split, so the IR type is the memory type.
975  assert(!In.Flags.isSplit());
976  if (In.ArgVT.isExtended()) {
977  // We have an extended type, like i24, so we should just use the register type
978  MemVT = In.VT;
979  } else {
980  MemVT = In.ArgVT;
981  }
982  } else if (In.ArgVT.isVector() && In.VT.isVector() &&
983  In.ArgVT.getScalarType() == In.VT.getScalarType()) {
985  // We have a vector value which has been split into a vector with
986  // the same scalar type, but fewer elements. This should handle
987  // all the floating-point vector types.
988  MemVT = In.VT;
989  } else if (In.ArgVT.isVector() &&
990  In.ArgVT.getVectorNumElements() == NumRegs) {
991  // This arg has been split so that each element is stored in a separate
992  // register.
993  MemVT = In.ArgVT.getScalarType();
994  } else if (In.ArgVT.isExtended()) {
995  // We have an extended type, like i65.
996  MemVT = In.VT;
997  } else {
998  unsigned MemoryBits = In.ArgVT.getStoreSizeInBits() / NumRegs;
999  assert(In.ArgVT.getStoreSizeInBits() % NumRegs == 0);
1000  if (In.VT.isInteger()) {
1001  MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
1002  } else if (In.VT.isVector()) {
1004  unsigned NumElements = In.VT.getVectorNumElements();
1005  assert(MemoryBits % NumElements == 0);
1006  // This vector type has been split into another vector type with
1007  // a different elements size.
1008  EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
1009  MemoryBits / NumElements);
1010  MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
1011  } else {
1012  llvm_unreachable("cannot deduce memory type.");
1013  }
1014  }
1015 
1016  // Convert one element vectors to scalar.
1017  if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
1018  MemVT = MemVT.getScalarType();
1019 
1020  if (MemVT.isExtended()) {
1021  // This should really only happen if we have vec3 arguments
1022  assert(MemVT.isVector() && MemVT.getVectorNumElements() == 3);
1023  MemVT = MemVT.getPow2VectorType(State.getContext());
1024  }
1025 
1026  assert(MemVT.isSimple());
1028  State);
1029  }
1030 }
1031 
1033  SDValue Chain, CallingConv::ID CallConv,
1034  bool isVarArg,
1035  const SmallVectorImpl<ISD::OutputArg> &Outs,
1036  const SmallVectorImpl<SDValue> &OutVals,
1037  const SDLoc &DL, SelectionDAG &DAG) const {
1038  // FIXME: Fails for r600 tests
1039  //assert(!isVarArg && Outs.empty() && OutVals.empty() &&
1040  // "wave terminate should not have return values");
1041  return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
1042 }
1043 
1044 //===---------------------------------------------------------------------===//
1045 // Target specific lowering
1046 //===---------------------------------------------------------------------===//
1047 
1048 /// Selects the correct CCAssignFn for a given CallingConvention value.
1050  bool IsVarArg) {
1051  return AMDGPUCallLowering::CCAssignFnForCall(CC, IsVarArg);
1052 }
1053 
1055  bool IsVarArg) {
1056  return AMDGPUCallLowering::CCAssignFnForReturn(CC, IsVarArg);
1057 }
1058 
1060  SelectionDAG &DAG,
1061  MachineFrameInfo &MFI,
1062  int ClobberedFI) const {
1063  SmallVector<SDValue, 8> ArgChains;
1064  int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
1065  int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
1066 
1067  // Include the original chain at the beginning of the list. When this is
1068  // used by target LowerCall hooks, this helps legalize find the
1069  // CALLSEQ_BEGIN node.
1070  ArgChains.push_back(Chain);
1071 
1072  // Add a chain value for each stack argument corresponding
1073  for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1074  UE = DAG.getEntryNode().getNode()->use_end();
1075  U != UE; ++U) {
1076  if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) {
1077  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) {
1078  if (FI->getIndex() < 0) {
1079  int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
1080  int64_t InLastByte = InFirstByte;
1081  InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
1082 
1083  if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1084  (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1085  ArgChains.push_back(SDValue(L, 1));
1086  }
1087  }
1088  }
1089  }
1090 
1091  // Build a tokenfactor for all the chains.
1092  return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
1093 }
1094 
1096  SmallVectorImpl<SDValue> &InVals,
1097  StringRef Reason) const {
1098  SDValue Callee = CLI.Callee;
1099  SelectionDAG &DAG = CLI.DAG;
1100 
1101  const Function &Fn = DAG.getMachineFunction().getFunction();
1102 
1103  StringRef FuncName("<unknown>");
1104 
1105  if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
1106  FuncName = G->getSymbol();
1107  else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1108  FuncName = G->getGlobal()->getName();
1109 
1110  DiagnosticInfoUnsupported NoCalls(
1111  Fn, Reason + FuncName, CLI.DL.getDebugLoc());
1112  DAG.getContext()->diagnose(NoCalls);
1113 
1114  if (!CLI.IsTailCall) {
1115  for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
1116  InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
1117  }
1118 
1119  return DAG.getEntryNode();
1120 }
1121 
1123  SmallVectorImpl<SDValue> &InVals) const {
1124  return lowerUnhandledCall(CLI, InVals, "unsupported call to function ");
1125 }
1126 
1128  SelectionDAG &DAG) const {
1129  const Function &Fn = DAG.getMachineFunction().getFunction();
1130 
1131  DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
1132  SDLoc(Op).getDebugLoc());
1133  DAG.getContext()->diagnose(NoDynamicAlloca);
1134  auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
1135  return DAG.getMergeValues(Ops, SDLoc());
1136 }
1137 
1139  SelectionDAG &DAG) const {
1140  switch (Op.getOpcode()) {
1141  default:
1142  Op->print(errs(), &DAG);
1143  llvm_unreachable("Custom lowering code for this"
1144  "instruction is not implemented yet!");
1145  break;
1146  case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
1147  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
1148  case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
1149  case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
1150  case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
1151  case ISD::FREM: return LowerFREM(Op, DAG);
1152  case ISD::FCEIL: return LowerFCEIL(Op, DAG);
1153  case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
1154  case ISD::FRINT: return LowerFRINT(Op, DAG);
1155  case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
1156  case ISD::FROUND: return LowerFROUND(Op, DAG);
1157  case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
1158  case ISD::FLOG:
1159  return LowerFLOG(Op, DAG, 1 / AMDGPU_LOG2E_F);
1160  case ISD::FLOG10:
1161  return LowerFLOG(Op, DAG, AMDGPU_LN2_F / AMDGPU_LN10_F);
1162  case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
1163  case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
1164  case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
1165  case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
1166  case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
1167  case ISD::CTTZ:
1168  case ISD::CTTZ_ZERO_UNDEF:
1169  case ISD::CTLZ:
1170  case ISD::CTLZ_ZERO_UNDEF:
1171  return LowerCTLZ_CTTZ(Op, DAG);
1172  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1173  }
1174  return Op;
1175 }
1176 
1179  SelectionDAG &DAG) const {
1180  switch (N->getOpcode()) {
1182  // Different parts of legalization seem to interpret which type of
1183  // sign_extend_inreg is the one to check for custom lowering. The extended
1184  // from type is what really matters, but some places check for custom
1185  // lowering of the result type. This results in trying to use
1186  // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
1187  // nothing here and let the illegal result integer be handled normally.
1188  return;
1189  default:
1190  return;
1191  }
1192 }
1193 
1194 static bool hasDefinedInitializer(const GlobalValue *GV) {
1195  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1196  if (!GVar || !GVar->hasInitializer())
1197  return false;
1198 
1199  return !isa<UndefValue>(GVar->getInitializer());
1200 }
1201 
1203  SDValue Op,
1204  SelectionDAG &DAG) const {
1205 
1206  const DataLayout &DL = DAG.getDataLayout();
1207  GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
1208  const GlobalValue *GV = G->getGlobal();
1209 
1210  if (G->getAddressSpace() == AMDGPUASI.LOCAL_ADDRESS ||
1212  if (!MFI->isEntryFunction()) {
1213  const Function &Fn = DAG.getMachineFunction().getFunction();
1214  DiagnosticInfoUnsupported BadLDSDecl(
1215  Fn, "local memory global used by non-kernel function", SDLoc(Op).getDebugLoc());
1216  DAG.getContext()->diagnose(BadLDSDecl);
1217  }
1218 
1219  // XXX: What does the value of G->getOffset() mean?
1220  assert(G->getOffset() == 0 &&
1221  "Do not know what to do with an non-zero offset");
1222 
1223  // TODO: We could emit code to handle the initialization somewhere.
1224  if (!hasDefinedInitializer(GV)) {
1225  unsigned Offset = MFI->allocateLDSGlobal(DL, *GV);
1226  return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
1227  }
1228  }
1229 
1230  const Function &Fn = DAG.getMachineFunction().getFunction();
1231  DiagnosticInfoUnsupported BadInit(
1232  Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
1233  DAG.getContext()->diagnose(BadInit);
1234  return SDValue();
1235 }
1236 
1238  SelectionDAG &DAG) const {
1240 
1241  EVT VT = Op.getValueType();
1242  if (VT == MVT::v4i16 || VT == MVT::v4f16) {
1243  SDLoc SL(Op);
1244  SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(0));
1245  SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(1));
1246 
1247  SDValue BV = DAG.getBuildVector(MVT::v2i32, SL, { Lo, Hi });
1248  return DAG.getNode(ISD::BITCAST, SL, VT, BV);
1249  }
1250 
1251  for (const SDUse &U : Op->ops())
1252  DAG.ExtractVectorElements(U.get(), Args);
1253 
1254  return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1255 }
1256 
1258  SelectionDAG &DAG) const {
1259 
1261  unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1262  EVT VT = Op.getValueType();
1263  DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
1264  VT.getVectorNumElements());
1265 
1266  return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1267 }
1268 
1269 /// Generate Min/Max node
1271  SDValue LHS, SDValue RHS,
1272  SDValue True, SDValue False,
1273  SDValue CC,
1274  DAGCombinerInfo &DCI) const {
1275  if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1276  return SDValue();
1277 
1278  SelectionDAG &DAG = DCI.DAG;
1279  ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1280  switch (CCOpcode) {
1281  case ISD::SETOEQ:
1282  case ISD::SETONE:
1283  case ISD::SETUNE:
1284  case ISD::SETNE:
1285  case ISD::SETUEQ:
1286  case ISD::SETEQ:
1287  case ISD::SETFALSE:
1288  case ISD::SETFALSE2:
1289  case ISD::SETTRUE:
1290  case ISD::SETTRUE2:
1291  case ISD::SETUO:
1292  case ISD::SETO:
1293  break;
1294  case ISD::SETULE:
1295  case ISD::SETULT: {
1296  if (LHS == True)
1297  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1298  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1299  }
1300  case ISD::SETOLE:
1301  case ISD::SETOLT:
1302  case ISD::SETLE:
1303  case ISD::SETLT: {
1304  // Ordered. Assume ordered for undefined.
1305 
1306  // Only do this after legalization to avoid interfering with other combines
1307  // which might occur.
1308  if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1309  !DCI.isCalledByLegalizer())
1310  return SDValue();
1311 
1312  // We need to permute the operands to get the correct NaN behavior. The
1313  // selected operand is the second one based on the failing compare with NaN,
1314  // so permute it based on the compare type the hardware uses.
1315  if (LHS == True)
1316  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1317  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1318  }
1319  case ISD::SETUGE:
1320  case ISD::SETUGT: {
1321  if (LHS == True)
1322  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1323  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1324  }
1325  case ISD::SETGT:
1326  case ISD::SETGE:
1327  case ISD::SETOGE:
1328  case ISD::SETOGT: {
1329  if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1330  !DCI.isCalledByLegalizer())
1331  return SDValue();
1332 
1333  if (LHS == True)
1334  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1335  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1336  }
1337  case ISD::SETCC_INVALID:
1338  llvm_unreachable("Invalid setcc condcode!");
1339  }
1340  return SDValue();
1341 }
1342 
1343 std::pair<SDValue, SDValue>
1345  SDLoc SL(Op);
1346 
1347  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1348 
1349  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1350  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1351 
1352  SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1353  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1354 
1355  return std::make_pair(Lo, Hi);
1356 }
1357 
1359  SDLoc SL(Op);
1360 
1361  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1362  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1363  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1364 }
1365 
1367  SDLoc SL(Op);
1368 
1369  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1370  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1371  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1372 }
1373 
1375  SelectionDAG &DAG) const {
1376  LoadSDNode *Load = cast<LoadSDNode>(Op);
1377  EVT VT = Op.getValueType();
1378 
1379 
1380  // If this is a 2 element vector, we really want to scalarize and not create
1381  // weird 1 element vectors.
1382  if (VT.getVectorNumElements() == 2)
1383  return scalarizeVectorLoad(Load, DAG);
1384 
1385  SDValue BasePtr = Load->getBasePtr();
1386  EVT MemVT = Load->getMemoryVT();
1387  SDLoc SL(Op);
1388 
1389  const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1390 
1391  EVT LoVT, HiVT;
1392  EVT LoMemVT, HiMemVT;
1393  SDValue Lo, Hi;
1394 
1395  std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1396  std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1397  std::tie(Lo, Hi) = DAG.SplitVector(Op, SL, LoVT, HiVT);
1398 
1399  unsigned Size = LoMemVT.getStoreSize();
1400  unsigned BaseAlign = Load->getAlignment();
1401  unsigned HiAlign = MinAlign(BaseAlign, Size);
1402 
1403  SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1404  Load->getChain(), BasePtr, SrcValue, LoMemVT,
1405  BaseAlign, Load->getMemOperand()->getFlags());
1406  SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, Size);
1407  SDValue HiLoad =
1408  DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1409  HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1410  HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1411 
1412  SDValue Ops[] = {
1413  DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad),
1415  LoLoad.getValue(1), HiLoad.getValue(1))
1416  };
1417 
1418  return DAG.getMergeValues(Ops, SL);
1419 }
1420 
1422  SelectionDAG &DAG) const {
1423  StoreSDNode *Store = cast<StoreSDNode>(Op);
1424  SDValue Val = Store->getValue();
1425  EVT VT = Val.getValueType();
1426 
1427  // If this is a 2 element vector, we really want to scalarize and not create
1428  // weird 1 element vectors.
1429  if (VT.getVectorNumElements() == 2)
1430  return scalarizeVectorStore(Store, DAG);
1431 
1432  EVT MemVT = Store->getMemoryVT();
1433  SDValue Chain = Store->getChain();
1434  SDValue BasePtr = Store->getBasePtr();
1435  SDLoc SL(Op);
1436 
1437  EVT LoVT, HiVT;
1438  EVT LoMemVT, HiMemVT;
1439  SDValue Lo, Hi;
1440 
1441  std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
1442  std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemVT);
1443  std::tie(Lo, Hi) = DAG.SplitVector(Val, SL, LoVT, HiVT);
1444 
1445  SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, LoMemVT.getStoreSize());
1446 
1447  const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1448  unsigned BaseAlign = Store->getAlignment();
1449  unsigned Size = LoMemVT.getStoreSize();
1450  unsigned HiAlign = MinAlign(BaseAlign, Size);
1451 
1452  SDValue LoStore =
1453  DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1454  Store->getMemOperand()->getFlags());
1455  SDValue HiStore =
1456  DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1457  HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1458 
1459  return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1460 }
1461 
1462 // This is a shortcut for integer division because we have fast i32<->f32
1463 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1464 // float is enough to accurately represent up to a 24-bit signed integer.
1466  bool Sign) const {
1467  SDLoc DL(Op);
1468  EVT VT = Op.getValueType();
1469  SDValue LHS = Op.getOperand(0);
1470  SDValue RHS = Op.getOperand(1);
1471  MVT IntVT = MVT::i32;
1472  MVT FltVT = MVT::f32;
1473 
1474  unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1475  if (LHSSignBits < 9)
1476  return SDValue();
1477 
1478  unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1479  if (RHSSignBits < 9)
1480  return SDValue();
1481 
1482  unsigned BitSize = VT.getSizeInBits();
1483  unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1484  unsigned DivBits = BitSize - SignBits;
1485  if (Sign)
1486  ++DivBits;
1487 
1490 
1491  SDValue jq = DAG.getConstant(1, DL, IntVT);
1492 
1493  if (Sign) {
1494  // char|short jq = ia ^ ib;
1495  jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1496 
1497  // jq = jq >> (bitsize - 2)
1498  jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1499  DAG.getConstant(BitSize - 2, DL, VT));
1500 
1501  // jq = jq | 0x1
1502  jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1503  }
1504 
1505  // int ia = (int)LHS;
1506  SDValue ia = LHS;
1507 
1508  // int ib, (int)RHS;
1509  SDValue ib = RHS;
1510 
1511  // float fa = (float)ia;
1512  SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1513 
1514  // float fb = (float)ib;
1515  SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1516 
1517  SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1518  fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1519 
1520  // fq = trunc(fq);
1521  fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1522 
1523  // float fqneg = -fq;
1524  SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1525 
1526  // float fr = mad(fqneg, fb, fa);
1527  unsigned OpCode = Subtarget->hasFP32Denormals() ?
1529  (unsigned)ISD::FMAD;
1530  SDValue fr = DAG.getNode(OpCode, DL, FltVT, fqneg, fb, fa);
1531 
1532  // int iq = (int)fq;
1533  SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1534 
1535  // fr = fabs(fr);
1536  fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1537 
1538  // fb = fabs(fb);
1539  fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1540 
1541  EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1542 
1543  // int cv = fr >= fb;
1544  SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1545 
1546  // jq = (cv ? jq : 0);
1547  jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1548 
1549  // dst = iq + jq;
1550  SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1551 
1552  // Rem needs compensation, it's easier to recompute it
1553  SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1554  Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1555 
1556  // Truncate to number of bits this divide really is.
1557  if (Sign) {
1558  SDValue InRegSize
1559  = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1560  Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1561  Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1562  } else {
1563  SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1564  Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1565  Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1566  }
1567 
1568  return DAG.getMergeValues({ Div, Rem }, DL);
1569 }
1570 
1572  SelectionDAG &DAG,
1574  SDLoc DL(Op);
1575  EVT VT = Op.getValueType();
1576 
1577  assert(VT == MVT::i64 && "LowerUDIVREM64 expects an i64");
1578 
1579  EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1580 
1581  SDValue One = DAG.getConstant(1, DL, HalfVT);
1582  SDValue Zero = DAG.getConstant(0, DL, HalfVT);
1583 
1584  //HiLo split
1585  SDValue LHS = Op.getOperand(0);
1586  SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1587  SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, One);
1588 
1589  SDValue RHS = Op.getOperand(1);
1590  SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1591  SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, One);
1592 
1593  if (DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1594  DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1595 
1596  SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1597  LHS_Lo, RHS_Lo);
1598 
1599  SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), Zero});
1600  SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), Zero});
1601 
1602  Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1603  Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1604  return;
1605  }
1606 
1607  if (isTypeLegal(MVT::i64)) {
1608  // Compute denominator reciprocal.
1609  unsigned FMAD = Subtarget->hasFP32Denormals() ?
1611  (unsigned)ISD::FMAD;
1612 
1613  SDValue Cvt_Lo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Lo);
1614  SDValue Cvt_Hi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Hi);
1615  SDValue Mad1 = DAG.getNode(FMAD, DL, MVT::f32, Cvt_Hi,
1616  DAG.getConstantFP(APInt(32, 0x4f800000).bitsToFloat(), DL, MVT::f32),
1617  Cvt_Lo);
1618  SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, DL, MVT::f32, Mad1);
1619  SDValue Mul1 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Rcp,
1620  DAG.getConstantFP(APInt(32, 0x5f7ffffc).bitsToFloat(), DL, MVT::f32));
1621  SDValue Mul2 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Mul1,
1622  DAG.getConstantFP(APInt(32, 0x2f800000).bitsToFloat(), DL, MVT::f32));
1623  SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, MVT::f32, Mul2);
1624  SDValue Mad2 = DAG.getNode(FMAD, DL, MVT::f32, Trunc,
1625  DAG.getConstantFP(APInt(32, 0xcf800000).bitsToFloat(), DL, MVT::f32),
1626  Mul1);
1627  SDValue Rcp_Lo = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Mad2);
1628  SDValue Rcp_Hi = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Trunc);
1629  SDValue Rcp64 = DAG.getBitcast(VT,
1630  DAG.getBuildVector(MVT::v2i32, DL, {Rcp_Lo, Rcp_Hi}));
1631 
1632  SDValue Zero64 = DAG.getConstant(0, DL, VT);
1633  SDValue One64 = DAG.getConstant(1, DL, VT);
1634  SDValue Zero1 = DAG.getConstant(0, DL, MVT::i1);
1635  SDVTList HalfCarryVT = DAG.getVTList(HalfVT, MVT::i1);
1636 
1637  SDValue Neg_RHS = DAG.getNode(ISD::SUB, DL, VT, Zero64, RHS);
1638  SDValue Mullo1 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Rcp64);
1639  SDValue Mulhi1 = DAG.getNode(ISD::MULHU, DL, VT, Rcp64, Mullo1);
1640  SDValue Mulhi1_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1641  Zero);
1642  SDValue Mulhi1_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1643  One);
1644 
1645  SDValue Add1_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Lo,
1646  Mulhi1_Lo, Zero1);
1647  SDValue Add1_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Hi,
1648  Mulhi1_Hi, Add1_Lo.getValue(1));
1649  SDValue Add1_HiNc = DAG.getNode(ISD::ADD, DL, HalfVT, Rcp_Hi, Mulhi1_Hi);
1650  SDValue Add1 = DAG.getBitcast(VT,
1651  DAG.getBuildVector(MVT::v2i32, DL, {Add1_Lo, Add1_Hi}));
1652 
1653  SDValue Mullo2 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Add1);
1654  SDValue Mulhi2 = DAG.getNode(ISD::MULHU, DL, VT, Add1, Mullo2);
1655  SDValue Mulhi2_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1656  Zero);
1657  SDValue Mulhi2_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1658  One);
1659 
1660  SDValue Add2_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_Lo,
1661  Mulhi2_Lo, Zero1);
1662  SDValue Add2_HiC = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_HiNc,
1663  Mulhi2_Hi, Add1_Lo.getValue(1));
1664  SDValue Add2_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add2_HiC,
1665  Zero, Add2_Lo.getValue(1));
1666  SDValue Add2 = DAG.getBitcast(VT,
1667  DAG.getBuildVector(MVT::v2i32, DL, {Add2_Lo, Add2_Hi}));
1668  SDValue Mulhi3 = DAG.getNode(ISD::MULHU, DL, VT, LHS, Add2);
1669 
1670  SDValue Mul3 = DAG.getNode(ISD::MUL, DL, VT, RHS, Mulhi3);
1671 
1672  SDValue Mul3_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, Zero);
1673  SDValue Mul3_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, One);
1674  SDValue Sub1_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Lo,
1675  Mul3_Lo, Zero1);
1676  SDValue Sub1_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Hi,
1677  Mul3_Hi, Sub1_Lo.getValue(1));
1678  SDValue Sub1_Mi = DAG.getNode(ISD::SUB, DL, HalfVT, LHS_Hi, Mul3_Hi);
1679  SDValue Sub1 = DAG.getBitcast(VT,
1680  DAG.getBuildVector(MVT::v2i32, DL, {Sub1_Lo, Sub1_Hi}));
1681 
1682  SDValue MinusOne = DAG.getConstant(0xffffffffu, DL, HalfVT);
1683  SDValue C1 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, MinusOne, Zero,
1684  ISD::SETUGE);
1685  SDValue C2 = DAG.getSelectCC(DL, Sub1_Lo, RHS_Lo, MinusOne, Zero,
1686  ISD::SETUGE);
1687  SDValue C3 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, C2, C1, ISD::SETEQ);
1688 
1689  // TODO: Here and below portions of the code can be enclosed into if/endif.
1690  // Currently control flow is unconditional and we have 4 selects after
1691  // potential endif to substitute PHIs.
1692 
1693  // if C3 != 0 ...
1694  SDValue Sub2_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Lo,
1695  RHS_Lo, Zero1);
1696  SDValue Sub2_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Mi,
1697  RHS_Hi, Sub1_Lo.getValue(1));
1698  SDValue Sub2_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1699  Zero, Sub2_Lo.getValue(1));
1700  SDValue Sub2 = DAG.getBitcast(VT,
1701  DAG.getBuildVector(MVT::v2i32, DL, {Sub2_Lo, Sub2_Hi}));
1702 
1703  SDValue Add3 = DAG.getNode(ISD::ADD, DL, VT, Mulhi3, One64);
1704 
1705  SDValue C4 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, MinusOne, Zero,
1706  ISD::SETUGE);
1707  SDValue C5 = DAG.getSelectCC(DL, Sub2_Lo, RHS_Lo, MinusOne, Zero,
1708  ISD::SETUGE);
1709  SDValue C6 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, C5, C4, ISD::SETEQ);
1710 
1711  // if (C6 != 0)
1712  SDValue Add4 = DAG.getNode(ISD::ADD, DL, VT, Add3, One64);
1713 
1714  SDValue Sub3_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Lo,
1715  RHS_Lo, Zero1);
1716  SDValue Sub3_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1717  RHS_Hi, Sub2_Lo.getValue(1));
1718  SDValue Sub3_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub3_Mi,
1719  Zero, Sub3_Lo.getValue(1));
1720  SDValue Sub3 = DAG.getBitcast(VT,
1721  DAG.getBuildVector(MVT::v2i32, DL, {Sub3_Lo, Sub3_Hi}));
1722 
1723  // endif C6
1724  // endif C3
1725 
1726  SDValue Sel1 = DAG.getSelectCC(DL, C6, Zero, Add4, Add3, ISD::SETNE);
1727  SDValue Div = DAG.getSelectCC(DL, C3, Zero, Sel1, Mulhi3, ISD::SETNE);
1728 
1729  SDValue Sel2 = DAG.getSelectCC(DL, C6, Zero, Sub3, Sub2, ISD::SETNE);
1730  SDValue Rem = DAG.getSelectCC(DL, C3, Zero, Sel2, Sub1, ISD::SETNE);
1731 
1732  Results.push_back(Div);
1733  Results.push_back(Rem);
1734 
1735  return;
1736  }
1737 
1738  // r600 expandion.
1739  // Get Speculative values
1740  SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1741  SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1742 
1743  SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, Zero, REM_Part, LHS_Hi, ISD::SETEQ);
1744  SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, Zero});
1745  REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1746 
1747  SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, Zero, DIV_Part, Zero, ISD::SETEQ);
1748  SDValue DIV_Lo = Zero;
1749 
1750  const unsigned halfBitWidth = HalfVT.getSizeInBits();
1751 
1752  for (unsigned i = 0; i < halfBitWidth; ++i) {
1753  const unsigned bitPos = halfBitWidth - i - 1;
1754  SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1755  // Get value of high bit
1756  SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1757  HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, One);
1758  HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1759 
1760  // Shift
1761  REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1762  // Add LHS high bit
1763  REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1764 
1765  SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1766  SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, Zero, ISD::SETUGE);
1767 
1768  DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1769 
1770  // Update REM
1771  SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1772  REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1773  }
1774 
1775  SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1776  DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1777  Results.push_back(DIV);
1778  Results.push_back(REM);
1779 }
1780 
1782  SelectionDAG &DAG) const {
1783  SDLoc DL(Op);
1784  EVT VT = Op.getValueType();
1785 
1786  if (VT == MVT::i64) {
1788  LowerUDIVREM64(Op, DAG, Results);
1789  return DAG.getMergeValues(Results, DL);
1790  }
1791 
1792  if (VT == MVT::i32) {
1793  if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1794  return Res;
1795  }
1796 
1797  SDValue Num = Op.getOperand(0);
1798  SDValue Den = Op.getOperand(1);
1799 
1800  // RCP = URECIP(Den) = 2^32 / Den + e
1801  // e is rounding error.
1802  SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1803 
1804  // RCP_LO = mul(RCP, Den) */
1805  SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1806 
1807  // RCP_HI = mulhu (RCP, Den) */
1808  SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1809 
1810  // NEG_RCP_LO = -RCP_LO
1811  SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1812  RCP_LO);
1813 
1814  // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1815  SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1816  NEG_RCP_LO, RCP_LO,
1817  ISD::SETEQ);
1818  // Calculate the rounding error from the URECIP instruction
1819  // E = mulhu(ABS_RCP_LO, RCP)
1820  SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1821 
1822  // RCP_A_E = RCP + E
1823  SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1824 
1825  // RCP_S_E = RCP - E
1826  SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1827 
1828  // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1829  SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1830  RCP_A_E, RCP_S_E,
1831  ISD::SETEQ);
1832  // Quotient = mulhu(Tmp0, Num)
1833  SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1834 
1835  // Num_S_Remainder = Quotient * Den
1836  SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1837 
1838  // Remainder = Num - Num_S_Remainder
1839  SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1840 
1841  // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1842  SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1843  DAG.getConstant(-1, DL, VT),
1844  DAG.getConstant(0, DL, VT),
1845  ISD::SETUGE);
1846  // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1847  SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1848  Num_S_Remainder,
1849  DAG.getConstant(-1, DL, VT),
1850  DAG.getConstant(0, DL, VT),
1851  ISD::SETUGE);
1852  // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1853  SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1854  Remainder_GE_Zero);
1855 
1856  // Calculate Division result:
1857 
1858  // Quotient_A_One = Quotient + 1
1859  SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1860  DAG.getConstant(1, DL, VT));
1861 
1862  // Quotient_S_One = Quotient - 1
1863  SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1864  DAG.getConstant(1, DL, VT));
1865 
1866  // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1867  SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1868  Quotient, Quotient_A_One, ISD::SETEQ);
1869 
1870  // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1871  Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1872  Quotient_S_One, Div, ISD::SETEQ);
1873 
1874  // Calculate Rem result:
1875 
1876  // Remainder_S_Den = Remainder - Den
1877  SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1878 
1879  // Remainder_A_Den = Remainder + Den
1880  SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1881 
1882  // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1883  SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1884  Remainder, Remainder_S_Den, ISD::SETEQ);
1885 
1886  // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1887  Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1888  Remainder_A_Den, Rem, ISD::SETEQ);
1889  SDValue Ops[2] = {
1890  Div,
1891  Rem
1892  };
1893  return DAG.getMergeValues(Ops, DL);
1894 }
1895 
1897  SelectionDAG &DAG) const {
1898  SDLoc DL(Op);
1899  EVT VT = Op.getValueType();
1900 
1901  SDValue LHS = Op.getOperand(0);
1902  SDValue RHS = Op.getOperand(1);
1903 
1904  SDValue Zero = DAG.getConstant(0, DL, VT);
1905  SDValue NegOne = DAG.getConstant(-1, DL, VT);
1906 
1907  if (VT == MVT::i32) {
1908  if (SDValue Res = LowerDIVREM24(Op, DAG, true))
1909  return Res;
1910  }
1911 
1912  if (VT == MVT::i64 &&
1913  DAG.ComputeNumSignBits(LHS) > 32 &&
1914  DAG.ComputeNumSignBits(RHS) > 32) {
1915  EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1916 
1917  //HiLo split
1918  SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1919  SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1920  SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1921  LHS_Lo, RHS_Lo);
1922  SDValue Res[2] = {
1923  DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
1924  DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
1925  };
1926  return DAG.getMergeValues(Res, DL);
1927  }
1928 
1929  SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
1930  SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
1931  SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
1932  SDValue RSign = LHSign; // Remainder sign is the same as LHS
1933 
1934  LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
1935  RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
1936 
1937  LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
1938  RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
1939 
1940  SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
1941  SDValue Rem = Div.getValue(1);
1942 
1943  Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
1944  Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
1945 
1946  Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
1947  Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
1948 
1949  SDValue Res[2] = {
1950  Div,
1951  Rem
1952  };
1953  return DAG.getMergeValues(Res, DL);
1954 }
1955 
1956 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
1958  SDLoc SL(Op);
1959  EVT VT = Op.getValueType();
1960  SDValue X = Op.getOperand(0);
1961  SDValue Y = Op.getOperand(1);
1962 
1963  // TODO: Should this propagate fast-math-flags?
1964 
1965  SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
1966  SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
1967  SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
1968 
1969  return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
1970 }
1971 
1973  SDLoc SL(Op);
1974  SDValue Src = Op.getOperand(0);
1975 
1976  // result = trunc(src)
1977  // if (src > 0.0 && src != result)
1978  // result += 1.0
1979 
1980  SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
1981 
1982  const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
1983  const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1984 
1985  EVT SetCCVT =
1987 
1988  SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
1989  SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
1990  SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
1991 
1992  SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
1993  // TODO: Should this propagate fast-math-flags?
1994  return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
1995 }
1996 
1998  SelectionDAG &DAG) {
1999  const unsigned FractBits = 52;
2000  const unsigned ExpBits = 11;
2001 
2002  SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
2003  Hi,
2004  DAG.getConstant(FractBits - 32, SL, MVT::i32),
2005  DAG.getConstant(ExpBits, SL, MVT::i32));
2006  SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
2007  DAG.getConstant(1023, SL, MVT::i32));
2008 
2009  return Exp;
2010 }
2011 
2013  SDLoc SL(Op);
2014  SDValue Src = Op.getOperand(0);
2015 
2016  assert(Op.getValueType() == MVT::f64);
2017 
2018  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2019  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2020 
2021  SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2022 
2023  // Extract the upper half, since this is where we will find the sign and
2024  // exponent.
2025  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
2026 
2027  SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2028 
2029  const unsigned FractBits = 52;
2030 
2031  // Extract the sign bit.
2032  const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
2033  SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
2034 
2035  // Extend back to 64-bits.
2036  SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
2037  SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
2038 
2039  SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
2040  const SDValue FractMask
2041  = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
2042 
2043  SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
2044  SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
2045  SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
2046 
2047  EVT SetCCVT =
2049 
2050  const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
2051 
2052  SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2053  SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2054 
2055  SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
2056  SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
2057 
2058  return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
2059 }
2060 
2062  SDLoc SL(Op);
2063  SDValue Src = Op.getOperand(0);
2064 
2065  assert(Op.getValueType() == MVT::f64);
2066 
2067  APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
2068  SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
2069  SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
2070 
2071  // TODO: Should this propagate fast-math-flags?
2072 
2073  SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
2074  SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
2075 
2076  SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
2077 
2078  APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
2079  SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
2080 
2081  EVT SetCCVT =
2083  SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
2084 
2085  return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
2086 }
2087 
2089  // FNEARBYINT and FRINT are the same, except in their handling of FP
2090  // exceptions. Those aren't really meaningful for us, and OpenCL only has
2091  // rint, so just treat them as equivalent.
2092  return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
2093 }
2094 
2095 // XXX - May require not supporting f32 denormals?
2096 
2097 // Don't handle v2f16. The extra instructions to scalarize and repack around the
2098 // compare and vselect end up producing worse code than scalarizing the whole
2099 // operation.
2101  SDLoc SL(Op);
2102  SDValue X = Op.getOperand(0);
2103  EVT VT = Op.getValueType();
2104 
2105  SDValue T = DAG.getNode(ISD::FTRUNC, SL, VT, X);
2106 
2107  // TODO: Should this propagate fast-math-flags?
2108 
2109  SDValue Diff = DAG.getNode(ISD::FSUB, SL, VT, X, T);
2110 
2111  SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, VT, Diff);
2112 
2113  const SDValue Zero = DAG.getConstantFP(0.0, SL, VT);
2114  const SDValue One = DAG.getConstantFP(1.0, SL, VT);
2115  const SDValue Half = DAG.getConstantFP(0.5, SL, VT);
2116 
2117  SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, VT, One, X);
2118 
2119  EVT SetCCVT =
2120  getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2121 
2122  SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
2123 
2124  SDValue Sel = DAG.getNode(ISD::SELECT, SL, VT, Cmp, SignOne, Zero);
2125 
2126  return DAG.getNode(ISD::FADD, SL, VT, T, Sel);
2127 }
2128 
2130  SDLoc SL(Op);
2131  SDValue X = Op.getOperand(0);
2132 
2133  SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
2134 
2135  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2136  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2137  const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
2138  const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
2139  EVT SetCCVT =
2141 
2142  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2143 
2144  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
2145 
2146  SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2147 
2148  const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
2149  MVT::i64);
2150 
2151  SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
2152  SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
2153  DAG.getConstant(INT64_C(0x0008000000000000), SL,
2154  MVT::i64),
2155  Exp);
2156 
2157  SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
2158  SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
2159  DAG.getConstant(0, SL, MVT::i64), Tmp0,
2160  ISD::SETNE);
2161 
2162  SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
2163  D, DAG.getConstant(0, SL, MVT::i64));
2164  SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
2165 
2166  K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
2167  K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
2168 
2169  SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2170  SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2171  SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
2172 
2173  SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
2174  ExpEqNegOne,
2175  DAG.getConstantFP(1.0, SL, MVT::f64),
2176  DAG.getConstantFP(0.0, SL, MVT::f64));
2177 
2178  SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
2179 
2180  K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
2181  K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
2182 
2183  return K;
2184 }
2185 
2187  EVT VT = Op.getValueType();
2188 
2189  if (VT == MVT::f32 || VT == MVT::f16)
2190  return LowerFROUND32_16(Op, DAG);
2191 
2192  if (VT == MVT::f64)
2193  return LowerFROUND64(Op, DAG);
2194 
2195  llvm_unreachable("unhandled type");
2196 }
2197 
2199  SDLoc SL(Op);
2200  SDValue Src = Op.getOperand(0);
2201 
2202  // result = trunc(src);
2203  // if (src < 0.0 && src != result)
2204  // result += -1.0.
2205 
2206  SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2207 
2208  const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2209  const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
2210 
2211  EVT SetCCVT =
2213 
2214  SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
2215  SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2216  SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2217 
2218  SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
2219  // TODO: Should this propagate fast-math-flags?
2220  return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2221 }
2222 
2224  double Log2BaseInverted) const {
2225  EVT VT = Op.getValueType();
2226 
2227  SDLoc SL(Op);
2228  SDValue Operand = Op.getOperand(0);
2229  SDValue Log2Operand = DAG.getNode(ISD::FLOG2, SL, VT, Operand);
2230  SDValue Log2BaseInvertedOperand = DAG.getConstantFP(Log2BaseInverted, SL, VT);
2231 
2232  return DAG.getNode(ISD::FMUL, SL, VT, Log2Operand, Log2BaseInvertedOperand);
2233 }
2234 
2235 static bool isCtlzOpc(unsigned Opc) {
2236  return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2237 }
2238 
2239 static bool isCttzOpc(unsigned Opc) {
2240  return Opc == ISD::CTTZ || Opc == ISD::CTTZ_ZERO_UNDEF;
2241 }
2242 
2244  SDLoc SL(Op);
2245  SDValue Src = Op.getOperand(0);
2246  bool ZeroUndef = Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
2248 
2249  unsigned ISDOpc, NewOpc;
2250  if (isCtlzOpc(Op.getOpcode())) {
2251  ISDOpc = ISD::CTLZ_ZERO_UNDEF;
2252  NewOpc = AMDGPUISD::FFBH_U32;
2253  } else if (isCttzOpc(Op.getOpcode())) {
2254  ISDOpc = ISD::CTTZ_ZERO_UNDEF;
2255  NewOpc = AMDGPUISD::FFBL_B32;
2256  } else
2257  llvm_unreachable("Unexpected OPCode!!!");
2258 
2259 
2260  if (ZeroUndef && Src.getValueType() == MVT::i32)
2261  return DAG.getNode(NewOpc, SL, MVT::i32, Src);
2262 
2263  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2264 
2265  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2266  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2267 
2268  SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
2269  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
2270 
2271  EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2272  *DAG.getContext(), MVT::i32);
2273 
2274  SDValue HiOrLo = isCtlzOpc(Op.getOpcode()) ? Hi : Lo;
2275  SDValue Hi0orLo0 = DAG.getSetCC(SL, SetCCVT, HiOrLo, Zero, ISD::SETEQ);
2276 
2277  SDValue OprLo = DAG.getNode(ISDOpc, SL, MVT::i32, Lo);
2278  SDValue OprHi = DAG.getNode(ISDOpc, SL, MVT::i32, Hi);
2279 
2280  const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
2281  SDValue Add, NewOpr;
2282  if (isCtlzOpc(Op.getOpcode())) {
2283  Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprLo, Bits32);
2284  // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
2285  NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprHi);
2286  } else {
2287  Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprHi, Bits32);
2288  // cttz(x) = lo_32(x) == 0 ? cttz(hi_32(x)) + 32 : cttz(lo_32(x))
2289  NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprLo);
2290  }
2291 
2292  if (!ZeroUndef) {
2293  // Test if the full 64-bit input is zero.
2294 
2295  // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
2296  // which we probably don't want.
2297  SDValue LoOrHi = isCtlzOpc(Op.getOpcode()) ? Lo : Hi;
2298  SDValue Lo0OrHi0 = DAG.getSetCC(SL, SetCCVT, LoOrHi, Zero, ISD::SETEQ);
2299  SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0OrHi0, Hi0orLo0);
2300 
2301  // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
2302  // with the same cycles, otherwise it is slower.
2303  // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
2304  // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
2305 
2306  const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
2307 
2308  // The instruction returns -1 for 0 input, but the defined intrinsic
2309  // behavior is to return the number of bits.
2310  NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32,
2311  SrcIsZero, Bits32, NewOpr);
2312  }
2313 
2314  return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewOpr);
2315 }
2316 
2318  bool Signed) const {
2319  // Unsigned
2320  // cul2f(ulong u)
2321  //{
2322  // uint lz = clz(u);
2323  // uint e = (u != 0) ? 127U + 63U - lz : 0;
2324  // u = (u << lz) & 0x7fffffffffffffffUL;
2325  // ulong t = u & 0xffffffffffUL;
2326  // uint v = (e << 23) | (uint)(u >> 40);
2327  // uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
2328  // return as_float(v + r);
2329  //}
2330  // Signed
2331  // cl2f(long l)
2332  //{
2333  // long s = l >> 63;
2334  // float r = cul2f((l + s) ^ s);
2335  // return s ? -r : r;
2336  //}
2337 
2338  SDLoc SL(Op);
2339  SDValue Src = Op.getOperand(0);
2340  SDValue L = Src;
2341 
2342  SDValue S;
2343  if (Signed) {
2344  const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
2345  S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
2346 
2347  SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
2348  L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
2349  }
2350 
2351  EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2352  *DAG.getContext(), MVT::f32);
2353 
2354 
2355  SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
2356  SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
2357  SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
2358  LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
2359 
2360  SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
2361  SDValue E = DAG.getSelect(SL, MVT::i32,
2362  DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
2363  DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
2364  ZeroI32);
2365 
2366  SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
2367  DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
2368  DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
2369 
2370  SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
2371  DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
2372 
2373  SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
2374  U, DAG.getConstant(40, SL, MVT::i64));
2375 
2376  SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
2377  DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
2378  DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, UShl));
2379 
2380  SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
2381  SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
2382  SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
2383 
2384  SDValue One = DAG.getConstant(1, SL, MVT::i32);
2385 
2386  SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
2387 
2388  SDValue R = DAG.getSelect(SL, MVT::i32,
2389  RCmp,
2390  One,
2391  DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
2392  R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
2393  R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
2394 
2395  if (!Signed)
2396  return R;
2397 
2398  SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
2399  return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
2400 }
2401 
2403  bool Signed) const {
2404  SDLoc SL(Op);
2405  SDValue Src = Op.getOperand(0);
2406 
2407  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2408 
2410  DAG.getConstant(0, SL, MVT::i32));
2412  DAG.getConstant(1, SL, MVT::i32));
2413 
2414  SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2415  SL, MVT::f64, Hi);
2416 
2417  SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2418 
2419  SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2420  DAG.getConstant(32, SL, MVT::i32));
2421  // TODO: Should this propagate fast-math-flags?
2422  return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2423 }
2424 
2426  SelectionDAG &DAG) const {
2427  assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2428  "operation should be legal");
2429 
2430  // TODO: Factor out code common with LowerSINT_TO_FP.
2431 
2432  EVT DestVT = Op.getValueType();
2433  if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2434  SDLoc DL(Op);
2435  SDValue Src = Op.getOperand(0);
2436 
2437  SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2438  SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2439  SDValue FPRound =
2440  DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2441 
2442  return FPRound;
2443  }
2444 
2445  if (DestVT == MVT::f32)
2446  return LowerINT_TO_FP32(Op, DAG, false);
2447 
2448  assert(DestVT == MVT::f64);
2449  return LowerINT_TO_FP64(Op, DAG, false);
2450 }
2451 
2453  SelectionDAG &DAG) const {
2454  assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2455  "operation should be legal");
2456 
2457  // TODO: Factor out code common with LowerUINT_TO_FP.
2458 
2459  EVT DestVT = Op.getValueType();
2460  if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2461  SDLoc DL(Op);
2462  SDValue Src = Op.getOperand(0);
2463 
2464  SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2465  SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2466  SDValue FPRound =
2467  DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2468 
2469  return FPRound;
2470  }
2471 
2472  if (DestVT == MVT::f32)
2473  return LowerINT_TO_FP32(Op, DAG, true);
2474 
2475  assert(DestVT == MVT::f64);
2476  return LowerINT_TO_FP64(Op, DAG, true);
2477 }
2478 
2480  bool Signed) const {
2481  SDLoc SL(Op);
2482 
2483  SDValue Src = Op.getOperand(0);
2484 
2485  SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2486 
2487  SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2488  MVT::f64);
2489  SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2490  MVT::f64);
2491  // TODO: Should this propagate fast-math-flags?
2492  SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2493 
2494  SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2495 
2496 
2497  SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2498 
2499  SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2500  MVT::i32, FloorMul);
2501  SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2502 
2503  SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2504 
2505  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2506 }
2507 
2509  SDLoc DL(Op);
2510  SDValue N0 = Op.getOperand(0);
2511 
2512  // Convert to target node to get known bits
2513  if (N0.getValueType() == MVT::f32)
2514  return DAG.getNode(AMDGPUISD::FP_TO_FP16, DL, Op.getValueType(), N0);
2515 
2517  // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2518  return SDValue();
2519  }
2520 
2522 
2523  // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2524  const unsigned ExpMask = 0x7ff;
2525  const unsigned ExpBiasf64 = 1023;
2526  const unsigned ExpBiasf16 = 15;
2527  SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2528  SDValue One = DAG.getConstant(1, DL, MVT::i32);
2529  SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2530  SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2531  DAG.getConstant(32, DL, MVT::i64));
2532  UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2533  U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2534  SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2535  DAG.getConstant(20, DL, MVT::i64));
2536  E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2537  DAG.getConstant(ExpMask, DL, MVT::i32));
2538  // Subtract the fp64 exponent bias (1023) to get the real exponent and
2539  // add the f16 bias (15) to get the biased exponent for the f16 format.
2540  E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2541  DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2542 
2543  SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2544  DAG.getConstant(8, DL, MVT::i32));
2545  M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2546  DAG.getConstant(0xffe, DL, MVT::i32));
2547 
2548  SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2549  DAG.getConstant(0x1ff, DL, MVT::i32));
2550  MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2551 
2552  SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2553  M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2554 
2555  // (M != 0 ? 0x0200 : 0) | 0x7c00;
2556  SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2557  DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2558  Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2559 
2560  // N = M | (E << 12);
2561  SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2562  DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2563  DAG.getConstant(12, DL, MVT::i32)));
2564 
2565  // B = clamp(1-E, 0, 13);
2566  SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2567  One, E);
2568  SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2569  B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2570  DAG.getConstant(13, DL, MVT::i32));
2571 
2572  SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2573  DAG.getConstant(0x1000, DL, MVT::i32));
2574 
2575  SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2576  SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2577  SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2578  D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2579 
2580  SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2581  SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2582  DAG.getConstant(0x7, DL, MVT::i32));
2583  V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2584  DAG.getConstant(2, DL, MVT::i32));
2585  SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2586  One, Zero, ISD::SETEQ);
2587  SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2588  One, Zero, ISD::SETGT);
2589  V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2590  V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2591 
2592  V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2593  DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2594  V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2595  I, V, ISD::SETEQ);
2596 
2597  // Extract the sign bit.
2598  SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2599  DAG.getConstant(16, DL, MVT::i32));
2600  Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2601  DAG.getConstant(0x8000, DL, MVT::i32));
2602 
2603  V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2604  return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2605 }
2606 
2608  SelectionDAG &DAG) const {
2609  SDValue Src = Op.getOperand(0);
2610 
2611  // TODO: Factor out code common with LowerFP_TO_UINT.
2612 
2613  EVT SrcVT = Src.getValueType();
2614  if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2615  SDLoc DL(Op);
2616 
2617  SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2618  SDValue FpToInt32 =
2619  DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2620 
2621  return FpToInt32;
2622  }
2623 
2624  if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2625  return LowerFP64_TO_INT(Op, DAG, true);
2626 
2627  return SDValue();
2628 }
2629 
2631  SelectionDAG &DAG) const {
2632  SDValue Src = Op.getOperand(0);
2633 
2634  // TODO: Factor out code common with LowerFP_TO_SINT.
2635 
2636  EVT SrcVT = Src.getValueType();
2637  if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2638  SDLoc DL(Op);
2639 
2640  SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2641  SDValue FpToInt32 =
2642  DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2643 
2644  return FpToInt32;
2645  }
2646 
2647  if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2648  return LowerFP64_TO_INT(Op, DAG, false);
2649 
2650  return SDValue();
2651 }
2652 
2654  SelectionDAG &DAG) const {
2655  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2656  MVT VT = Op.getSimpleValueType();
2657  MVT ScalarVT = VT.getScalarType();
2658 
2659  assert(VT.isVector());
2660 
2661  SDValue Src = Op.getOperand(0);
2662  SDLoc DL(Op);
2663 
2664  // TODO: Don't scalarize on Evergreen?
2665  unsigned NElts = VT.getVectorNumElements();
2667  DAG.ExtractVectorElements(Src, Args, 0, NElts);
2668 
2669  SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2670  for (unsigned I = 0; I < NElts; ++I)
2671  Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2672 
2673  return DAG.getBuildVector(VT, DL, Args);
2674 }
2675 
2676 //===----------------------------------------------------------------------===//
2677 // Custom DAG optimizations
2678 //===----------------------------------------------------------------------===//
2679 
2680 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2681  return AMDGPUTargetLowering::numBitsUnsigned(Op, DAG) <= 24;
2682 }
2683 
2684 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2685  EVT VT = Op.getValueType();
2686  return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2687  // as unsigned 24-bit values.
2689 }
2690 
2691 static bool simplifyI24(SDNode *Node24, unsigned OpIdx,
2693 
2694  SelectionDAG &DAG = DCI.DAG;
2695  SDValue Op = Node24->getOperand(OpIdx);
2696  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2697  EVT VT = Op.getValueType();
2698 
2699  APInt Demanded = APInt::getLowBitsSet(VT.getSizeInBits(), 24);
2700  APInt KnownZero, KnownOne;
2701  TargetLowering::TargetLoweringOpt TLO(DAG, true, true);
2702  if (TLI.SimplifyDemandedBits(Node24, OpIdx, Demanded, DCI, TLO))
2703  return true;
2704 
2705  return false;
2706 }
2707 
2708 template <typename IntTy>
2710  uint32_t Width, const SDLoc &DL) {
2711  if (Width + Offset < 32) {
2712  uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2713  IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2714  return DAG.getConstant(Result, DL, MVT::i32);
2715  }
2716 
2717  return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2718 }
2719 
2720 static bool hasVolatileUser(SDNode *Val) {
2721  for (SDNode *U : Val->uses()) {
2722  if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2723  if (M->isVolatile())
2724  return true;
2725  }
2726  }
2727 
2728  return false;
2729 }
2730 
2732  // i32 vectors are the canonical memory type.
2733  if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2734  return false;
2735 
2736  if (!VT.isByteSized())
2737  return false;
2738 
2739  unsigned Size = VT.getStoreSize();
2740 
2741  if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2742  return false;
2743 
2744  if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2745  return false;
2746 
2747  return true;
2748 }
2749 
2750 // Replace load of an illegal type with a store of a bitcast to a friendlier
2751 // type.
2753  DAGCombinerInfo &DCI) const {
2754  if (!DCI.isBeforeLegalize())
2755  return SDValue();
2756 
2757  LoadSDNode *LN = cast<LoadSDNode>(N);
2758  if (LN->isVolatile() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2759  return SDValue();
2760 
2761  SDLoc SL(N);
2762  SelectionDAG &DAG = DCI.DAG;
2763  EVT VT = LN->getMemoryVT();
2764 
2765  unsigned Size = VT.getStoreSize();
2766  unsigned Align = LN->getAlignment();
2767  if (Align < Size && isTypeLegal(VT)) {
2768  bool IsFast;
2769  unsigned AS = LN->getAddressSpace();
2770 
2771  // Expand unaligned loads earlier than legalization. Due to visitation order
2772  // problems during legalization, the emitted instructions to pack and unpack
2773  // the bytes again are not eliminated in the case of an unaligned copy.
2774  if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2775  if (VT.isVector())
2776  return scalarizeVectorLoad(LN, DAG);
2777 
2778  SDValue Ops[2];
2779  std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2780  return DAG.getMergeValues(Ops, SDLoc(N));
2781  }
2782 
2783  if (!IsFast)
2784  return SDValue();
2785  }
2786 
2787  if (!shouldCombineMemoryType(VT))
2788  return SDValue();
2789 
2790  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2791 
2792  SDValue NewLoad
2793  = DAG.getLoad(NewVT, SL, LN->getChain(),
2794  LN->getBasePtr(), LN->getMemOperand());
2795 
2796  SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2797  DCI.CombineTo(N, BC, NewLoad.getValue(1));
2798  return SDValue(N, 0);
2799 }
2800 
2801 // Replace store of an illegal type with a store of a bitcast to a friendlier
2802 // type.
2804  DAGCombinerInfo &DCI) const {
2805  if (!DCI.isBeforeLegalize())
2806  return SDValue();
2807 
2808  StoreSDNode *SN = cast<StoreSDNode>(N);
2809  if (SN->isVolatile() || !ISD::isNormalStore(SN))
2810  return SDValue();
2811 
2812  EVT VT = SN->getMemoryVT();
2813  unsigned Size = VT.getStoreSize();
2814 
2815  SDLoc SL(N);
2816  SelectionDAG &DAG = DCI.DAG;
2817  unsigned Align = SN->getAlignment();
2818  if (Align < Size && isTypeLegal(VT)) {
2819  bool IsFast;
2820  unsigned AS = SN->getAddressSpace();
2821 
2822  // Expand unaligned stores earlier than legalization. Due to visitation
2823  // order problems during legalization, the emitted instructions to pack and
2824  // unpack the bytes again are not eliminated in the case of an unaligned
2825  // copy.
2826  if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2827  if (VT.isVector())
2828  return scalarizeVectorStore(SN, DAG);
2829 
2830  return expandUnalignedStore(SN, DAG);
2831  }
2832 
2833  if (!IsFast)
2834  return SDValue();
2835  }
2836 
2837  if (!shouldCombineMemoryType(VT))
2838  return SDValue();
2839 
2840  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2841  SDValue Val = SN->getValue();
2842 
2843  //DCI.AddToWorklist(Val.getNode());
2844 
2845  bool OtherUses = !Val.hasOneUse();
2846  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2847  if (OtherUses) {
2848  SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
2849  DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
2850  }
2851 
2852  return DAG.getStore(SN->getChain(), SL, CastVal,
2853  SN->getBasePtr(), SN->getMemOperand());
2854 }
2855 
2856 // FIXME: This should go in generic DAG combiner with an isTruncateFree check,
2857 // but isTruncateFree is inaccurate for i16 now because of SALU vs. VALU
2858 // issues.
2860  DAGCombinerInfo &DCI) const {
2861  SelectionDAG &DAG = DCI.DAG;
2862  SDValue N0 = N->getOperand(0);
2863 
2864  // (vt2 (assertzext (truncate vt0:x), vt1)) ->
2865  // (vt2 (truncate (assertzext vt0:x, vt1)))
2866  if (N0.getOpcode() == ISD::TRUNCATE) {
2867  SDValue N1 = N->getOperand(1);
2868  EVT ExtVT = cast<VTSDNode>(N1)->getVT();
2869  SDLoc SL(N);
2870 
2871  SDValue Src = N0.getOperand(0);
2872  EVT SrcVT = Src.getValueType();
2873  if (SrcVT.bitsGE(ExtVT)) {
2874  SDValue NewInReg = DAG.getNode(N->getOpcode(), SL, SrcVT, Src, N1);
2875  return DAG.getNode(ISD::TRUNCATE, SL, N->getValueType(0), NewInReg);
2876  }
2877  }
2878 
2879  return SDValue();
2880 }
2881 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
2882 /// binary operation \p Opc to it with the corresponding constant operands.
2884  DAGCombinerInfo &DCI, const SDLoc &SL,
2885  unsigned Opc, SDValue LHS,
2886  uint32_t ValLo, uint32_t ValHi) const {
2887  SelectionDAG &DAG = DCI.DAG;
2888  SDValue Lo, Hi;
2889  std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
2890 
2891  SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
2892  SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
2893 
2894  SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
2895  SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
2896 
2897  // Re-visit the ands. It's possible we eliminated one of them and it could
2898  // simplify the vector.
2899  DCI.AddToWorklist(Lo.getNode());
2900  DCI.AddToWorklist(Hi.getNode());
2901 
2902  SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
2903  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2904 }
2905 
2907  DAGCombinerInfo &DCI) const {
2908  EVT VT = N->getValueType(0);
2909 
2911  if (!RHS)
2912  return SDValue();
2913 
2914  SDValue LHS = N->getOperand(0);
2915  unsigned RHSVal = RHS->getZExtValue();
2916  if (!RHSVal)
2917  return LHS;
2918 
2919  SDLoc SL(N);
2920  SelectionDAG &DAG = DCI.DAG;
2921 
2922  switch (LHS->getOpcode()) {
2923  default:
2924  break;
2925  case ISD::ZERO_EXTEND:
2926  case ISD::SIGN_EXTEND:
2927  case ISD::ANY_EXTEND: {
2928  SDValue X = LHS->getOperand(0);
2929 
2930  if (VT == MVT::i32 && RHSVal == 16 && X.getValueType() == MVT::i16 &&
2932  // Prefer build_vector as the canonical form if packed types are legal.
2933  // (shl ([asz]ext i16:x), 16 -> build_vector 0, x
2934  SDValue Vec = DAG.getBuildVector(MVT::v2i16, SL,
2935  { DAG.getConstant(0, SL, MVT::i16), LHS->getOperand(0) });
2936  return DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2937  }
2938 
2939  // shl (ext x) => zext (shl x), if shift does not overflow int
2940  if (VT != MVT::i64)
2941  break;
2942  KnownBits Known;
2943  DAG.computeKnownBits(X, Known);
2944  unsigned LZ = Known.countMinLeadingZeros();
2945  if (LZ < RHSVal)
2946  break;
2947  EVT XVT = X.getValueType();
2948  SDValue Shl = DAG.getNode(ISD::SHL, SL, XVT, X, SDValue(RHS, 0));
2949  return DAG.getZExtOrTrunc(Shl, SL, VT);
2950  }
2951  }
2952 
2953  if (VT != MVT::i64)
2954  return SDValue();
2955 
2956  // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
2957 
2958  // On some subtargets, 64-bit shift is a quarter rate instruction. In the
2959  // common case, splitting this into a move and a 32-bit shift is faster and
2960  // the same code size.
2961  if (RHSVal < 32)
2962  return SDValue();
2963 
2964  SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
2965 
2966  SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
2967  SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
2968 
2969  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2970 
2971  SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
2972  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2973 }
2974 
2976  DAGCombinerInfo &DCI) const {
2977  if (N->getValueType(0) != MVT::i64)
2978  return SDValue();
2979 
2980  const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
2981  if (!RHS)
2982  return SDValue();
2983 
2984  SelectionDAG &DAG = DCI.DAG;
2985  SDLoc SL(N);
2986  unsigned RHSVal = RHS->getZExtValue();
2987 
2988  // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
2989  if (RHSVal == 32) {
2990  SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
2991  SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
2992  DAG.getConstant(31, SL, MVT::i32));
2993 
2994  SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
2995  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
2996  }
2997 
2998  // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
2999  if (RHSVal == 63) {
3000  SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3001  SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3002  DAG.getConstant(31, SL, MVT::i32));
3003  SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
3004  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3005  }
3006 
3007  return SDValue();
3008 }
3009 
3011  DAGCombinerInfo &DCI) const {
3012  if (N->getValueType(0) != MVT::i64)
3013  return SDValue();
3014 
3015  const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3016  if (!RHS)
3017  return SDValue();
3018 
3019  unsigned ShiftAmt = RHS->getZExtValue();
3020  if (ShiftAmt < 32)
3021  return SDValue();
3022 
3023  // srl i64:x, C for C >= 32
3024  // =>
3025  // build_pair (srl hi_32(x), C - 32), 0
3026 
3027  SelectionDAG &DAG = DCI.DAG;
3028  SDLoc SL(N);
3029 
3030  SDValue One = DAG.getConstant(1, SL, MVT::i32);
3031  SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3032 
3033  SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, N->getOperand(0));
3035  VecOp, One);
3036 
3037  SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
3038  SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
3039 
3040  SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
3041 
3042  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
3043 }
3044 
3046  SDNode *N, DAGCombinerInfo &DCI) const {
3047  SDLoc SL(N);
3048  SelectionDAG &DAG = DCI.DAG;
3049  EVT VT = N->getValueType(0);
3050  SDValue Src = N->getOperand(0);
3051 
3052  // vt1 (truncate (bitcast (build_vector vt0:x, ...))) -> vt1 (bitcast vt0:x)
3053  if (Src.getOpcode() == ISD::BITCAST) {
3054  SDValue Vec = Src.getOperand(0);
3055  if (Vec.getOpcode() == ISD::BUILD_VECTOR) {
3056  SDValue Elt0 = Vec.getOperand(0);
3057  EVT EltVT = Elt0.getValueType();
3058  if (VT.getSizeInBits() <= EltVT.getSizeInBits()) {
3059  if (EltVT.isFloatingPoint()) {
3060  Elt0 = DAG.getNode(ISD::BITCAST, SL,
3061  EltVT.changeTypeToInteger(), Elt0);
3062  }
3063 
3064  return DAG.getNode(ISD::TRUNCATE, SL, VT, Elt0);
3065  }
3066  }
3067  }
3068 
3069  // Equivalent of above for accessing the high element of a vector as an
3070  // integer operation.
3071  // trunc (srl (bitcast (build_vector x, y))), 16 -> trunc (bitcast y)
3072  if (Src.getOpcode() == ISD::SRL) {
3073  if (auto K = isConstOrConstSplat(Src.getOperand(1))) {
3074  if (2 * K->getZExtValue() == Src.getValueType().getScalarSizeInBits()) {
3075  SDValue BV = stripBitcast(Src.getOperand(0));
3076  if (BV.getOpcode() == ISD::BUILD_VECTOR &&
3077  BV.getValueType().getVectorNumElements() == 2) {
3078  SDValue SrcElt = BV.getOperand(1);
3079  EVT SrcEltVT = SrcElt.getValueType();
3080  if (SrcEltVT.isFloatingPoint()) {
3081  SrcElt = DAG.getNode(ISD::BITCAST, SL,
3082  SrcEltVT.changeTypeToInteger(), SrcElt);
3083  }
3084 
3085  return DAG.getNode(ISD::TRUNCATE, SL, VT, SrcElt);
3086  }
3087  }
3088  }
3089  }
3090 
3091  // Partially shrink 64-bit shifts to 32-bit if reduced to 16-bit.
3092  //
3093  // i16 (trunc (srl i64:x, K)), K <= 16 ->
3094  // i16 (trunc (srl (i32 (trunc x), K)))
3095  if (VT.getScalarSizeInBits() < 32) {
3096  EVT SrcVT = Src.getValueType();
3097  if (SrcVT.getScalarSizeInBits() > 32 &&
3098  (Src.getOpcode() == ISD::SRL ||
3099  Src.getOpcode() == ISD::SRA ||
3100  Src.getOpcode() == ISD::SHL)) {
3101  SDValue Amt = Src.getOperand(1);
3102  KnownBits Known;
3103  DAG.computeKnownBits(Amt, Known);
3104  unsigned Size = VT.getScalarSizeInBits();
3105  if ((Known.isConstant() && Known.getConstant().ule(Size)) ||
3106  (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size))) {
3107  EVT MidVT = VT.isVector() ?
3110 
3111  EVT NewShiftVT = getShiftAmountTy(MidVT, DAG.getDataLayout());
3112  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MidVT,
3113  Src.getOperand(0));
3114  DCI.AddToWorklist(Trunc.getNode());
3115 
3116  if (Amt.getValueType() != NewShiftVT) {
3117  Amt = DAG.getZExtOrTrunc(Amt, SL, NewShiftVT);
3118  DCI.AddToWorklist(Amt.getNode());
3119  }
3120 
3121  SDValue ShrunkShift = DAG.getNode(Src.getOpcode(), SL, MidVT,
3122  Trunc, Amt);
3123  return DAG.getNode(ISD::TRUNCATE, SL, VT, ShrunkShift);
3124  }
3125  }
3126  }
3127 
3128  return SDValue();
3129 }
3130 
3131 // We need to specifically handle i64 mul here to avoid unnecessary conversion
3132 // instructions. If we only match on the legalized i64 mul expansion,
3133 // SimplifyDemandedBits will be unable to remove them because there will be
3134 // multiple uses due to the separate mul + mulh[su].
3135 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
3136  SDValue N0, SDValue N1, unsigned Size, bool Signed) {
3137  if (Size <= 32) {
3138  unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3139  return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
3140  }
3141 
3142  // Because we want to eliminate extension instructions before the
3143  // operation, we need to create a single user here (i.e. not the separate
3144  // mul_lo + mul_hi) so that SimplifyDemandedBits will deal with it.
3145 
3146  unsigned MulOpc = Signed ? AMDGPUISD::MUL_LOHI_I24 : AMDGPUISD::MUL_LOHI_U24;
3147 
3148  SDValue Mul = DAG.getNode(MulOpc, SL,
3149  DAG.getVTList(MVT::i32, MVT::i32), N0, N1);
3150 
3151  return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64,
3152  Mul.getValue(0), Mul.getValue(1));
3153 }
3154 
3156  DAGCombinerInfo &DCI) const {
3157  EVT VT = N->getValueType(0);
3158 
3159  unsigned Size = VT.getSizeInBits();
3160  if (VT.isVector() || Size > 64)
3161  return SDValue();
3162 
3163  // There are i16 integer mul/mad.
3165  return SDValue();
3166 
3167  SelectionDAG &DAG = DCI.DAG;
3168  SDLoc DL(N);
3169 
3170  SDValue N0 = N->getOperand(0);
3171  SDValue N1 = N->getOperand(1);
3172 
3173  // SimplifyDemandedBits has the annoying habit of turning useful zero_extends
3174  // in the source into any_extends if the result of the mul is truncated. Since
3175  // we can assume the high bits are whatever we want, use the underlying value
3176  // to avoid the unknown high bits from interfering.
3177  if (N0.getOpcode() == ISD::ANY_EXTEND)
3178  N0 = N0.getOperand(0);
3179 
3180  if (N1.getOpcode() == ISD::ANY_EXTEND)
3181  N1 = N1.getOperand(0);
3182 
3183  SDValue Mul;
3184 
3185  if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
3186  N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3187  N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3188  Mul = getMul24(DAG, DL, N0, N1, Size, false);
3189  } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
3190  N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3191  N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3192  Mul = getMul24(DAG, DL, N0, N1, Size, true);
3193  } else {
3194  return SDValue();
3195  }
3196 
3197  // We need to use sext even for MUL_U24, because MUL_U24 is used
3198  // for signed multiply of 8 and 16-bit types.
3199  return DAG.getSExtOrTrunc(Mul, DL, VT);
3200 }
3201 
3203  DAGCombinerInfo &DCI) const {
3204  EVT VT = N->getValueType(0);
3205 
3206  if (!Subtarget->hasMulI24() || VT.isVector())
3207  return SDValue();
3208 
3209  SelectionDAG &DAG = DCI.DAG;
3210  SDLoc DL(N);
3211 
3212  SDValue N0 = N->getOperand(0);
3213  SDValue N1 = N->getOperand(1);
3214 
3215  if (!isI24(N0, DAG) || !isI24(N1, DAG))
3216  return SDValue();
3217 
3218  N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3219  N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3220 
3221  SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
3222  DCI.AddToWorklist(Mulhi.getNode());
3223  return DAG.getSExtOrTrunc(Mulhi, DL, VT);
3224 }
3225 
3227  DAGCombinerInfo &DCI) const {
3228  EVT VT = N->getValueType(0);
3229 
3230  if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
3231  return SDValue();
3232 
3233  SelectionDAG &DAG = DCI.DAG;
3234  SDLoc DL(N);
3235 
3236  SDValue N0 = N->getOperand(0);
3237  SDValue N1 = N->getOperand(1);
3238 
3239  if (!isU24(N0, DAG) || !isU24(N1, DAG))
3240  return SDValue();
3241 
3242  N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3243  N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3244 
3245  SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
3246  DCI.AddToWorklist(Mulhi.getNode());
3247  return DAG.getZExtOrTrunc(Mulhi, DL, VT);
3248 }
3249 
3251  SDNode *N, DAGCombinerInfo &DCI) const {
3252  SelectionDAG &DAG = DCI.DAG;
3253 
3254  // Simplify demanded bits before splitting into multiple users.
3255  if (simplifyI24(N, 0, DCI) || simplifyI24(N, 1, DCI))
3256  return SDValue();
3257 
3258  SDValue N0 = N->getOperand(0);
3259  SDValue N1 = N->getOperand(1);
3260 
3261  bool Signed = (N->getOpcode() == AMDGPUISD::MUL_LOHI_I24);
3262 
3263  unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3264  unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
3265 
3266  SDLoc SL(N);
3267 
3268  SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
3269  SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
3270  return DAG.getMergeValues({ MulLo, MulHi }, SL);
3271 }
3272 
3273 static bool isNegativeOne(SDValue Val) {
3274  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
3275  return C->isAllOnesValue();
3276  return false;
3277 }
3278 
3279 SDValue AMDGPUTargetLowering::getFFBX_U32(SelectionDAG &DAG,
3280  SDValue Op,
3281  const SDLoc &DL,
3282  unsigned Opc) const {
3283  EVT VT = Op.getValueType();
3284  EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
3285  if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
3286  LegalVT != MVT::i16))
3287  return SDValue();
3288 
3289  if (VT != MVT::i32)
3290  Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
3291 
3292  SDValue FFBX = DAG.getNode(Opc, DL, MVT::i32, Op);
3293  if (VT != MVT::i32)
3294  FFBX = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBX);
3295 
3296  return FFBX;
3297 }
3298 
3299 // The native instructions return -1 on 0 input. Optimize out a select that
3300 // produces -1 on 0.
3301 //
3302 // TODO: If zero is not undef, we could also do this if the output is compared
3303 // against the bitwidth.
3304 //
3305 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
3307  SDValue LHS, SDValue RHS,
3308  DAGCombinerInfo &DCI) const {
3309  ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3310  if (!CmpRhs || !CmpRhs->isNullValue())
3311  return SDValue();
3312 
3313  SelectionDAG &DAG = DCI.DAG;
3314  ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
3315  SDValue CmpLHS = Cond.getOperand(0);
3316 
3317  unsigned Opc = isCttzOpc(RHS.getOpcode()) ? AMDGPUISD::FFBL_B32 :
3319 
3320  // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
3321  // select (setcc x, 0, eq), -1, (cttz_zero_undef x) -> ffbl_u32 x
3322  if (CCOpcode == ISD::SETEQ &&
3323  (isCtlzOpc(RHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3324  RHS.getOperand(0) == CmpLHS &&
3325  isNegativeOne(LHS)) {
3326  return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3327  }
3328 
3329  // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
3330  // select (setcc x, 0, ne), (cttz_zero_undef x), -1 -> ffbl_u32 x
3331  if (CCOpcode == ISD::SETNE &&
3332  (isCtlzOpc(LHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3333  LHS.getOperand(0) == CmpLHS &&
3334  isNegativeOne(RHS)) {
3335  return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3336  }
3337 
3338  return SDValue();
3339 }
3340 
3342  unsigned Op,
3343  const SDLoc &SL,
3344  SDValue Cond,
3345  SDValue N1,
3346  SDValue N2) {
3347  SelectionDAG &DAG = DCI.DAG;
3348  EVT VT = N1.getValueType();
3349 
3350  SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
3351  N1.getOperand(0), N2.getOperand(0));
3352  DCI.AddToWorklist(NewSelect.getNode());
3353  return DAG.getNode(Op, SL, VT, NewSelect);
3354 }
3355 
3356 // Pull a free FP operation out of a select so it may fold into uses.
3357 //
3358 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
3359 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
3360 //
3361 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
3362 // select c, (fabs x), +k -> fabs (select c, x, k)
3364  SDValue N) {
3365  SelectionDAG &DAG = DCI.DAG;
3366  SDValue Cond = N.getOperand(0);
3367  SDValue LHS = N.getOperand(1);
3368  SDValue RHS = N.getOperand(2);
3369 
3370  EVT VT = N.getValueType();
3371  if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
3372  (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
3373  return distributeOpThroughSelect(DCI, LHS.getOpcode(),
3374  SDLoc(N), Cond, LHS, RHS);
3375  }
3376 
3377  bool Inv = false;
3378  if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
3379  std::swap(LHS, RHS);
3380  Inv = true;
3381  }
3382 
3383  // TODO: Support vector constants.
3385  if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
3386  SDLoc SL(N);
3387  // If one side is an fneg/fabs and the other is a constant, we can push the
3388  // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
3389  SDValue NewLHS = LHS.getOperand(0);
3390  SDValue NewRHS = RHS;
3391 
3392  // Careful: if the neg can be folded up, don't try to pull it back down.
3393  bool ShouldFoldNeg = true;
3394 
3395  if (NewLHS.hasOneUse()) {
3396  unsigned Opc = NewLHS.getOpcode();
3397  if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
3398  ShouldFoldNeg = false;
3399  if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
3400  ShouldFoldNeg = false;
3401  }
3402 
3403  if (ShouldFoldNeg) {
3404  if (LHS.getOpcode() == ISD::FNEG)
3405  NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3406  else if (CRHS->isNegative())
3407  return SDValue();
3408 
3409  if (Inv)
3410  std::swap(NewLHS, NewRHS);
3411 
3412  SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
3413  Cond, NewLHS, NewRHS);
3414  DCI.AddToWorklist(NewSelect.getNode());
3415  return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
3416  }
3417  }
3418 
3419  return SDValue();
3420 }
3421 
3422 
3424  DAGCombinerInfo &DCI) const {
3425  if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
3426  return Folded;
3427 
3428  SDValue Cond = N->getOperand(0);
3429  if (Cond.getOpcode() != ISD::SETCC)
3430  return SDValue();
3431 
3432  EVT VT = N->getValueType(0);
3433  SDValue LHS = Cond.getOperand(0);
3434  SDValue RHS = Cond.getOperand(1);
3435  SDValue CC = Cond.getOperand(2);
3436 
3437  SDValue True = N->getOperand(1);
3438  SDValue False = N->getOperand(2);
3439 
3440  if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
3441  SelectionDAG &DAG = DCI.DAG;
3442  if ((DAG.isConstantValueOfAnyType(True) ||
3443  DAG.isConstantValueOfAnyType(True)) &&
3444  (!DAG.isConstantValueOfAnyType(False) &&
3445  !DAG.isConstantValueOfAnyType(False))) {
3446  // Swap cmp + select pair to move constant to false input.
3447  // This will allow using VOPC cndmasks more often.
3448  // select (setcc x, y), k, x -> select (setcc y, x) x, x
3449 
3450  SDLoc SL(N);
3451  ISD::CondCode NewCC = getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3452  LHS.getValueType().isInteger());
3453 
3454  SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
3455  return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
3456  }
3457 
3458  if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
3459  SDValue MinMax
3460  = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
3461  // Revisit this node so we can catch min3/max3/med3 patterns.
3462  //DCI.AddToWorklist(MinMax.getNode());
3463  return MinMax;
3464  }
3465  }
3466 
3467  // There's no reason to not do this if the condition has other uses.
3468  return performCtlz_CttzCombine(SDLoc(N), Cond, True, False, DCI);
3469 }
3470 
3472  if (const ConstantFPSDNode *C = isConstOrConstSplatFP(N))
3473  return C->isZero() && !C->isNegative();
3474  return false;
3475 }
3476 
3477 static unsigned inverseMinMax(unsigned Opc) {
3478  switch (Opc) {
3479  case ISD::FMAXNUM:
3480  return ISD::FMINNUM;
3481  case ISD::FMINNUM:
3482  return ISD::FMAXNUM;
3484  return AMDGPUISD::FMIN_LEGACY;
3486  return AMDGPUISD::FMAX_LEGACY;
3487  default:
3488  llvm_unreachable("invalid min/max opcode");
3489  }
3490 }
3491 
3493  DAGCombinerInfo &DCI) const {
3494  SelectionDAG &DAG = DCI.DAG;
3495  SDValue N0 = N->getOperand(0);
3496  EVT VT = N->getValueType(0);
3497 
3498  unsigned Opc = N0.getOpcode();
3499 
3500  // If the input has multiple uses and we can either fold the negate down, or
3501  // the other uses cannot, give up. This both prevents unprofitable
3502  // transformations and infinite loops: we won't repeatedly try to fold around
3503  // a negate that has no 'good' form.
3504  if (N0.hasOneUse()) {
3505  // This may be able to fold into the source, but at a code size cost. Don't
3506  // fold if the fold into the user is free.
3507  if (allUsesHaveSourceMods(N, 0))
3508  return SDValue();
3509  } else {
3510  if (fnegFoldsIntoOp(Opc) &&
3512  return SDValue();
3513  }
3514 
3515  SDLoc SL(N);
3516  switch (Opc) {
3517  case ISD::FADD: {
3518  if (!mayIgnoreSignedZero(N0))
3519  return SDValue();
3520 
3521  // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
3522  SDValue LHS = N0.getOperand(0);
3523  SDValue RHS = N0.getOperand(1);
3524 
3525  if (LHS.getOpcode() != ISD::FNEG)
3526  LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3527  else
3528  LHS = LHS.getOperand(0);
3529 
3530  if (RHS.getOpcode() != ISD::FNEG)
3531  RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3532  else
3533  RHS = RHS.getOperand(0);
3534 
3535  SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
3536  if (!N0.hasOneUse())
3537  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3538  return Res;
3539  }
3540  case ISD::FMUL:
3541  case AMDGPUISD::FMUL_LEGACY: {
3542  // (fneg (fmul x, y)) -> (fmul x, (fneg y))
3543  // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
3544  SDValue LHS = N0.getOperand(0);
3545  SDValue RHS = N0.getOperand(1);
3546 
3547  if (LHS.getOpcode() == ISD::FNEG)
3548  LHS = LHS.getOperand(0);
3549  else if (RHS.getOpcode() == ISD::FNEG)
3550  RHS = RHS.getOperand(0);
3551  else
3552  RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3553 
3554  SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
3555  if (!N0.hasOneUse())
3556  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3557  return Res;
3558  }
3559  case ISD::FMA:
3560  case ISD::FMAD: {
3561  if (!mayIgnoreSignedZero(N0))
3562  return SDValue();
3563 
3564  // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
3565  SDValue LHS = N0.getOperand(0);
3566  SDValue MHS = N0.getOperand(1);
3567  SDValue RHS = N0.getOperand(2);
3568 
3569  if (LHS.getOpcode() == ISD::FNEG)
3570  LHS = LHS.getOperand(0);
3571  else if (MHS.getOpcode() == ISD::FNEG)
3572  MHS = MHS.getOperand(0);
3573  else
3574  MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
3575 
3576  if (RHS.getOpcode() != ISD::FNEG)
3577  RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3578  else
3579  RHS = RHS.getOperand(0);
3580 
3581  SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
3582  if (!N0.hasOneUse())
3583  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3584  return Res;
3585  }
3586  case ISD::FMAXNUM:
3587  case ISD::FMINNUM:
3589  case AMDGPUISD::FMIN_LEGACY: {
3590  // fneg (fmaxnum x, y) -> fminnum (fneg x), (fneg y)
3591  // fneg (fminnum x, y) -> fmaxnum (fneg x), (fneg y)
3592  // fneg (fmax_legacy x, y) -> fmin_legacy (fneg x), (fneg y)
3593  // fneg (fmin_legacy x, y) -> fmax_legacy (fneg x), (fneg y)
3594 
3595  SDValue LHS = N0.getOperand(0);
3596  SDValue RHS = N0.getOperand(1);
3597 
3598  // 0 doesn't have a negated inline immediate.
3599  // TODO: Shouldn't fold 1/2pi either, and should be generalized to other
3600  // operations.
3601  if (isConstantFPZero(RHS))
3602  return SDValue();
3603 
3604  SDValue NegLHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3605  SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3606  unsigned Opposite = inverseMinMax(Opc);
3607 
3608  SDValue Res = DAG.getNode(Opposite, SL, VT, NegLHS, NegRHS, N0->getFlags());
3609  if (!N0.hasOneUse())
3610  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3611  return Res;
3612  }
3613  case ISD::FP_EXTEND:
3614  case ISD::FTRUNC:
3615  case ISD::FRINT:
3616  case ISD::FNEARBYINT: // XXX - Should fround be handled?
3617  case ISD::FSIN:
3618  case AMDGPUISD::RCP:
3619  case AMDGPUISD::RCP_LEGACY:
3620  case AMDGPUISD::SIN_HW: {
3621  SDValue CvtSrc = N0.getOperand(0);
3622  if (CvtSrc.getOpcode() == ISD::FNEG) {
3623  // (fneg (fp_extend (fneg x))) -> (fp_extend x)
3624  // (fneg (rcp (fneg x))) -> (rcp x)
3625  return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
3626  }
3627 
3628  if (!N0.hasOneUse())
3629  return SDValue();
3630 
3631  // (fneg (fp_extend x)) -> (fp_extend (fneg x))
3632  // (fneg (rcp x)) -> (rcp (fneg x))
3633  SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3634  return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
3635  }
3636  case ISD::FP_ROUND: {
3637  SDValue CvtSrc = N0.getOperand(0);
3638 
3639  if (CvtSrc.getOpcode() == ISD::FNEG) {
3640  // (fneg (fp_round (fneg x))) -> (fp_round x)
3641  return DAG.getNode(ISD::FP_ROUND, SL, VT,
3642  CvtSrc.getOperand(0), N0.getOperand(1));
3643  }
3644 
3645  if (!N0.hasOneUse())
3646  return SDValue();
3647 
3648  // (fneg (fp_round x)) -> (fp_round (fneg x))
3649  SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3650  return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
3651  }
3652  case ISD::FP16_TO_FP: {
3653  // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
3654  // f16, but legalization of f16 fneg ends up pulling it out of the source.
3655  // Put the fneg back as a legal source operation that can be matched later.
3656  SDLoc SL(N);
3657 
3658  SDValue Src = N0.getOperand(0);
3659  EVT SrcVT = Src.getValueType();
3660 
3661  // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
3662  SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
3663  DAG.getConstant(0x8000, SL, SrcVT));
3664  return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
3665  }
3666  default:
3667  return SDValue();
3668  }
3669 }
3670 
3672  DAGCombinerInfo &DCI) const {
3673  SelectionDAG &DAG = DCI.DAG;
3674  SDValue N0 = N->getOperand(0);
3675 
3676  if (!N0.hasOneUse())
3677  return SDValue();
3678 
3679  switch (N0.getOpcode()) {
3680  case ISD::FP16_TO_FP: {
3681  assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3682  SDLoc SL(N);
3683  SDValue Src = N0.getOperand(0);
3684  EVT SrcVT = Src.getValueType();
3685 
3686  // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3687  SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3688  DAG.getConstant(0x7fff, SL, SrcVT));
3689  return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3690  }
3691  default:
3692  return SDValue();
3693  }
3694 }
3695 
3697  DAGCombinerInfo &DCI) const {
3698  SelectionDAG &DAG = DCI.DAG;
3699  SDLoc DL(N);
3700 
3701  switch(N->getOpcode()) {
3702  default:
3703  break;
3704  case ISD::BITCAST: {
3705  EVT DestVT = N->getValueType(0);
3706 
3707  // Push casts through vector builds. This helps avoid emitting a large
3708  // number of copies when materializing floating point vector constants.
3709  //
3710  // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3711  // vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3712  if (DestVT.isVector()) {
3713  SDValue Src = N->getOperand(0);
3714  if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3715  EVT SrcVT = Src.getValueType();
3716  unsigned NElts = DestVT.getVectorNumElements();
3717 
3718  if (SrcVT.getVectorNumElements() == NElts) {
3719  EVT DestEltVT = DestVT.getVectorElementType();
3720 
3721  SmallVector<SDValue, 8> CastedElts;
3722  SDLoc SL(N);
3723  for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3724  SDValue Elt = Src.getOperand(I);
3725  CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3726  }
3727 
3728  return DAG.getBuildVector(DestVT, SL, CastedElts);
3729  }
3730  }
3731  }
3732 
3733  if (DestVT.getSizeInBits() != 64 && !DestVT.isVector())
3734  break;
3735 
3736  // Fold bitcasts of constants.
3737  //
3738  // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3739  // TODO: Generalize and move to DAGCombiner
3740  SDValue Src = N->getOperand(0);
3741  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3742  if (Src.getValueType() == MVT::i64) {
3743  SDLoc SL(N);
3744  uint64_t CVal = C->getZExtValue();
3745  return DAG.getNode(ISD::BUILD_VECTOR, SL, DestVT,
3746  DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3747  DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3748  }
3749  }
3750 
3751  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3752  const APInt &Val = C->getValueAPF().bitcastToAPInt();
3753  SDLoc SL(N);
3754  uint64_t CVal = Val.getZExtValue();
3756  DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3757  DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3758 
3759  return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3760  }
3761 
3762  break;
3763  }
3764  case ISD::SHL: {
3766  break;
3767 
3768  return performShlCombine(N, DCI);
3769  }
3770  case ISD::SRL: {
3772  break;
3773 
3774  return performSrlCombine(N, DCI);
3775  }
3776  case ISD::SRA: {
3778  break;
3779 
3780  return performSraCombine(N, DCI);
3781  }
3782  case ISD::TRUNCATE:
3783  return performTruncateCombine(N, DCI);
3784  case ISD::MUL:
3785  return performMulCombine(N, DCI);
3786  case ISD::MULHS:
3787  return performMulhsCombine(N, DCI);
3788  case ISD::MULHU:
3789  return performMulhuCombine(N, DCI);
3790  case AMDGPUISD::MUL_I24:
3791  case AMDGPUISD::MUL_U24:
3792  case AMDGPUISD::MULHI_I24:
3793  case AMDGPUISD::MULHI_U24: {
3794  // If the first call to simplify is successfull, then N may end up being
3795  // deleted, so we shouldn't call simplifyI24 again.
3796  simplifyI24(N, 0, DCI) || simplifyI24(N, 1, DCI);
3797  return SDValue();
3798  }
3801  return performMulLoHi24Combine(N, DCI);
3802  case ISD::SELECT:
3803  return performSelectCombine(N, DCI);
3804  case ISD::FNEG:
3805  return performFNegCombine(N, DCI);
3806  case ISD::FABS:
3807  return performFAbsCombine(N, DCI);
3808  case AMDGPUISD::BFE_I32:
3809  case AMDGPUISD::BFE_U32: {
3810  assert(!N->getValueType(0).isVector() &&
3811  "Vector handling of BFE not implemented");
3813  if (!Width)
3814  break;
3815 
3816  uint32_t WidthVal = Width->getZExtValue() & 0x1f;
3817  if (WidthVal == 0)
3818  return DAG.getConstant(0, DL, MVT::i32);
3819 
3821  if (!Offset)
3822  break;
3823 
3824  SDValue BitsFrom = N->getOperand(0);
3825  uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
3826 
3827  bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
3828 
3829  if (OffsetVal == 0) {
3830  // This is already sign / zero extended, so try to fold away extra BFEs.
3831  unsigned SignBits = Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
3832 
3833  unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
3834  if (OpSignBits >= SignBits)
3835  return BitsFrom;
3836 
3837  EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
3838  if (Signed) {
3839  // This is a sign_extend_inreg. Replace it to take advantage of existing
3840  // DAG Combines. If not eliminated, we will match back to BFE during
3841  // selection.
3842 
3843  // TODO: The sext_inreg of extended types ends, although we can could
3844  // handle them in a single BFE.
3845  return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
3846  DAG.getValueType(SmallVT));
3847  }
3848 
3849  return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
3850  }
3851 
3852  if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
3853  if (Signed) {
3854  return constantFoldBFE<int32_t>(DAG,
3855  CVal->getSExtValue(),
3856  OffsetVal,
3857  WidthVal,
3858  DL);
3859  }
3860 
3861  return constantFoldBFE<uint32_t>(DAG,
3862  CVal->getZExtValue(),
3863  OffsetVal,
3864  WidthVal,
3865  DL);
3866  }
3867 
3868  if ((OffsetVal + WidthVal) >= 32 &&
3869  !(Subtarget->hasSDWA() && OffsetVal == 16 && WidthVal == 16)) {
3870  SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
3871  return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
3872  BitsFrom, ShiftVal);
3873  }
3874 
3875  if (BitsFrom.hasOneUse()) {
3876  APInt Demanded = APInt::getBitsSet(32,
3877  OffsetVal,
3878  OffsetVal + WidthVal);
3879 
3880  KnownBits Known;
3882  !DCI.isBeforeLegalizeOps());
3883  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3884  if (TLI.ShrinkDemandedConstant(BitsFrom, Demanded, TLO) ||
3885  TLI.SimplifyDemandedBits(BitsFrom, Demanded, Known, TLO)) {
3886  DCI.CommitTargetLoweringOpt(TLO);
3887  }
3888  }
3889 
3890  break;
3891  }
3892  case ISD::LOAD:
3893  return performLoadCombine(N, DCI);
3894  case ISD::STORE:
3895  return performStoreCombine(N, DCI);
3896  case AMDGPUISD::RCP: {
3897  if (const auto *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
3898  // XXX - Should this flush denormals?
3899  const APFloat &Val = CFP->getValueAPF();
3900  APFloat One(Val.getSemantics(), "1.0");
3901  return DAG.getConstantFP(One / Val, SDLoc(N), N->getValueType(0));
3902  }
3903 
3904  break;
3905  }
3906  case ISD::AssertZext:
3907  case ISD::AssertSext:
3908  return performAssertSZExtCombine(N, DCI);
3909  }
3910  return SDValue();
3911 }
3912 
3913 //===----------------------------------------------------------------------===//
3914 // Helper functions
3915 //===----------------------------------------------------------------------===//
3916 
3918  const TargetRegisterClass *RC,
3919  unsigned Reg, EVT VT,
3920  const SDLoc &SL,
3921  bool RawReg) const {
3922  MachineFunction &MF = DAG.getMachineFunction();
3924  unsigned VReg;
3925 
3926  if (!MRI.isLiveIn(Reg)) {
3927  VReg = MRI.createVirtualRegister(RC);
3928  MRI.addLiveIn(Reg, VReg);
3929  } else {
3930  VReg = MRI.getLiveInVirtReg(Reg);
3931  }
3932 
3933  if (RawReg)
3934  return DAG.getRegister(VReg, VT);
3935 
3936  return DAG.getCopyFromReg(DAG.getEntryNode(), SL, VReg, VT);
3937 }
3938 
3940  EVT VT,
3941  const SDLoc &SL,
3942  int64_t Offset) const {
3943  MachineFunction &MF = DAG.getMachineFunction();
3944  MachineFrameInfo &MFI = MF.getFrameInfo();
3945 
3946  int FI = MFI.CreateFixedObject(VT.getStoreSize(), Offset, true);
3947  auto SrcPtrInfo = MachinePointerInfo::getStack(MF, Offset);
3948  SDValue Ptr = DAG.getFrameIndex(FI, MVT::i32);
3949 
3950  return DAG.getLoad(VT, SL, DAG.getEntryNode(), Ptr, SrcPtrInfo, 4,
3953 }
3954 
3956  const SDLoc &SL,
3957  SDValue Chain,
3958  SDValue StackPtr,
3959  SDValue ArgVal,
3960  int64_t Offset) const {
3961  MachineFunction &MF = DAG.getMachineFunction();
3962  MachinePointerInfo DstInfo = MachinePointerInfo::getStack(MF, Offset);
3963 
3964  SDValue Ptr = DAG.getObjectPtrOffset(SL, StackPtr, Offset);
3965  SDValue Store = DAG.getStore(Chain, SL, ArgVal, Ptr, DstInfo, 4,
3967  return Store;
3968 }
3969 
3971  const TargetRegisterClass *RC,
3972  EVT VT, const SDLoc &SL,
3973  const ArgDescriptor &Arg) const {
3974  assert(Arg && "Attempting to load missing argument");
3975 
3976  if (Arg.isRegister())
3977  return CreateLiveInRegister(DAG, RC, Arg.getRegister(), VT, SL);
3978  return loadStackInputValue(DAG, VT, SL, Arg.getStackOffset());
3979 }
3980 
3982  const AMDGPUMachineFunction *MFI, const ImplicitParameter Param) const {
3983  unsigned Alignment = Subtarget->getAlignmentForImplicitArgPtr();
3984  uint64_t ArgOffset = alignTo(MFI->getABIArgOffset(), Alignment);
3985  switch (Param) {
3986  case GRID_DIM:
3987  return ArgOffset;
3988  case GRID_OFFSET:
3989  return ArgOffset + 4;
3990  }
3991  llvm_unreachable("unexpected implicit parameter type");
3992 }
3993 
3994 #define NODE_NAME_CASE(node) case AMDGPUISD::node: return #node;
3995 
3996 const char* AMDGPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
3997  switch ((AMDGPUISD::NodeType)Opcode) {
3998  case AMDGPUISD::FIRST_NUMBER: break;
3999  // AMDIL DAG nodes
4002 
4003  // AMDGPU DAG nodes