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