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