LLVM  6.0.0svn
AArch64ISelLowering.cpp
Go to the documentation of this file.
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64ISelLowering.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/Use.h"
64 #include "llvm/IR/Value.h"
65 #include "llvm/MC/MCRegisterInfo.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/KnownBits.h"
77 #include <algorithm>
78 #include <bitset>
79 #include <cassert>
80 #include <cctype>
81 #include <cstdint>
82 #include <cstdlib>
83 #include <iterator>
84 #include <limits>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "aarch64-lower"
92 
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
96 
97 static cl::opt<bool>
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99  cl::desc("Allow AArch64 SLI/SRI formation"),
100  cl::init(false));
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
106  "aarch64-elf-ldtls-generation", cl::Hidden,
107  cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108  cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112  cl::desc("Enable AArch64 logical imm instruction "
113  "optimization"),
114  cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
120  const AArch64Subtarget &STI)
121  : TargetLowering(TM), Subtarget(&STI) {
122  // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123  // we have to make something up. Arbitrarily, choose ZeroOrOne.
125  // When comparing vectors the result sets the different elements in the
126  // vector to all-one or all-zero.
128 
129  // Set up the register classes.
130  addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131  addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132 
133  if (Subtarget->hasFPARMv8()) {
134  addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135  addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136  addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137  addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138  }
139 
140  if (Subtarget->hasNEON()) {
141  addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142  addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143  // Someone set us up the NEON.
144  addDRTypeForNEON(MVT::v2f32);
145  addDRTypeForNEON(MVT::v8i8);
146  addDRTypeForNEON(MVT::v4i16);
147  addDRTypeForNEON(MVT::v2i32);
148  addDRTypeForNEON(MVT::v1i64);
149  addDRTypeForNEON(MVT::v1f64);
150  addDRTypeForNEON(MVT::v4f16);
151 
152  addQRTypeForNEON(MVT::v4f32);
153  addQRTypeForNEON(MVT::v2f64);
154  addQRTypeForNEON(MVT::v16i8);
155  addQRTypeForNEON(MVT::v8i16);
156  addQRTypeForNEON(MVT::v4i32);
157  addQRTypeForNEON(MVT::v2i64);
158  addQRTypeForNEON(MVT::v8f16);
159  }
160 
161  // Compute derived properties from the register classes
163 
164  // Provide all sorts of operation actions
192 
196 
200 
201  // Custom lowering hooks are needed for XOR
202  // to fold it into CSINC/CSINV.
205 
206  // Virtually no operation on f128 is legal, but LLVM can't expand them when
207  // there's a valid register class, so we need custom operations in most cases.
229 
230  // Lowering for many of the conversions is actually specified by the non-f128
231  // type. The LowerXXX function will be trivial when f128 isn't involved.
246 
247  // Variable arguments.
252 
253  // Variable-sized objects.
257 
258  // Constant pool entries
260 
261  // BlockAddress
263 
264  // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
273 
274  // AArch64 lacks both left-rotate and popcount instructions.
277  for (MVT VT : MVT::vector_valuetypes()) {
280  }
281 
282  // AArch64 doesn't have {U|S}MUL_LOHI.
285 
288 
291  for (MVT VT : MVT::vector_valuetypes()) {
294  }
301 
302  // Custom lower Add/Sub/Mul with overflow.
315 
324  if (Subtarget->hasFullFP16())
326  else
328 
360 
361  if (!Subtarget->hasFullFP16()) {
384 
385  // promote v4f16 to v4f32 when that is known to be safe.
398 
414 
435  }
436 
437  // AArch64 has implementations of a lot of rounding-like FP operations.
438  for (MVT Ty : {MVT::f32, MVT::f64}) {
449  }
450 
451  if (Subtarget->hasFullFP16()) {
462  }
463 
465 
467 
468  // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
469  // This requires the Performance Monitors extension.
470  if (Subtarget->hasPerfMon())
472 
473  if (Subtarget->isTargetMachO()) {
474  // For iOS, we don't want to the normal expansion of a libcall to
475  // sincos. We want to issue a libcall to __sincos_stret to avoid memory
476  // traffic.
479  } else {
482  }
483 
484  // Make floating-point constants legal for the large code model, so they don't
485  // become loads from the constant pool.
486  if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
489  }
490 
491  // AArch64 does not have floating-point extending loads, i1 sign-extending
492  // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
493  for (MVT VT : MVT::fp_valuetypes()) {
498  }
499  for (MVT VT : MVT::integer_valuetypes())
501 
509 
512 
513  // Indexed loads and stores are supported.
514  for (unsigned im = (unsigned)ISD::PRE_INC;
530  }
531 
532  // Trap.
534 
535  // We combine OR nodes for bitfield operations.
537 
538  // Vector add and sub nodes may conceal a high-half opportunity.
539  // Also, try to fold ADD into CSINC/CSINV..
546 
550 
552 
559  if (Subtarget->supportsAddressTopByteIgnored())
561 
563 
566 
570 
574 
576 
578 
579  EnableExtLdPromotion = true;
580 
581  // Set required alignment.
583  // Set preferred alignments.
586 
587  // Only change the limit for entries in a jump table if specified by
588  // the subtarget, but not at the command line.
589  unsigned MaxJT = STI.getMaximumJumpTableSize();
590  if (MaxJT && getMaximumJumpTableSize() == 0)
592 
593  setHasExtractBitsInsn(true);
594 
596 
597  if (Subtarget->hasNEON()) {
598  // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
599  // silliness like this:
625 
631 
633 
634  // AArch64 doesn't have a direct vector ->f32 conversion instructions for
635  // elements smaller than i32, so promote the input to i32 first.
640  // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
641  // -> v8f16 conversions.
646  // Similarly, there is no direct i32 -> f64 vector conversion instruction.
651  // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
652  // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
655 
658 
667 
668  // AArch64 doesn't have MUL.2d:
670  // Custom handling for some quad-vector types to detect MULL.
674 
675  // Vector reductions
676  for (MVT VT : MVT::integer_valuetypes()) {
682  }
683  for (MVT VT : MVT::fp_valuetypes()) {
686  }
687 
690  // Likewise, narrowing and extending vector loads/stores aren't handled
691  // directly.
692  for (MVT VT : MVT::vector_valuetypes()) {
694 
699 
701 
702  for (MVT InnerVT : MVT::vector_valuetypes()) {
703  setTruncStoreAction(VT, InnerVT, Expand);
704  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
705  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
706  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
707  }
708  }
709 
710  // AArch64 has implementations of a lot of rounding-like FP operations.
711  for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
718  }
719  }
720 
722 }
723 
724 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
725  if (VT == MVT::v2f32 || VT == MVT::v4f16) {
728 
731  } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
734 
737  }
738 
739  // Mark vector float intrinsics as expand.
740  if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
749 
750  // But we do support custom-lowering for FCOPYSIGN.
752  }
753 
766 
770  for (MVT InnerVT : MVT::all_valuetypes())
771  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
772 
773  // CNT supports only B element sizes.
774  if (VT != MVT::v8i8 && VT != MVT::v16i8)
776 
782 
785 
786  if (!VT.isFloatingPoint())
788 
789  // [SU][MIN|MAX] are available for all NEON types apart from i64.
790  if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
791  for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
792  setOperationAction(Opcode, VT, Legal);
793 
794  // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
795  if (VT.isFloatingPoint() &&
796  (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
797  for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
799  setOperationAction(Opcode, VT, Legal);
800 
801  if (Subtarget->isLittleEndian()) {
802  for (unsigned im = (unsigned)ISD::PRE_INC;
806  }
807  }
808 }
809 
810 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
811  addRegisterClass(VT, &AArch64::FPR64RegClass);
812  addTypeForNEON(VT, MVT::v2i32);
813 }
814 
815 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
816  addRegisterClass(VT, &AArch64::FPR128RegClass);
817  addTypeForNEON(VT, MVT::v4i32);
818 }
819 
821  EVT VT) const {
822  if (!VT.isVector())
823  return MVT::i32;
825 }
826 
827 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
828  const APInt &Demanded,
830  unsigned NewOpc) {
831  uint64_t OldImm = Imm, NewImm, Enc;
832  uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
833 
834  // Return if the immediate is already all zeros, all ones, a bimm32 or a
835  // bimm64.
836  if (Imm == 0 || Imm == Mask ||
837  AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
838  return false;
839 
840  unsigned EltSize = Size;
841  uint64_t DemandedBits = Demanded.getZExtValue();
842 
843  // Clear bits that are not demanded.
844  Imm &= DemandedBits;
845 
846  while (true) {
847  // The goal here is to set the non-demanded bits in a way that minimizes
848  // the number of switching between 0 and 1. In order to achieve this goal,
849  // we set the non-demanded bits to the value of the preceding demanded bits.
850  // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
851  // non-demanded bit), we copy bit0 (1) to the least significant 'x',
852  // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
853  // The final result is 0b11000011.
854  uint64_t NonDemandedBits = ~DemandedBits;
855  uint64_t InvertedImm = ~Imm & DemandedBits;
856  uint64_t RotatedImm =
857  ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
858  NonDemandedBits;
859  uint64_t Sum = RotatedImm + NonDemandedBits;
860  bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
861  uint64_t Ones = (Sum + Carry) & NonDemandedBits;
862  NewImm = (Imm | Ones) & Mask;
863 
864  // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
865  // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
866  // we halve the element size and continue the search.
867  if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
868  break;
869 
870  // We cannot shrink the element size any further if it is 2-bits.
871  if (EltSize == 2)
872  return false;
873 
874  EltSize /= 2;
875  Mask >>= EltSize;
876  uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
877 
878  // Return if there is mismatch in any of the demanded bits of Imm and Hi.
879  if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
880  return false;
881 
882  // Merge the upper and lower halves of Imm and DemandedBits.
883  Imm |= Hi;
884  DemandedBits |= DemandedBitsHi;
885  }
886 
887  ++NumOptimizedImms;
888 
889  // Replicate the element across the register width.
890  while (EltSize < Size) {
891  NewImm |= NewImm << EltSize;
892  EltSize *= 2;
893  }
894 
895  (void)OldImm;
896  assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
897  "demanded bits should never be altered");
898  assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
899 
900  // Create the new constant immediate node.
901  EVT VT = Op.getValueType();
902  SDLoc DL(Op);
903  SDValue New;
904 
905  // If the new constant immediate is all-zeros or all-ones, let the target
906  // independent DAG combine optimize this node.
907  if (NewImm == 0 || NewImm == OrigMask) {
908  New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
909  TLO.DAG.getConstant(NewImm, DL, VT));
910  // Otherwise, create a machine node so that target independent DAG combine
911  // doesn't undo this optimization.
912  } else {
913  Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
914  SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
915  New = SDValue(
916  TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
917  }
918 
919  return TLO.CombineTo(Op, New);
920 }
921 
923  SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
924  // Delay this optimization to as late as possible.
925  if (!TLO.LegalOps)
926  return false;
927 
929  return false;
930 
931  EVT VT = Op.getValueType();
932  if (VT.isVector())
933  return false;
934 
935  unsigned Size = VT.getSizeInBits();
936  assert((Size == 32 || Size == 64) &&
937  "i32 or i64 is expected after legalization.");
938 
939  // Exit early if we demand all bits.
940  if (Demanded.countPopulation() == Size)
941  return false;
942 
943  unsigned NewOpc;
944  switch (Op.getOpcode()) {
945  default:
946  return false;
947  case ISD::AND:
948  NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
949  break;
950  case ISD::OR:
951  NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
952  break;
953  case ISD::XOR:
954  NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
955  break;
956  }
958  if (!C)
959  return false;
960  uint64_t Imm = C->getZExtValue();
961  return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
962 }
963 
964 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
965 /// Mask are known to be either zero or one and return them Known.
967  const SDValue Op, KnownBits &Known,
968  const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
969  switch (Op.getOpcode()) {
970  default:
971  break;
972  case AArch64ISD::CSEL: {
973  KnownBits Known2;
974  DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
975  DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
976  Known.Zero &= Known2.Zero;
977  Known.One &= Known2.One;
978  break;
979  }
980  case ISD::INTRINSIC_W_CHAIN: {
981  ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
982  Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
983  switch (IntID) {
984  default: return;
985  case Intrinsic::aarch64_ldaxr:
986  case Intrinsic::aarch64_ldxr: {
987  unsigned BitWidth = Known.getBitWidth();
988  EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
989  unsigned MemBits = VT.getScalarSizeInBits();
990  Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
991  return;
992  }
993  }
994  break;
995  }
997  case ISD::INTRINSIC_VOID: {
998  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
999  switch (IntNo) {
1000  default:
1001  break;
1002  case Intrinsic::aarch64_neon_umaxv:
1003  case Intrinsic::aarch64_neon_uminv: {
1004  // Figure out the datatype of the vector operand. The UMINV instruction
1005  // will zero extend the result, so we can mark as known zero all the
1006  // bits larger than the element datatype. 32-bit or larget doesn't need
1007  // this as those are legal types and will be handled by isel directly.
1008  MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1009  unsigned BitWidth = Known.getBitWidth();
1010  if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1011  assert(BitWidth >= 8 && "Unexpected width!");
1012  APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1013  Known.Zero |= Mask;
1014  } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1015  assert(BitWidth >= 16 && "Unexpected width!");
1016  APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1017  Known.Zero |= Mask;
1018  }
1019  break;
1020  } break;
1021  }
1022  }
1023  }
1024 }
1025 
1027  EVT) const {
1028  return MVT::i64;
1029 }
1030 
1032  unsigned AddrSpace,
1033  unsigned Align,
1034  bool *Fast) const {
1035  if (Subtarget->requiresStrictAlign())
1036  return false;
1037 
1038  if (Fast) {
1039  // Some CPUs are fine with unaligned stores except for 128-bit ones.
1040  *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1041  // See comments in performSTORECombine() for more details about
1042  // these conditions.
1043 
1044  // Code that uses clang vector extensions can mark that it
1045  // wants unaligned accesses to be treated as fast by
1046  // underspecifying alignment to be 1 or 2.
1047  Align <= 2 ||
1048 
1049  // Disregard v2i64. Memcpy lowering produces those and splitting
1050  // them regresses performance on micro-benchmarks and olden/bh.
1051  VT == MVT::v2i64;
1052  }
1053  return true;
1054 }
1055 
1056 FastISel *
1058  const TargetLibraryInfo *libInfo) const {
1059  return AArch64::createFastISel(funcInfo, libInfo);
1060 }
1061 
1062 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1063  switch ((AArch64ISD::NodeType)Opcode) {
1064  case AArch64ISD::FIRST_NUMBER: break;
1065  case AArch64ISD::CALL: return "AArch64ISD::CALL";
1066  case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1067  case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1068  case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1069  case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1070  case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1071  case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1072  case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1073  case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1074  case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1075  case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1076  case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1077  case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1078  case AArch64ISD::ADC: return "AArch64ISD::ADC";
1079  case AArch64ISD::SBC: return "AArch64ISD::SBC";
1080  case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1081  case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1082  case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1083  case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1084  case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1085  case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1086  case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1087  case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1088  case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1089  case AArch64ISD::DUP: return "AArch64ISD::DUP";
1090  case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1091  case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1092  case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1093  case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1094  case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1095  case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1096  case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1097  case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1098  case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1099  case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1100  case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1101  case AArch64ISD::BICi: return "AArch64ISD::BICi";
1102  case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1103  case AArch64ISD::BSL: return "AArch64ISD::BSL";
1104  case AArch64ISD::NEG: return "AArch64ISD::NEG";
1105  case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1106  case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1107  case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1108  case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1109  case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1110  case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1111  case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1112  case AArch64ISD::REV16: return "AArch64ISD::REV16";
1113  case AArch64ISD::REV32: return "AArch64ISD::REV32";
1114  case AArch64ISD::REV64: return "AArch64ISD::REV64";
1115  case AArch64ISD::EXT: return "AArch64ISD::EXT";
1116  case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1117  case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1118  case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1119  case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1120  case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1121  case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1122  case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1123  case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1124  case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1125  case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1126  case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1127  case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1128  case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1129  case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1130  case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1131  case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1132  case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1133  case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1134  case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1135  case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1136  case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1137  case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1138  case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1139  case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1140  case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1141  case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1142  case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1143  case AArch64ISD::NOT: return "AArch64ISD::NOT";
1144  case AArch64ISD::BIT: return "AArch64ISD::BIT";
1145  case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1146  case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1147  case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1148  case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1149  case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1150  case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1151  case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1152  case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1153  case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1154  case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1155  case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1156  case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1157  case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1158  case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1159  case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1160  case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1161  case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1162  case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1163  case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1164  case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1165  case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1166  case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1167  case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1168  case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1169  case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1170  case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1171  case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1172  case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1173  case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1174  case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1175  case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1176  case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1177  case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1178  case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1179  case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1180  case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1181  case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1182  case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1183  case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1184  case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1185  case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1186  case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1187  case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1188  case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1189  }
1190  return nullptr;
1191 }
1192 
1195  MachineBasicBlock *MBB) const {
1196  // We materialise the F128CSEL pseudo-instruction as some control flow and a
1197  // phi node:
1198 
1199  // OrigBB:
1200  // [... previous instrs leading to comparison ...]
1201  // b.ne TrueBB
1202  // b EndBB
1203  // TrueBB:
1204  // ; Fallthrough
1205  // EndBB:
1206  // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1207 
1208  MachineFunction *MF = MBB->getParent();
1209  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1210  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1211  DebugLoc DL = MI.getDebugLoc();
1212  MachineFunction::iterator It = ++MBB->getIterator();
1213 
1214  unsigned DestReg = MI.getOperand(0).getReg();
1215  unsigned IfTrueReg = MI.getOperand(1).getReg();
1216  unsigned IfFalseReg = MI.getOperand(2).getReg();
1217  unsigned CondCode = MI.getOperand(3).getImm();
1218  bool NZCVKilled = MI.getOperand(4).isKill();
1219 
1220  MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1221  MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1222  MF->insert(It, TrueBB);
1223  MF->insert(It, EndBB);
1224 
1225  // Transfer rest of current basic-block to EndBB
1226  EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1227  MBB->end());
1228  EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1229 
1230  BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1231  BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1232  MBB->addSuccessor(TrueBB);
1233  MBB->addSuccessor(EndBB);
1234 
1235  // TrueBB falls through to the end.
1236  TrueBB->addSuccessor(EndBB);
1237 
1238  if (!NZCVKilled) {
1239  TrueBB->addLiveIn(AArch64::NZCV);
1240  EndBB->addLiveIn(AArch64::NZCV);
1241  }
1242 
1243  BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1244  .addReg(IfTrueReg)
1245  .addMBB(TrueBB)
1246  .addReg(IfFalseReg)
1247  .addMBB(MBB);
1248 
1249  MI.eraseFromParent();
1250  return EndBB;
1251 }
1252 
1254  MachineInstr &MI, MachineBasicBlock *BB) const {
1255  switch (MI.getOpcode()) {
1256  default:
1257 #ifndef NDEBUG
1258  MI.dump();
1259 #endif
1260  llvm_unreachable("Unexpected instruction for custom inserter!");
1261 
1262  case AArch64::F128CSEL:
1263  return EmitF128CSEL(MI, BB);
1264 
1265  case TargetOpcode::STACKMAP:
1266  case TargetOpcode::PATCHPOINT:
1267  return emitPatchPoint(MI, BB);
1268  }
1269 }
1270 
1271 //===----------------------------------------------------------------------===//
1272 // AArch64 Lowering private implementation.
1273 //===----------------------------------------------------------------------===//
1274 
1275 //===----------------------------------------------------------------------===//
1276 // Lowering Code
1277 //===----------------------------------------------------------------------===//
1278 
1279 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1280 /// CC
1282  switch (CC) {
1283  default:
1284  llvm_unreachable("Unknown condition code!");
1285  case ISD::SETNE:
1286  return AArch64CC::NE;
1287  case ISD::SETEQ:
1288  return AArch64CC::EQ;
1289  case ISD::SETGT:
1290  return AArch64CC::GT;
1291  case ISD::SETGE:
1292  return AArch64CC::GE;
1293  case ISD::SETLT:
1294  return AArch64CC::LT;
1295  case ISD::SETLE:
1296  return AArch64CC::LE;
1297  case ISD::SETUGT:
1298  return AArch64CC::HI;
1299  case ISD::SETUGE:
1300  return AArch64CC::HS;
1301  case ISD::SETULT:
1302  return AArch64CC::LO;
1303  case ISD::SETULE:
1304  return AArch64CC::LS;
1305  }
1306 }
1307 
1308 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1311  AArch64CC::CondCode &CondCode2) {
1312  CondCode2 = AArch64CC::AL;
1313  switch (CC) {
1314  default:
1315  llvm_unreachable("Unknown FP condition!");
1316  case ISD::SETEQ:
1317  case ISD::SETOEQ:
1318  CondCode = AArch64CC::EQ;
1319  break;
1320  case ISD::SETGT:
1321  case ISD::SETOGT:
1322  CondCode = AArch64CC::GT;
1323  break;
1324  case ISD::SETGE:
1325  case ISD::SETOGE:
1326  CondCode = AArch64CC::GE;
1327  break;
1328  case ISD::SETOLT:
1329  CondCode = AArch64CC::MI;
1330  break;
1331  case ISD::SETOLE:
1332  CondCode = AArch64CC::LS;
1333  break;
1334  case ISD::SETONE:
1335  CondCode = AArch64CC::MI;
1336  CondCode2 = AArch64CC::GT;
1337  break;
1338  case ISD::SETO:
1339  CondCode = AArch64CC::VC;
1340  break;
1341  case ISD::SETUO:
1342  CondCode = AArch64CC::VS;
1343  break;
1344  case ISD::SETUEQ:
1345  CondCode = AArch64CC::EQ;
1346  CondCode2 = AArch64CC::VS;
1347  break;
1348  case ISD::SETUGT:
1349  CondCode = AArch64CC::HI;
1350  break;
1351  case ISD::SETUGE:
1352  CondCode = AArch64CC::PL;
1353  break;
1354  case ISD::SETLT:
1355  case ISD::SETULT:
1356  CondCode = AArch64CC::LT;
1357  break;
1358  case ISD::SETLE:
1359  case ISD::SETULE:
1360  CondCode = AArch64CC::LE;
1361  break;
1362  case ISD::SETNE:
1363  case ISD::SETUNE:
1364  CondCode = AArch64CC::NE;
1365  break;
1366  }
1367 }
1368 
1369 /// Convert a DAG fp condition code to an AArch64 CC.
1370 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1371 /// should be AND'ed instead of OR'ed.
1374  AArch64CC::CondCode &CondCode2) {
1375  CondCode2 = AArch64CC::AL;
1376  switch (CC) {
1377  default:
1378  changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1379  assert(CondCode2 == AArch64CC::AL);
1380  break;
1381  case ISD::SETONE:
1382  // (a one b)
1383  // == ((a olt b) || (a ogt b))
1384  // == ((a ord b) && (a une b))
1385  CondCode = AArch64CC::VC;
1386  CondCode2 = AArch64CC::NE;
1387  break;
1388  case ISD::SETUEQ:
1389  // (a ueq b)
1390  // == ((a uno b) || (a oeq b))
1391  // == ((a ule b) && (a uge b))
1392  CondCode = AArch64CC::PL;
1393  CondCode2 = AArch64CC::LE;
1394  break;
1395  }
1396 }
1397 
1398 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1399 /// CC usable with the vector instructions. Fewer operations are available
1400 /// without a real NZCV register, so we have to use less efficient combinations
1401 /// to get the same effect.
1404  AArch64CC::CondCode &CondCode2,
1405  bool &Invert) {
1406  Invert = false;
1407  switch (CC) {
1408  default:
1409  // Mostly the scalar mappings work fine.
1410  changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1411  break;
1412  case ISD::SETUO:
1413  Invert = true;
1415  case ISD::SETO:
1416  CondCode = AArch64CC::MI;
1417  CondCode2 = AArch64CC::GE;
1418  break;
1419  case ISD::SETUEQ:
1420  case ISD::SETULT:
1421  case ISD::SETULE:
1422  case ISD::SETUGT:
1423  case ISD::SETUGE:
1424  // All of the compare-mask comparisons are ordered, but we can switch
1425  // between the two by a double inversion. E.g. ULE == !OGT.
1426  Invert = true;
1427  changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1428  break;
1429  }
1430 }
1431 
1432 static bool isLegalArithImmed(uint64_t C) {
1433  // Matches AArch64DAGToDAGISel::SelectArithImmed().
1434  bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1435  DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1436  return IsLegal;
1437 }
1438 
1440  const SDLoc &dl, SelectionDAG &DAG) {
1441  EVT VT = LHS.getValueType();
1442  const bool FullFP16 =
1443  static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1444 
1445  if (VT.isFloatingPoint()) {
1446  assert(VT != MVT::f128);
1447  if (VT == MVT::f16 && !FullFP16) {
1448  LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1449  RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1450  VT = MVT::f32;
1451  }
1452  return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1453  }
1454 
1455  // The CMP instruction is just an alias for SUBS, and representing it as
1456  // SUBS means that it's possible to get CSE with subtract operations.
1457  // A later phase can perform the optimization of setting the destination
1458  // register to WZR/XZR if it ends up being unused.
1459  unsigned Opcode = AArch64ISD::SUBS;
1460 
1461  if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1462  (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1463  // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1464  // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1465  // can be set differently by this operation. It comes down to whether
1466  // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1467  // everything is fine. If not then the optimization is wrong. Thus general
1468  // comparisons are only valid if op2 != 0.
1469 
1470  // So, finally, the only LLVM-native comparisons that don't mention C and V
1471  // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1472  // the absence of information about op2.
1473  Opcode = AArch64ISD::ADDS;
1474  RHS = RHS.getOperand(1);
1475  } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1476  !isUnsignedIntSetCC(CC)) {
1477  // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1478  // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1479  // of the signed comparisons.
1480  Opcode = AArch64ISD::ANDS;
1481  RHS = LHS.getOperand(1);
1482  LHS = LHS.getOperand(0);
1483  }
1484 
1485  return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1486  .getValue(1);
1487 }
1488 
1489 /// \defgroup AArch64CCMP CMP;CCMP matching
1490 ///
1491 /// These functions deal with the formation of CMP;CCMP;... sequences.
1492 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1493 /// a comparison. They set the NZCV flags to a predefined value if their
1494 /// predicate is false. This allows to express arbitrary conjunctions, for
1495 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1496 /// expressed as:
1497 /// cmp A
1498 /// ccmp B, inv(CB), CA
1499 /// check for CB flags
1500 ///
1501 /// In general we can create code for arbitrary "... (and (and A B) C)"
1502 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1503 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1504 /// negation operations:
1505 /// We can negate the results of a single comparison by inverting the flags
1506 /// used when the predicate fails and inverting the flags tested in the next
1507 /// instruction; We can also negate the results of the whole previous
1508 /// conditional compare sequence by inverting the flags tested in the next
1509 /// instruction. However there is no way to negate the result of a partial
1510 /// sequence.
1511 ///
1512 /// Therefore on encountering an "or" expression we can negate the subtree on
1513 /// one side and have to be able to push the negate to the leafs of the subtree
1514 /// on the other side (see also the comments in code). As complete example:
1515 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1516 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1517 /// is transformed to
1518 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1519 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1520 /// and implemented as:
1521 /// cmp C
1522 /// ccmp D, inv(CD), CC
1523 /// ccmp A, CA, inv(CD)
1524 /// ccmp B, CB, inv(CA)
1525 /// check for CB flags
1526 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1527 /// by conditional compare sequences.
1528 /// @{
1529 
1530 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1532  ISD::CondCode CC, SDValue CCOp,
1534  AArch64CC::CondCode OutCC,
1535  const SDLoc &DL, SelectionDAG &DAG) {
1536  unsigned Opcode = 0;
1537  const bool FullFP16 =
1538  static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1539 
1540  if (LHS.getValueType().isFloatingPoint()) {
1541  assert(LHS.getValueType() != MVT::f128);
1542  if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1543  LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1544  RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1545  }
1546  Opcode = AArch64ISD::FCCMP;
1547  } else if (RHS.getOpcode() == ISD::SUB) {
1548  SDValue SubOp0 = RHS.getOperand(0);
1549  if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1550  // See emitComparison() on why we can only do this for SETEQ and SETNE.
1551  Opcode = AArch64ISD::CCMN;
1552  RHS = RHS.getOperand(1);
1553  }
1554  }
1555  if (Opcode == 0)
1556  Opcode = AArch64ISD::CCMP;
1557 
1558  SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1560  unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1561  SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1562  return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1563 }
1564 
1565 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1566 /// CanPushNegate is set to true if we can push a negate operation through
1567 /// the tree in a was that we are left with AND operations and negate operations
1568 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1569 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1570 /// brought into such a form.
1571 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1572  unsigned Depth = 0) {
1573  if (!Val.hasOneUse())
1574  return false;
1575  unsigned Opcode = Val->getOpcode();
1576  if (Opcode == ISD::SETCC) {
1577  if (Val->getOperand(0).getValueType() == MVT::f128)
1578  return false;
1579  CanNegate = true;
1580  return true;
1581  }
1582  // Protect against exponential runtime and stack overflow.
1583  if (Depth > 6)
1584  return false;
1585  if (Opcode == ISD::AND || Opcode == ISD::OR) {
1586  SDValue O0 = Val->getOperand(0);
1587  SDValue O1 = Val->getOperand(1);
1588  bool CanNegateL;
1589  if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1590  return false;
1591  bool CanNegateR;
1592  if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1593  return false;
1594 
1595  if (Opcode == ISD::OR) {
1596  // For an OR expression we need to be able to negate at least one side or
1597  // we cannot do the transformation at all.
1598  if (!CanNegateL && !CanNegateR)
1599  return false;
1600  // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1601  // can negate the x and y subtrees.
1602  CanNegate = CanNegateL && CanNegateR;
1603  } else {
1604  // If the operands are OR expressions then we finally need to negate their
1605  // outputs, we can only do that for the operand with emitted last by
1606  // negating OutCC, not for both operands.
1607  bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1608  bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1609  if (NeedsNegOutL && NeedsNegOutR)
1610  return false;
1611  // We cannot negate an AND operation (it would become an OR),
1612  CanNegate = false;
1613  }
1614  return true;
1615  }
1616  return false;
1617 }
1618 
1619 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1620 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1621 /// Tries to transform the given i1 producing node @p Val to a series compare
1622 /// and conditional compare operations. @returns an NZCV flags producing node
1623 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1624 /// transformation was not possible.
1625 /// On recursive invocations @p PushNegate may be set to true to have negation
1626 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1627 /// for the comparisons in the current subtree; @p Depth limits the search
1628 /// depth to avoid stack overflow.
1630  AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1632  // We're at a tree leaf, produce a conditional comparison operation.
1633  unsigned Opcode = Val->getOpcode();
1634  if (Opcode == ISD::SETCC) {
1635  SDValue LHS = Val->getOperand(0);
1636  SDValue RHS = Val->getOperand(1);
1637  ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1638  bool isInteger = LHS.getValueType().isInteger();
1639  if (Negate)
1640  CC = getSetCCInverse(CC, isInteger);
1641  SDLoc DL(Val);
1642  // Determine OutCC and handle FP special case.
1643  if (isInteger) {
1644  OutCC = changeIntCCToAArch64CC(CC);
1645  } else {
1647  AArch64CC::CondCode ExtraCC;
1648  changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1649  // Some floating point conditions can't be tested with a single condition
1650  // code. Construct an additional comparison in this case.
1651  if (ExtraCC != AArch64CC::AL) {
1652  SDValue ExtraCmp;
1653  if (!CCOp.getNode())
1654  ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1655  else
1656  ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1657  ExtraCC, DL, DAG);
1658  CCOp = ExtraCmp;
1659  Predicate = ExtraCC;
1660  }
1661  }
1662 
1663  // Produce a normal comparison if we are first in the chain
1664  if (!CCOp)
1665  return emitComparison(LHS, RHS, CC, DL, DAG);
1666  // Otherwise produce a ccmp.
1667  return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1668  DAG);
1669  }
1670  assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1671  "Valid conjunction/disjunction tree");
1672 
1673  // Check if both sides can be transformed.
1674  SDValue LHS = Val->getOperand(0);
1675  SDValue RHS = Val->getOperand(1);
1676 
1677  // In case of an OR we need to negate our operands and the result.
1678  // (A v B) <=> not(not(A) ^ not(B))
1679  bool NegateOpsAndResult = Opcode == ISD::OR;
1680  // We can negate the results of all previous operations by inverting the
1681  // predicate flags giving us a free negation for one side. The other side
1682  // must be negatable by itself.
1683  if (NegateOpsAndResult) {
1684  // See which side we can negate.
1685  bool CanNegateL;
1686  bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1687  assert(isValidL && "Valid conjunction/disjunction tree");
1688  (void)isValidL;
1689 
1690 #ifndef NDEBUG
1691  bool CanNegateR;
1692  bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1693  assert(isValidR && "Valid conjunction/disjunction tree");
1694  assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1695 #endif
1696 
1697  // Order the side which we cannot negate to RHS so we can emit it first.
1698  if (!CanNegateL)
1699  std::swap(LHS, RHS);
1700  } else {
1701  bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1702  assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1703  "Valid conjunction/disjunction tree");
1704  // Order the side where we need to negate the output flags to RHS so it
1705  // gets emitted first.
1706  if (NeedsNegOutL)
1707  std::swap(LHS, RHS);
1708  }
1709 
1710  // Emit RHS. If we want to negate the tree we only need to push a negate
1711  // through if we are already in a PushNegate case, otherwise we can negate
1712  // the "flags to test" afterwards.
1713  AArch64CC::CondCode RHSCC;
1714  SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1715  CCOp, Predicate);
1716  if (NegateOpsAndResult && !Negate)
1717  RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1718  // Emit LHS. We may need to negate it.
1719  SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1720  NegateOpsAndResult, CmpR,
1721  RHSCC);
1722  // If we transformed an OR to and AND then we have to negate the result
1723  // (or absorb the Negate parameter).
1724  if (NegateOpsAndResult && !Negate)
1725  OutCC = AArch64CC::getInvertedCondCode(OutCC);
1726  return CmpL;
1727 }
1728 
1729 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1730 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1731 /// \see emitConjunctionDisjunctionTreeRec().
1733  AArch64CC::CondCode &OutCC) {
1734  bool CanNegate;
1735  if (!isConjunctionDisjunctionTree(Val, CanNegate))
1736  return SDValue();
1737 
1738  return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1739  AArch64CC::AL);
1740 }
1741 
1742 /// @}
1743 
1745  SDValue &AArch64cc, SelectionDAG &DAG,
1746  const SDLoc &dl) {
1747  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1748  EVT VT = RHS.getValueType();
1749  uint64_t C = RHSC->getZExtValue();
1750  if (!isLegalArithImmed(C)) {
1751  // Constant does not fit, try adjusting it by one?
1752  switch (CC) {
1753  default:
1754  break;
1755  case ISD::SETLT:
1756  case ISD::SETGE:
1757  if ((VT == MVT::i32 && C != 0x80000000 &&
1758  isLegalArithImmed((uint32_t)(C - 1))) ||
1759  (VT == MVT::i64 && C != 0x80000000ULL &&
1760  isLegalArithImmed(C - 1ULL))) {
1761  CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1762  C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1763  RHS = DAG.getConstant(C, dl, VT);
1764  }
1765  break;
1766  case ISD::SETULT:
1767  case ISD::SETUGE:
1768  if ((VT == MVT::i32 && C != 0 &&
1769  isLegalArithImmed((uint32_t)(C - 1))) ||
1770  (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1771  CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1772  C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1773  RHS = DAG.getConstant(C, dl, VT);
1774  }
1775  break;
1776  case ISD::SETLE:
1777  case ISD::SETGT:
1778  if ((VT == MVT::i32 && C != INT32_MAX &&
1779  isLegalArithImmed((uint32_t)(C + 1))) ||
1780  (VT == MVT::i64 && C != INT64_MAX &&
1781  isLegalArithImmed(C + 1ULL))) {
1782  CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1783  C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1784  RHS = DAG.getConstant(C, dl, VT);
1785  }
1786  break;
1787  case ISD::SETULE:
1788  case ISD::SETUGT:
1789  if ((VT == MVT::i32 && C != UINT32_MAX &&
1790  isLegalArithImmed((uint32_t)(C + 1))) ||
1791  (VT == MVT::i64 && C != UINT64_MAX &&
1792  isLegalArithImmed(C + 1ULL))) {
1793  CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1794  C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1795  RHS = DAG.getConstant(C, dl, VT);
1796  }
1797  break;
1798  }
1799  }
1800  }
1801  SDValue Cmp;
1802  AArch64CC::CondCode AArch64CC;
1803  if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1804  const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1805 
1806  // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1807  // For the i8 operand, the largest immediate is 255, so this can be easily
1808  // encoded in the compare instruction. For the i16 operand, however, the
1809  // largest immediate cannot be encoded in the compare.
1810  // Therefore, use a sign extending load and cmn to avoid materializing the
1811  // -1 constant. For example,
1812  // movz w1, #65535
1813  // ldrh w0, [x0, #0]
1814  // cmp w0, w1
1815  // >
1816  // ldrsh w0, [x0, #0]
1817  // cmn w0, #1
1818  // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1819  // if and only if (sext LHS) == (sext RHS). The checks are in place to
1820  // ensure both the LHS and RHS are truly zero extended and to make sure the
1821  // transformation is profitable.
1822  if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1823  cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1824  cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1825  LHS.getNode()->hasNUsesOfValue(1, 0)) {
1826  int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1827  if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1828  SDValue SExt =
1829  DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1830  DAG.getValueType(MVT::i16));
1831  Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1832  RHS.getValueType()),
1833  CC, dl, DAG);
1834  AArch64CC = changeIntCCToAArch64CC(CC);
1835  }
1836  }
1837 
1838  if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1839  if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1840  if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1841  AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1842  }
1843  }
1844  }
1845 
1846  if (!Cmp) {
1847  Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1848  AArch64CC = changeIntCCToAArch64CC(CC);
1849  }
1850  AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1851  return Cmp;
1852 }
1853 
1854 static std::pair<SDValue, SDValue>
1856  assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1857  "Unsupported value type");
1858  SDValue Value, Overflow;
1859  SDLoc DL(Op);
1860  SDValue LHS = Op.getOperand(0);
1861  SDValue RHS = Op.getOperand(1);
1862  unsigned Opc = 0;
1863  switch (Op.getOpcode()) {
1864  default:
1865  llvm_unreachable("Unknown overflow instruction!");
1866  case ISD::SADDO:
1867  Opc = AArch64ISD::ADDS;
1868  CC = AArch64CC::VS;
1869  break;
1870  case ISD::UADDO:
1871  Opc = AArch64ISD::ADDS;
1872  CC = AArch64CC::HS;
1873  break;
1874  case ISD::SSUBO:
1875  Opc = AArch64ISD::SUBS;
1876  CC = AArch64CC::VS;
1877  break;
1878  case ISD::USUBO:
1879  Opc = AArch64ISD::SUBS;
1880  CC = AArch64CC::LO;
1881  break;
1882  // Multiply needs a little bit extra work.
1883  case ISD::SMULO:
1884  case ISD::UMULO: {
1885  CC = AArch64CC::NE;
1886  bool IsSigned = Op.getOpcode() == ISD::SMULO;
1887  if (Op.getValueType() == MVT::i32) {
1888  unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1889  // For a 32 bit multiply with overflow check we want the instruction
1890  // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1891  // need to generate the following pattern:
1892  // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1893  LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1894  RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1895  SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1896  SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1897  DAG.getConstant(0, DL, MVT::i64));
1898  // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1899  // operation. We need to clear out the upper 32 bits, because we used a
1900  // widening multiply that wrote all 64 bits. In the end this should be a
1901  // noop.
1902  Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1903  if (IsSigned) {
1904  // The signed overflow check requires more than just a simple check for
1905  // any bit set in the upper 32 bits of the result. These bits could be
1906  // just the sign bits of a negative number. To perform the overflow
1907  // check we have to arithmetic shift right the 32nd bit of the result by
1908  // 31 bits. Then we compare the result to the upper 32 bits.
1909  SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1910  DAG.getConstant(32, DL, MVT::i64));
1911  UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1912  SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1913  DAG.getConstant(31, DL, MVT::i64));
1914  // It is important that LowerBits is last, otherwise the arithmetic
1915  // shift will not be folded into the compare (SUBS).
1916  SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1917  Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1918  .getValue(1);
1919  } else {
1920  // The overflow check for unsigned multiply is easy. We only need to
1921  // check if any of the upper 32 bits are set. This can be done with a
1922  // CMP (shifted register). For that we need to generate the following
1923  // pattern:
1924  // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1925  SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1926  DAG.getConstant(32, DL, MVT::i64));
1927  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1928  Overflow =
1929  DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1930  DAG.getConstant(0, DL, MVT::i64),
1931  UpperBits).getValue(1);
1932  }
1933  break;
1934  }
1935  assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1936  // For the 64 bit multiply
1937  Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1938  if (IsSigned) {
1939  SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1940  SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1941  DAG.getConstant(63, DL, MVT::i64));
1942  // It is important that LowerBits is last, otherwise the arithmetic
1943  // shift will not be folded into the compare (SUBS).
1944  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1945  Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1946  .getValue(1);
1947  } else {
1948  SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1949  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1950  Overflow =
1951  DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1952  DAG.getConstant(0, DL, MVT::i64),
1953  UpperBits).getValue(1);
1954  }
1955  break;
1956  }
1957  } // switch (...)
1958 
1959  if (Opc) {
1960  SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1961 
1962  // Emit the AArch64 operation with overflow check.
1963  Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1964  Overflow = Value.getValue(1);
1965  }
1966  return std::make_pair(Value, Overflow);
1967 }
1968 
1969 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1970  RTLIB::Libcall Call) const {
1971  SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1972  return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1973 }
1974 
1975 // Returns true if the given Op is the overflow flag result of an overflow
1976 // intrinsic operation.
1977 static bool isOverflowIntrOpRes(SDValue Op) {
1978  unsigned Opc = Op.getOpcode();
1979  return (Op.getResNo() == 1 &&
1980  (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
1981  Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
1982 }
1983 
1985  SDValue Sel = Op.getOperand(0);
1986  SDValue Other = Op.getOperand(1);
1987  SDLoc dl(Sel);
1988 
1989  // If the operand is an overflow checking operation, invert the condition
1990  // code and kill the Not operation. I.e., transform:
1991  // (xor (overflow_op_bool, 1))
1992  // -->
1993  // (csel 1, 0, invert(cc), overflow_op_bool)
1994  // ... which later gets transformed to just a cset instruction with an
1995  // inverted condition code, rather than a cset + eor sequence.
1996  if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
1997  // Only lower legal XALUO ops.
1998  if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
1999  return SDValue();
2000 
2001  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2002  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2004  SDValue Value, Overflow;
2005  std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2006  SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2007  return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2008  CCVal, Overflow);
2009  }
2010  // If neither operand is a SELECT_CC, give up.
2011  if (Sel.getOpcode() != ISD::SELECT_CC)
2012  std::swap(Sel, Other);
2013  if (Sel.getOpcode() != ISD::SELECT_CC)
2014  return Op;
2015 
2016  // The folding we want to perform is:
2017  // (xor x, (select_cc a, b, cc, 0, -1) )
2018  // -->
2019  // (csel x, (xor x, -1), cc ...)
2020  //
2021  // The latter will get matched to a CSINV instruction.
2022 
2023  ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2024  SDValue LHS = Sel.getOperand(0);
2025  SDValue RHS = Sel.getOperand(1);
2026  SDValue TVal = Sel.getOperand(2);
2027  SDValue FVal = Sel.getOperand(3);
2028 
2029  // FIXME: This could be generalized to non-integer comparisons.
2030  if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2031  return Op;
2032 
2033  ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2034  ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2035 
2036  // The values aren't constants, this isn't the pattern we're looking for.
2037  if (!CFVal || !CTVal)
2038  return Op;
2039 
2040  // We can commute the SELECT_CC by inverting the condition. This
2041  // might be needed to make this fit into a CSINV pattern.
2042  if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2043  std::swap(TVal, FVal);
2044  std::swap(CTVal, CFVal);
2045  CC = ISD::getSetCCInverse(CC, true);
2046  }
2047 
2048  // If the constants line up, perform the transform!
2049  if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2050  SDValue CCVal;
2051  SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2052 
2053  FVal = Other;
2054  TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2055  DAG.getConstant(-1ULL, dl, Other.getValueType()));
2056 
2057  return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2058  CCVal, Cmp);
2059  }
2060 
2061  return Op;
2062 }
2063 
2065  EVT VT = Op.getValueType();
2066 
2067  // Let legalize expand this if it isn't a legal type yet.
2068  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2069  return SDValue();
2070 
2071  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2072 
2073  unsigned Opc;
2074  bool ExtraOp = false;
2075  switch (Op.getOpcode()) {
2076  default:
2077  llvm_unreachable("Invalid code");
2078  case ISD::ADDC:
2079  Opc = AArch64ISD::ADDS;
2080  break;
2081  case ISD::SUBC:
2082  Opc = AArch64ISD::SUBS;
2083  break;
2084  case ISD::ADDE:
2085  Opc = AArch64ISD::ADCS;
2086  ExtraOp = true;
2087  break;
2088  case ISD::SUBE:
2089  Opc = AArch64ISD::SBCS;
2090  ExtraOp = true;
2091  break;
2092  }
2093 
2094  if (!ExtraOp)
2095  return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2096  return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2097  Op.getOperand(2));
2098 }
2099 
2101  // Let legalize expand this if it isn't a legal type yet.
2103  return SDValue();
2104 
2105  SDLoc dl(Op);
2107  // The actual operation that sets the overflow or carry flag.
2108  SDValue Value, Overflow;
2109  std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2110 
2111  // We use 0 and 1 as false and true values.
2112  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2113  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2114 
2115  // We use an inverted condition, because the conditional select is inverted
2116  // too. This will allow it to be selected to a single instruction:
2117  // CSINC Wd, WZR, WZR, invert(cond).
2118  SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2119  Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2120  CCVal, Overflow);
2121 
2122  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2123  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2124 }
2125 
2126 // Prefetch operands are:
2127 // 1: Address to prefetch
2128 // 2: bool isWrite
2129 // 3: int locality (0 = no locality ... 3 = extreme locality)
2130 // 4: bool isDataCache
2132  SDLoc DL(Op);
2133  unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2134  unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2135  unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2136 
2137  bool IsStream = !Locality;
2138  // When the locality number is set
2139  if (Locality) {
2140  // The front-end should have filtered out the out-of-range values
2141  assert(Locality <= 3 && "Prefetch locality out-of-range");
2142  // The locality degree is the opposite of the cache speed.
2143  // Put the number the other way around.
2144  // The encoding starts at 0 for level 1
2145  Locality = 3 - Locality;
2146  }
2147 
2148  // built the mask value encoding the expected behavior.
2149  unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2150  (!IsData << 3) | // IsDataCache bit
2151  (Locality << 1) | // Cache level bits
2152  (unsigned)IsStream; // Stream bit
2153  return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2154  DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2155 }
2156 
2157 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2158  SelectionDAG &DAG) const {
2159  assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2160 
2161  RTLIB::Libcall LC;
2163 
2164  return LowerF128Call(Op, DAG, LC);
2165 }
2166 
2167 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2168  SelectionDAG &DAG) const {
2169  if (Op.getOperand(0).getValueType() != MVT::f128) {
2170  // It's legal except when f128 is involved
2171  return Op;
2172  }
2173 
2174  RTLIB::Libcall LC;
2176 
2177  // FP_ROUND node has a second operand indicating whether it is known to be
2178  // precise. That doesn't take part in the LibCall so we can't directly use
2179  // LowerF128Call.
2180  SDValue SrcVal = Op.getOperand(0);
2181  return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2182  SDLoc(Op)).first;
2183 }
2184 
2186  // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2187  // Any additional optimization in this function should be recorded
2188  // in the cost tables.
2189  EVT InVT = Op.getOperand(0).getValueType();
2190  EVT VT = Op.getValueType();
2191  unsigned NumElts = InVT.getVectorNumElements();
2192 
2193  // f16 vectors are promoted to f32 before a conversion.
2194  if (InVT.getVectorElementType() == MVT::f16) {
2195  MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2196  SDLoc dl(Op);
2197  return DAG.getNode(
2198  Op.getOpcode(), dl, Op.getValueType(),
2199  DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2200  }
2201 
2202  if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2203  SDLoc dl(Op);
2204  SDValue Cv =
2205  DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2206  Op.getOperand(0));
2207  return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2208  }
2209 
2210  if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2211  SDLoc dl(Op);
2212  MVT ExtVT =
2214  VT.getVectorNumElements());
2215  SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2216  return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2217  }
2218 
2219  // Type changing conversions are illegal.
2220  return Op;
2221 }
2222 
2223 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2224  SelectionDAG &DAG) const {
2225  if (Op.getOperand(0).getValueType().isVector())
2226  return LowerVectorFP_TO_INT(Op, DAG);
2227 
2228  // f16 conversions are promoted to f32 when full fp16 is not supported.
2229  if (Op.getOperand(0).getValueType() == MVT::f16 &&
2230  !Subtarget->hasFullFP16()) {
2231  SDLoc dl(Op);
2232  return DAG.getNode(
2233  Op.getOpcode(), dl, Op.getValueType(),
2234  DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2235  }
2236 
2237  if (Op.getOperand(0).getValueType() != MVT::f128) {
2238  // It's legal except when f128 is involved
2239  return Op;
2240  }
2241 
2242  RTLIB::Libcall LC;
2243  if (Op.getOpcode() == ISD::FP_TO_SINT)
2245  else
2247 
2248  SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2249  return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2250 }
2251 
2253  // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2254  // Any additional optimization in this function should be recorded
2255  // in the cost tables.
2256  EVT VT = Op.getValueType();
2257  SDLoc dl(Op);
2258  SDValue In = Op.getOperand(0);
2259  EVT InVT = In.getValueType();
2260 
2261  if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2262  MVT CastVT =
2264  InVT.getVectorNumElements());
2265  In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2266  return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2267  }
2268 
2269  if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2270  unsigned CastOpc =
2272  EVT CastVT = VT.changeVectorElementTypeToInteger();
2273  In = DAG.getNode(CastOpc, dl, CastVT, In);
2274  return DAG.getNode(Op.getOpcode(), dl, VT, In);
2275  }
2276 
2277  return Op;
2278 }
2279 
2280 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2281  SelectionDAG &DAG) const {
2282  if (Op.getValueType().isVector())
2283  return LowerVectorINT_TO_FP(Op, DAG);
2284 
2285  // f16 conversions are promoted to f32 when full fp16 is not supported.
2286  if (Op.getValueType() == MVT::f16 &&
2287  !Subtarget->hasFullFP16()) {
2288  SDLoc dl(Op);
2289  return DAG.getNode(
2290  ISD::FP_ROUND, dl, MVT::f16,
2291  DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2292  DAG.getIntPtrConstant(0, dl));
2293  }
2294 
2295  // i128 conversions are libcalls.
2296  if (Op.getOperand(0).getValueType() == MVT::i128)
2297  return SDValue();
2298 
2299  // Other conversions are legal, unless it's to the completely software-based
2300  // fp128.
2301  if (Op.getValueType() != MVT::f128)
2302  return Op;
2303 
2304  RTLIB::Libcall LC;
2305  if (Op.getOpcode() == ISD::SINT_TO_FP)
2307  else
2309 
2310  return LowerF128Call(Op, DAG, LC);
2311 }
2312 
2313 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2314  SelectionDAG &DAG) const {
2315  // For iOS, we want to call an alternative entry point: __sincos_stret,
2316  // which returns the values in two S / D registers.
2317  SDLoc dl(Op);
2318  SDValue Arg = Op.getOperand(0);
2319  EVT ArgVT = Arg.getValueType();
2320  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2321 
2322  ArgListTy Args;
2323  ArgListEntry Entry;
2324 
2325  Entry.Node = Arg;
2326  Entry.Ty = ArgTy;
2327  Entry.IsSExt = false;
2328  Entry.IsZExt = false;
2329  Args.push_back(Entry);
2330 
2331  const char *LibcallName =
2332  (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2333  SDValue Callee =
2334  DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2335 
2336  StructType *RetTy = StructType::get(ArgTy, ArgTy);
2338  CLI.setDebugLoc(dl)
2339  .setChain(DAG.getEntryNode())
2340  .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2341 
2342  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2343  return CallResult.first;
2344 }
2345 
2347  if (Op.getValueType() != MVT::f16)
2348  return SDValue();
2349 
2350  assert(Op.getOperand(0).getValueType() == MVT::i16);
2351  SDLoc DL(Op);
2352 
2353  Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2354  Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2355  return SDValue(
2356  DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2357  DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2358  0);
2359 }
2360 
2361 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2362  if (OrigVT.getSizeInBits() >= 64)
2363  return OrigVT;
2364 
2365  assert(OrigVT.isSimple() && "Expecting a simple value type");
2366 
2367  MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2368  switch (OrigSimpleTy) {
2369  default: llvm_unreachable("Unexpected Vector Type");
2370  case MVT::v2i8:
2371  case MVT::v2i16:
2372  return MVT::v2i32;
2373  case MVT::v4i8:
2374  return MVT::v4i16;
2375  }
2376 }
2377 
2379  const EVT &OrigTy,
2380  const EVT &ExtTy,
2381  unsigned ExtOpcode) {
2382  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2383  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2384  // 64-bits we need to insert a new extension so that it will be 64-bits.
2385  assert(ExtTy.is128BitVector() && "Unexpected extension size");
2386  if (OrigTy.getSizeInBits() >= 64)
2387  return N;
2388 
2389  // Must extend size to at least 64 bits to be used as an operand for VMULL.
2390  EVT NewVT = getExtensionTo64Bits(OrigTy);
2391 
2392  return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2393 }
2394 
2396  bool isSigned) {
2397  EVT VT = N->getValueType(0);
2398 
2399  if (N->getOpcode() != ISD::BUILD_VECTOR)
2400  return false;
2401 
2402  for (const SDValue &Elt : N->op_values()) {
2403  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2404  unsigned EltSize = VT.getScalarSizeInBits();
2405  unsigned HalfSize = EltSize / 2;
2406  if (isSigned) {
2407  if (!isIntN(HalfSize, C->getSExtValue()))
2408  return false;
2409  } else {
2410  if (!isUIntN(HalfSize, C->getZExtValue()))
2411  return false;
2412  }
2413  continue;
2414  }
2415  return false;
2416  }
2417 
2418  return true;
2419 }
2420 
2422  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2424  N->getOperand(0)->getValueType(0),
2425  N->getValueType(0),
2426  N->getOpcode());
2427 
2428  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2429  EVT VT = N->getValueType(0);
2430  SDLoc dl(N);
2431  unsigned EltSize = VT.getScalarSizeInBits() / 2;
2432  unsigned NumElts = VT.getVectorNumElements();
2433  MVT TruncVT = MVT::getIntegerVT(EltSize);
2435  for (unsigned i = 0; i != NumElts; ++i) {
2436  ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2437  const APInt &CInt = C->getAPIntValue();
2438  // Element types smaller than 32 bits are not legal, so use i32 elements.
2439  // The values are implicitly truncated so sext vs. zext doesn't matter.
2440  Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2441  }
2442  return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2443 }
2444 
2445 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2446  return N->getOpcode() == ISD::SIGN_EXTEND ||
2447  isExtendedBUILD_VECTOR(N, DAG, true);
2448 }
2449 
2450 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2451  return N->getOpcode() == ISD::ZERO_EXTEND ||
2452  isExtendedBUILD_VECTOR(N, DAG, false);
2453 }
2454 
2455 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2456  unsigned Opcode = N->getOpcode();
2457  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2458  SDNode *N0 = N->getOperand(0).getNode();
2459  SDNode *N1 = N->getOperand(1).getNode();
2460  return N0->hasOneUse() && N1->hasOneUse() &&
2461  isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2462  }
2463  return false;
2464 }
2465 
2466 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2467  unsigned Opcode = N->getOpcode();
2468  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2469  SDNode *N0 = N->getOperand(0).getNode();
2470  SDNode *N1 = N->getOperand(1).getNode();
2471  return N0->hasOneUse() && N1->hasOneUse() &&
2472  isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2473  }
2474  return false;
2475 }
2476 
2478  // Multiplications are only custom-lowered for 128-bit vectors so that
2479  // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2480  EVT VT = Op.getValueType();
2481  assert(VT.is128BitVector() && VT.isInteger() &&
2482  "unexpected type for custom-lowering ISD::MUL");
2483  SDNode *N0 = Op.getOperand(0).getNode();
2484  SDNode *N1 = Op.getOperand(1).getNode();
2485  unsigned NewOpc = 0;
2486  bool isMLA = false;
2487  bool isN0SExt = isSignExtended(N0, DAG);
2488  bool isN1SExt = isSignExtended(N1, DAG);
2489  if (isN0SExt && isN1SExt)
2490  NewOpc = AArch64ISD::SMULL;
2491  else {
2492  bool isN0ZExt = isZeroExtended(N0, DAG);
2493  bool isN1ZExt = isZeroExtended(N1, DAG);
2494  if (isN0ZExt && isN1ZExt)
2495  NewOpc = AArch64ISD::UMULL;
2496  else if (isN1SExt || isN1ZExt) {
2497  // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2498  // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2499  if (isN1SExt && isAddSubSExt(N0, DAG)) {
2500  NewOpc = AArch64ISD::SMULL;
2501  isMLA = true;
2502  } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2503  NewOpc = AArch64ISD::UMULL;
2504  isMLA = true;
2505  } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2506  std::swap(N0, N1);
2507  NewOpc = AArch64ISD::UMULL;
2508  isMLA = true;
2509  }
2510  }
2511 
2512  if (!NewOpc) {
2513  if (VT == MVT::v2i64)
2514  // Fall through to expand this. It is not legal.
2515  return SDValue();
2516  else
2517  // Other vector multiplications are legal.
2518  return Op;
2519  }
2520  }
2521 
2522  // Legalize to a S/UMULL instruction
2523  SDLoc DL(Op);
2524  SDValue Op0;
2525  SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2526  if (!isMLA) {
2527  Op0 = skipExtensionForVectorMULL(N0, DAG);
2528  assert(Op0.getValueType().is64BitVector() &&
2529  Op1.getValueType().is64BitVector() &&
2530  "unexpected types for extended operands to VMULL");
2531  return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2532  }
2533  // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2534  // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2535  // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2536  SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2537  SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2538  EVT Op1VT = Op1.getValueType();
2539  return DAG.getNode(N0->getOpcode(), DL, VT,
2540  DAG.getNode(NewOpc, DL, VT,
2541  DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2542  DAG.getNode(NewOpc, DL, VT,
2543  DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2544 }
2545 
2546 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2547  SelectionDAG &DAG) const {
2548  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2549  SDLoc dl(Op);
2550  switch (IntNo) {
2551  default: return SDValue(); // Don't custom lower most intrinsics.
2552  case Intrinsic::thread_pointer: {
2553  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2554  return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2555  }
2556  case Intrinsic::aarch64_neon_abs:
2557  return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2558  Op.getOperand(1));
2559  case Intrinsic::aarch64_neon_smax:
2560  return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2561  Op.getOperand(1), Op.getOperand(2));
2562  case Intrinsic::aarch64_neon_umax:
2563  return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2564  Op.getOperand(1), Op.getOperand(2));
2565  case Intrinsic::aarch64_neon_smin:
2566  return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2567  Op.getOperand(1), Op.getOperand(2));
2568  case Intrinsic::aarch64_neon_umin:
2569  return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2570  Op.getOperand(1), Op.getOperand(2));
2571  }
2572 }
2573 
2575  SelectionDAG &DAG) const {
2576  DEBUG(dbgs() << "Custom lowering: ");
2577  DEBUG(Op.dump());
2578 
2579  switch (Op.getOpcode()) {
2580  default:
2581  llvm_unreachable("unimplemented operand");
2582  return SDValue();
2583  case ISD::BITCAST:
2584  return LowerBITCAST(Op, DAG);
2585  case ISD::GlobalAddress:
2586  return LowerGlobalAddress(Op, DAG);
2587  case ISD::GlobalTLSAddress:
2588  return LowerGlobalTLSAddress(Op, DAG);
2589  case ISD::SETCC:
2590  return LowerSETCC(Op, DAG);
2591  case ISD::BR_CC:
2592  return LowerBR_CC(Op, DAG);
2593  case ISD::SELECT:
2594  return LowerSELECT(Op, DAG);
2595  case ISD::SELECT_CC:
2596  return LowerSELECT_CC(Op, DAG);
2597  case ISD::JumpTable:
2598  return LowerJumpTable(Op, DAG);
2599  case ISD::ConstantPool:
2600  return LowerConstantPool(Op, DAG);
2601  case ISD::BlockAddress:
2602  return LowerBlockAddress(Op, DAG);
2603  case ISD::VASTART:
2604  return LowerVASTART(Op, DAG);
2605  case ISD::VACOPY:
2606  return LowerVACOPY(Op, DAG);
2607  case ISD::VAARG:
2608  return LowerVAARG(Op, DAG);
2609  case ISD::ADDC:
2610  case ISD::ADDE:
2611  case ISD::SUBC:
2612  case ISD::SUBE:
2613  return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2614  case ISD::SADDO:
2615  case ISD::UADDO:
2616  case ISD::SSUBO:
2617  case ISD::USUBO:
2618  case ISD::SMULO:
2619  case ISD::UMULO:
2620  return LowerXALUO(Op, DAG);
2621  case ISD::FADD:
2622  return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2623  case ISD::FSUB:
2624  return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2625  case ISD::FMUL:
2626  return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2627  case ISD::FDIV:
2628  return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2629  case ISD::FP_ROUND:
2630  return LowerFP_ROUND(Op, DAG);
2631  case ISD::FP_EXTEND:
2632  return LowerFP_EXTEND(Op, DAG);
2633  case ISD::FRAMEADDR:
2634  return LowerFRAMEADDR(Op, DAG);
2635  case ISD::RETURNADDR:
2636  return LowerRETURNADDR(Op, DAG);
2638  return LowerINSERT_VECTOR_ELT(Op, DAG);
2640  return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2641  case ISD::BUILD_VECTOR:
2642  return LowerBUILD_VECTOR(Op, DAG);
2643  case ISD::VECTOR_SHUFFLE:
2644  return LowerVECTOR_SHUFFLE(Op, DAG);
2646  return LowerEXTRACT_SUBVECTOR(Op, DAG);
2647  case ISD::SRA:
2648  case ISD::SRL:
2649  case ISD::SHL:
2650  return LowerVectorSRA_SRL_SHL(Op, DAG);
2651  case ISD::SHL_PARTS:
2652  return LowerShiftLeftParts(Op, DAG);
2653  case ISD::SRL_PARTS:
2654  case ISD::SRA_PARTS:
2655  return LowerShiftRightParts(Op, DAG);
2656  case ISD::CTPOP:
2657  return LowerCTPOP(Op, DAG);
2658  case ISD::FCOPYSIGN:
2659  return LowerFCOPYSIGN(Op, DAG);
2660  case ISD::AND:
2661  return LowerVectorAND(Op, DAG);
2662  case ISD::OR:
2663  return LowerVectorOR(Op, DAG);
2664  case ISD::XOR:
2665  return LowerXOR(Op, DAG);
2666  case ISD::PREFETCH:
2667  return LowerPREFETCH(Op, DAG);
2668  case ISD::SINT_TO_FP:
2669  case ISD::UINT_TO_FP:
2670  return LowerINT_TO_FP(Op, DAG);
2671  case ISD::FP_TO_SINT:
2672  case ISD::FP_TO_UINT:
2673  return LowerFP_TO_INT(Op, DAG);
2674  case ISD::FSINCOS:
2675  return LowerFSINCOS(Op, DAG);
2676  case ISD::MUL:
2677  return LowerMUL(Op, DAG);
2679  return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2680  case ISD::VECREDUCE_ADD:
2681  case ISD::VECREDUCE_SMAX:
2682  case ISD::VECREDUCE_SMIN:
2683  case ISD::VECREDUCE_UMAX:
2684  case ISD::VECREDUCE_UMIN:
2685  case ISD::VECREDUCE_FMAX:
2686  case ISD::VECREDUCE_FMIN:
2687  return LowerVECREDUCE(Op, DAG);
2688  }
2689 }
2690 
2691 //===----------------------------------------------------------------------===//
2692 // Calling Convention Implementation
2693 //===----------------------------------------------------------------------===//
2694 
2695 #include "AArch64GenCallingConv.inc"
2696 
2697 /// Selects the correct CCAssignFn for a given CallingConvention value.
2699  bool IsVarArg) const {
2700  switch (CC) {
2701  default:
2702  report_fatal_error("Unsupported calling convention.");
2704  return CC_AArch64_WebKit_JS;
2705  case CallingConv::GHC:
2706  return CC_AArch64_GHC;
2707  case CallingConv::C:
2708  case CallingConv::Fast:
2711  case CallingConv::Swift:
2712  if (Subtarget->isTargetWindows() && IsVarArg)
2713  return CC_AArch64_Win64_VarArg;
2714  if (!Subtarget->isTargetDarwin())
2715  return CC_AArch64_AAPCS;
2716  return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2717  case CallingConv::Win64:
2718  return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2719  }
2720 }
2721 
2722 CCAssignFn *
2724  return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2725  : RetCC_AArch64_AAPCS;
2726 }
2727 
2728 SDValue AArch64TargetLowering::LowerFormalArguments(
2729  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2730  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2731  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2732  MachineFunction &MF = DAG.getMachineFunction();
2733  MachineFrameInfo &MFI = MF.getFrameInfo();
2734  bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2735 
2736  // Assign locations to all of the incoming arguments.
2738  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2739  *DAG.getContext());
2740 
2741  // At this point, Ins[].VT may already be promoted to i32. To correctly
2742  // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2743  // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2744  // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2745  // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2746  // LocVT.
2747  unsigned NumArgs = Ins.size();
2749  unsigned CurArgIdx = 0;
2750  for (unsigned i = 0; i != NumArgs; ++i) {
2751  MVT ValVT = Ins[i].VT;
2752  if (Ins[i].isOrigArg()) {
2753  std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2754  CurArgIdx = Ins[i].getOrigArgIndex();
2755 
2756  // Get type of the original argument.
2757  EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2758  /*AllowUnknown*/ true);
2759  MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2760  // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2761  if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2762  ValVT = MVT::i8;
2763  else if (ActualMVT == MVT::i16)
2764  ValVT = MVT::i16;
2765  }
2766  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2767  bool Res =
2768  AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2769  assert(!Res && "Call operand has unhandled type");
2770  (void)Res;
2771  }
2772  assert(ArgLocs.size() == Ins.size());
2773  SmallVector<SDValue, 16> ArgValues;
2774  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2775  CCValAssign &VA = ArgLocs[i];
2776 
2777  if (Ins[i].Flags.isByVal()) {
2778  // Byval is used for HFAs in the PCS, but the system should work in a
2779  // non-compliant manner for larger structs.
2780  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2781  int Size = Ins[i].Flags.getByValSize();
2782  unsigned NumRegs = (Size + 7) / 8;
2783 
2784  // FIXME: This works on big-endian for composite byvals, which are the common
2785  // case. It should also work for fundamental types too.
2786  unsigned FrameIdx =
2787  MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2788  SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2789  InVals.push_back(FrameIdxN);
2790 
2791  continue;
2792  }
2793 
2794  if (VA.isRegLoc()) {
2795  // Arguments stored in registers.
2796  EVT RegVT = VA.getLocVT();
2797 
2798  SDValue ArgValue;
2799  const TargetRegisterClass *RC;
2800 
2801  if (RegVT == MVT::i32)
2802  RC = &AArch64::GPR32RegClass;
2803  else if (RegVT == MVT::i64)
2804  RC = &AArch64::GPR64RegClass;
2805  else if (RegVT == MVT::f16)
2806  RC = &AArch64::FPR16RegClass;
2807  else if (RegVT == MVT::f32)
2808  RC = &AArch64::FPR32RegClass;
2809  else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2810  RC = &AArch64::FPR64RegClass;
2811  else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2812  RC = &AArch64::FPR128RegClass;
2813  else
2814  llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2815 
2816  // Transform the arguments in physical registers into virtual ones.
2817  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2818  ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2819 
2820  // If this is an 8, 16 or 32-bit value, it is really passed promoted
2821  // to 64 bits. Insert an assert[sz]ext to capture this, then
2822  // truncate to the right size.
2823  switch (VA.getLocInfo()) {
2824  default:
2825  llvm_unreachable("Unknown loc info!");
2826  case CCValAssign::Full:
2827  break;
2828  case CCValAssign::BCvt:
2829  ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2830  break;
2831  case CCValAssign::AExt:
2832  case CCValAssign::SExt:
2833  case CCValAssign::ZExt:
2834  // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2835  // nodes after our lowering.
2836  assert(RegVT == Ins[i].VT && "incorrect register location selected");
2837  break;
2838  }
2839 
2840  InVals.push_back(ArgValue);
2841 
2842  } else { // VA.isRegLoc()
2843  assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2844  unsigned ArgOffset = VA.getLocMemOffset();
2845  unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2846 
2847  uint32_t BEAlign = 0;
2848  if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2849  !Ins[i].Flags.isInConsecutiveRegs())
2850  BEAlign = 8 - ArgSize;
2851 
2852  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2853 
2854  // Create load nodes to retrieve arguments from the stack.
2855  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2856  SDValue ArgValue;
2857 
2858  // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2860  MVT MemVT = VA.getValVT();
2861 
2862  switch (VA.getLocInfo()) {
2863  default:
2864  break;
2865  case CCValAssign::BCvt:
2866  MemVT = VA.getLocVT();
2867  break;
2868  case CCValAssign::SExt:
2869  ExtType = ISD::SEXTLOAD;
2870  break;
2871  case CCValAssign::ZExt:
2872  ExtType = ISD::ZEXTLOAD;
2873  break;
2874  case CCValAssign::AExt:
2875  ExtType = ISD::EXTLOAD;
2876  break;
2877  }
2878 
2879  ArgValue = DAG.getExtLoad(
2880  ExtType, DL, VA.getLocVT(), Chain, FIN,
2882  MemVT);
2883 
2884  InVals.push_back(ArgValue);
2885  }
2886  }
2887 
2888  // varargs
2890  if (isVarArg) {
2891  if (!Subtarget->isTargetDarwin() || IsWin64) {
2892  // The AAPCS variadic function ABI is identical to the non-variadic
2893  // one. As a result there may be more arguments in registers and we should
2894  // save them for future reference.
2895  // Win64 variadic functions also pass arguments in registers, but all float
2896  // arguments are passed in integer registers.
2897  saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2898  }
2899 
2900  // This will point to the next argument passed via stack.
2901  unsigned StackOffset = CCInfo.getNextStackOffset();
2902  // We currently pass all varargs at 8-byte alignment.
2903  StackOffset = ((StackOffset + 7) & ~7);
2904  FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2905  }
2906 
2907  unsigned StackArgSize = CCInfo.getNextStackOffset();
2908  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2909  if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2910  // This is a non-standard ABI so by fiat I say we're allowed to make full
2911  // use of the stack area to be popped, which must be aligned to 16 bytes in
2912  // any case:
2913  StackArgSize = alignTo(StackArgSize, 16);
2914 
2915  // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2916  // a multiple of 16.
2917  FuncInfo->setArgumentStackToRestore(StackArgSize);
2918 
2919  // This realignment carries over to the available bytes below. Our own
2920  // callers will guarantee the space is free by giving an aligned value to
2921  // CALLSEQ_START.
2922  }
2923  // Even if we're not expected to free up the space, it's useful to know how
2924  // much is there while considering tail calls (because we can reuse it).
2925  FuncInfo->setBytesInStackArgArea(StackArgSize);
2926 
2927  return Chain;
2928 }
2929 
2930 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2931  SelectionDAG &DAG,
2932  const SDLoc &DL,
2933  SDValue &Chain) const {
2934  MachineFunction &MF = DAG.getMachineFunction();
2935  MachineFrameInfo &MFI = MF.getFrameInfo();
2937  auto PtrVT = getPointerTy(DAG.getDataLayout());
2938  bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2939 
2940  SmallVector<SDValue, 8> MemOps;
2941 
2942  static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2943  AArch64::X3, AArch64::X4, AArch64::X5,
2944  AArch64::X6, AArch64::X7 };
2945  static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2946  unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2947 
2948  unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2949  int GPRIdx = 0;
2950  if (GPRSaveSize != 0) {
2951  if (IsWin64) {
2952  GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
2953  if (GPRSaveSize & 15)
2954  // The extra size here, if triggered, will always be 8.
2955  MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
2956  } else
2957  GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2958 
2959  SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2960 
2961  for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2962  unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2963  SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2964  SDValue Store = DAG.getStore(
2965  Val.getValue(1), DL, Val, FIN,
2966  IsWin64
2968  GPRIdx,
2969  (i - FirstVariadicGPR) * 8)
2971  MemOps.push_back(Store);
2972  FIN =
2973  DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2974  }
2975  }
2976  FuncInfo->setVarArgsGPRIndex(GPRIdx);
2977  FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2978 
2979  if (Subtarget->hasFPARMv8() && !IsWin64) {
2980  static const MCPhysReg FPRArgRegs[] = {
2981  AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2982  AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2983  static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2984  unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2985 
2986  unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2987  int FPRIdx = 0;
2988  if (FPRSaveSize != 0) {
2989  FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2990 
2991  SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2992 
2993  for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2994  unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2995  SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2996 
2997  SDValue Store = DAG.getStore(
2998  Val.getValue(1), DL, Val, FIN,
3000  MemOps.push_back(Store);
3001  FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3002  DAG.getConstant(16, DL, PtrVT));
3003  }
3004  }
3005  FuncInfo->setVarArgsFPRIndex(FPRIdx);
3006  FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3007  }
3008 
3009  if (!MemOps.empty()) {
3010  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3011  }
3012 }
3013 
3014 /// LowerCallResult - Lower the result values of a call into the
3015 /// appropriate copies out of appropriate physical registers.
3016 SDValue AArch64TargetLowering::LowerCallResult(
3017  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3018  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3019  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3020  SDValue ThisVal) const {
3021  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3022  ? RetCC_AArch64_WebKit_JS
3023  : RetCC_AArch64_AAPCS;
3024  // Assign locations to each value returned by this call.
3026  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3027  *DAG.getContext());
3028  CCInfo.AnalyzeCallResult(Ins, RetCC);
3029 
3030  // Copy all of the result registers out of their specified physreg.
3031  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3032  CCValAssign VA = RVLocs[i];
3033 
3034  // Pass 'this' value directly from the argument to return value, to avoid
3035  // reg unit interference
3036  if (i == 0 && isThisReturn) {
3037  assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3038  "unexpected return calling convention register assignment");
3039  InVals.push_back(ThisVal);
3040  continue;
3041  }
3042 
3043  SDValue Val =
3044  DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3045  Chain = Val.getValue(1);
3046  InFlag = Val.getValue(2);
3047 
3048  switch (VA.getLocInfo()) {
3049  default:
3050  llvm_unreachable("Unknown loc info!");
3051  case CCValAssign::Full:
3052  break;
3053  case CCValAssign::BCvt:
3054  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3055  break;
3056  }
3057 
3058  InVals.push_back(Val);
3059  }
3060 
3061  return Chain;
3062 }
3063 
3064 /// Return true if the calling convention is one that we can guarantee TCO for.
3066  return CC == CallingConv::Fast;
3067 }
3068 
3069 /// Return true if we might ever do TCO for calls with this calling convention.
3071  switch (CC) {
3072  case CallingConv::C:
3074  case CallingConv::Swift:
3075  return true;
3076  default:
3077  return canGuaranteeTCO(CC);
3078  }
3079 }
3080 
3081 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3082  SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3083  const SmallVectorImpl<ISD::OutputArg> &Outs,
3084  const SmallVectorImpl<SDValue> &OutVals,
3085  const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3086  if (!mayTailCallThisCC(CalleeCC))
3087  return false;
3088 
3089  MachineFunction &MF = DAG.getMachineFunction();
3090  const Function &CallerF = MF.getFunction();
3091  CallingConv::ID CallerCC = CallerF.getCallingConv();
3092  bool CCMatch = CallerCC == CalleeCC;
3093 
3094  // Byval parameters hand the function a pointer directly into the stack area
3095  // we want to reuse during a tail call. Working around this *is* possible (see
3096  // X86) but less efficient and uglier in LowerCall.
3097  for (Function::const_arg_iterator i = CallerF.arg_begin(),
3098  e = CallerF.arg_end();
3099  i != e; ++i)
3100  if (i->hasByValAttr())
3101  return false;
3102 
3104  return canGuaranteeTCO(CalleeCC) && CCMatch;
3105 
3106  // Externally-defined functions with weak linkage should not be
3107  // tail-called on AArch64 when the OS does not support dynamic
3108  // pre-emption of symbols, as the AAELF spec requires normal calls
3109  // to undefined weak functions to be replaced with a NOP or jump to the
3110  // next instruction. The behaviour of branch instructions in this
3111  // situation (as used for tail calls) is implementation-defined, so we
3112  // cannot rely on the linker replacing the tail call with a return.
3113  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3114  const GlobalValue *GV = G->getGlobal();
3115  const Triple &TT = getTargetMachine().getTargetTriple();
3116  if (GV->hasExternalWeakLinkage() &&
3117  (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3118  return false;
3119  }
3120 
3121  // Now we search for cases where we can use a tail call without changing the
3122  // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3123  // concept.
3124 
3125  // I want anyone implementing a new calling convention to think long and hard
3126  // about this assert.
3127  assert((!isVarArg || CalleeCC == CallingConv::C) &&
3128  "Unexpected variadic calling convention");
3129 
3130  LLVMContext &C = *DAG.getContext();
3131  if (isVarArg && !Outs.empty()) {
3132  // At least two cases here: if caller is fastcc then we can't have any
3133  // memory arguments (we'd be expected to clean up the stack afterwards). If
3134  // caller is C then we could potentially use its argument area.
3135 
3136  // FIXME: for now we take the most conservative of these in both cases:
3137  // disallow all variadic memory operands.
3139  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3140 
3141  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3142  for (const CCValAssign &ArgLoc : ArgLocs)
3143  if (!ArgLoc.isRegLoc())
3144  return false;
3145  }
3146 
3147  // Check that the call results are passed in the same way.
3148  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3149  CCAssignFnForCall(CalleeCC, isVarArg),
3150  CCAssignFnForCall(CallerCC, isVarArg)))
3151  return false;
3152  // The callee has to preserve all registers the caller needs to preserve.
3153  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3154  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3155  if (!CCMatch) {
3156  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3157  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3158  return false;
3159  }
3160 
3161  // Nothing more to check if the callee is taking no arguments
3162  if (Outs.empty())
3163  return true;
3164 
3166  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3167 
3168  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3169 
3170  const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3171 
3172  // If the stack arguments for this call do not fit into our own save area then
3173  // the call cannot be made tail.
3174  if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3175  return false;
3176 
3177  const MachineRegisterInfo &MRI = MF.getRegInfo();
3178  if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3179  return false;
3180 
3181  return true;
3182 }
3183 
3184 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3185  SelectionDAG &DAG,
3186  MachineFrameInfo &MFI,
3187  int ClobberedFI) const {
3188  SmallVector<SDValue, 8> ArgChains;
3189  int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3190  int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3191 
3192  // Include the original chain at the beginning of the list. When this is
3193  // used by target LowerCall hooks, this helps legalize find the
3194  // CALLSEQ_BEGIN node.
3195  ArgChains.push_back(Chain);
3196 
3197  // Add a chain value for each stack argument corresponding
3198  for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3199  UE = DAG.getEntryNode().getNode()->use_end();
3200  U != UE; ++U)
3201  if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3202  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3203  if (FI->getIndex() < 0) {
3204  int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3205  int64_t InLastByte = InFirstByte;
3206  InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3207 
3208  if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3209  (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3210  ArgChains.push_back(SDValue(L, 1));
3211  }
3212 
3213  // Build a tokenfactor for all the chains.
3214  return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3215 }
3216 
3217 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3218  bool TailCallOpt) const {
3219  return CallCC == CallingConv::Fast && TailCallOpt;
3220 }
3221 
3222 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3223 /// and add input and output parameter nodes.
3224 SDValue
3225 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3226  SmallVectorImpl<SDValue> &InVals) const {
3227  SelectionDAG &DAG = CLI.DAG;
3228  SDLoc &DL = CLI.DL;
3229  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3230  SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3231  SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3232  SDValue Chain = CLI.Chain;
3233  SDValue Callee = CLI.Callee;
3234  bool &IsTailCall = CLI.IsTailCall;
3235  CallingConv::ID CallConv = CLI.CallConv;
3236  bool IsVarArg = CLI.IsVarArg;
3237 
3238  MachineFunction &MF = DAG.getMachineFunction();
3239  bool IsThisReturn = false;
3240 
3242  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3243  bool IsSibCall = false;
3244 
3245  if (IsTailCall) {
3246  // Check if it's really possible to do a tail call.
3247  IsTailCall = isEligibleForTailCallOptimization(
3248  Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3249  if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3250  report_fatal_error("failed to perform tail call elimination on a call "
3251  "site marked musttail");
3252 
3253  // A sibling call is one where we're under the usual C ABI and not planning
3254  // to change that but can still do a tail call:
3255  if (!TailCallOpt && IsTailCall)
3256  IsSibCall = true;
3257 
3258  if (IsTailCall)
3259  ++NumTailCalls;
3260  }
3261 
3262  // Analyze operands of the call, assigning locations to each operand.
3264  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3265  *DAG.getContext());
3266 
3267  if (IsVarArg) {
3268  // Handle fixed and variable vector arguments differently.
3269  // Variable vector arguments always go into memory.
3270  unsigned NumArgs = Outs.size();
3271 
3272  for (unsigned i = 0; i != NumArgs; ++i) {
3273  MVT ArgVT = Outs[i].VT;
3274  ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3275  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3276  /*IsVarArg=*/ !Outs[i].IsFixed);
3277  bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3278  assert(!Res && "Call operand has unhandled type");
3279  (void)Res;
3280  }
3281  } else {
3282  // At this point, Outs[].VT may already be promoted to i32. To correctly
3283  // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3284  // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3285  // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3286  // we use a special version of AnalyzeCallOperands to pass in ValVT and
3287  // LocVT.
3288  unsigned NumArgs = Outs.size();
3289  for (unsigned i = 0; i != NumArgs; ++i) {
3290  MVT ValVT = Outs[i].VT;
3291  // Get type of the original argument.
3292  EVT ActualVT = getValueType(DAG.getDataLayout(),
3293  CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3294  /*AllowUnknown*/ true);
3295  MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3296  ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3297  // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3298  if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3299  ValVT = MVT::i8;
3300  else if (ActualMVT == MVT::i16)
3301  ValVT = MVT::i16;
3302 
3303  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3304  bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3305  assert(!Res && "Call operand has unhandled type");
3306  (void)Res;
3307  }
3308  }
3309 
3310  // Get a count of how many bytes are to be pushed on the stack.
3311  unsigned NumBytes = CCInfo.getNextStackOffset();
3312 
3313  if (IsSibCall) {
3314  // Since we're not changing the ABI to make this a tail call, the memory
3315  // operands are already available in the caller's incoming argument space.
3316  NumBytes = 0;
3317  }
3318 
3319  // FPDiff is the byte offset of the call's argument area from the callee's.
3320  // Stores to callee stack arguments will be placed in FixedStackSlots offset
3321  // by this amount for a tail call. In a sibling call it must be 0 because the
3322  // caller will deallocate the entire stack and the callee still expects its
3323  // arguments to begin at SP+0. Completely unused for non-tail calls.
3324  int FPDiff = 0;
3325 
3326  if (IsTailCall && !IsSibCall) {
3327  unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3328 
3329  // Since callee will pop argument stack as a tail call, we must keep the
3330  // popped size 16-byte aligned.
3331  NumBytes = alignTo(NumBytes, 16);
3332 
3333  // FPDiff will be negative if this tail call requires more space than we
3334  // would automatically have in our incoming argument space. Positive if we
3335  // can actually shrink the stack.
3336  FPDiff = NumReusableBytes - NumBytes;
3337 
3338  // The stack pointer must be 16-byte aligned at all times it's used for a
3339  // memory operation, which in practice means at *all* times and in
3340  // particular across call boundaries. Therefore our own arguments started at
3341  // a 16-byte aligned SP and the delta applied for the tail call should
3342  // satisfy the same constraint.
3343  assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3344  }
3345 
3346  // Adjust the stack pointer for the new arguments...
3347  // These operations are automatically eliminated by the prolog/epilog pass
3348  if (!IsSibCall)
3349  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3350 
3351  SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3352  getPointerTy(DAG.getDataLayout()));
3353 
3355  SmallVector<SDValue, 8> MemOpChains;
3356  auto PtrVT = getPointerTy(DAG.getDataLayout());
3357 
3358  // Walk the register/memloc assignments, inserting copies/loads.
3359  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3360  ++i, ++realArgIdx) {
3361  CCValAssign &VA = ArgLocs[i];
3362  SDValue Arg = OutVals[realArgIdx];
3363  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3364 
3365  // Promote the value if needed.
3366  switch (VA.getLocInfo()) {
3367  default:
3368  llvm_unreachable("Unknown loc info!");
3369  case CCValAssign::Full:
3370  break;
3371  case CCValAssign::SExt:
3372  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3373  break;
3374  case CCValAssign::ZExt:
3375  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3376  break;
3377  case CCValAssign::AExt:
3378  if (Outs[realArgIdx].ArgVT == MVT::i1) {
3379  // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3380  Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3381  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3382  }
3383  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3384  break;
3385  case CCValAssign::BCvt:
3386  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3387  break;
3388  case CCValAssign::FPExt:
3389  Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3390  break;
3391  }
3392 
3393  if (VA.isRegLoc()) {
3394  if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3395  Outs[0].VT == MVT::i64) {
3396  assert(VA.getLocVT() == MVT::i64 &&
3397  "unexpected calling convention register assignment");
3398  assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3399  "unexpected use of 'returned'");
3400  IsThisReturn = true;
3401  }
3402  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3403  } else {
3404  assert(VA.isMemLoc());
3405 
3406  SDValue DstAddr;
3407  MachinePointerInfo DstInfo;
3408 
3409  // FIXME: This works on big-endian for composite byvals, which are the
3410  // common case. It should also work for fundamental types too.
3411  uint32_t BEAlign = 0;
3412  unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3413  : VA.getValVT().getSizeInBits();
3414  OpSize = (OpSize + 7) / 8;
3415  if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3416  !Flags.isInConsecutiveRegs()) {
3417  if (OpSize < 8)
3418  BEAlign = 8 - OpSize;
3419  }
3420  unsigned LocMemOffset = VA.getLocMemOffset();
3421  int32_t Offset = LocMemOffset + BEAlign;
3422  SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3423  PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3424 
3425  if (IsTailCall) {
3426  Offset = Offset + FPDiff;
3427  int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3428 
3429  DstAddr = DAG.getFrameIndex(FI, PtrVT);
3430  DstInfo =
3432 
3433  // Make sure any stack arguments overlapping with where we're storing
3434  // are loaded before this eventual operation. Otherwise they'll be
3435  // clobbered.
3436  Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3437  } else {
3438  SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3439 
3440  DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3442  LocMemOffset);
3443  }
3444 
3445  if (Outs[i].Flags.isByVal()) {
3446  SDValue SizeNode =
3447  DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3448  SDValue Cpy = DAG.getMemcpy(
3449  Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3450  /*isVol = */ false, /*AlwaysInline = */ false,
3451  /*isTailCall = */ false,
3452  DstInfo, MachinePointerInfo());
3453 
3454  MemOpChains.push_back(Cpy);
3455  } else {
3456  // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3457  // promoted to a legal register type i32, we should truncate Arg back to
3458  // i1/i8/i16.
3459  if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3460  VA.getValVT() == MVT::i16)
3461  Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3462 
3463  SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3464  MemOpChains.push_back(Store);
3465  }
3466  }
3467  }
3468 
3469  if (!MemOpChains.empty())
3470  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3471 
3472  // Build a sequence of copy-to-reg nodes chained together with token chain
3473  // and flag operands which copy the outgoing args into the appropriate regs.
3474  SDValue InFlag;
3475  for (auto &RegToPass : RegsToPass) {
3476  Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3477  RegToPass.second, InFlag);
3478  InFlag = Chain.getValue(1);
3479  }
3480 
3481  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3482  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3483  // node so that legalize doesn't hack it.
3484  if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3485  auto GV = G->getGlobal();
3486  if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3488  Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3489  Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3490  } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3491  assert(Subtarget->isTargetWindows() &&
3492  "Windows is the only supported COFF target");
3493  Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3494  } else {
3495  const GlobalValue *GV = G->getGlobal();
3496  Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3497  }
3498  } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3499  if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3500  Subtarget->isTargetMachO()) {
3501  const char *Sym = S->getSymbol();
3502  Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3503  Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3504  } else {
3505  const char *Sym = S->getSymbol();
3506  Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3507  }
3508  }
3509 
3510  // We don't usually want to end the call-sequence here because we would tidy
3511  // the frame up *after* the call, however in the ABI-changing tail-call case
3512  // we've carefully laid out the parameters so that when sp is reset they'll be
3513  // in the correct location.
3514  if (IsTailCall && !IsSibCall) {
3515  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3516  DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3517  InFlag = Chain.getValue(1);
3518  }
3519 
3520  std::vector<SDValue> Ops;
3521  Ops.push_back(Chain);
3522  Ops.push_back(Callee);
3523 
3524  if (IsTailCall) {
3525  // Each tail call may have to adjust the stack by a different amount, so
3526  // this information must travel along with the operation for eventual
3527  // consumption by emitEpilogue.
3528  Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3529  }
3530 
3531  // Add argument registers to the end of the list so that they are known live
3532  // into the call.
3533  for (auto &RegToPass : RegsToPass)
3534  Ops.push_back(DAG.getRegister(RegToPass.first,
3535  RegToPass.second.getValueType()));
3536 
3537  // Add a register mask operand representing the call-preserved registers.
3538  const uint32_t *Mask;
3539  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3540  if (IsThisReturn) {
3541  // For 'this' returns, use the X0-preserving mask if applicable
3542  Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3543  if (!Mask) {
3544  IsThisReturn = false;
3545  Mask = TRI->getCallPreservedMask(MF, CallConv);
3546  }
3547  } else
3548  Mask = TRI->getCallPreservedMask(MF, CallConv);
3549 
3550  assert(Mask && "Missing call preserved mask for calling convention");
3551  Ops.push_back(DAG.getRegisterMask(Mask));
3552 
3553  if (InFlag.getNode())
3554  Ops.push_back(InFlag);
3555 
3556  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3557 
3558  // If we're doing a tall call, use a TC_RETURN here rather than an
3559  // actual call instruction.
3560  if (IsTailCall) {
3562  return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3563  }
3564 
3565  // Returns a chain and a flag for retval copy to use.
3566  Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3567  InFlag = Chain.getValue(1);
3568 
3569  uint64_t CalleePopBytes =
3570  DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3571 
3572  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3573  DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3574  InFlag, DL);
3575  if (!Ins.empty())
3576  InFlag = Chain.getValue(1);
3577 
3578  // Handle result values, copying them out of physregs into vregs that we
3579  // return.
3580  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3581  InVals, IsThisReturn,
3582  IsThisReturn ? OutVals[0] : SDValue());
3583 }
3584 
3585 bool AArch64TargetLowering::CanLowerReturn(
3586  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3587  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3588  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3589  ? RetCC_AArch64_WebKit_JS
3590  : RetCC_AArch64_AAPCS;
3592  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3593  return CCInfo.CheckReturn(Outs, RetCC);
3594 }
3595 
3596 SDValue
3597 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3598  bool isVarArg,
3599  const SmallVectorImpl<ISD::OutputArg> &Outs,
3600  const SmallVectorImpl<SDValue> &OutVals,
3601  const SDLoc &DL, SelectionDAG &DAG) const {
3602  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3603  ? RetCC_AArch64_WebKit_JS
3604  : RetCC_AArch64_AAPCS;
3606  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3607  *DAG.getContext());
3608  CCInfo.AnalyzeReturn(Outs, RetCC);
3609 
3610  // Copy the result values into the output registers.
3611  SDValue Flag;
3612  SmallVector<SDValue, 4> RetOps(1, Chain);
3613  for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3614  ++i, ++realRVLocIdx) {
3615  CCValAssign &VA = RVLocs[i];
3616  assert(VA.isRegLoc() && "Can only return in registers!");
3617  SDValue Arg = OutVals[realRVLocIdx];
3618 
3619  switch (VA.getLocInfo()) {
3620  default:
3621  llvm_unreachable("Unknown loc info!");
3622  case CCValAssign::Full:
3623  if (Outs[i].ArgVT == MVT::i1) {
3624  // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3625  // value. This is strictly redundant on Darwin (which uses "zeroext
3626  // i1"), but will be optimised out before ISel.
3627  Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3628  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3629  }
3630  break;
3631  case CCValAssign::BCvt:
3632  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3633  break;
3634  }
3635 
3636  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3637  Flag = Chain.getValue(1);
3638  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3639  }
3640  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3641  const MCPhysReg *I =
3643  if (I) {
3644  for (; *I; ++I) {
3645  if (AArch64::GPR64RegClass.contains(*I))
3646  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3647  else if (AArch64::FPR64RegClass.contains(*I))
3648  RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3649  else
3650  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3651  }
3652  }
3653 
3654  RetOps[0] = Chain; // Update chain.
3655 
3656  // Add the flag if we have it.
3657  if (Flag.getNode())
3658  RetOps.push_back(Flag);
3659 
3660  return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3661 }
3662 
3663 //===----------------------------------------------------------------------===//
3664 // Other Lowering Code
3665 //===----------------------------------------------------------------------===//
3666 
3667 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3668  SelectionDAG &DAG,
3669  unsigned Flag) const {
3670  return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3671 }
3672 
3673 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3674  SelectionDAG &DAG,
3675  unsigned Flag) const {
3676  return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3677 }
3678 
3679 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3680  SelectionDAG &DAG,
3681  unsigned Flag) const {
3682  return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3683  N->getOffset(), Flag);
3684 }
3685 
3686 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3687  SelectionDAG &DAG,
3688  unsigned Flag) const {
3689  return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3690 }
3691 
3692 // (loadGOT sym)
3693 template <class NodeTy>
3694 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3695  unsigned Flags) const {
3696  DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3697  SDLoc DL(N);
3698  EVT Ty = getPointerTy(DAG.getDataLayout());
3699  SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
3700  // FIXME: Once remat is capable of dealing with instructions with register
3701  // operands, expand this into two nodes instead of using a wrapper node.
3702  return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3703 }
3704 
3705 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3706 template <class NodeTy>
3707 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3708  unsigned Flags) const {
3709  DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3710  SDLoc DL(N);
3711  EVT Ty = getPointerTy(DAG.getDataLayout());
3712  const unsigned char MO_NC = AArch64II::MO_NC;
3713  return DAG.getNode(
3714  AArch64ISD::WrapperLarge, DL, Ty,
3715  getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3716  getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3717  getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3718  getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
3719 }
3720 
3721 // (addlow (adrp %hi(sym)) %lo(sym))
3722 template <class NodeTy>
3723 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3724  unsigned Flags) const {
3725  DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3726  SDLoc DL(N);
3727  EVT Ty = getPointerTy(DAG.getDataLayout());
3728  SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
3729  SDValue Lo = getTargetNode(N, Ty, DAG,
3731  SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3732  return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3733 }
3734 
3735 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3736  SelectionDAG &DAG) const {
3737  GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3738  const GlobalValue *GV = GN->getGlobal();
3739  const AArch64II::TOF TargetFlags =
3740  (GV->hasDLLImportStorageClass() ? AArch64II::MO_DLLIMPORT
3742  unsigned char OpFlags =
3743  Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3744 
3745  assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3746  "unexpected offset in global node");
3747 
3748  // This also catches the large code model case for Darwin.
3749  if ((OpFlags & AArch64II::MO_GOT) != 0) {
3750  return getGOT(GN, DAG, TargetFlags);
3751  }
3752 
3753  SDValue Result;
3754  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3755  Result = getAddrLarge(GN, DAG, TargetFlags);
3756  } else {
3757  Result = getAddr(GN, DAG, TargetFlags);
3758  }
3759  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3760  SDLoc DL(GN);
3761  if (GV->hasDLLImportStorageClass())
3762  Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3764  return Result;
3765 }
3766 
3767 /// \brief Convert a TLS address reference into the correct sequence of loads
3768 /// and calls to compute the variable's address (for Darwin, currently) and
3769 /// return an SDValue containing the final node.
3770 
3771 /// Darwin only has one TLS scheme which must be capable of dealing with the
3772 /// fully general situation, in the worst case. This means:
3773 /// + "extern __thread" declaration.
3774 /// + Defined in a possibly unknown dynamic library.
3775 ///
3776 /// The general system is that each __thread variable has a [3 x i64] descriptor
3777 /// which contains information used by the runtime to calculate the address. The
3778 /// only part of this the compiler needs to know about is the first xword, which
3779 /// contains a function pointer that must be called with the address of the
3780 /// entire descriptor in "x0".
3781 ///
3782 /// Since this descriptor may be in a different unit, in general even the
3783 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3784 /// is:
3785 /// adrp x0, _var@TLVPPAGE
3786 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3787 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3788 /// ; the function pointer
3789 /// blr x1 ; Uses descriptor address in x0
3790 /// ; Address of _var is now in x0.
3791 ///
3792 /// If the address of _var's descriptor *is* known to the linker, then it can
3793 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3794 /// a slight efficiency gain.
3795 SDValue
3796 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3797  SelectionDAG &DAG) const {
3798  assert(Subtarget->isTargetDarwin() &&
3799  "This function expects a Darwin target");
3800 
3801  SDLoc DL(Op);
3802  MVT PtrVT = getPointerTy(DAG.getDataLayout());
3803  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3804 
3805  SDValue TLVPAddr =
3806  DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3807  SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3808 
3809  // The first entry in the descriptor is a function pointer that we must call
3810  // to obtain the address of the variable.
3811  SDValue Chain = DAG.getEntryNode();
3812  SDValue FuncTLVGet = DAG.getLoad(
3813  MVT::i64, DL, Chain, DescAddr,
3815  /* Alignment = */ 8,
3818  Chain = FuncTLVGet.getValue(1);
3819 
3821  MFI.setAdjustsStack(true);
3822 
3823  // TLS calls preserve all registers except those that absolutely must be
3824  // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3825  // silly).
3826  const uint32_t *Mask =
3827  Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3828 
3829  // Finally, we can make the call. This is just a degenerate version of a
3830  // normal AArch64 call node: x0 takes the address of the descriptor, and
3831  // returns the address of the variable in this thread.
3832  Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3833  Chain =
3835  Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3836  DAG.getRegisterMask(Mask), Chain.getValue(1));
3837  return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3838 }
3839 
3840 /// When accessing thread-local variables under either the general-dynamic or
3841 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3842 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3843 /// is a function pointer to carry out the resolution.
3844 ///
3845 /// The sequence is:
3846 /// adrp x0, :tlsdesc:var
3847 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3848 /// add x0, x0, #:tlsdesc_lo12:var
3849 /// .tlsdesccall var
3850 /// blr x1
3851 /// (TPIDR_EL0 offset now in x0)
3852 ///
3853 /// The above sequence must be produced unscheduled, to enable the linker to
3854 /// optimize/relax this sequence.
3855 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3856 /// above sequence, and expanded really late in the compilation flow, to ensure
3857 /// the sequence is produced as per above.
3858 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3859  const SDLoc &DL,
3860  SelectionDAG &DAG) const {
3861  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3862 
3863  SDValue Chain = DAG.getEntryNode();
3864  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3865 
3866  Chain =
3867  DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3868  SDValue Glue = Chain.getValue(1);
3869 
3870  return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3871 }
3872 
3873 SDValue
3874 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3875  SelectionDAG &DAG) const {
3876  assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3877  assert(Subtarget->useSmallAddressing() &&
3878  "ELF TLS only supported in small memory model");
3879  // Different choices can be made for the maximum size of the TLS area for a
3880  // module. For the small address model, the default TLS size is 16MiB and the
3881  // maximum TLS size is 4GiB.
3882  // FIXME: add -mtls-size command line option and make it control the 16MiB
3883  // vs. 4GiB code sequence generation.
3884  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3885 
3886  TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3887 
3889  if (Model == TLSModel::LocalDynamic)
3890  Model = TLSModel::GeneralDynamic;
3891  }
3892 
3893  SDValue TPOff;
3894  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3895  SDLoc DL(Op);
3896  const GlobalValue *GV = GA->getGlobal();
3897 
3898  SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3899 
3900  if (Model == TLSModel::LocalExec) {
3901  SDValue HiVar = DAG.getTargetGlobalAddress(
3902  GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3903  SDValue LoVar = DAG.getTargetGlobalAddress(
3904  GV, DL, PtrVT, 0,
3906 
3907  SDValue TPWithOff_lo =
3908  SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3909  HiVar,
3910  DAG.getTargetConstant(0, DL, MVT::i32)),
3911  0);
3912  SDValue TPWithOff =
3913  SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3914  LoVar,
3915  DAG.getTargetConstant(0, DL, MVT::i32)),
3916  0);
3917  return TPWithOff;
3918  } else if (Model == TLSModel::InitialExec) {
3919  TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3920  TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3921  } else if (Model == TLSModel::LocalDynamic) {
3922  // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3923  // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3924  // the beginning of the module's TLS region, followed by a DTPREL offset
3925  // calculation.
3926 
3927  // These accesses will need deduplicating if there's more than one.
3928  AArch64FunctionInfo *MFI =
3931 
3932  // The call needs a relocation too for linker relaxation. It doesn't make
3933  // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3934  // the address.
3935  SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3937 
3938  // Now we can calculate the offset from TPIDR_EL0 to this module's
3939  // thread-local area.
3940  TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3941 
3942  // Now use :dtprel_whatever: operations to calculate this variable's offset
3943  // in its thread-storage area.
3944  SDValue HiVar = DAG.getTargetGlobalAddress(
3946  SDValue LoVar = DAG.getTargetGlobalAddress(
3947  GV, DL, MVT::i64, 0,
3949 
3950  TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3951  DAG.getTargetConstant(0, DL, MVT::i32)),
3952  0);
3953  TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3954  DAG.getTargetConstant(0, DL, MVT::i32)),
3955  0);
3956  } else if (Model == TLSModel::GeneralDynamic) {
3957  // The call needs a relocation too for linker relaxation. It doesn't make
3958  // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3959  // the address.
3960  SDValue SymAddr =
3961  DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3962 
3963  // Finally we can make a call to calculate the offset from tpidr_el0.
3964  TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3965  } else
3966  llvm_unreachable("Unsupported ELF TLS access model");
3967 
3968  return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3969 }
3970 
3971 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3972  SelectionDAG &DAG) const {
3973  const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3974  if (DAG.getTarget().Options.EmulatedTLS)
3975  return LowerToTLSEmulatedModel(GA, DAG);
3976 
3977  if (Subtarget->isTargetDarwin())
3978  return LowerDarwinGlobalTLSAddress(Op, DAG);
3979  if (Subtarget->isTargetELF())
3980  return LowerELFGlobalTLSAddress(Op, DAG);
3981 
3982  llvm_unreachable("Unexpected platform trying to use TLS");
3983 }
3984 
3985 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3986  SDValue Chain = Op.getOperand(0);
3987  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3988  SDValue LHS = Op.getOperand(2);
3989  SDValue RHS = Op.getOperand(3);
3990  SDValue Dest = Op.getOperand(4);
3991  SDLoc dl(Op);
3992 
3993  // Handle f128 first, since lowering it will result in comparing the return
3994  // value of a libcall against zero, which is just what the rest of LowerBR_CC
3995  // is expecting to deal with.
3996  if (LHS.getValueType() == MVT::f128) {
3997  softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3998 
3999  // If softenSetCCOperands returned a scalar, we need to compare the result
4000  // against zero to select between true and false values.
4001  if (!RHS.getNode()) {
4002  RHS = DAG.getConstant(0, dl, LHS.getValueType());
4003  CC = ISD::SETNE;
4004  }
4005  }
4006 
4007  // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4008  // instruction.
4009  if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4010  (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4011  // Only lower legal XALUO ops.
4012  if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4013  return SDValue();
4014 
4015  // The actual operation with overflow check.
4016  AArch64CC::CondCode OFCC;
4017  SDValue Value, Overflow;
4018  std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4019 
4020  if (CC == ISD::SETNE)
4021  OFCC = getInvertedCondCode(OFCC);
4022  SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4023 
4024  return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4025  Overflow);
4026  }
4027 
4028  if (LHS.getValueType().isInteger()) {
4029  assert((LHS.getValueType() == RHS.getValueType()) &&
4030  (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4031 
4032  // If the RHS of the comparison is zero, we can potentially fold this
4033  // to a specialized branch.
4034  const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4035  if (RHSC && RHSC->getZExtValue() == 0) {
4036  if (CC == ISD::SETEQ) {
4037  // See if we can use a TBZ to fold in an AND as well.
4038  // TBZ has a smaller branch displacement than CBZ. If the offset is
4039  // out of bounds, a late MI-layer pass rewrites branches.
4040  // 403.gcc is an example that hits this case.
4041  if (LHS.getOpcode() == ISD::AND &&
4042  isa<ConstantSDNode>(LHS.getOperand(1)) &&
4044  SDValue Test = LHS.getOperand(0);
4045  uint64_t Mask = LHS.getConstantOperandVal(1);
4046  return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4047  DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4048  Dest);
4049  }
4050 
4051  return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4052  } else if (CC == ISD::SETNE) {
4053  // See if we can use a TBZ to fold in an AND as well.
4054  // TBZ has a smaller branch displacement than CBZ. If the offset is
4055  // out of bounds, a late MI-layer pass rewrites branches.
4056  // 403.gcc is an example that hits this case.
4057  if (LHS.getOpcode() == ISD::AND &&
4058  isa<ConstantSDNode>(LHS.getOperand(1)) &&
4060  SDValue Test = LHS.getOperand(0);
4061  uint64_t Mask = LHS.getConstantOperandVal(1);
4062  return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4063  DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4064  Dest);
4065  }
4066 
4067  return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4068  } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4069  // Don't combine AND since emitComparison converts the AND to an ANDS
4070  // (a.k.a. TST) and the test in the test bit and branch instruction
4071  // becomes redundant. This would also increase register pressure.
4072  uint64_t Mask = LHS.getValueSizeInBits() - 1;
4073  return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4074  DAG.getConstant(Mask, dl, MVT::i64), Dest);
4075  }
4076  }
4077  if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4078  LHS.getOpcode() != ISD::AND) {
4079  // Don't combine AND since emitComparison converts the AND to an ANDS
4080  // (a.k.a. TST) and the test in the test bit and branch instruction
4081  // becomes redundant. This would also increase register pressure.
4082  uint64_t Mask = LHS.getValueSizeInBits() - 1;
4083  return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4084  DAG.getConstant(Mask, dl, MVT::i64), Dest);
4085  }
4086 
4087  SDValue CCVal;
4088  SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4089  return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4090  Cmp);
4091  }
4092 
4093  assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4094  LHS.