1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the AArch64TargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "AArch64ISelLowering.h" 14 #include "AArch64CallingConvention.h" 15 #include "AArch64ExpandImm.h" 16 #include "AArch64MachineFunctionInfo.h" 17 #include "AArch64PerfectShuffle.h" 18 #include "AArch64RegisterInfo.h" 19 #include "AArch64Subtarget.h" 20 #include "MCTargetDesc/AArch64AddressingModes.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/SmallSet.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/Analysis/ObjCARCUtil.h" 33 #include "llvm/Analysis/VectorUtils.h" 34 #include "llvm/CodeGen/CallingConvLower.h" 35 #include "llvm/CodeGen/MachineBasicBlock.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineInstr.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineMemOperand.h" 41 #include "llvm/CodeGen/MachineRegisterInfo.h" 42 #include "llvm/CodeGen/RuntimeLibcalls.h" 43 #include "llvm/CodeGen/SelectionDAG.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/TargetCallingConv.h" 46 #include "llvm/CodeGen/TargetInstrInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Attributes.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GetElementPtrTypeIterator.h" 55 #include "llvm/IR/GlobalValue.h" 56 #include "llvm/IR/IRBuilder.h" 57 #include "llvm/IR/Instruction.h" 58 #include "llvm/IR/Instructions.h" 59 #include "llvm/IR/IntrinsicInst.h" 60 #include "llvm/IR/Intrinsics.h" 61 #include "llvm/IR/IntrinsicsAArch64.h" 62 #include "llvm/IR/Module.h" 63 #include "llvm/IR/OperandTraits.h" 64 #include "llvm/IR/PatternMatch.h" 65 #include "llvm/IR/Type.h" 66 #include "llvm/IR/Use.h" 67 #include "llvm/IR/Value.h" 68 #include "llvm/MC/MCRegisterInfo.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/CodeGen.h" 71 #include "llvm/Support/CommandLine.h" 72 #include "llvm/Support/Compiler.h" 73 #include "llvm/Support/Debug.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Support/raw_ostream.h" 79 #include "llvm/Target/TargetMachine.h" 80 #include "llvm/Target/TargetOptions.h" 81 #include <algorithm> 82 #include <bitset> 83 #include <cassert> 84 #include <cctype> 85 #include <cstdint> 86 #include <cstdlib> 87 #include <iterator> 88 #include <limits> 89 #include <tuple> 90 #include <utility> 91 #include <vector> 92 93 using namespace llvm; 94 using namespace llvm::PatternMatch; 95 96 #define DEBUG_TYPE "aarch64-lower" 97 98 STATISTIC(NumTailCalls, "Number of tail calls"); 99 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 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. 105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 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 // Temporary option added for the purpose of testing functionality added 117 // to DAGCombiner.cpp in D92230. It is expected that this can be removed 118 // in future when both implementations will be based off MGATHER rather 119 // than the GLD1 nodes added for the SVE gather load intrinsics. 120 static cl::opt<bool> 121 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden, 122 cl::desc("Combine extends of AArch64 masked " 123 "gather intrinsics"), 124 cl::init(true)); 125 126 /// Value type used for condition codes. 127 static const MVT MVT_CC = MVT::i32; 128 129 static inline EVT getPackedSVEVectorVT(EVT VT) { 130 switch (VT.getSimpleVT().SimpleTy) { 131 default: 132 llvm_unreachable("unexpected element type for vector"); 133 case MVT::i8: 134 return MVT::nxv16i8; 135 case MVT::i16: 136 return MVT::nxv8i16; 137 case MVT::i32: 138 return MVT::nxv4i32; 139 case MVT::i64: 140 return MVT::nxv2i64; 141 case MVT::f16: 142 return MVT::nxv8f16; 143 case MVT::f32: 144 return MVT::nxv4f32; 145 case MVT::f64: 146 return MVT::nxv2f64; 147 case MVT::bf16: 148 return MVT::nxv8bf16; 149 } 150 } 151 152 // NOTE: Currently there's only a need to return integer vector types. If this 153 // changes then just add an extra "type" parameter. 154 static inline EVT getPackedSVEVectorVT(ElementCount EC) { 155 switch (EC.getKnownMinValue()) { 156 default: 157 llvm_unreachable("unexpected element count for vector"); 158 case 16: 159 return MVT::nxv16i8; 160 case 8: 161 return MVT::nxv8i16; 162 case 4: 163 return MVT::nxv4i32; 164 case 2: 165 return MVT::nxv2i64; 166 } 167 } 168 169 static inline EVT getPromotedVTForPredicate(EVT VT) { 170 assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) && 171 "Expected scalable predicate vector type!"); 172 switch (VT.getVectorMinNumElements()) { 173 default: 174 llvm_unreachable("unexpected element count for vector"); 175 case 2: 176 return MVT::nxv2i64; 177 case 4: 178 return MVT::nxv4i32; 179 case 8: 180 return MVT::nxv8i16; 181 case 16: 182 return MVT::nxv16i8; 183 } 184 } 185 186 /// Returns true if VT's elements occupy the lowest bit positions of its 187 /// associated register class without any intervening space. 188 /// 189 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the 190 /// same register class, but only nxv8f16 can be treated as a packed vector. 191 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) { 192 assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 193 "Expected legal vector type!"); 194 return VT.isFixedLengthVector() || 195 VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock; 196 } 197 198 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading 199 // predicate and end with a passthru value matching the result type. 200 static bool isMergePassthruOpcode(unsigned Opc) { 201 switch (Opc) { 202 default: 203 return false; 204 case AArch64ISD::BITREVERSE_MERGE_PASSTHRU: 205 case AArch64ISD::BSWAP_MERGE_PASSTHRU: 206 case AArch64ISD::CTLZ_MERGE_PASSTHRU: 207 case AArch64ISD::CTPOP_MERGE_PASSTHRU: 208 case AArch64ISD::DUP_MERGE_PASSTHRU: 209 case AArch64ISD::ABS_MERGE_PASSTHRU: 210 case AArch64ISD::NEG_MERGE_PASSTHRU: 211 case AArch64ISD::FNEG_MERGE_PASSTHRU: 212 case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU: 213 case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU: 214 case AArch64ISD::FCEIL_MERGE_PASSTHRU: 215 case AArch64ISD::FFLOOR_MERGE_PASSTHRU: 216 case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU: 217 case AArch64ISD::FRINT_MERGE_PASSTHRU: 218 case AArch64ISD::FROUND_MERGE_PASSTHRU: 219 case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU: 220 case AArch64ISD::FTRUNC_MERGE_PASSTHRU: 221 case AArch64ISD::FP_ROUND_MERGE_PASSTHRU: 222 case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU: 223 case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU: 224 case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU: 225 case AArch64ISD::FCVTZU_MERGE_PASSTHRU: 226 case AArch64ISD::FCVTZS_MERGE_PASSTHRU: 227 case AArch64ISD::FSQRT_MERGE_PASSTHRU: 228 case AArch64ISD::FRECPX_MERGE_PASSTHRU: 229 case AArch64ISD::FABS_MERGE_PASSTHRU: 230 return true; 231 } 232 } 233 234 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 235 const AArch64Subtarget &STI) 236 : TargetLowering(TM), Subtarget(&STI) { 237 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 238 // we have to make something up. Arbitrarily, choose ZeroOrOne. 239 setBooleanContents(ZeroOrOneBooleanContent); 240 // When comparing vectors the result sets the different elements in the 241 // vector to all-one or all-zero. 242 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 243 244 // Set up the register classes. 245 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 246 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 247 248 if (Subtarget->hasFPARMv8()) { 249 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 250 addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass); 251 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 252 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 253 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 254 } 255 256 if (Subtarget->hasNEON()) { 257 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 258 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 259 // Someone set us up the NEON. 260 addDRTypeForNEON(MVT::v2f32); 261 addDRTypeForNEON(MVT::v8i8); 262 addDRTypeForNEON(MVT::v4i16); 263 addDRTypeForNEON(MVT::v2i32); 264 addDRTypeForNEON(MVT::v1i64); 265 addDRTypeForNEON(MVT::v1f64); 266 addDRTypeForNEON(MVT::v4f16); 267 if (Subtarget->hasBF16()) 268 addDRTypeForNEON(MVT::v4bf16); 269 270 addQRTypeForNEON(MVT::v4f32); 271 addQRTypeForNEON(MVT::v2f64); 272 addQRTypeForNEON(MVT::v16i8); 273 addQRTypeForNEON(MVT::v8i16); 274 addQRTypeForNEON(MVT::v4i32); 275 addQRTypeForNEON(MVT::v2i64); 276 addQRTypeForNEON(MVT::v8f16); 277 if (Subtarget->hasBF16()) 278 addQRTypeForNEON(MVT::v8bf16); 279 } 280 281 if (Subtarget->hasSVE()) { 282 // Add legal sve predicate types 283 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 284 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 285 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 286 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 287 288 // Add legal sve data types 289 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 290 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 291 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 292 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 293 294 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 295 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 296 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 297 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 298 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 299 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 300 301 if (Subtarget->hasBF16()) { 302 addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass); 303 addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass); 304 addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass); 305 } 306 307 if (Subtarget->useSVEForFixedLengthVectors()) { 308 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 309 if (useSVEForFixedLengthVectorVT(VT)) 310 addRegisterClass(VT, &AArch64::ZPRRegClass); 311 312 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 313 if (useSVEForFixedLengthVectorVT(VT)) 314 addRegisterClass(VT, &AArch64::ZPRRegClass); 315 } 316 317 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) { 318 setOperationAction(ISD::SADDSAT, VT, Legal); 319 setOperationAction(ISD::UADDSAT, VT, Legal); 320 setOperationAction(ISD::SSUBSAT, VT, Legal); 321 setOperationAction(ISD::USUBSAT, VT, Legal); 322 setOperationAction(ISD::UREM, VT, Expand); 323 setOperationAction(ISD::SREM, VT, Expand); 324 setOperationAction(ISD::SDIVREM, VT, Expand); 325 setOperationAction(ISD::UDIVREM, VT, Expand); 326 } 327 328 for (auto VT : 329 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8, 330 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 }) 331 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal); 332 333 for (auto VT : 334 { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32, 335 MVT::nxv2f64 }) { 336 setCondCodeAction(ISD::SETO, VT, Expand); 337 setCondCodeAction(ISD::SETOLT, VT, Expand); 338 setCondCodeAction(ISD::SETLT, VT, Expand); 339 setCondCodeAction(ISD::SETOLE, VT, Expand); 340 setCondCodeAction(ISD::SETLE, VT, Expand); 341 setCondCodeAction(ISD::SETULT, VT, Expand); 342 setCondCodeAction(ISD::SETULE, VT, Expand); 343 setCondCodeAction(ISD::SETUGE, VT, Expand); 344 setCondCodeAction(ISD::SETUGT, VT, Expand); 345 setCondCodeAction(ISD::SETUEQ, VT, Expand); 346 setCondCodeAction(ISD::SETUNE, VT, Expand); 347 } 348 } 349 350 // Compute derived properties from the register classes 351 computeRegisterProperties(Subtarget->getRegisterInfo()); 352 353 // Provide all sorts of operation actions 354 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 355 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 356 setOperationAction(ISD::SETCC, MVT::i32, Custom); 357 setOperationAction(ISD::SETCC, MVT::i64, Custom); 358 setOperationAction(ISD::SETCC, MVT::f16, Custom); 359 setOperationAction(ISD::SETCC, MVT::f32, Custom); 360 setOperationAction(ISD::SETCC, MVT::f64, Custom); 361 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 362 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 363 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 364 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 365 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 366 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 367 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 368 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 369 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 370 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 371 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 372 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 373 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 374 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 375 setOperationAction(ISD::SELECT, MVT::i32, Custom); 376 setOperationAction(ISD::SELECT, MVT::i64, Custom); 377 setOperationAction(ISD::SELECT, MVT::f16, Custom); 378 setOperationAction(ISD::SELECT, MVT::f32, Custom); 379 setOperationAction(ISD::SELECT, MVT::f64, Custom); 380 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 381 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 382 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 383 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 384 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 385 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 386 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 387 388 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 389 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 390 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 391 392 setOperationAction(ISD::FREM, MVT::f32, Expand); 393 setOperationAction(ISD::FREM, MVT::f64, Expand); 394 setOperationAction(ISD::FREM, MVT::f80, Expand); 395 396 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 397 398 // Custom lowering hooks are needed for XOR 399 // to fold it into CSINC/CSINV. 400 setOperationAction(ISD::XOR, MVT::i32, Custom); 401 setOperationAction(ISD::XOR, MVT::i64, Custom); 402 403 // Virtually no operation on f128 is legal, but LLVM can't expand them when 404 // there's a valid register class, so we need custom operations in most cases. 405 setOperationAction(ISD::FABS, MVT::f128, Expand); 406 setOperationAction(ISD::FADD, MVT::f128, LibCall); 407 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 408 setOperationAction(ISD::FCOS, MVT::f128, Expand); 409 setOperationAction(ISD::FDIV, MVT::f128, LibCall); 410 setOperationAction(ISD::FMA, MVT::f128, Expand); 411 setOperationAction(ISD::FMUL, MVT::f128, LibCall); 412 setOperationAction(ISD::FNEG, MVT::f128, Expand); 413 setOperationAction(ISD::FPOW, MVT::f128, Expand); 414 setOperationAction(ISD::FREM, MVT::f128, Expand); 415 setOperationAction(ISD::FRINT, MVT::f128, Expand); 416 setOperationAction(ISD::FSIN, MVT::f128, Expand); 417 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 418 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 419 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 420 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 421 setOperationAction(ISD::SETCC, MVT::f128, Custom); 422 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 423 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 424 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 425 setOperationAction(ISD::SELECT, MVT::f128, Custom); 426 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 427 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 428 429 // Lowering for many of the conversions is actually specified by the non-f128 430 // type. The LowerXXX function will be trivial when f128 isn't involved. 431 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 432 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 433 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 434 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 435 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 436 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom); 437 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 438 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 439 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 440 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 441 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 442 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom); 443 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 444 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 445 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 446 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 447 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 448 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom); 449 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 450 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 451 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 452 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 453 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 454 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom); 455 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 456 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 457 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 458 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom); 459 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 460 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom); 461 462 // Variable arguments. 463 setOperationAction(ISD::VASTART, MVT::Other, Custom); 464 setOperationAction(ISD::VAARG, MVT::Other, Custom); 465 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 466 setOperationAction(ISD::VAEND, MVT::Other, Expand); 467 468 // Variable-sized objects. 469 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 470 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 471 472 if (Subtarget->isTargetWindows()) 473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 474 else 475 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 476 477 // Constant pool entries 478 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 479 480 // BlockAddress 481 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 482 483 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 484 setOperationAction(ISD::ADDC, MVT::i32, Custom); 485 setOperationAction(ISD::ADDE, MVT::i32, Custom); 486 setOperationAction(ISD::SUBC, MVT::i32, Custom); 487 setOperationAction(ISD::SUBE, MVT::i32, Custom); 488 setOperationAction(ISD::ADDC, MVT::i64, Custom); 489 setOperationAction(ISD::ADDE, MVT::i64, Custom); 490 setOperationAction(ISD::SUBC, MVT::i64, Custom); 491 setOperationAction(ISD::SUBE, MVT::i64, Custom); 492 493 // AArch64 lacks both left-rotate and popcount instructions. 494 setOperationAction(ISD::ROTL, MVT::i32, Expand); 495 setOperationAction(ISD::ROTL, MVT::i64, Expand); 496 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 497 setOperationAction(ISD::ROTL, VT, Expand); 498 setOperationAction(ISD::ROTR, VT, Expand); 499 } 500 501 // AArch64 doesn't have i32 MULH{S|U}. 502 setOperationAction(ISD::MULHU, MVT::i32, Expand); 503 setOperationAction(ISD::MULHS, MVT::i32, Expand); 504 505 // AArch64 doesn't have {U|S}MUL_LOHI. 506 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 507 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 508 509 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 510 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 511 setOperationAction(ISD::CTPOP, MVT::i128, Custom); 512 513 setOperationAction(ISD::ABS, MVT::i32, Custom); 514 setOperationAction(ISD::ABS, MVT::i64, Custom); 515 516 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 517 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 518 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 519 setOperationAction(ISD::SDIVREM, VT, Expand); 520 setOperationAction(ISD::UDIVREM, VT, Expand); 521 } 522 setOperationAction(ISD::SREM, MVT::i32, Expand); 523 setOperationAction(ISD::SREM, MVT::i64, Expand); 524 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 525 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 526 setOperationAction(ISD::UREM, MVT::i32, Expand); 527 setOperationAction(ISD::UREM, MVT::i64, Expand); 528 529 // Custom lower Add/Sub/Mul with overflow. 530 setOperationAction(ISD::SADDO, MVT::i32, Custom); 531 setOperationAction(ISD::SADDO, MVT::i64, Custom); 532 setOperationAction(ISD::UADDO, MVT::i32, Custom); 533 setOperationAction(ISD::UADDO, MVT::i64, Custom); 534 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 535 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 536 setOperationAction(ISD::USUBO, MVT::i32, Custom); 537 setOperationAction(ISD::USUBO, MVT::i64, Custom); 538 setOperationAction(ISD::SMULO, MVT::i32, Custom); 539 setOperationAction(ISD::SMULO, MVT::i64, Custom); 540 setOperationAction(ISD::UMULO, MVT::i32, Custom); 541 setOperationAction(ISD::UMULO, MVT::i64, Custom); 542 543 setOperationAction(ISD::FSIN, MVT::f32, Expand); 544 setOperationAction(ISD::FSIN, MVT::f64, Expand); 545 setOperationAction(ISD::FCOS, MVT::f32, Expand); 546 setOperationAction(ISD::FCOS, MVT::f64, Expand); 547 setOperationAction(ISD::FPOW, MVT::f32, Expand); 548 setOperationAction(ISD::FPOW, MVT::f64, Expand); 549 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 550 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 551 if (Subtarget->hasFullFP16()) 552 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 553 else 554 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 555 556 setOperationAction(ISD::FREM, MVT::f16, Promote); 557 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 558 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 559 setOperationAction(ISD::FPOW, MVT::f16, Promote); 560 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 561 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 562 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 563 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 564 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 565 setOperationAction(ISD::FCOS, MVT::f16, Promote); 566 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 567 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 568 setOperationAction(ISD::FSIN, MVT::f16, Promote); 569 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 570 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 571 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 572 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 573 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 574 setOperationAction(ISD::FEXP, MVT::f16, Promote); 575 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 576 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 577 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 578 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 579 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 580 setOperationAction(ISD::FLOG, MVT::f16, Promote); 581 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 582 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 583 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 584 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 585 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 586 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 587 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 588 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 589 590 if (!Subtarget->hasFullFP16()) { 591 setOperationAction(ISD::SELECT, MVT::f16, Promote); 592 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 593 setOperationAction(ISD::SETCC, MVT::f16, Promote); 594 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 595 setOperationAction(ISD::FADD, MVT::f16, Promote); 596 setOperationAction(ISD::FSUB, MVT::f16, Promote); 597 setOperationAction(ISD::FMUL, MVT::f16, Promote); 598 setOperationAction(ISD::FDIV, MVT::f16, Promote); 599 setOperationAction(ISD::FMA, MVT::f16, Promote); 600 setOperationAction(ISD::FNEG, MVT::f16, Promote); 601 setOperationAction(ISD::FABS, MVT::f16, Promote); 602 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 603 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 604 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 605 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 606 setOperationAction(ISD::FRINT, MVT::f16, Promote); 607 setOperationAction(ISD::FROUND, MVT::f16, Promote); 608 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote); 609 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 610 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 611 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 612 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 613 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 614 615 // promote v4f16 to v4f32 when that is known to be safe. 616 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 617 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 618 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 619 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 620 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 621 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 622 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 623 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 624 625 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 626 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 627 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 628 setOperationAction(ISD::FROUNDEVEN, MVT::v4f16, Expand); 629 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 630 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 631 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 632 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 633 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 634 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 635 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 636 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 637 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 638 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 639 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 640 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 641 642 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 643 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 644 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 645 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 646 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 647 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 648 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 649 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 650 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 651 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 652 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 653 setOperationAction(ISD::FROUNDEVEN, MVT::v8f16, Expand); 654 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 655 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 656 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 657 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 658 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 659 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 660 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 661 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 662 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 663 } 664 665 // AArch64 has implementations of a lot of rounding-like FP operations. 666 for (MVT Ty : {MVT::f32, MVT::f64}) { 667 setOperationAction(ISD::FFLOOR, Ty, Legal); 668 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 669 setOperationAction(ISD::FCEIL, Ty, Legal); 670 setOperationAction(ISD::FRINT, Ty, Legal); 671 setOperationAction(ISD::FTRUNC, Ty, Legal); 672 setOperationAction(ISD::FROUND, Ty, Legal); 673 setOperationAction(ISD::FROUNDEVEN, Ty, Legal); 674 setOperationAction(ISD::FMINNUM, Ty, Legal); 675 setOperationAction(ISD::FMAXNUM, Ty, Legal); 676 setOperationAction(ISD::FMINIMUM, Ty, Legal); 677 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 678 setOperationAction(ISD::LROUND, Ty, Legal); 679 setOperationAction(ISD::LLROUND, Ty, Legal); 680 setOperationAction(ISD::LRINT, Ty, Legal); 681 setOperationAction(ISD::LLRINT, Ty, Legal); 682 } 683 684 if (Subtarget->hasFullFP16()) { 685 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 686 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 687 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 688 setOperationAction(ISD::FRINT, MVT::f16, Legal); 689 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 690 setOperationAction(ISD::FROUND, MVT::f16, Legal); 691 setOperationAction(ISD::FROUNDEVEN, MVT::f16, Legal); 692 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 693 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 694 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 695 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 696 } 697 698 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 699 700 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 701 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 702 703 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 704 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 705 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 706 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 707 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 708 709 // Generate outline atomics library calls only if LSE was not specified for 710 // subtarget 711 if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) { 712 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall); 713 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall); 714 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall); 715 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall); 716 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall); 717 setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall); 718 setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall); 719 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall); 720 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall); 721 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall); 722 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall); 723 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall); 724 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall); 725 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall); 726 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall); 727 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall); 728 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall); 729 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall); 730 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall); 731 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall); 732 setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall); 733 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall); 734 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall); 735 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall); 736 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall); 737 #define LCALLNAMES(A, B, N) \ 738 setLibcallName(A##N##_RELAX, #B #N "_relax"); \ 739 setLibcallName(A##N##_ACQ, #B #N "_acq"); \ 740 setLibcallName(A##N##_REL, #B #N "_rel"); \ 741 setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel"); 742 #define LCALLNAME4(A, B) \ 743 LCALLNAMES(A, B, 1) \ 744 LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) 745 #define LCALLNAME5(A, B) \ 746 LCALLNAMES(A, B, 1) \ 747 LCALLNAMES(A, B, 2) \ 748 LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16) 749 LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas) 750 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp) 751 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd) 752 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset) 753 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr) 754 LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor) 755 #undef LCALLNAMES 756 #undef LCALLNAME4 757 #undef LCALLNAME5 758 } 759 760 // 128-bit loads and stores can be done without expanding 761 setOperationAction(ISD::LOAD, MVT::i128, Custom); 762 setOperationAction(ISD::STORE, MVT::i128, Custom); 763 764 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the 765 // custom lowering, as there are no un-paired non-temporal stores and 766 // legalization will break up 256 bit inputs. 767 setOperationAction(ISD::STORE, MVT::v32i8, Custom); 768 setOperationAction(ISD::STORE, MVT::v16i16, Custom); 769 setOperationAction(ISD::STORE, MVT::v16f16, Custom); 770 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 771 setOperationAction(ISD::STORE, MVT::v8f32, Custom); 772 setOperationAction(ISD::STORE, MVT::v4f64, Custom); 773 setOperationAction(ISD::STORE, MVT::v4i64, Custom); 774 775 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 776 // This requires the Performance Monitors extension. 777 if (Subtarget->hasPerfMon()) 778 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 779 780 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 781 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 782 // Issue __sincos_stret if available. 783 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 784 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 785 } else { 786 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 787 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 788 } 789 790 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 791 // MSVCRT doesn't have powi; fall back to pow 792 setLibcallName(RTLIB::POWI_F32, nullptr); 793 setLibcallName(RTLIB::POWI_F64, nullptr); 794 } 795 796 // Make floating-point constants legal for the large code model, so they don't 797 // become loads from the constant pool. 798 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 799 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 800 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 801 } 802 803 // AArch64 does not have floating-point extending loads, i1 sign-extending 804 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 805 for (MVT VT : MVT::fp_valuetypes()) { 806 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 807 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 808 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 809 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 810 } 811 for (MVT VT : MVT::integer_valuetypes()) 812 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 813 814 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 815 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 816 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 817 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 818 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 819 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 820 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 821 822 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 823 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 824 setOperationAction(ISD::BITCAST, MVT::bf16, Custom); 825 826 // Indexed loads and stores are supported. 827 for (unsigned im = (unsigned)ISD::PRE_INC; 828 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 829 setIndexedLoadAction(im, MVT::i8, Legal); 830 setIndexedLoadAction(im, MVT::i16, Legal); 831 setIndexedLoadAction(im, MVT::i32, Legal); 832 setIndexedLoadAction(im, MVT::i64, Legal); 833 setIndexedLoadAction(im, MVT::f64, Legal); 834 setIndexedLoadAction(im, MVT::f32, Legal); 835 setIndexedLoadAction(im, MVT::f16, Legal); 836 setIndexedLoadAction(im, MVT::bf16, Legal); 837 setIndexedStoreAction(im, MVT::i8, Legal); 838 setIndexedStoreAction(im, MVT::i16, Legal); 839 setIndexedStoreAction(im, MVT::i32, Legal); 840 setIndexedStoreAction(im, MVT::i64, Legal); 841 setIndexedStoreAction(im, MVT::f64, Legal); 842 setIndexedStoreAction(im, MVT::f32, Legal); 843 setIndexedStoreAction(im, MVT::f16, Legal); 844 setIndexedStoreAction(im, MVT::bf16, Legal); 845 } 846 847 // Trap. 848 setOperationAction(ISD::TRAP, MVT::Other, Legal); 849 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 850 setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal); 851 852 // We combine OR nodes for bitfield operations. 853 setTargetDAGCombine(ISD::OR); 854 // Try to create BICs for vector ANDs. 855 setTargetDAGCombine(ISD::AND); 856 857 // Vector add and sub nodes may conceal a high-half opportunity. 858 // Also, try to fold ADD into CSINC/CSINV.. 859 setTargetDAGCombine(ISD::ADD); 860 setTargetDAGCombine(ISD::ABS); 861 setTargetDAGCombine(ISD::SUB); 862 setTargetDAGCombine(ISD::SRL); 863 setTargetDAGCombine(ISD::XOR); 864 setTargetDAGCombine(ISD::SINT_TO_FP); 865 setTargetDAGCombine(ISD::UINT_TO_FP); 866 867 setTargetDAGCombine(ISD::FP_TO_SINT); 868 setTargetDAGCombine(ISD::FP_TO_UINT); 869 setTargetDAGCombine(ISD::FDIV); 870 871 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 872 873 setTargetDAGCombine(ISD::ANY_EXTEND); 874 setTargetDAGCombine(ISD::ZERO_EXTEND); 875 setTargetDAGCombine(ISD::SIGN_EXTEND); 876 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 877 setTargetDAGCombine(ISD::TRUNCATE); 878 setTargetDAGCombine(ISD::CONCAT_VECTORS); 879 setTargetDAGCombine(ISD::STORE); 880 if (Subtarget->supportsAddressTopByteIgnored()) 881 setTargetDAGCombine(ISD::LOAD); 882 883 setTargetDAGCombine(ISD::MUL); 884 885 setTargetDAGCombine(ISD::SELECT); 886 setTargetDAGCombine(ISD::VSELECT); 887 888 setTargetDAGCombine(ISD::INTRINSIC_VOID); 889 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 890 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 891 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 892 setTargetDAGCombine(ISD::VECREDUCE_ADD); 893 894 setTargetDAGCombine(ISD::GlobalAddress); 895 896 // In case of strict alignment, avoid an excessive number of byte wide stores. 897 MaxStoresPerMemsetOptSize = 8; 898 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 899 ? MaxStoresPerMemsetOptSize : 32; 900 901 MaxGluedStoresPerMemcpy = 4; 902 MaxStoresPerMemcpyOptSize = 4; 903 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 904 ? MaxStoresPerMemcpyOptSize : 16; 905 906 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 907 908 MaxLoadsPerMemcmpOptSize = 4; 909 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 910 ? MaxLoadsPerMemcmpOptSize : 8; 911 912 setStackPointerRegisterToSaveRestore(AArch64::SP); 913 914 setSchedulingPreference(Sched::Hybrid); 915 916 EnableExtLdPromotion = true; 917 918 // Set required alignment. 919 setMinFunctionAlignment(Align(4)); 920 // Set preferred alignments. 921 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 922 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 923 924 // Only change the limit for entries in a jump table if specified by 925 // the sub target, but not at the command line. 926 unsigned MaxJT = STI.getMaximumJumpTableSize(); 927 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 928 setMaximumJumpTableSize(MaxJT); 929 930 setHasExtractBitsInsn(true); 931 932 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 933 934 if (Subtarget->hasNEON()) { 935 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 936 // silliness like this: 937 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 938 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 939 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 940 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 941 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 942 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 943 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 944 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 945 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 946 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 947 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 948 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 949 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 950 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 951 setOperationAction(ISD::FROUNDEVEN, MVT::v1f64, Expand); 952 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 953 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 954 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 955 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 956 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 957 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 958 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 959 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 960 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 961 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 962 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 963 964 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 965 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 966 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 967 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 968 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 969 970 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 971 972 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 973 // elements smaller than i32, so promote the input to i32 first. 974 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 975 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 976 // i8 vector elements also need promotion to i32 for v8i8 977 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 978 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 979 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 980 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 981 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 982 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 983 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 984 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 985 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 986 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 987 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 988 989 if (Subtarget->hasFullFP16()) { 990 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 991 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 992 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 993 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 994 } else { 995 // when AArch64 doesn't have fullfp16 support, promote the input 996 // to i32 first. 997 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 998 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 999 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 1000 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 1001 } 1002 1003 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 1004 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 1005 1006 // AArch64 doesn't have MUL.2d: 1007 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 1008 // Custom handling for some quad-vector types to detect MULL. 1009 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 1010 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 1011 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 1012 1013 // Saturates 1014 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 1015 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 1016 setOperationAction(ISD::SADDSAT, VT, Legal); 1017 setOperationAction(ISD::UADDSAT, VT, Legal); 1018 setOperationAction(ISD::SSUBSAT, VT, Legal); 1019 setOperationAction(ISD::USUBSAT, VT, Legal); 1020 } 1021 1022 // Vector reductions 1023 for (MVT VT : { MVT::v4f16, MVT::v2f32, 1024 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 1025 if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) { 1026 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1027 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1028 1029 setOperationAction(ISD::VECREDUCE_FADD, VT, Legal); 1030 } 1031 } 1032 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 1033 MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 1034 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1035 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1036 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1037 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1038 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1039 } 1040 setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom); 1041 1042 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 1043 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 1044 // Likewise, narrowing and extending vector loads/stores aren't handled 1045 // directly. 1046 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 1047 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 1048 1049 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 1050 setOperationAction(ISD::MULHS, VT, Legal); 1051 setOperationAction(ISD::MULHU, VT, Legal); 1052 } else { 1053 setOperationAction(ISD::MULHS, VT, Expand); 1054 setOperationAction(ISD::MULHU, VT, Expand); 1055 } 1056 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 1057 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 1058 1059 setOperationAction(ISD::BSWAP, VT, Expand); 1060 setOperationAction(ISD::CTTZ, VT, Expand); 1061 1062 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 1063 setTruncStoreAction(VT, InnerVT, Expand); 1064 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 1065 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 1066 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 1067 } 1068 } 1069 1070 // AArch64 has implementations of a lot of rounding-like FP operations. 1071 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 1072 setOperationAction(ISD::FFLOOR, Ty, Legal); 1073 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 1074 setOperationAction(ISD::FCEIL, Ty, Legal); 1075 setOperationAction(ISD::FRINT, Ty, Legal); 1076 setOperationAction(ISD::FTRUNC, Ty, Legal); 1077 setOperationAction(ISD::FROUND, Ty, Legal); 1078 setOperationAction(ISD::FROUNDEVEN, Ty, Legal); 1079 } 1080 1081 if (Subtarget->hasFullFP16()) { 1082 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 1083 setOperationAction(ISD::FFLOOR, Ty, Legal); 1084 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 1085 setOperationAction(ISD::FCEIL, Ty, Legal); 1086 setOperationAction(ISD::FRINT, Ty, Legal); 1087 setOperationAction(ISD::FTRUNC, Ty, Legal); 1088 setOperationAction(ISD::FROUND, Ty, Legal); 1089 setOperationAction(ISD::FROUNDEVEN, Ty, Legal); 1090 } 1091 } 1092 1093 if (Subtarget->hasSVE()) 1094 setOperationAction(ISD::VSCALE, MVT::i32, Custom); 1095 1096 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 1097 } 1098 1099 if (Subtarget->hasSVE()) { 1100 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a 1101 // splat of 0 or undef) once vector selects supported in SVE codegen. See 1102 // D68877 for more details. 1103 for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) { 1104 setOperationAction(ISD::BITREVERSE, VT, Custom); 1105 setOperationAction(ISD::BSWAP, VT, Custom); 1106 setOperationAction(ISD::CTLZ, VT, Custom); 1107 setOperationAction(ISD::CTPOP, VT, Custom); 1108 setOperationAction(ISD::CTTZ, VT, Custom); 1109 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1110 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 1111 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 1112 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 1113 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 1114 setOperationAction(ISD::MGATHER, VT, Custom); 1115 setOperationAction(ISD::MSCATTER, VT, Custom); 1116 setOperationAction(ISD::MUL, VT, Custom); 1117 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1118 setOperationAction(ISD::SELECT, VT, Custom); 1119 setOperationAction(ISD::SETCC, VT, Custom); 1120 setOperationAction(ISD::SDIV, VT, Custom); 1121 setOperationAction(ISD::UDIV, VT, Custom); 1122 setOperationAction(ISD::SMIN, VT, Custom); 1123 setOperationAction(ISD::UMIN, VT, Custom); 1124 setOperationAction(ISD::SMAX, VT, Custom); 1125 setOperationAction(ISD::UMAX, VT, Custom); 1126 setOperationAction(ISD::SHL, VT, Custom); 1127 setOperationAction(ISD::SRL, VT, Custom); 1128 setOperationAction(ISD::SRA, VT, Custom); 1129 setOperationAction(ISD::ABS, VT, Custom); 1130 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1131 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1132 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1133 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1134 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1135 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1136 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1137 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1138 setOperationAction(ISD::STEP_VECTOR, VT, Custom); 1139 1140 setOperationAction(ISD::MULHU, VT, Expand); 1141 setOperationAction(ISD::MULHS, VT, Expand); 1142 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 1143 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 1144 } 1145 1146 // Illegal unpacked integer vector types. 1147 for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) { 1148 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1149 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1150 } 1151 1152 for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) { 1153 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1154 setOperationAction(ISD::SELECT, VT, Custom); 1155 setOperationAction(ISD::SETCC, VT, Custom); 1156 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1157 setOperationAction(ISD::TRUNCATE, VT, Custom); 1158 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1159 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1160 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1161 1162 // There are no legal MVT::nxv16f## based types. 1163 if (VT != MVT::nxv16i1) { 1164 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 1165 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 1166 } 1167 } 1168 1169 for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, 1170 MVT::nxv4f32, MVT::nxv2f64}) { 1171 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1172 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1173 setOperationAction(ISD::MGATHER, VT, Custom); 1174 setOperationAction(ISD::MSCATTER, VT, Custom); 1175 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1176 setOperationAction(ISD::SELECT, VT, Custom); 1177 setOperationAction(ISD::FADD, VT, Custom); 1178 setOperationAction(ISD::FDIV, VT, Custom); 1179 setOperationAction(ISD::FMA, VT, Custom); 1180 setOperationAction(ISD::FMAXIMUM, VT, Custom); 1181 setOperationAction(ISD::FMAXNUM, VT, Custom); 1182 setOperationAction(ISD::FMINIMUM, VT, Custom); 1183 setOperationAction(ISD::FMINNUM, VT, Custom); 1184 setOperationAction(ISD::FMUL, VT, Custom); 1185 setOperationAction(ISD::FNEG, VT, Custom); 1186 setOperationAction(ISD::FSUB, VT, Custom); 1187 setOperationAction(ISD::FCEIL, VT, Custom); 1188 setOperationAction(ISD::FFLOOR, VT, Custom); 1189 setOperationAction(ISD::FNEARBYINT, VT, Custom); 1190 setOperationAction(ISD::FRINT, VT, Custom); 1191 setOperationAction(ISD::FROUND, VT, Custom); 1192 setOperationAction(ISD::FROUNDEVEN, VT, Custom); 1193 setOperationAction(ISD::FTRUNC, VT, Custom); 1194 setOperationAction(ISD::FSQRT, VT, Custom); 1195 setOperationAction(ISD::FABS, VT, Custom); 1196 setOperationAction(ISD::FP_EXTEND, VT, Custom); 1197 setOperationAction(ISD::FP_ROUND, VT, Custom); 1198 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1199 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1200 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1201 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1202 } 1203 1204 for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) { 1205 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1206 setOperationAction(ISD::MGATHER, VT, Custom); 1207 setOperationAction(ISD::MSCATTER, VT, Custom); 1208 } 1209 1210 setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom); 1211 1212 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 1213 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 1214 1215 // NOTE: Currently this has to happen after computeRegisterProperties rather 1216 // than the preferred option of combining it with the addRegisterClass call. 1217 if (Subtarget->useSVEForFixedLengthVectors()) { 1218 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 1219 if (useSVEForFixedLengthVectorVT(VT)) 1220 addTypeForFixedLengthSVE(VT); 1221 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 1222 if (useSVEForFixedLengthVectorVT(VT)) 1223 addTypeForFixedLengthSVE(VT); 1224 1225 // 64bit results can mean a bigger than NEON input. 1226 for (auto VT : {MVT::v8i8, MVT::v4i16}) 1227 setOperationAction(ISD::TRUNCATE, VT, Custom); 1228 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom); 1229 1230 // 128bit results imply a bigger than NEON input. 1231 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32}) 1232 setOperationAction(ISD::TRUNCATE, VT, Custom); 1233 for (auto VT : {MVT::v8f16, MVT::v4f32}) 1234 setOperationAction(ISD::FP_ROUND, VT, Expand); 1235 1236 // These operations are not supported on NEON but SVE can do them. 1237 setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom); 1238 setOperationAction(ISD::CTLZ, MVT::v1i64, Custom); 1239 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom); 1240 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 1241 setOperationAction(ISD::MUL, MVT::v1i64, Custom); 1242 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 1243 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 1244 setOperationAction(ISD::SDIV, MVT::v16i8, Custom); 1245 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 1246 setOperationAction(ISD::SDIV, MVT::v8i16, Custom); 1247 setOperationAction(ISD::SDIV, MVT::v2i32, Custom); 1248 setOperationAction(ISD::SDIV, MVT::v4i32, Custom); 1249 setOperationAction(ISD::SDIV, MVT::v1i64, Custom); 1250 setOperationAction(ISD::SDIV, MVT::v2i64, Custom); 1251 setOperationAction(ISD::SMAX, MVT::v1i64, Custom); 1252 setOperationAction(ISD::SMAX, MVT::v2i64, Custom); 1253 setOperationAction(ISD::SMIN, MVT::v1i64, Custom); 1254 setOperationAction(ISD::SMIN, MVT::v2i64, Custom); 1255 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 1256 setOperationAction(ISD::UDIV, MVT::v16i8, Custom); 1257 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 1258 setOperationAction(ISD::UDIV, MVT::v8i16, Custom); 1259 setOperationAction(ISD::UDIV, MVT::v2i32, Custom); 1260 setOperationAction(ISD::UDIV, MVT::v4i32, Custom); 1261 setOperationAction(ISD::UDIV, MVT::v1i64, Custom); 1262 setOperationAction(ISD::UDIV, MVT::v2i64, Custom); 1263 setOperationAction(ISD::UMAX, MVT::v1i64, Custom); 1264 setOperationAction(ISD::UMAX, MVT::v2i64, Custom); 1265 setOperationAction(ISD::UMIN, MVT::v1i64, Custom); 1266 setOperationAction(ISD::UMIN, MVT::v2i64, Custom); 1267 setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom); 1268 setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom); 1269 setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom); 1270 setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom); 1271 1272 // Int operations with no NEON support. 1273 for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, 1274 MVT::v2i32, MVT::v4i32, MVT::v2i64}) { 1275 setOperationAction(ISD::BITREVERSE, VT, Custom); 1276 setOperationAction(ISD::CTTZ, VT, Custom); 1277 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1278 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1279 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1280 } 1281 1282 // FP operations with no NEON support. 1283 for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, 1284 MVT::v1f64, MVT::v2f64}) 1285 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1286 1287 // Use SVE for vectors with more than 2 elements. 1288 for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32}) 1289 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1290 } 1291 1292 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64); 1293 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32); 1294 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16); 1295 setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8); 1296 } 1297 1298 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 1299 } 1300 1301 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 1302 assert(VT.isVector() && "VT should be a vector type"); 1303 1304 if (VT.isFloatingPoint()) { 1305 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 1306 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 1307 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 1308 } 1309 1310 // Mark vector float intrinsics as expand. 1311 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 1312 setOperationAction(ISD::FSIN, VT, Expand); 1313 setOperationAction(ISD::FCOS, VT, Expand); 1314 setOperationAction(ISD::FPOW, VT, Expand); 1315 setOperationAction(ISD::FLOG, VT, Expand); 1316 setOperationAction(ISD::FLOG2, VT, Expand); 1317 setOperationAction(ISD::FLOG10, VT, Expand); 1318 setOperationAction(ISD::FEXP, VT, Expand); 1319 setOperationAction(ISD::FEXP2, VT, Expand); 1320 1321 // But we do support custom-lowering for FCOPYSIGN. 1322 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 1323 } 1324 1325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1326 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1327 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1328 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1329 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1330 setOperationAction(ISD::SRA, VT, Custom); 1331 setOperationAction(ISD::SRL, VT, Custom); 1332 setOperationAction(ISD::SHL, VT, Custom); 1333 setOperationAction(ISD::OR, VT, Custom); 1334 setOperationAction(ISD::SETCC, VT, Custom); 1335 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 1336 1337 setOperationAction(ISD::SELECT, VT, Expand); 1338 setOperationAction(ISD::SELECT_CC, VT, Expand); 1339 setOperationAction(ISD::VSELECT, VT, Expand); 1340 for (MVT InnerVT : MVT::all_valuetypes()) 1341 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 1342 1343 // CNT supports only B element sizes, then use UADDLP to widen. 1344 if (VT != MVT::v8i8 && VT != MVT::v16i8) 1345 setOperationAction(ISD::CTPOP, VT, Custom); 1346 1347 setOperationAction(ISD::UDIV, VT, Expand); 1348 setOperationAction(ISD::SDIV, VT, Expand); 1349 setOperationAction(ISD::UREM, VT, Expand); 1350 setOperationAction(ISD::SREM, VT, Expand); 1351 setOperationAction(ISD::FREM, VT, Expand); 1352 1353 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 1354 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 1355 1356 if (!VT.isFloatingPoint()) 1357 setOperationAction(ISD::ABS, VT, Legal); 1358 1359 // [SU][MIN|MAX] are available for all NEON types apart from i64. 1360 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 1361 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 1362 setOperationAction(Opcode, VT, Legal); 1363 1364 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 1365 if (VT.isFloatingPoint() && 1366 VT.getVectorElementType() != MVT::bf16 && 1367 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 1368 for (unsigned Opcode : 1369 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 1370 setOperationAction(Opcode, VT, Legal); 1371 1372 if (Subtarget->isLittleEndian()) { 1373 for (unsigned im = (unsigned)ISD::PRE_INC; 1374 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 1375 setIndexedLoadAction(im, VT, Legal); 1376 setIndexedStoreAction(im, VT, Legal); 1377 } 1378 } 1379 } 1380 1381 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) { 1382 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 1383 1384 // By default everything must be expanded. 1385 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 1386 setOperationAction(Op, VT, Expand); 1387 1388 // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one. 1389 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1390 1391 // Lower fixed length vector operations to scalable equivalents. 1392 setOperationAction(ISD::ABS, VT, Custom); 1393 setOperationAction(ISD::ADD, VT, Custom); 1394 setOperationAction(ISD::AND, VT, Custom); 1395 setOperationAction(ISD::ANY_EXTEND, VT, Custom); 1396 setOperationAction(ISD::BITREVERSE, VT, Custom); 1397 setOperationAction(ISD::BSWAP, VT, Custom); 1398 setOperationAction(ISD::CTLZ, VT, Custom); 1399 setOperationAction(ISD::CTPOP, VT, Custom); 1400 setOperationAction(ISD::CTTZ, VT, Custom); 1401 setOperationAction(ISD::FABS, VT, Custom); 1402 setOperationAction(ISD::FADD, VT, Custom); 1403 setOperationAction(ISD::FCEIL, VT, Custom); 1404 setOperationAction(ISD::FDIV, VT, Custom); 1405 setOperationAction(ISD::FFLOOR, VT, Custom); 1406 setOperationAction(ISD::FMA, VT, Custom); 1407 setOperationAction(ISD::FMAXIMUM, VT, Custom); 1408 setOperationAction(ISD::FMAXNUM, VT, Custom); 1409 setOperationAction(ISD::FMINIMUM, VT, Custom); 1410 setOperationAction(ISD::FMINNUM, VT, Custom); 1411 setOperationAction(ISD::FMUL, VT, Custom); 1412 setOperationAction(ISD::FNEARBYINT, VT, Custom); 1413 setOperationAction(ISD::FNEG, VT, Custom); 1414 setOperationAction(ISD::FRINT, VT, Custom); 1415 setOperationAction(ISD::FROUND, VT, Custom); 1416 setOperationAction(ISD::FROUNDEVEN, VT, Custom); 1417 setOperationAction(ISD::FSQRT, VT, Custom); 1418 setOperationAction(ISD::FSUB, VT, Custom); 1419 setOperationAction(ISD::FTRUNC, VT, Custom); 1420 setOperationAction(ISD::LOAD, VT, Custom); 1421 setOperationAction(ISD::MUL, VT, Custom); 1422 setOperationAction(ISD::OR, VT, Custom); 1423 setOperationAction(ISD::SDIV, VT, Custom); 1424 setOperationAction(ISD::SETCC, VT, Custom); 1425 setOperationAction(ISD::SHL, VT, Custom); 1426 setOperationAction(ISD::SIGN_EXTEND, VT, Custom); 1427 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom); 1428 setOperationAction(ISD::SMAX, VT, Custom); 1429 setOperationAction(ISD::SMIN, VT, Custom); 1430 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 1431 setOperationAction(ISD::SRA, VT, Custom); 1432 setOperationAction(ISD::SRL, VT, Custom); 1433 setOperationAction(ISD::STORE, VT, Custom); 1434 setOperationAction(ISD::SUB, VT, Custom); 1435 setOperationAction(ISD::TRUNCATE, VT, Custom); 1436 setOperationAction(ISD::UDIV, VT, Custom); 1437 setOperationAction(ISD::UMAX, VT, Custom); 1438 setOperationAction(ISD::UMIN, VT, Custom); 1439 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 1440 setOperationAction(ISD::VECREDUCE_AND, VT, Custom); 1441 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 1442 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 1443 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 1444 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 1445 setOperationAction(ISD::VECREDUCE_OR, VT, Custom); 1446 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 1447 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 1448 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 1449 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 1450 setOperationAction(ISD::VECREDUCE_XOR, VT, Custom); 1451 setOperationAction(ISD::VSELECT, VT, Custom); 1452 setOperationAction(ISD::XOR, VT, Custom); 1453 setOperationAction(ISD::ZERO_EXTEND, VT, Custom); 1454 } 1455 1456 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 1457 addRegisterClass(VT, &AArch64::FPR64RegClass); 1458 addTypeForNEON(VT, MVT::v2i32); 1459 } 1460 1461 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 1462 addRegisterClass(VT, &AArch64::FPR128RegClass); 1463 addTypeForNEON(VT, MVT::v4i32); 1464 } 1465 1466 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, 1467 LLVMContext &C, EVT VT) const { 1468 if (!VT.isVector()) 1469 return MVT::i32; 1470 if (VT.isScalableVector()) 1471 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount()); 1472 return VT.changeVectorElementTypeToInteger(); 1473 } 1474 1475 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 1476 const APInt &Demanded, 1477 TargetLowering::TargetLoweringOpt &TLO, 1478 unsigned NewOpc) { 1479 uint64_t OldImm = Imm, NewImm, Enc; 1480 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 1481 1482 // Return if the immediate is already all zeros, all ones, a bimm32 or a 1483 // bimm64. 1484 if (Imm == 0 || Imm == Mask || 1485 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 1486 return false; 1487 1488 unsigned EltSize = Size; 1489 uint64_t DemandedBits = Demanded.getZExtValue(); 1490 1491 // Clear bits that are not demanded. 1492 Imm &= DemandedBits; 1493 1494 while (true) { 1495 // The goal here is to set the non-demanded bits in a way that minimizes 1496 // the number of switching between 0 and 1. In order to achieve this goal, 1497 // we set the non-demanded bits to the value of the preceding demanded bits. 1498 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 1499 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 1500 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 1501 // The final result is 0b11000011. 1502 uint64_t NonDemandedBits = ~DemandedBits; 1503 uint64_t InvertedImm = ~Imm & DemandedBits; 1504 uint64_t RotatedImm = 1505 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 1506 NonDemandedBits; 1507 uint64_t Sum = RotatedImm + NonDemandedBits; 1508 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 1509 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 1510 NewImm = (Imm | Ones) & Mask; 1511 1512 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 1513 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 1514 // we halve the element size and continue the search. 1515 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 1516 break; 1517 1518 // We cannot shrink the element size any further if it is 2-bits. 1519 if (EltSize == 2) 1520 return false; 1521 1522 EltSize /= 2; 1523 Mask >>= EltSize; 1524 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 1525 1526 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 1527 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 1528 return false; 1529 1530 // Merge the upper and lower halves of Imm and DemandedBits. 1531 Imm |= Hi; 1532 DemandedBits |= DemandedBitsHi; 1533 } 1534 1535 ++NumOptimizedImms; 1536 1537 // Replicate the element across the register width. 1538 while (EltSize < Size) { 1539 NewImm |= NewImm << EltSize; 1540 EltSize *= 2; 1541 } 1542 1543 (void)OldImm; 1544 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 1545 "demanded bits should never be altered"); 1546 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 1547 1548 // Create the new constant immediate node. 1549 EVT VT = Op.getValueType(); 1550 SDLoc DL(Op); 1551 SDValue New; 1552 1553 // If the new constant immediate is all-zeros or all-ones, let the target 1554 // independent DAG combine optimize this node. 1555 if (NewImm == 0 || NewImm == OrigMask) { 1556 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 1557 TLO.DAG.getConstant(NewImm, DL, VT)); 1558 // Otherwise, create a machine node so that target independent DAG combine 1559 // doesn't undo this optimization. 1560 } else { 1561 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 1562 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 1563 New = SDValue( 1564 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1565 } 1566 1567 return TLO.CombineTo(Op, New); 1568 } 1569 1570 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1571 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 1572 TargetLoweringOpt &TLO) const { 1573 // Delay this optimization to as late as possible. 1574 if (!TLO.LegalOps) 1575 return false; 1576 1577 if (!EnableOptimizeLogicalImm) 1578 return false; 1579 1580 EVT VT = Op.getValueType(); 1581 if (VT.isVector()) 1582 return false; 1583 1584 unsigned Size = VT.getSizeInBits(); 1585 assert((Size == 32 || Size == 64) && 1586 "i32 or i64 is expected after legalization."); 1587 1588 // Exit early if we demand all bits. 1589 if (DemandedBits.countPopulation() == Size) 1590 return false; 1591 1592 unsigned NewOpc; 1593 switch (Op.getOpcode()) { 1594 default: 1595 return false; 1596 case ISD::AND: 1597 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1598 break; 1599 case ISD::OR: 1600 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1601 break; 1602 case ISD::XOR: 1603 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1604 break; 1605 } 1606 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1607 if (!C) 1608 return false; 1609 uint64_t Imm = C->getZExtValue(); 1610 return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc); 1611 } 1612 1613 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1614 /// Mask are known to be either zero or one and return them Known. 1615 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1616 const SDValue Op, KnownBits &Known, 1617 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1618 switch (Op.getOpcode()) { 1619 default: 1620 break; 1621 case AArch64ISD::CSEL: { 1622 KnownBits Known2; 1623 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1624 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1625 Known = KnownBits::commonBits(Known, Known2); 1626 break; 1627 } 1628 case AArch64ISD::LOADgot: 1629 case AArch64ISD::ADDlow: { 1630 if (!Subtarget->isTargetILP32()) 1631 break; 1632 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1633 Known.Zero = APInt::getHighBitsSet(64, 32); 1634 break; 1635 } 1636 case ISD::INTRINSIC_W_CHAIN: { 1637 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1638 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1639 switch (IntID) { 1640 default: return; 1641 case Intrinsic::aarch64_ldaxr: 1642 case Intrinsic::aarch64_ldxr: { 1643 unsigned BitWidth = Known.getBitWidth(); 1644 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1645 unsigned MemBits = VT.getScalarSizeInBits(); 1646 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1647 return; 1648 } 1649 } 1650 break; 1651 } 1652 case ISD::INTRINSIC_WO_CHAIN: 1653 case ISD::INTRINSIC_VOID: { 1654 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1655 switch (IntNo) { 1656 default: 1657 break; 1658 case Intrinsic::aarch64_neon_umaxv: 1659 case Intrinsic::aarch64_neon_uminv: { 1660 // Figure out the datatype of the vector operand. The UMINV instruction 1661 // will zero extend the result, so we can mark as known zero all the 1662 // bits larger than the element datatype. 32-bit or larget doesn't need 1663 // this as those are legal types and will be handled by isel directly. 1664 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1665 unsigned BitWidth = Known.getBitWidth(); 1666 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1667 assert(BitWidth >= 8 && "Unexpected width!"); 1668 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1669 Known.Zero |= Mask; 1670 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1671 assert(BitWidth >= 16 && "Unexpected width!"); 1672 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1673 Known.Zero |= Mask; 1674 } 1675 break; 1676 } break; 1677 } 1678 } 1679 } 1680 } 1681 1682 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1683 EVT) const { 1684 return MVT::i64; 1685 } 1686 1687 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1688 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1689 bool *Fast) const { 1690 if (Subtarget->requiresStrictAlign()) 1691 return false; 1692 1693 if (Fast) { 1694 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1695 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1696 // See comments in performSTORECombine() for more details about 1697 // these conditions. 1698 1699 // Code that uses clang vector extensions can mark that it 1700 // wants unaligned accesses to be treated as fast by 1701 // underspecifying alignment to be 1 or 2. 1702 Alignment <= 2 || 1703 1704 // Disregard v2i64. Memcpy lowering produces those and splitting 1705 // them regresses performance on micro-benchmarks and olden/bh. 1706 VT == MVT::v2i64; 1707 } 1708 return true; 1709 } 1710 1711 // Same as above but handling LLTs instead. 1712 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1713 LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1714 bool *Fast) const { 1715 if (Subtarget->requiresStrictAlign()) 1716 return false; 1717 1718 if (Fast) { 1719 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1720 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1721 Ty.getSizeInBytes() != 16 || 1722 // See comments in performSTORECombine() for more details about 1723 // these conditions. 1724 1725 // Code that uses clang vector extensions can mark that it 1726 // wants unaligned accesses to be treated as fast by 1727 // underspecifying alignment to be 1 or 2. 1728 Alignment <= 2 || 1729 1730 // Disregard v2i64. Memcpy lowering produces those and splitting 1731 // them regresses performance on micro-benchmarks and olden/bh. 1732 Ty == LLT::vector(2, 64); 1733 } 1734 return true; 1735 } 1736 1737 FastISel * 1738 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1739 const TargetLibraryInfo *libInfo) const { 1740 return AArch64::createFastISel(funcInfo, libInfo); 1741 } 1742 1743 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1744 #define MAKE_CASE(V) \ 1745 case V: \ 1746 return #V; 1747 switch ((AArch64ISD::NodeType)Opcode) { 1748 case AArch64ISD::FIRST_NUMBER: 1749 break; 1750 MAKE_CASE(AArch64ISD::CALL) 1751 MAKE_CASE(AArch64ISD::ADRP) 1752 MAKE_CASE(AArch64ISD::ADR) 1753 MAKE_CASE(AArch64ISD::ADDlow) 1754 MAKE_CASE(AArch64ISD::LOADgot) 1755 MAKE_CASE(AArch64ISD::RET_FLAG) 1756 MAKE_CASE(AArch64ISD::BRCOND) 1757 MAKE_CASE(AArch64ISD::CSEL) 1758 MAKE_CASE(AArch64ISD::FCSEL) 1759 MAKE_CASE(AArch64ISD::CSINV) 1760 MAKE_CASE(AArch64ISD::CSNEG) 1761 MAKE_CASE(AArch64ISD::CSINC) 1762 MAKE_CASE(AArch64ISD::THREAD_POINTER) 1763 MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ) 1764 MAKE_CASE(AArch64ISD::ADD_PRED) 1765 MAKE_CASE(AArch64ISD::MUL_PRED) 1766 MAKE_CASE(AArch64ISD::SDIV_PRED) 1767 MAKE_CASE(AArch64ISD::SHL_PRED) 1768 MAKE_CASE(AArch64ISD::SMAX_PRED) 1769 MAKE_CASE(AArch64ISD::SMIN_PRED) 1770 MAKE_CASE(AArch64ISD::SRA_PRED) 1771 MAKE_CASE(AArch64ISD::SRL_PRED) 1772 MAKE_CASE(AArch64ISD::SUB_PRED) 1773 MAKE_CASE(AArch64ISD::UDIV_PRED) 1774 MAKE_CASE(AArch64ISD::UMAX_PRED) 1775 MAKE_CASE(AArch64ISD::UMIN_PRED) 1776 MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU) 1777 MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU) 1778 MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU) 1779 MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU) 1780 MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU) 1781 MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU) 1782 MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU) 1783 MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU) 1784 MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU) 1785 MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU) 1786 MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU) 1787 MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU) 1788 MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU) 1789 MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU) 1790 MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU) 1791 MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU) 1792 MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU) 1793 MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU) 1794 MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU) 1795 MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU) 1796 MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU) 1797 MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO) 1798 MAKE_CASE(AArch64ISD::ADC) 1799 MAKE_CASE(AArch64ISD::SBC) 1800 MAKE_CASE(AArch64ISD::ADDS) 1801 MAKE_CASE(AArch64ISD::SUBS) 1802 MAKE_CASE(AArch64ISD::ADCS) 1803 MAKE_CASE(AArch64ISD::SBCS) 1804 MAKE_CASE(AArch64ISD::ANDS) 1805 MAKE_CASE(AArch64ISD::CCMP) 1806 MAKE_CASE(AArch64ISD::CCMN) 1807 MAKE_CASE(AArch64ISD::FCCMP) 1808 MAKE_CASE(AArch64ISD::FCMP) 1809 MAKE_CASE(AArch64ISD::STRICT_FCMP) 1810 MAKE_CASE(AArch64ISD::STRICT_FCMPE) 1811 MAKE_CASE(AArch64ISD::DUP) 1812 MAKE_CASE(AArch64ISD::DUPLANE8) 1813 MAKE_CASE(AArch64ISD::DUPLANE16) 1814 MAKE_CASE(AArch64ISD::DUPLANE32) 1815 MAKE_CASE(AArch64ISD::DUPLANE64) 1816 MAKE_CASE(AArch64ISD::MOVI) 1817 MAKE_CASE(AArch64ISD::MOVIshift) 1818 MAKE_CASE(AArch64ISD::MOVIedit) 1819 MAKE_CASE(AArch64ISD::MOVImsl) 1820 MAKE_CASE(AArch64ISD::FMOV) 1821 MAKE_CASE(AArch64ISD::MVNIshift) 1822 MAKE_CASE(AArch64ISD::MVNImsl) 1823 MAKE_CASE(AArch64ISD::BICi) 1824 MAKE_CASE(AArch64ISD::ORRi) 1825 MAKE_CASE(AArch64ISD::BSP) 1826 MAKE_CASE(AArch64ISD::NEG) 1827 MAKE_CASE(AArch64ISD::EXTR) 1828 MAKE_CASE(AArch64ISD::ZIP1) 1829 MAKE_CASE(AArch64ISD::ZIP2) 1830 MAKE_CASE(AArch64ISD::UZP1) 1831 MAKE_CASE(AArch64ISD::UZP2) 1832 MAKE_CASE(AArch64ISD::TRN1) 1833 MAKE_CASE(AArch64ISD::TRN2) 1834 MAKE_CASE(AArch64ISD::REV16) 1835 MAKE_CASE(AArch64ISD::REV32) 1836 MAKE_CASE(AArch64ISD::REV64) 1837 MAKE_CASE(AArch64ISD::EXT) 1838 MAKE_CASE(AArch64ISD::VSHL) 1839 MAKE_CASE(AArch64ISD::VLSHR) 1840 MAKE_CASE(AArch64ISD::VASHR) 1841 MAKE_CASE(AArch64ISD::VSLI) 1842 MAKE_CASE(AArch64ISD::VSRI) 1843 MAKE_CASE(AArch64ISD::CMEQ) 1844 MAKE_CASE(AArch64ISD::CMGE) 1845 MAKE_CASE(AArch64ISD::CMGT) 1846 MAKE_CASE(AArch64ISD::CMHI) 1847 MAKE_CASE(AArch64ISD::CMHS) 1848 MAKE_CASE(AArch64ISD::FCMEQ) 1849 MAKE_CASE(AArch64ISD::FCMGE) 1850 MAKE_CASE(AArch64ISD::FCMGT) 1851 MAKE_CASE(AArch64ISD::CMEQz) 1852 MAKE_CASE(AArch64ISD::CMGEz) 1853 MAKE_CASE(AArch64ISD::CMGTz) 1854 MAKE_CASE(AArch64ISD::CMLEz) 1855 MAKE_CASE(AArch64ISD::CMLTz) 1856 MAKE_CASE(AArch64ISD::FCMEQz) 1857 MAKE_CASE(AArch64ISD::FCMGEz) 1858 MAKE_CASE(AArch64ISD::FCMGTz) 1859 MAKE_CASE(AArch64ISD::FCMLEz) 1860 MAKE_CASE(AArch64ISD::FCMLTz) 1861 MAKE_CASE(AArch64ISD::SADDV) 1862 MAKE_CASE(AArch64ISD::UADDV) 1863 MAKE_CASE(AArch64ISD::SRHADD) 1864 MAKE_CASE(AArch64ISD::URHADD) 1865 MAKE_CASE(AArch64ISD::SHADD) 1866 MAKE_CASE(AArch64ISD::UHADD) 1867 MAKE_CASE(AArch64ISD::SDOT) 1868 MAKE_CASE(AArch64ISD::UDOT) 1869 MAKE_CASE(AArch64ISD::SMINV) 1870 MAKE_CASE(AArch64ISD::UMINV) 1871 MAKE_CASE(AArch64ISD::SMAXV) 1872 MAKE_CASE(AArch64ISD::UMAXV) 1873 MAKE_CASE(AArch64ISD::SADDV_PRED) 1874 MAKE_CASE(AArch64ISD::UADDV_PRED) 1875 MAKE_CASE(AArch64ISD::SMAXV_PRED) 1876 MAKE_CASE(AArch64ISD::UMAXV_PRED) 1877 MAKE_CASE(AArch64ISD::SMINV_PRED) 1878 MAKE_CASE(AArch64ISD::UMINV_PRED) 1879 MAKE_CASE(AArch64ISD::ORV_PRED) 1880 MAKE_CASE(AArch64ISD::EORV_PRED) 1881 MAKE_CASE(AArch64ISD::ANDV_PRED) 1882 MAKE_CASE(AArch64ISD::CLASTA_N) 1883 MAKE_CASE(AArch64ISD::CLASTB_N) 1884 MAKE_CASE(AArch64ISD::LASTA) 1885 MAKE_CASE(AArch64ISD::LASTB) 1886 MAKE_CASE(AArch64ISD::REINTERPRET_CAST) 1887 MAKE_CASE(AArch64ISD::TBL) 1888 MAKE_CASE(AArch64ISD::FADD_PRED) 1889 MAKE_CASE(AArch64ISD::FADDA_PRED) 1890 MAKE_CASE(AArch64ISD::FADDV_PRED) 1891 MAKE_CASE(AArch64ISD::FDIV_PRED) 1892 MAKE_CASE(AArch64ISD::FMA_PRED) 1893 MAKE_CASE(AArch64ISD::FMAX_PRED) 1894 MAKE_CASE(AArch64ISD::FMAXV_PRED) 1895 MAKE_CASE(AArch64ISD::FMAXNM_PRED) 1896 MAKE_CASE(AArch64ISD::FMAXNMV_PRED) 1897 MAKE_CASE(AArch64ISD::FMIN_PRED) 1898 MAKE_CASE(AArch64ISD::FMINV_PRED) 1899 MAKE_CASE(AArch64ISD::FMINNM_PRED) 1900 MAKE_CASE(AArch64ISD::FMINNMV_PRED) 1901 MAKE_CASE(AArch64ISD::FMUL_PRED) 1902 MAKE_CASE(AArch64ISD::FSUB_PRED) 1903 MAKE_CASE(AArch64ISD::BIT) 1904 MAKE_CASE(AArch64ISD::CBZ) 1905 MAKE_CASE(AArch64ISD::CBNZ) 1906 MAKE_CASE(AArch64ISD::TBZ) 1907 MAKE_CASE(AArch64ISD::TBNZ) 1908 MAKE_CASE(AArch64ISD::TC_RETURN) 1909 MAKE_CASE(AArch64ISD::PREFETCH) 1910 MAKE_CASE(AArch64ISD::SITOF) 1911 MAKE_CASE(AArch64ISD::UITOF) 1912 MAKE_CASE(AArch64ISD::NVCAST) 1913 MAKE_CASE(AArch64ISD::MRS) 1914 MAKE_CASE(AArch64ISD::SQSHL_I) 1915 MAKE_CASE(AArch64ISD::UQSHL_I) 1916 MAKE_CASE(AArch64ISD::SRSHR_I) 1917 MAKE_CASE(AArch64ISD::URSHR_I) 1918 MAKE_CASE(AArch64ISD::SQSHLU_I) 1919 MAKE_CASE(AArch64ISD::WrapperLarge) 1920 MAKE_CASE(AArch64ISD::LD2post) 1921 MAKE_CASE(AArch64ISD::LD3post) 1922 MAKE_CASE(AArch64ISD::LD4post) 1923 MAKE_CASE(AArch64ISD::ST2post) 1924 MAKE_CASE(AArch64ISD::ST3post) 1925 MAKE_CASE(AArch64ISD::ST4post) 1926 MAKE_CASE(AArch64ISD::LD1x2post) 1927 MAKE_CASE(AArch64ISD::LD1x3post) 1928 MAKE_CASE(AArch64ISD::LD1x4post) 1929 MAKE_CASE(AArch64ISD::ST1x2post) 1930 MAKE_CASE(AArch64ISD::ST1x3post) 1931 MAKE_CASE(AArch64ISD::ST1x4post) 1932 MAKE_CASE(AArch64ISD::LD1DUPpost) 1933 MAKE_CASE(AArch64ISD::LD2DUPpost) 1934 MAKE_CASE(AArch64ISD::LD3DUPpost) 1935 MAKE_CASE(AArch64ISD::LD4DUPpost) 1936 MAKE_CASE(AArch64ISD::LD1LANEpost) 1937 MAKE_CASE(AArch64ISD::LD2LANEpost) 1938 MAKE_CASE(AArch64ISD::LD3LANEpost) 1939 MAKE_CASE(AArch64ISD::LD4LANEpost) 1940 MAKE_CASE(AArch64ISD::ST2LANEpost) 1941 MAKE_CASE(AArch64ISD::ST3LANEpost) 1942 MAKE_CASE(AArch64ISD::ST4LANEpost) 1943 MAKE_CASE(AArch64ISD::SMULL) 1944 MAKE_CASE(AArch64ISD::UMULL) 1945 MAKE_CASE(AArch64ISD::FRECPE) 1946 MAKE_CASE(AArch64ISD::FRECPS) 1947 MAKE_CASE(AArch64ISD::FRSQRTE) 1948 MAKE_CASE(AArch64ISD::FRSQRTS) 1949 MAKE_CASE(AArch64ISD::STG) 1950 MAKE_CASE(AArch64ISD::STZG) 1951 MAKE_CASE(AArch64ISD::ST2G) 1952 MAKE_CASE(AArch64ISD::STZ2G) 1953 MAKE_CASE(AArch64ISD::SUNPKHI) 1954 MAKE_CASE(AArch64ISD::SUNPKLO) 1955 MAKE_CASE(AArch64ISD::UUNPKHI) 1956 MAKE_CASE(AArch64ISD::UUNPKLO) 1957 MAKE_CASE(AArch64ISD::INSR) 1958 MAKE_CASE(AArch64ISD::PTEST) 1959 MAKE_CASE(AArch64ISD::PTRUE) 1960 MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO) 1961 MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO) 1962 MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO) 1963 MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO) 1964 MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO) 1965 MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO) 1966 MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO) 1967 MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO) 1968 MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO) 1969 MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO) 1970 MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO) 1971 MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO) 1972 MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO) 1973 MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO) 1974 MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO) 1975 MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO) 1976 MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO) 1977 MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO) 1978 MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO) 1979 MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO) 1980 MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO) 1981 MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO) 1982 MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO) 1983 MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO) 1984 MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO) 1985 MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO) 1986 MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO) 1987 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO) 1988 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO) 1989 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO) 1990 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO) 1991 MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO) 1992 MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO) 1993 MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO) 1994 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO) 1995 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO) 1996 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO) 1997 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO) 1998 MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO) 1999 MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO) 2000 MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) 2001 MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO) 2002 MAKE_CASE(AArch64ISD::ST1_PRED) 2003 MAKE_CASE(AArch64ISD::SST1_PRED) 2004 MAKE_CASE(AArch64ISD::SST1_SCALED_PRED) 2005 MAKE_CASE(AArch64ISD::SST1_SXTW_PRED) 2006 MAKE_CASE(AArch64ISD::SST1_UXTW_PRED) 2007 MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED) 2008 MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED) 2009 MAKE_CASE(AArch64ISD::SST1_IMM_PRED) 2010 MAKE_CASE(AArch64ISD::SSTNT1_PRED) 2011 MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED) 2012 MAKE_CASE(AArch64ISD::LDP) 2013 MAKE_CASE(AArch64ISD::STP) 2014 MAKE_CASE(AArch64ISD::STNP) 2015 MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU) 2016 MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU) 2017 MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU) 2018 MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU) 2019 MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU) 2020 MAKE_CASE(AArch64ISD::INDEX_VECTOR) 2021 MAKE_CASE(AArch64ISD::UABD) 2022 MAKE_CASE(AArch64ISD::SABD) 2023 MAKE_CASE(AArch64ISD::CALL_RVMARKER) 2024 } 2025 #undef MAKE_CASE 2026 return nullptr; 2027 } 2028 2029 MachineBasicBlock * 2030 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 2031 MachineBasicBlock *MBB) const { 2032 // We materialise the F128CSEL pseudo-instruction as some control flow and a 2033 // phi node: 2034 2035 // OrigBB: 2036 // [... previous instrs leading to comparison ...] 2037 // b.ne TrueBB 2038 // b EndBB 2039 // TrueBB: 2040 // ; Fallthrough 2041 // EndBB: 2042 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 2043 2044 MachineFunction *MF = MBB->getParent(); 2045 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2046 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 2047 DebugLoc DL = MI.getDebugLoc(); 2048 MachineFunction::iterator It = ++MBB->getIterator(); 2049 2050 Register DestReg = MI.getOperand(0).getReg(); 2051 Register IfTrueReg = MI.getOperand(1).getReg(); 2052 Register IfFalseReg = MI.getOperand(2).getReg(); 2053 unsigned CondCode = MI.getOperand(3).getImm(); 2054 bool NZCVKilled = MI.getOperand(4).isKill(); 2055 2056 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 2057 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 2058 MF->insert(It, TrueBB); 2059 MF->insert(It, EndBB); 2060 2061 // Transfer rest of current basic-block to EndBB 2062 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 2063 MBB->end()); 2064 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 2065 2066 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 2067 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 2068 MBB->addSuccessor(TrueBB); 2069 MBB->addSuccessor(EndBB); 2070 2071 // TrueBB falls through to the end. 2072 TrueBB->addSuccessor(EndBB); 2073 2074 if (!NZCVKilled) { 2075 TrueBB->addLiveIn(AArch64::NZCV); 2076 EndBB->addLiveIn(AArch64::NZCV); 2077 } 2078 2079 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 2080 .addReg(IfTrueReg) 2081 .addMBB(TrueBB) 2082 .addReg(IfFalseReg) 2083 .addMBB(MBB); 2084 2085 MI.eraseFromParent(); 2086 return EndBB; 2087 } 2088 2089 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 2090 MachineInstr &MI, MachineBasicBlock *BB) const { 2091 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 2092 BB->getParent()->getFunction().getPersonalityFn())) && 2093 "SEH does not use catchret!"); 2094 return BB; 2095 } 2096 2097 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 2098 MachineInstr &MI, MachineBasicBlock *BB) const { 2099 switch (MI.getOpcode()) { 2100 default: 2101 #ifndef NDEBUG 2102 MI.dump(); 2103 #endif 2104 llvm_unreachable("Unexpected instruction for custom inserter!"); 2105 2106 case AArch64::F128CSEL: 2107 return EmitF128CSEL(MI, BB); 2108 2109 case TargetOpcode::STACKMAP: 2110 case TargetOpcode::PATCHPOINT: 2111 case TargetOpcode::STATEPOINT: 2112 return emitPatchPoint(MI, BB); 2113 2114 case AArch64::CATCHRET: 2115 return EmitLoweredCatchRet(MI, BB); 2116 } 2117 } 2118 2119 //===----------------------------------------------------------------------===// 2120 // AArch64 Lowering private implementation. 2121 //===----------------------------------------------------------------------===// 2122 2123 //===----------------------------------------------------------------------===// 2124 // Lowering Code 2125 //===----------------------------------------------------------------------===// 2126 2127 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 2128 /// CC 2129 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 2130 switch (CC) { 2131 default: 2132 llvm_unreachable("Unknown condition code!"); 2133 case ISD::SETNE: 2134 return AArch64CC::NE; 2135 case ISD::SETEQ: 2136 return AArch64CC::EQ; 2137 case ISD::SETGT: 2138 return AArch64CC::GT; 2139 case ISD::SETGE: 2140 return AArch64CC::GE; 2141 case ISD::SETLT: 2142 return AArch64CC::LT; 2143 case ISD::SETLE: 2144 return AArch64CC::LE; 2145 case ISD::SETUGT: 2146 return AArch64CC::HI; 2147 case ISD::SETUGE: 2148 return AArch64CC::HS; 2149 case ISD::SETULT: 2150 return AArch64CC::LO; 2151 case ISD::SETULE: 2152 return AArch64CC::LS; 2153 } 2154 } 2155 2156 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 2157 static void changeFPCCToAArch64CC(ISD::CondCode CC, 2158 AArch64CC::CondCode &CondCode, 2159 AArch64CC::CondCode &CondCode2) { 2160 CondCode2 = AArch64CC::AL; 2161 switch (CC) { 2162 default: 2163 llvm_unreachable("Unknown FP condition!"); 2164 case ISD::SETEQ: 2165 case ISD::SETOEQ: 2166 CondCode = AArch64CC::EQ; 2167 break; 2168 case ISD::SETGT: 2169 case ISD::SETOGT: 2170 CondCode = AArch64CC::GT; 2171 break; 2172 case ISD::SETGE: 2173 case ISD::SETOGE: 2174 CondCode = AArch64CC::GE; 2175 break; 2176 case ISD::SETOLT: 2177 CondCode = AArch64CC::MI; 2178 break; 2179 case ISD::SETOLE: 2180 CondCode = AArch64CC::LS; 2181 break; 2182 case ISD::SETONE: 2183 CondCode = AArch64CC::MI; 2184 CondCode2 = AArch64CC::GT; 2185 break; 2186 case ISD::SETO: 2187 CondCode = AArch64CC::VC; 2188 break; 2189 case ISD::SETUO: 2190 CondCode = AArch64CC::VS; 2191 break; 2192 case ISD::SETUEQ: 2193 CondCode = AArch64CC::EQ; 2194 CondCode2 = AArch64CC::VS; 2195 break; 2196 case ISD::SETUGT: 2197 CondCode = AArch64CC::HI; 2198 break; 2199 case ISD::SETUGE: 2200 CondCode = AArch64CC::PL; 2201 break; 2202 case ISD::SETLT: 2203 case ISD::SETULT: 2204 CondCode = AArch64CC::LT; 2205 break; 2206 case ISD::SETLE: 2207 case ISD::SETULE: 2208 CondCode = AArch64CC::LE; 2209 break; 2210 case ISD::SETNE: 2211 case ISD::SETUNE: 2212 CondCode = AArch64CC::NE; 2213 break; 2214 } 2215 } 2216 2217 /// Convert a DAG fp condition code to an AArch64 CC. 2218 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 2219 /// should be AND'ed instead of OR'ed. 2220 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 2221 AArch64CC::CondCode &CondCode, 2222 AArch64CC::CondCode &CondCode2) { 2223 CondCode2 = AArch64CC::AL; 2224 switch (CC) { 2225 default: 2226 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 2227 assert(CondCode2 == AArch64CC::AL); 2228 break; 2229 case ISD::SETONE: 2230 // (a one b) 2231 // == ((a olt b) || (a ogt b)) 2232 // == ((a ord b) && (a une b)) 2233 CondCode = AArch64CC::VC; 2234 CondCode2 = AArch64CC::NE; 2235 break; 2236 case ISD::SETUEQ: 2237 // (a ueq b) 2238 // == ((a uno b) || (a oeq b)) 2239 // == ((a ule b) && (a uge b)) 2240 CondCode = AArch64CC::PL; 2241 CondCode2 = AArch64CC::LE; 2242 break; 2243 } 2244 } 2245 2246 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 2247 /// CC usable with the vector instructions. Fewer operations are available 2248 /// without a real NZCV register, so we have to use less efficient combinations 2249 /// to get the same effect. 2250 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 2251 AArch64CC::CondCode &CondCode, 2252 AArch64CC::CondCode &CondCode2, 2253 bool &Invert) { 2254 Invert = false; 2255 switch (CC) { 2256 default: 2257 // Mostly the scalar mappings work fine. 2258 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 2259 break; 2260 case ISD::SETUO: 2261 Invert = true; 2262 LLVM_FALLTHROUGH; 2263 case ISD::SETO: 2264 CondCode = AArch64CC::MI; 2265 CondCode2 = AArch64CC::GE; 2266 break; 2267 case ISD::SETUEQ: 2268 case ISD::SETULT: 2269 case ISD::SETULE: 2270 case ISD::SETUGT: 2271 case ISD::SETUGE: 2272 // All of the compare-mask comparisons are ordered, but we can switch 2273 // between the two by a double inversion. E.g. ULE == !OGT. 2274 Invert = true; 2275 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32), 2276 CondCode, CondCode2); 2277 break; 2278 } 2279 } 2280 2281 static bool isLegalArithImmed(uint64_t C) { 2282 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 2283 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 2284 LLVM_DEBUG(dbgs() << "Is imm " << C 2285 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 2286 return IsLegal; 2287 } 2288 2289 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 2290 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 2291 // can be set differently by this operation. It comes down to whether 2292 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 2293 // everything is fine. If not then the optimization is wrong. Thus general 2294 // comparisons are only valid if op2 != 0. 2295 // 2296 // So, finally, the only LLVM-native comparisons that don't mention C and V 2297 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 2298 // the absence of information about op2. 2299 static bool isCMN(SDValue Op, ISD::CondCode CC) { 2300 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 2301 (CC == ISD::SETEQ || CC == ISD::SETNE); 2302 } 2303 2304 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl, 2305 SelectionDAG &DAG, SDValue Chain, 2306 bool IsSignaling) { 2307 EVT VT = LHS.getValueType(); 2308 assert(VT != MVT::f128); 2309 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented"); 2310 unsigned Opcode = 2311 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP; 2312 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS}); 2313 } 2314 2315 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2316 const SDLoc &dl, SelectionDAG &DAG) { 2317 EVT VT = LHS.getValueType(); 2318 const bool FullFP16 = 2319 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 2320 2321 if (VT.isFloatingPoint()) { 2322 assert(VT != MVT::f128); 2323 if (VT == MVT::f16 && !FullFP16) { 2324 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 2325 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 2326 VT = MVT::f32; 2327 } 2328 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 2329 } 2330 2331 // The CMP instruction is just an alias for SUBS, and representing it as 2332 // SUBS means that it's possible to get CSE with subtract operations. 2333 // A later phase can perform the optimization of setting the destination 2334 // register to WZR/XZR if it ends up being unused. 2335 unsigned Opcode = AArch64ISD::SUBS; 2336 2337 if (isCMN(RHS, CC)) { 2338 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 2339 Opcode = AArch64ISD::ADDS; 2340 RHS = RHS.getOperand(1); 2341 } else if (isCMN(LHS, CC)) { 2342 // As we are looking for EQ/NE compares, the operands can be commuted ; can 2343 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 2344 Opcode = AArch64ISD::ADDS; 2345 LHS = LHS.getOperand(1); 2346 } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) { 2347 if (LHS.getOpcode() == ISD::AND) { 2348 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 2349 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 2350 // of the signed comparisons. 2351 const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl, 2352 DAG.getVTList(VT, MVT_CC), 2353 LHS.getOperand(0), 2354 LHS.getOperand(1)); 2355 // Replace all users of (and X, Y) with newly generated (ands X, Y) 2356 DAG.ReplaceAllUsesWith(LHS, ANDSNode); 2357 return ANDSNode.getValue(1); 2358 } else if (LHS.getOpcode() == AArch64ISD::ANDS) { 2359 // Use result of ANDS 2360 return LHS.getValue(1); 2361 } 2362 } 2363 2364 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 2365 .getValue(1); 2366 } 2367 2368 /// \defgroup AArch64CCMP CMP;CCMP matching 2369 /// 2370 /// These functions deal with the formation of CMP;CCMP;... sequences. 2371 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 2372 /// a comparison. They set the NZCV flags to a predefined value if their 2373 /// predicate is false. This allows to express arbitrary conjunctions, for 2374 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 2375 /// expressed as: 2376 /// cmp A 2377 /// ccmp B, inv(CB), CA 2378 /// check for CB flags 2379 /// 2380 /// This naturally lets us implement chains of AND operations with SETCC 2381 /// operands. And we can even implement some other situations by transforming 2382 /// them: 2383 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 2384 /// negating the flags used in a CCMP/FCCMP operations. 2385 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 2386 /// by negating the flags we test for afterwards. i.e. 2387 /// NEG (CMP CCMP CCCMP ...) can be implemented. 2388 /// - Note that we can only ever negate all previously processed results. 2389 /// What we can not implement by flipping the flags to test is a negation 2390 /// of two sub-trees (because the negation affects all sub-trees emitted so 2391 /// far, so the 2nd sub-tree we emit would also affect the first). 2392 /// With those tools we can implement some OR operations: 2393 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 2394 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 2395 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 2396 /// elimination rules from earlier to implement the whole thing as a 2397 /// CCMP/FCCMP chain. 2398 /// 2399 /// As complete example: 2400 /// or (or (setCA (cmp A)) (setCB (cmp B))) 2401 /// (and (setCC (cmp C)) (setCD (cmp D)))" 2402 /// can be reassociated to: 2403 /// or (and (setCC (cmp C)) setCD (cmp D)) 2404 // (or (setCA (cmp A)) (setCB (cmp B))) 2405 /// can be transformed to: 2406 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 2407 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 2408 /// which can be implemented as: 2409 /// cmp C 2410 /// ccmp D, inv(CD), CC 2411 /// ccmp A, CA, inv(CD) 2412 /// ccmp B, CB, inv(CA) 2413 /// check for CB flags 2414 /// 2415 /// A counterexample is "or (and A B) (and C D)" which translates to 2416 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 2417 /// can only implement 1 of the inner (not) operations, but not both! 2418 /// @{ 2419 2420 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 2421 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 2422 ISD::CondCode CC, SDValue CCOp, 2423 AArch64CC::CondCode Predicate, 2424 AArch64CC::CondCode OutCC, 2425 const SDLoc &DL, SelectionDAG &DAG) { 2426 unsigned Opcode = 0; 2427 const bool FullFP16 = 2428 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 2429 2430 if (LHS.getValueType().isFloatingPoint()) { 2431 assert(LHS.getValueType() != MVT::f128); 2432 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 2433 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 2434 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 2435 } 2436 Opcode = AArch64ISD::FCCMP; 2437 } else if (RHS.getOpcode() == ISD::SUB) { 2438 SDValue SubOp0 = RHS.getOperand(0); 2439 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2440 // See emitComparison() on why we can only do this for SETEQ and SETNE. 2441 Opcode = AArch64ISD::CCMN; 2442 RHS = RHS.getOperand(1); 2443 } 2444 } 2445 if (Opcode == 0) 2446 Opcode = AArch64ISD::CCMP; 2447 2448 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 2449 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 2450 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 2451 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 2452 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 2453 } 2454 2455 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 2456 /// expressed as a conjunction. See \ref AArch64CCMP. 2457 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 2458 /// changing the conditions on the SETCC tests. 2459 /// (this means we can call emitConjunctionRec() with 2460 /// Negate==true on this sub-tree) 2461 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 2462 /// cannot do the negation naturally. We are required to 2463 /// emit the subtree first in this case. 2464 /// \param WillNegate Is true if are called when the result of this 2465 /// subexpression must be negated. This happens when the 2466 /// outer expression is an OR. We can use this fact to know 2467 /// that we have a double negation (or (or ...) ...) that 2468 /// can be implemented for free. 2469 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 2470 bool &MustBeFirst, bool WillNegate, 2471 unsigned Depth = 0) { 2472 if (!Val.hasOneUse()) 2473 return false; 2474 unsigned Opcode = Val->getOpcode(); 2475 if (Opcode == ISD::SETCC) { 2476 if (Val->getOperand(0).getValueType() == MVT::f128) 2477 return false; 2478 CanNegate = true; 2479 MustBeFirst = false; 2480 return true; 2481 } 2482 // Protect against exponential runtime and stack overflow. 2483 if (Depth > 6) 2484 return false; 2485 if (Opcode == ISD::AND || Opcode == ISD::OR) { 2486 bool IsOR = Opcode == ISD::OR; 2487 SDValue O0 = Val->getOperand(0); 2488 SDValue O1 = Val->getOperand(1); 2489 bool CanNegateL; 2490 bool MustBeFirstL; 2491 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 2492 return false; 2493 bool CanNegateR; 2494 bool MustBeFirstR; 2495 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 2496 return false; 2497 2498 if (MustBeFirstL && MustBeFirstR) 2499 return false; 2500 2501 if (IsOR) { 2502 // For an OR expression we need to be able to naturally negate at least 2503 // one side or we cannot do the transformation at all. 2504 if (!CanNegateL && !CanNegateR) 2505 return false; 2506 // If we the result of the OR will be negated and we can naturally negate 2507 // the leafs, then this sub-tree as a whole negates naturally. 2508 CanNegate = WillNegate && CanNegateL && CanNegateR; 2509 // If we cannot naturally negate the whole sub-tree, then this must be 2510 // emitted first. 2511 MustBeFirst = !CanNegate; 2512 } else { 2513 assert(Opcode == ISD::AND && "Must be OR or AND"); 2514 // We cannot naturally negate an AND operation. 2515 CanNegate = false; 2516 MustBeFirst = MustBeFirstL || MustBeFirstR; 2517 } 2518 return true; 2519 } 2520 return false; 2521 } 2522 2523 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 2524 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 2525 /// Tries to transform the given i1 producing node @p Val to a series compare 2526 /// and conditional compare operations. @returns an NZCV flags producing node 2527 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 2528 /// transformation was not possible. 2529 /// \p Negate is true if we want this sub-tree being negated just by changing 2530 /// SETCC conditions. 2531 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 2532 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 2533 AArch64CC::CondCode Predicate) { 2534 // We're at a tree leaf, produce a conditional comparison operation. 2535 unsigned Opcode = Val->getOpcode(); 2536 if (Opcode == ISD::SETCC) { 2537 SDValue LHS = Val->getOperand(0); 2538 SDValue RHS = Val->getOperand(1); 2539 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 2540 bool isInteger = LHS.getValueType().isInteger(); 2541 if (Negate) 2542 CC = getSetCCInverse(CC, LHS.getValueType()); 2543 SDLoc DL(Val); 2544 // Determine OutCC and handle FP special case. 2545 if (isInteger) { 2546 OutCC = changeIntCCToAArch64CC(CC); 2547 } else { 2548 assert(LHS.getValueType().isFloatingPoint()); 2549 AArch64CC::CondCode ExtraCC; 2550 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 2551 // Some floating point conditions can't be tested with a single condition 2552 // code. Construct an additional comparison in this case. 2553 if (ExtraCC != AArch64CC::AL) { 2554 SDValue ExtraCmp; 2555 if (!CCOp.getNode()) 2556 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 2557 else 2558 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 2559 ExtraCC, DL, DAG); 2560 CCOp = ExtraCmp; 2561 Predicate = ExtraCC; 2562 } 2563 } 2564 2565 // Produce a normal comparison if we are first in the chain 2566 if (!CCOp) 2567 return emitComparison(LHS, RHS, CC, DL, DAG); 2568 // Otherwise produce a ccmp. 2569 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 2570 DAG); 2571 } 2572 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 2573 2574 bool IsOR = Opcode == ISD::OR; 2575 2576 SDValue LHS = Val->getOperand(0); 2577 bool CanNegateL; 2578 bool MustBeFirstL; 2579 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 2580 assert(ValidL && "Valid conjunction/disjunction tree"); 2581 (void)ValidL; 2582 2583 SDValue RHS = Val->getOperand(1); 2584 bool CanNegateR; 2585 bool MustBeFirstR; 2586 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 2587 assert(ValidR && "Valid conjunction/disjunction tree"); 2588 (void)ValidR; 2589 2590 // Swap sub-tree that must come first to the right side. 2591 if (MustBeFirstL) { 2592 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 2593 std::swap(LHS, RHS); 2594 std::swap(CanNegateL, CanNegateR); 2595 std::swap(MustBeFirstL, MustBeFirstR); 2596 } 2597 2598 bool NegateR; 2599 bool NegateAfterR; 2600 bool NegateL; 2601 bool NegateAfterAll; 2602 if (Opcode == ISD::OR) { 2603 // Swap the sub-tree that we can negate naturally to the left. 2604 if (!CanNegateL) { 2605 assert(CanNegateR && "at least one side must be negatable"); 2606 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 2607 assert(!Negate); 2608 std::swap(LHS, RHS); 2609 NegateR = false; 2610 NegateAfterR = true; 2611 } else { 2612 // Negate the left sub-tree if possible, otherwise negate the result. 2613 NegateR = CanNegateR; 2614 NegateAfterR = !CanNegateR; 2615 } 2616 NegateL = true; 2617 NegateAfterAll = !Negate; 2618 } else { 2619 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 2620 assert(!Negate && "Valid conjunction/disjunction tree"); 2621 2622 NegateL = false; 2623 NegateR = false; 2624 NegateAfterR = false; 2625 NegateAfterAll = false; 2626 } 2627 2628 // Emit sub-trees. 2629 AArch64CC::CondCode RHSCC; 2630 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 2631 if (NegateAfterR) 2632 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 2633 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 2634 if (NegateAfterAll) 2635 OutCC = AArch64CC::getInvertedCondCode(OutCC); 2636 return CmpL; 2637 } 2638 2639 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 2640 /// In some cases this is even possible with OR operations in the expression. 2641 /// See \ref AArch64CCMP. 2642 /// \see emitConjunctionRec(). 2643 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 2644 AArch64CC::CondCode &OutCC) { 2645 bool DummyCanNegate; 2646 bool DummyMustBeFirst; 2647 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 2648 return SDValue(); 2649 2650 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 2651 } 2652 2653 /// @} 2654 2655 /// Returns how profitable it is to fold a comparison's operand's shift and/or 2656 /// extension operations. 2657 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 2658 auto isSupportedExtend = [&](SDValue V) { 2659 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 2660 return true; 2661 2662 if (V.getOpcode() == ISD::AND) 2663 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2664 uint64_t Mask = MaskCst->getZExtValue(); 2665 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 2666 } 2667 2668 return false; 2669 }; 2670 2671 if (!Op.hasOneUse()) 2672 return 0; 2673 2674 if (isSupportedExtend(Op)) 2675 return 1; 2676 2677 unsigned Opc = Op.getOpcode(); 2678 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 2679 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2680 uint64_t Shift = ShiftCst->getZExtValue(); 2681 if (isSupportedExtend(Op.getOperand(0))) 2682 return (Shift <= 4) ? 2 : 1; 2683 EVT VT = Op.getValueType(); 2684 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 2685 return 1; 2686 } 2687 2688 return 0; 2689 } 2690 2691 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2692 SDValue &AArch64cc, SelectionDAG &DAG, 2693 const SDLoc &dl) { 2694 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 2695 EVT VT = RHS.getValueType(); 2696 uint64_t C = RHSC->getZExtValue(); 2697 if (!isLegalArithImmed(C)) { 2698 // Constant does not fit, try adjusting it by one? 2699 switch (CC) { 2700 default: 2701 break; 2702 case ISD::SETLT: 2703 case ISD::SETGE: 2704 if ((VT == MVT::i32 && C != 0x80000000 && 2705 isLegalArithImmed((uint32_t)(C - 1))) || 2706 (VT == MVT::i64 && C != 0x80000000ULL && 2707 isLegalArithImmed(C - 1ULL))) { 2708 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 2709 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2710 RHS = DAG.getConstant(C, dl, VT); 2711 } 2712 break; 2713 case ISD::SETULT: 2714 case ISD::SETUGE: 2715 if ((VT == MVT::i32 && C != 0 && 2716 isLegalArithImmed((uint32_t)(C - 1))) || 2717 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 2718 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 2719 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2720 RHS = DAG.getConstant(C, dl, VT); 2721 } 2722 break; 2723 case ISD::SETLE: 2724 case ISD::SETGT: 2725 if ((VT == MVT::i32 && C != INT32_MAX && 2726 isLegalArithImmed((uint32_t)(C + 1))) || 2727 (VT == MVT::i64 && C != INT64_MAX && 2728 isLegalArithImmed(C + 1ULL))) { 2729 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2730 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2731 RHS = DAG.getConstant(C, dl, VT); 2732 } 2733 break; 2734 case ISD::SETULE: 2735 case ISD::SETUGT: 2736 if ((VT == MVT::i32 && C != UINT32_MAX && 2737 isLegalArithImmed((uint32_t)(C + 1))) || 2738 (VT == MVT::i64 && C != UINT64_MAX && 2739 isLegalArithImmed(C + 1ULL))) { 2740 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2741 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2742 RHS = DAG.getConstant(C, dl, VT); 2743 } 2744 break; 2745 } 2746 } 2747 } 2748 2749 // Comparisons are canonicalized so that the RHS operand is simpler than the 2750 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2751 // can fold some shift+extend operations on the RHS operand, so swap the 2752 // operands if that can be done. 2753 // 2754 // For example: 2755 // lsl w13, w11, #1 2756 // cmp w13, w12 2757 // can be turned into: 2758 // cmp w12, w11, lsl #1 2759 if (!isa<ConstantSDNode>(RHS) || 2760 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2761 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2762 2763 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2764 std::swap(LHS, RHS); 2765 CC = ISD::getSetCCSwappedOperands(CC); 2766 } 2767 } 2768 2769 SDValue Cmp; 2770 AArch64CC::CondCode AArch64CC; 2771 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2772 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2773 2774 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2775 // For the i8 operand, the largest immediate is 255, so this can be easily 2776 // encoded in the compare instruction. For the i16 operand, however, the 2777 // largest immediate cannot be encoded in the compare. 2778 // Therefore, use a sign extending load and cmn to avoid materializing the 2779 // -1 constant. For example, 2780 // movz w1, #65535 2781 // ldrh w0, [x0, #0] 2782 // cmp w0, w1 2783 // > 2784 // ldrsh w0, [x0, #0] 2785 // cmn w0, #1 2786 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2787 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2788 // ensure both the LHS and RHS are truly zero extended and to make sure the 2789 // transformation is profitable. 2790 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2791 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2792 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2793 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2794 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2795 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2796 SDValue SExt = 2797 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2798 DAG.getValueType(MVT::i16)); 2799 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2800 RHS.getValueType()), 2801 CC, dl, DAG); 2802 AArch64CC = changeIntCCToAArch64CC(CC); 2803 } 2804 } 2805 2806 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2807 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2808 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2809 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2810 } 2811 } 2812 } 2813 2814 if (!Cmp) { 2815 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2816 AArch64CC = changeIntCCToAArch64CC(CC); 2817 } 2818 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2819 return Cmp; 2820 } 2821 2822 static std::pair<SDValue, SDValue> 2823 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2824 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2825 "Unsupported value type"); 2826 SDValue Value, Overflow; 2827 SDLoc DL(Op); 2828 SDValue LHS = Op.getOperand(0); 2829 SDValue RHS = Op.getOperand(1); 2830 unsigned Opc = 0; 2831 switch (Op.getOpcode()) { 2832 default: 2833 llvm_unreachable("Unknown overflow instruction!"); 2834 case ISD::SADDO: 2835 Opc = AArch64ISD::ADDS; 2836 CC = AArch64CC::VS; 2837 break; 2838 case ISD::UADDO: 2839 Opc = AArch64ISD::ADDS; 2840 CC = AArch64CC::HS; 2841 break; 2842 case ISD::SSUBO: 2843 Opc = AArch64ISD::SUBS; 2844 CC = AArch64CC::VS; 2845 break; 2846 case ISD::USUBO: 2847 Opc = AArch64ISD::SUBS; 2848 CC = AArch64CC::LO; 2849 break; 2850 // Multiply needs a little bit extra work. 2851 case ISD::SMULO: 2852 case ISD::UMULO: { 2853 CC = AArch64CC::NE; 2854 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2855 if (Op.getValueType() == MVT::i32) { 2856 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2857 // For a 32 bit multiply with overflow check we want the instruction 2858 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2859 // need to generate the following pattern: 2860 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2861 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2862 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2863 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2864 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2865 DAG.getConstant(0, DL, MVT::i64)); 2866 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2867 // operation. We need to clear out the upper 32 bits, because we used a 2868 // widening multiply that wrote all 64 bits. In the end this should be a 2869 // noop. 2870 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2871 if (IsSigned) { 2872 // The signed overflow check requires more than just a simple check for 2873 // any bit set in the upper 32 bits of the result. These bits could be 2874 // just the sign bits of a negative number. To perform the overflow 2875 // check we have to arithmetic shift right the 32nd bit of the result by 2876 // 31 bits. Then we compare the result to the upper 32 bits. 2877 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2878 DAG.getConstant(32, DL, MVT::i64)); 2879 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2880 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2881 DAG.getConstant(31, DL, MVT::i64)); 2882 // It is important that LowerBits is last, otherwise the arithmetic 2883 // shift will not be folded into the compare (SUBS). 2884 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2885 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2886 .getValue(1); 2887 } else { 2888 // The overflow check for unsigned multiply is easy. We only need to 2889 // check if any of the upper 32 bits are set. This can be done with a 2890 // CMP (shifted register). For that we need to generate the following 2891 // pattern: 2892 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2893 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2894 DAG.getConstant(32, DL, MVT::i64)); 2895 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2896 Overflow = 2897 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2898 DAG.getConstant(0, DL, MVT::i64), 2899 UpperBits).getValue(1); 2900 } 2901 break; 2902 } 2903 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2904 // For the 64 bit multiply 2905 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2906 if (IsSigned) { 2907 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2908 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2909 DAG.getConstant(63, DL, MVT::i64)); 2910 // It is important that LowerBits is last, otherwise the arithmetic 2911 // shift will not be folded into the compare (SUBS). 2912 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2913 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2914 .getValue(1); 2915 } else { 2916 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2917 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2918 Overflow = 2919 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2920 DAG.getConstant(0, DL, MVT::i64), 2921 UpperBits).getValue(1); 2922 } 2923 break; 2924 } 2925 } // switch (...) 2926 2927 if (Opc) { 2928 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2929 2930 // Emit the AArch64 operation with overflow check. 2931 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2932 Overflow = Value.getValue(1); 2933 } 2934 return std::make_pair(Value, Overflow); 2935 } 2936 2937 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const { 2938 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 2939 return LowerToScalableOp(Op, DAG); 2940 2941 SDValue Sel = Op.getOperand(0); 2942 SDValue Other = Op.getOperand(1); 2943 SDLoc dl(Sel); 2944 2945 // If the operand is an overflow checking operation, invert the condition 2946 // code and kill the Not operation. I.e., transform: 2947 // (xor (overflow_op_bool, 1)) 2948 // --> 2949 // (csel 1, 0, invert(cc), overflow_op_bool) 2950 // ... which later gets transformed to just a cset instruction with an 2951 // inverted condition code, rather than a cset + eor sequence. 2952 if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) { 2953 // Only lower legal XALUO ops. 2954 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2955 return SDValue(); 2956 2957 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2958 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2959 AArch64CC::CondCode CC; 2960 SDValue Value, Overflow; 2961 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2962 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2963 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2964 CCVal, Overflow); 2965 } 2966 // If neither operand is a SELECT_CC, give up. 2967 if (Sel.getOpcode() != ISD::SELECT_CC) 2968 std::swap(Sel, Other); 2969 if (Sel.getOpcode() != ISD::SELECT_CC) 2970 return Op; 2971 2972 // The folding we want to perform is: 2973 // (xor x, (select_cc a, b, cc, 0, -1) ) 2974 // --> 2975 // (csel x, (xor x, -1), cc ...) 2976 // 2977 // The latter will get matched to a CSINV instruction. 2978 2979 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2980 SDValue LHS = Sel.getOperand(0); 2981 SDValue RHS = Sel.getOperand(1); 2982 SDValue TVal = Sel.getOperand(2); 2983 SDValue FVal = Sel.getOperand(3); 2984 2985 // FIXME: This could be generalized to non-integer comparisons. 2986 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2987 return Op; 2988 2989 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2990 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2991 2992 // The values aren't constants, this isn't the pattern we're looking for. 2993 if (!CFVal || !CTVal) 2994 return Op; 2995 2996 // We can commute the SELECT_CC by inverting the condition. This 2997 // might be needed to make this fit into a CSINV pattern. 2998 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2999 std::swap(TVal, FVal); 3000 std::swap(CTVal, CFVal); 3001 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 3002 } 3003 3004 // If the constants line up, perform the transform! 3005 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 3006 SDValue CCVal; 3007 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 3008 3009 FVal = Other; 3010 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 3011 DAG.getConstant(-1ULL, dl, Other.getValueType())); 3012 3013 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 3014 CCVal, Cmp); 3015 } 3016 3017 return Op; 3018 } 3019 3020 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 3021 EVT VT = Op.getValueType(); 3022 3023 // Let legalize expand this if it isn't a legal type yet. 3024 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 3025 return SDValue(); 3026 3027 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 3028 3029 unsigned Opc; 3030 bool ExtraOp = false; 3031 switch (Op.getOpcode()) { 3032 default: 3033 llvm_unreachable("Invalid code"); 3034 case ISD::ADDC: 3035 Opc = AArch64ISD::ADDS; 3036 break; 3037 case ISD::SUBC: 3038 Opc = AArch64ISD::SUBS; 3039 break; 3040 case ISD::ADDE: 3041 Opc = AArch64ISD::ADCS; 3042 ExtraOp = true; 3043 break; 3044 case ISD::SUBE: 3045 Opc = AArch64ISD::SBCS; 3046 ExtraOp = true; 3047 break; 3048 } 3049 3050 if (!ExtraOp) 3051 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 3052 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 3053 Op.getOperand(2)); 3054 } 3055 3056 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 3057 // Let legalize expand this if it isn't a legal type yet. 3058 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3059 return SDValue(); 3060 3061 SDLoc dl(Op); 3062 AArch64CC::CondCode CC; 3063 // The actual operation that sets the overflow or carry flag. 3064 SDValue Value, Overflow; 3065 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 3066 3067 // We use 0 and 1 as false and true values. 3068 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3069 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3070 3071 // We use an inverted condition, because the conditional select is inverted 3072 // too. This will allow it to be selected to a single instruction: 3073 // CSINC Wd, WZR, WZR, invert(cond). 3074 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 3075 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 3076 CCVal, Overflow); 3077 3078 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3079 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3080 } 3081 3082 // Prefetch operands are: 3083 // 1: Address to prefetch 3084 // 2: bool isWrite 3085 // 3: int locality (0 = no locality ... 3 = extreme locality) 3086 // 4: bool isDataCache 3087 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 3088 SDLoc DL(Op); 3089 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 3090 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 3091 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3092 3093 bool IsStream = !Locality; 3094 // When the locality number is set 3095 if (Locality) { 3096 // The front-end should have filtered out the out-of-range values 3097 assert(Locality <= 3 && "Prefetch locality out-of-range"); 3098 // The locality degree is the opposite of the cache speed. 3099 // Put the number the other way around. 3100 // The encoding starts at 0 for level 1 3101 Locality = 3 - Locality; 3102 } 3103 3104 // built the mask value encoding the expected behavior. 3105 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 3106 (!IsData << 3) | // IsDataCache bit 3107 (Locality << 1) | // Cache level bits 3108 (unsigned)IsStream; // Stream bit 3109 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 3110 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 3111 } 3112 3113 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 3114 SelectionDAG &DAG) const { 3115 if (Op.getValueType().isScalableVector()) 3116 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU); 3117 3118 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 3119 return SDValue(); 3120 } 3121 3122 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 3123 SelectionDAG &DAG) const { 3124 if (Op.getValueType().isScalableVector()) 3125 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU); 3126 3127 bool IsStrict = Op->isStrictFPOpcode(); 3128 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3129 EVT SrcVT = SrcVal.getValueType(); 3130 3131 if (SrcVT != MVT::f128) { 3132 // Expand cases where the input is a vector bigger than NEON. 3133 if (useSVEForFixedLengthVectorVT(SrcVT)) 3134 return SDValue(); 3135 3136 // It's legal except when f128 is involved 3137 return Op; 3138 } 3139 3140 return SDValue(); 3141 } 3142 3143 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 3144 SelectionDAG &DAG) const { 3145 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 3146 // Any additional optimization in this function should be recorded 3147 // in the cost tables. 3148 EVT InVT = Op.getOperand(0).getValueType(); 3149 EVT VT = Op.getValueType(); 3150 3151 if (VT.isScalableVector()) { 3152 unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT 3153 ? AArch64ISD::FCVTZU_MERGE_PASSTHRU 3154 : AArch64ISD::FCVTZS_MERGE_PASSTHRU; 3155 return LowerToPredicatedOp(Op, DAG, Opcode); 3156 } 3157 3158 unsigned NumElts = InVT.getVectorNumElements(); 3159 3160 // f16 conversions are promoted to f32 when full fp16 is not supported. 3161 if (InVT.getVectorElementType() == MVT::f16 && 3162 !Subtarget->hasFullFP16()) { 3163 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 3164 SDLoc dl(Op); 3165 return DAG.getNode( 3166 Op.getOpcode(), dl, Op.getValueType(), 3167 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 3168 } 3169 3170 uint64_t VTSize = VT.getFixedSizeInBits(); 3171 uint64_t InVTSize = InVT.getFixedSizeInBits(); 3172 if (VTSize < InVTSize) { 3173 SDLoc dl(Op); 3174 SDValue Cv = 3175 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 3176 Op.getOperand(0)); 3177 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 3178 } 3179 3180 if (VTSize > InVTSize) { 3181 SDLoc dl(Op); 3182 MVT ExtVT = 3183 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 3184 VT.getVectorNumElements()); 3185 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 3186 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 3187 } 3188 3189 // Type changing conversions are illegal. 3190 return Op; 3191 } 3192 3193 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 3194 SelectionDAG &DAG) const { 3195 bool IsStrict = Op->isStrictFPOpcode(); 3196 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3197 3198 if (SrcVal.getValueType().isVector()) 3199 return LowerVectorFP_TO_INT(Op, DAG); 3200 3201 // f16 conversions are promoted to f32 when full fp16 is not supported. 3202 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 3203 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 3204 SDLoc dl(Op); 3205 return DAG.getNode( 3206 Op.getOpcode(), dl, Op.getValueType(), 3207 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal)); 3208 } 3209 3210 if (SrcVal.getValueType() != MVT::f128) { 3211 // It's legal except when f128 is involved 3212 return Op; 3213 } 3214 3215 return SDValue(); 3216 } 3217 3218 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op, 3219 SelectionDAG &DAG) const { 3220 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 3221 // Any additional optimization in this function should be recorded 3222 // in the cost tables. 3223 EVT VT = Op.getValueType(); 3224 SDLoc dl(Op); 3225 SDValue In = Op.getOperand(0); 3226 EVT InVT = In.getValueType(); 3227 unsigned Opc = Op.getOpcode(); 3228 bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 3229 3230 if (VT.isScalableVector()) { 3231 if (InVT.getVectorElementType() == MVT::i1) { 3232 // We can't directly extend an SVE predicate; extend it first. 3233 unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3234 EVT CastVT = getPromotedVTForPredicate(InVT); 3235 In = DAG.getNode(CastOpc, dl, CastVT, In); 3236 return DAG.getNode(Opc, dl, VT, In); 3237 } 3238 3239 unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU 3240 : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU; 3241 return LowerToPredicatedOp(Op, DAG, Opcode); 3242 } 3243 3244 uint64_t VTSize = VT.getFixedSizeInBits(); 3245 uint64_t InVTSize = InVT.getFixedSizeInBits(); 3246 if (VTSize < InVTSize) { 3247 MVT CastVT = 3248 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 3249 InVT.getVectorNumElements()); 3250 In = DAG.getNode(Opc, dl, CastVT, In); 3251 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 3252 } 3253 3254 if (VTSize > InVTSize) { 3255 unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 3256 EVT CastVT = VT.changeVectorElementTypeToInteger(); 3257 In = DAG.getNode(CastOpc, dl, CastVT, In); 3258 return DAG.getNode(Opc, dl, VT, In); 3259 } 3260 3261 return Op; 3262 } 3263 3264 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 3265 SelectionDAG &DAG) const { 3266 if (Op.getValueType().isVector()) 3267 return LowerVectorINT_TO_FP(Op, DAG); 3268 3269 bool IsStrict = Op->isStrictFPOpcode(); 3270 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 3271 3272 // f16 conversions are promoted to f32 when full fp16 is not supported. 3273 if (Op.getValueType() == MVT::f16 && 3274 !Subtarget->hasFullFP16()) { 3275 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 3276 SDLoc dl(Op); 3277 return DAG.getNode( 3278 ISD::FP_ROUND, dl, MVT::f16, 3279 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal), 3280 DAG.getIntPtrConstant(0, dl)); 3281 } 3282 3283 // i128 conversions are libcalls. 3284 if (SrcVal.getValueType() == MVT::i128) 3285 return SDValue(); 3286 3287 // Other conversions are legal, unless it's to the completely software-based 3288 // fp128. 3289 if (Op.getValueType() != MVT::f128) 3290 return Op; 3291 return SDValue(); 3292 } 3293 3294 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 3295 SelectionDAG &DAG) const { 3296 // For iOS, we want to call an alternative entry point: __sincos_stret, 3297 // which returns the values in two S / D registers. 3298 SDLoc dl(Op); 3299 SDValue Arg = Op.getOperand(0); 3300 EVT ArgVT = Arg.getValueType(); 3301 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 3302 3303 ArgListTy Args; 3304 ArgListEntry Entry; 3305 3306 Entry.Node = Arg; 3307 Entry.Ty = ArgTy; 3308 Entry.IsSExt = false; 3309 Entry.IsZExt = false; 3310 Args.push_back(Entry); 3311 3312 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 3313 : RTLIB::SINCOS_STRET_F32; 3314 const char *LibcallName = getLibcallName(LC); 3315 SDValue Callee = 3316 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 3317 3318 StructType *RetTy = StructType::get(ArgTy, ArgTy); 3319 TargetLowering::CallLoweringInfo CLI(DAG); 3320 CLI.setDebugLoc(dl) 3321 .setChain(DAG.getEntryNode()) 3322 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 3323 3324 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3325 return CallResult.first; 3326 } 3327 3328 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 3329 EVT OpVT = Op.getValueType(); 3330 if (OpVT != MVT::f16 && OpVT != MVT::bf16) 3331 return SDValue(); 3332 3333 assert(Op.getOperand(0).getValueType() == MVT::i16); 3334 SDLoc DL(Op); 3335 3336 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 3337 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 3338 return SDValue( 3339 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op, 3340 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 3341 0); 3342 } 3343 3344 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 3345 if (OrigVT.getSizeInBits() >= 64) 3346 return OrigVT; 3347 3348 assert(OrigVT.isSimple() && "Expecting a simple value type"); 3349 3350 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 3351 switch (OrigSimpleTy) { 3352 default: llvm_unreachable("Unexpected Vector Type"); 3353 case MVT::v2i8: 3354 case MVT::v2i16: 3355 return MVT::v2i32; 3356 case MVT::v4i8: 3357 return MVT::v4i16; 3358 } 3359 } 3360 3361 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 3362 const EVT &OrigTy, 3363 const EVT &ExtTy, 3364 unsigned ExtOpcode) { 3365 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 3366 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 3367 // 64-bits we need to insert a new extension so that it will be 64-bits. 3368 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 3369 if (OrigTy.getSizeInBits() >= 64) 3370 return N; 3371 3372 // Must extend size to at least 64 bits to be used as an operand for VMULL. 3373 EVT NewVT = getExtensionTo64Bits(OrigTy); 3374 3375 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 3376 } 3377 3378 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 3379 bool isSigned) { 3380 EVT VT = N->getValueType(0); 3381 3382 if (N->getOpcode() != ISD::BUILD_VECTOR) 3383 return false; 3384 3385 for (const SDValue &Elt : N->op_values()) { 3386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 3387 unsigned EltSize = VT.getScalarSizeInBits(); 3388 unsigned HalfSize = EltSize / 2; 3389 if (isSigned) { 3390 if (!isIntN(HalfSize, C->getSExtValue())) 3391 return false; 3392 } else { 3393 if (!isUIntN(HalfSize, C->getZExtValue())) 3394 return false; 3395 } 3396 continue; 3397 } 3398 return false; 3399 } 3400 3401 return true; 3402 } 3403 3404 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 3405 if (N->getOpcode() == ISD::SIGN_EXTEND || 3406 N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND) 3407 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 3408 N->getOperand(0)->getValueType(0), 3409 N->getValueType(0), 3410 N->getOpcode()); 3411 3412 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 3413 EVT VT = N->getValueType(0); 3414 SDLoc dl(N); 3415 unsigned EltSize = VT.getScalarSizeInBits() / 2; 3416 unsigned NumElts = VT.getVectorNumElements(); 3417 MVT TruncVT = MVT::getIntegerVT(EltSize); 3418 SmallVector<SDValue, 8> Ops; 3419 for (unsigned i = 0; i != NumElts; ++i) { 3420 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 3421 const APInt &CInt = C->getAPIntValue(); 3422 // Element types smaller than 32 bits are not legal, so use i32 elements. 3423 // The values are implicitly truncated so sext vs. zext doesn't matter. 3424 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 3425 } 3426 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 3427 } 3428 3429 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 3430 return N->getOpcode() == ISD::SIGN_EXTEND || 3431 N->getOpcode() == ISD::ANY_EXTEND || 3432 isExtendedBUILD_VECTOR(N, DAG, true); 3433 } 3434 3435 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 3436 return N->getOpcode() == ISD::ZERO_EXTEND || 3437 N->getOpcode() == ISD::ANY_EXTEND || 3438 isExtendedBUILD_VECTOR(N, DAG, false); 3439 } 3440 3441 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 3442 unsigned Opcode = N->getOpcode(); 3443 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 3444 SDNode *N0 = N->getOperand(0).getNode(); 3445 SDNode *N1 = N->getOperand(1).getNode(); 3446 return N0->hasOneUse() && N1->hasOneUse() && 3447 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 3448 } 3449 return false; 3450 } 3451 3452 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 3453 unsigned Opcode = N->getOpcode(); 3454 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 3455 SDNode *N0 = N->getOperand(0).getNode(); 3456 SDNode *N1 = N->getOperand(1).getNode(); 3457 return N0->hasOneUse() && N1->hasOneUse() && 3458 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 3459 } 3460 return false; 3461 } 3462 3463 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 3464 SelectionDAG &DAG) const { 3465 // The rounding mode is in bits 23:22 of the FPSCR. 3466 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 3467 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 3468 // so that the shift + and get folded into a bitfield extract. 3469 SDLoc dl(Op); 3470 3471 SDValue Chain = Op.getOperand(0); 3472 SDValue FPCR_64 = DAG.getNode( 3473 ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other}, 3474 {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)}); 3475 Chain = FPCR_64.getValue(1); 3476 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 3477 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 3478 DAG.getConstant(1U << 22, dl, MVT::i32)); 3479 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 3480 DAG.getConstant(22, dl, MVT::i32)); 3481 SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 3482 DAG.getConstant(3, dl, MVT::i32)); 3483 return DAG.getMergeValues({AND, Chain}, dl); 3484 } 3485 3486 SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op, 3487 SelectionDAG &DAG) const { 3488 SDLoc DL(Op); 3489 SDValue Chain = Op->getOperand(0); 3490 SDValue RMValue = Op->getOperand(1); 3491 3492 // The rounding mode is in bits 23:22 of the FPCR. 3493 // The llvm.set.rounding argument value to the rounding mode in FPCR mapping 3494 // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is 3495 // ((arg - 1) & 3) << 22). 3496 // 3497 // The argument of llvm.set.rounding must be within the segment [0, 3], so 3498 // NearestTiesToAway (4) is not handled here. It is responsibility of the code 3499 // generated llvm.set.rounding to ensure this condition. 3500 3501 // Calculate new value of FPCR[23:22]. 3502 RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue, 3503 DAG.getConstant(1, DL, MVT::i32)); 3504 RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue, 3505 DAG.getConstant(0x3, DL, MVT::i32)); 3506 RMValue = 3507 DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue, 3508 DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32)); 3509 RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue); 3510 3511 // Get current value of FPCR. 3512 SDValue Ops[] = { 3513 Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)}; 3514 SDValue FPCR = 3515 DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops); 3516 Chain = FPCR.getValue(1); 3517 FPCR = FPCR.getValue(0); 3518 3519 // Put new rounding mode into FPSCR[23:22]. 3520 const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos); 3521 FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR, 3522 DAG.getConstant(RMMask, DL, MVT::i64)); 3523 FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue); 3524 SDValue Ops2[] = { 3525 Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64), 3526 FPCR}; 3527 return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2); 3528 } 3529 3530 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 3531 EVT VT = Op.getValueType(); 3532 3533 // If SVE is available then i64 vector multiplications can also be made legal. 3534 bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64; 3535 3536 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON)) 3537 return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON); 3538 3539 // Multiplications are only custom-lowered for 128-bit vectors so that 3540 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 3541 assert(VT.is128BitVector() && VT.isInteger() && 3542 "unexpected type for custom-lowering ISD::MUL"); 3543 SDNode *N0 = Op.getOperand(0).getNode(); 3544 SDNode *N1 = Op.getOperand(1).getNode(); 3545 unsigned NewOpc = 0; 3546 bool isMLA = false; 3547 bool isN0SExt = isSignExtended(N0, DAG); 3548 bool isN1SExt = isSignExtended(N1, DAG); 3549 if (isN0SExt && isN1SExt) 3550 NewOpc = AArch64ISD::SMULL; 3551 else { 3552 bool isN0ZExt = isZeroExtended(N0, DAG); 3553 bool isN1ZExt = isZeroExtended(N1, DAG); 3554 if (isN0ZExt && isN1ZExt) 3555 NewOpc = AArch64ISD::UMULL; 3556 else if (isN1SExt || isN1ZExt) { 3557 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 3558 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 3559 if (isN1SExt && isAddSubSExt(N0, DAG)) { 3560 NewOpc = AArch64ISD::SMULL; 3561 isMLA = true; 3562 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 3563 NewOpc = AArch64ISD::UMULL; 3564 isMLA = true; 3565 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 3566 std::swap(N0, N1); 3567 NewOpc = AArch64ISD::UMULL; 3568 isMLA = true; 3569 } 3570 } 3571 3572 if (!NewOpc) { 3573 if (VT == MVT::v2i64) 3574 // Fall through to expand this. It is not legal. 3575 return SDValue(); 3576 else 3577 // Other vector multiplications are legal. 3578 return Op; 3579 } 3580 } 3581 3582 // Legalize to a S/UMULL instruction 3583 SDLoc DL(Op); 3584 SDValue Op0; 3585 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 3586 if (!isMLA) { 3587 Op0 = skipExtensionForVectorMULL(N0, DAG); 3588 assert(Op0.getValueType().is64BitVector() && 3589 Op1.getValueType().is64BitVector() && 3590 "unexpected types for extended operands to VMULL"); 3591 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 3592 } 3593 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 3594 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 3595 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 3596 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 3597 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 3598 EVT Op1VT = Op1.getValueType(); 3599 return DAG.getNode(N0->getOpcode(), DL, VT, 3600 DAG.getNode(NewOpc, DL, VT, 3601 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 3602 DAG.getNode(NewOpc, DL, VT, 3603 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 3604 } 3605 3606 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT, 3607 int Pattern) { 3608 return DAG.getNode(AArch64ISD::PTRUE, DL, VT, 3609 DAG.getTargetConstant(Pattern, DL, MVT::i32)); 3610 } 3611 3612 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 3613 SelectionDAG &DAG) const { 3614 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3615 SDLoc dl(Op); 3616 switch (IntNo) { 3617 default: return SDValue(); // Don't custom lower most intrinsics. 3618 case Intrinsic::thread_pointer: { 3619 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3620 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 3621 } 3622 case Intrinsic::aarch64_neon_abs: { 3623 EVT Ty = Op.getValueType(); 3624 if (Ty == MVT::i64) { 3625 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 3626 Op.getOperand(1)); 3627 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 3628 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 3629 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 3630 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 3631 } else { 3632 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 3633 } 3634 } 3635 case Intrinsic::aarch64_neon_smax: 3636 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 3637 Op.getOperand(1), Op.getOperand(2)); 3638 case Intrinsic::aarch64_neon_umax: 3639 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 3640 Op.getOperand(1), Op.getOperand(2)); 3641 case Intrinsic::aarch64_neon_smin: 3642 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 3643 Op.getOperand(1), Op.getOperand(2)); 3644 case Intrinsic::aarch64_neon_umin: 3645 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 3646 Op.getOperand(1), Op.getOperand(2)); 3647 3648 case Intrinsic::aarch64_sve_sunpkhi: 3649 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 3650 Op.getOperand(1)); 3651 case Intrinsic::aarch64_sve_sunpklo: 3652 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 3653 Op.getOperand(1)); 3654 case Intrinsic::aarch64_sve_uunpkhi: 3655 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 3656 Op.getOperand(1)); 3657 case Intrinsic::aarch64_sve_uunpklo: 3658 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 3659 Op.getOperand(1)); 3660 case Intrinsic::aarch64_sve_clasta_n: 3661 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(), 3662 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3663 case Intrinsic::aarch64_sve_clastb_n: 3664 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(), 3665 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3666 case Intrinsic::aarch64_sve_lasta: 3667 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(), 3668 Op.getOperand(1), Op.getOperand(2)); 3669 case Intrinsic::aarch64_sve_lastb: 3670 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(), 3671 Op.getOperand(1), Op.getOperand(2)); 3672 case Intrinsic::aarch64_sve_rev: 3673 return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(), 3674 Op.getOperand(1)); 3675 case Intrinsic::aarch64_sve_tbl: 3676 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(), 3677 Op.getOperand(1), Op.getOperand(2)); 3678 case Intrinsic::aarch64_sve_trn1: 3679 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(), 3680 Op.getOperand(1), Op.getOperand(2)); 3681 case Intrinsic::aarch64_sve_trn2: 3682 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(), 3683 Op.getOperand(1), Op.getOperand(2)); 3684 case Intrinsic::aarch64_sve_uzp1: 3685 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(), 3686 Op.getOperand(1), Op.getOperand(2)); 3687 case Intrinsic::aarch64_sve_uzp2: 3688 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(), 3689 Op.getOperand(1), Op.getOperand(2)); 3690 case Intrinsic::aarch64_sve_zip1: 3691 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(), 3692 Op.getOperand(1), Op.getOperand(2)); 3693 case Intrinsic::aarch64_sve_zip2: 3694 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(), 3695 Op.getOperand(1), Op.getOperand(2)); 3696 case Intrinsic::aarch64_sve_ptrue: 3697 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(), 3698 Op.getOperand(1)); 3699 case Intrinsic::aarch64_sve_clz: 3700 return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(), 3701 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3702 case Intrinsic::aarch64_sve_cnt: { 3703 SDValue Data = Op.getOperand(3); 3704 // CTPOP only supports integer operands. 3705 if (Data.getValueType().isFloatingPoint()) 3706 Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data); 3707 return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(), 3708 Op.getOperand(2), Data, Op.getOperand(1)); 3709 } 3710 case Intrinsic::aarch64_sve_dupq_lane: 3711 return LowerDUPQLane(Op, DAG); 3712 case Intrinsic::aarch64_sve_convert_from_svbool: 3713 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(), 3714 Op.getOperand(1)); 3715 case Intrinsic::aarch64_sve_fneg: 3716 return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(), 3717 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3718 case Intrinsic::aarch64_sve_frintp: 3719 return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(), 3720 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3721 case Intrinsic::aarch64_sve_frintm: 3722 return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(), 3723 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3724 case Intrinsic::aarch64_sve_frinti: 3725 return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(), 3726 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3727 case Intrinsic::aarch64_sve_frintx: 3728 return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(), 3729 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3730 case Intrinsic::aarch64_sve_frinta: 3731 return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(), 3732 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3733 case Intrinsic::aarch64_sve_frintn: 3734 return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(), 3735 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3736 case Intrinsic::aarch64_sve_frintz: 3737 return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(), 3738 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3739 case Intrinsic::aarch64_sve_ucvtf: 3740 return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl, 3741 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3742 Op.getOperand(1)); 3743 case Intrinsic::aarch64_sve_scvtf: 3744 return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl, 3745 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3746 Op.getOperand(1)); 3747 case Intrinsic::aarch64_sve_fcvtzu: 3748 return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl, 3749 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3750 Op.getOperand(1)); 3751 case Intrinsic::aarch64_sve_fcvtzs: 3752 return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl, 3753 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3754 Op.getOperand(1)); 3755 case Intrinsic::aarch64_sve_fsqrt: 3756 return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(), 3757 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3758 case Intrinsic::aarch64_sve_frecpx: 3759 return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(), 3760 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3761 case Intrinsic::aarch64_sve_fabs: 3762 return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(), 3763 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3764 case Intrinsic::aarch64_sve_abs: 3765 return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(), 3766 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3767 case Intrinsic::aarch64_sve_neg: 3768 return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(), 3769 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3770 case Intrinsic::aarch64_sve_convert_to_svbool: { 3771 EVT OutVT = Op.getValueType(); 3772 EVT InVT = Op.getOperand(1).getValueType(); 3773 // Return the operand if the cast isn't changing type, 3774 // i.e. <n x 16 x i1> -> <n x 16 x i1> 3775 if (InVT == OutVT) 3776 return Op.getOperand(1); 3777 // Otherwise, zero the newly introduced lanes. 3778 SDValue Reinterpret = 3779 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1)); 3780 SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all); 3781 SDValue MaskReinterpret = 3782 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask); 3783 return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret); 3784 } 3785 3786 case Intrinsic::aarch64_sve_insr: { 3787 SDValue Scalar = Op.getOperand(2); 3788 EVT ScalarTy = Scalar.getValueType(); 3789 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 3790 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 3791 3792 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(), 3793 Op.getOperand(1), Scalar); 3794 } 3795 case Intrinsic::aarch64_sve_rbit: 3796 return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl, 3797 Op.getValueType(), Op.getOperand(2), Op.getOperand(3), 3798 Op.getOperand(1)); 3799 case Intrinsic::aarch64_sve_revb: 3800 return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(), 3801 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1)); 3802 case Intrinsic::aarch64_sve_sxtb: 3803 return DAG.getNode( 3804 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3805 Op.getOperand(2), Op.getOperand(3), 3806 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)), 3807 Op.getOperand(1)); 3808 case Intrinsic::aarch64_sve_sxth: 3809 return DAG.getNode( 3810 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3811 Op.getOperand(2), Op.getOperand(3), 3812 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)), 3813 Op.getOperand(1)); 3814 case Intrinsic::aarch64_sve_sxtw: 3815 return DAG.getNode( 3816 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3817 Op.getOperand(2), Op.getOperand(3), 3818 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)), 3819 Op.getOperand(1)); 3820 case Intrinsic::aarch64_sve_uxtb: 3821 return DAG.getNode( 3822 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3823 Op.getOperand(2), Op.getOperand(3), 3824 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)), 3825 Op.getOperand(1)); 3826 case Intrinsic::aarch64_sve_uxth: 3827 return DAG.getNode( 3828 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3829 Op.getOperand(2), Op.getOperand(3), 3830 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)), 3831 Op.getOperand(1)); 3832 case Intrinsic::aarch64_sve_uxtw: 3833 return DAG.getNode( 3834 AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(), 3835 Op.getOperand(2), Op.getOperand(3), 3836 DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)), 3837 Op.getOperand(1)); 3838 3839 case Intrinsic::localaddress: { 3840 const auto &MF = DAG.getMachineFunction(); 3841 const auto *RegInfo = Subtarget->getRegisterInfo(); 3842 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 3843 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 3844 Op.getSimpleValueType()); 3845 } 3846 3847 case Intrinsic::eh_recoverfp: { 3848 // FIXME: This needs to be implemented to correctly handle highly aligned 3849 // stack objects. For now we simply return the incoming FP. Refer D53541 3850 // for more details. 3851 SDValue FnOp = Op.getOperand(1); 3852 SDValue IncomingFPOp = Op.getOperand(2); 3853 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 3854 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 3855 if (!Fn) 3856 report_fatal_error( 3857 "llvm.eh.recoverfp must take a function as the first argument"); 3858 return IncomingFPOp; 3859 } 3860 3861 case Intrinsic::aarch64_neon_vsri: 3862 case Intrinsic::aarch64_neon_vsli: { 3863 EVT Ty = Op.getValueType(); 3864 3865 if (!Ty.isVector()) 3866 report_fatal_error("Unexpected type for aarch64_neon_vsli"); 3867 3868 assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits()); 3869 3870 bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri; 3871 unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 3872 return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2), 3873 Op.getOperand(3)); 3874 } 3875 3876 case Intrinsic::aarch64_neon_srhadd: 3877 case Intrinsic::aarch64_neon_urhadd: 3878 case Intrinsic::aarch64_neon_shadd: 3879 case Intrinsic::aarch64_neon_uhadd: { 3880 bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd || 3881 IntNo == Intrinsic::aarch64_neon_shadd); 3882 bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd || 3883 IntNo == Intrinsic::aarch64_neon_urhadd); 3884 unsigned Opcode = 3885 IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD) 3886 : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD); 3887 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3888 Op.getOperand(2)); 3889 } 3890 case Intrinsic::aarch64_neon_sabd: 3891 case Intrinsic::aarch64_neon_uabd: { 3892 unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uabd ? AArch64ISD::UABD 3893 : AArch64ISD::SABD; 3894 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3895 Op.getOperand(2)); 3896 } 3897 case Intrinsic::aarch64_neon_sdot: 3898 case Intrinsic::aarch64_neon_udot: { 3899 unsigned Opcode = IntNo == Intrinsic::aarch64_neon_udot ? AArch64ISD::UDOT 3900 : AArch64ISD::SDOT; 3901 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1), 3902 Op.getOperand(2), Op.getOperand(3)); 3903 } 3904 } 3905 } 3906 3907 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const { 3908 if (VT.getVectorElementType() == MVT::i8 || 3909 VT.getVectorElementType() == MVT::i16) { 3910 EltTy = MVT::i32; 3911 return true; 3912 } 3913 return false; 3914 } 3915 3916 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 3917 if (VT.getVectorElementType() == MVT::i32 && 3918 VT.getVectorElementCount().getKnownMinValue() >= 4) 3919 return true; 3920 3921 return false; 3922 } 3923 3924 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 3925 return ExtVal.getValueType().isScalableVector(); 3926 } 3927 3928 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) { 3929 std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = { 3930 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false), 3931 AArch64ISD::GLD1_MERGE_ZERO}, 3932 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true), 3933 AArch64ISD::GLD1_UXTW_MERGE_ZERO}, 3934 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false), 3935 AArch64ISD::GLD1_MERGE_ZERO}, 3936 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true), 3937 AArch64ISD::GLD1_SXTW_MERGE_ZERO}, 3938 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false), 3939 AArch64ISD::GLD1_SCALED_MERGE_ZERO}, 3940 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true), 3941 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO}, 3942 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false), 3943 AArch64ISD::GLD1_SCALED_MERGE_ZERO}, 3944 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true), 3945 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO}, 3946 }; 3947 auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend); 3948 return AddrModes.find(Key)->second; 3949 } 3950 3951 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) { 3952 std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = { 3953 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false), 3954 AArch64ISD::SST1_PRED}, 3955 {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true), 3956 AArch64ISD::SST1_UXTW_PRED}, 3957 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false), 3958 AArch64ISD::SST1_PRED}, 3959 {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true), 3960 AArch64ISD::SST1_SXTW_PRED}, 3961 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false), 3962 AArch64ISD::SST1_SCALED_PRED}, 3963 {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true), 3964 AArch64ISD::SST1_UXTW_SCALED_PRED}, 3965 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false), 3966 AArch64ISD::SST1_SCALED_PRED}, 3967 {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true), 3968 AArch64ISD::SST1_SXTW_SCALED_PRED}, 3969 }; 3970 auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend); 3971 return AddrModes.find(Key)->second; 3972 } 3973 3974 unsigned getSignExtendedGatherOpcode(unsigned Opcode) { 3975 switch (Opcode) { 3976 default: 3977 llvm_unreachable("unimplemented opcode"); 3978 return Opcode; 3979 case AArch64ISD::GLD1_MERGE_ZERO: 3980 return AArch64ISD::GLD1S_MERGE_ZERO; 3981 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 3982 return AArch64ISD::GLD1S_IMM_MERGE_ZERO; 3983 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 3984 return AArch64ISD::GLD1S_UXTW_MERGE_ZERO; 3985 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 3986 return AArch64ISD::GLD1S_SXTW_MERGE_ZERO; 3987 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 3988 return AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 3989 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 3990 return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO; 3991 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 3992 return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO; 3993 } 3994 } 3995 3996 bool getGatherScatterIndexIsExtended(SDValue Index) { 3997 unsigned Opcode = Index.getOpcode(); 3998 if (Opcode == ISD::SIGN_EXTEND_INREG) 3999 return true; 4000 4001 if (Opcode == ISD::AND) { 4002 SDValue Splat = Index.getOperand(1); 4003 if (Splat.getOpcode() != ISD::SPLAT_VECTOR) 4004 return false; 4005 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0)); 4006 if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF) 4007 return false; 4008 return true; 4009 } 4010 4011 return false; 4012 } 4013 4014 // If the base pointer of a masked gather or scatter is null, we 4015 // may be able to swap BasePtr & Index and use the vector + register 4016 // or vector + immediate addressing mode, e.g. 4017 // VECTOR + REGISTER: 4018 // getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices) 4019 // -> getelementptr %offset, <vscale x N x T> %indices 4020 // VECTOR + IMMEDIATE: 4021 // getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices) 4022 // -> getelementptr #x, <vscale x N x T> %indices 4023 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT, 4024 unsigned &Opcode, bool IsGather, 4025 SelectionDAG &DAG) { 4026 if (!isNullConstant(BasePtr)) 4027 return; 4028 4029 ConstantSDNode *Offset = nullptr; 4030 if (Index.getOpcode() == ISD::ADD) 4031 if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) { 4032 if (isa<ConstantSDNode>(SplatVal)) 4033 Offset = cast<ConstantSDNode>(SplatVal); 4034 else { 4035 BasePtr = SplatVal; 4036 Index = Index->getOperand(0); 4037 return; 4038 } 4039 } 4040 4041 unsigned NewOp = 4042 IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED; 4043 4044 if (!Offset) { 4045 std::swap(BasePtr, Index); 4046 Opcode = NewOp; 4047 return; 4048 } 4049 4050 uint64_t OffsetVal = Offset->getZExtValue(); 4051 unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8; 4052 auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64); 4053 4054 if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) { 4055 // Index is out of range for the immediate addressing mode 4056 BasePtr = ConstOffset; 4057 Index = Index->getOperand(0); 4058 return; 4059 } 4060 4061 // Immediate is in range 4062 Opcode = NewOp; 4063 BasePtr = Index->getOperand(0); 4064 Index = ConstOffset; 4065 } 4066 4067 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op, 4068 SelectionDAG &DAG) const { 4069 SDLoc DL(Op); 4070 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op); 4071 assert(MGT && "Can only custom lower gather load nodes"); 4072 4073 SDValue Index = MGT->getIndex(); 4074 SDValue Chain = MGT->getChain(); 4075 SDValue PassThru = MGT->getPassThru(); 4076 SDValue Mask = MGT->getMask(); 4077 SDValue BasePtr = MGT->getBasePtr(); 4078 ISD::LoadExtType ExtTy = MGT->getExtensionType(); 4079 4080 ISD::MemIndexType IndexType = MGT->getIndexType(); 4081 bool IsScaled = 4082 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED; 4083 bool IsSigned = 4084 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED; 4085 bool IdxNeedsExtend = 4086 getGatherScatterIndexIsExtended(Index) || 4087 Index.getSimpleValueType().getVectorElementType() == MVT::i32; 4088 bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD; 4089 4090 EVT VT = PassThru.getSimpleValueType(); 4091 EVT MemVT = MGT->getMemoryVT(); 4092 SDValue InputVT = DAG.getValueType(MemVT); 4093 4094 if (VT.getVectorElementType() == MVT::bf16 && 4095 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 4096 return SDValue(); 4097 4098 // Handle FP data by using an integer gather and casting the result. 4099 if (VT.isFloatingPoint()) { 4100 EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount()); 4101 PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG); 4102 InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger()); 4103 } 4104 4105 SDVTList VTs = DAG.getVTList(PassThru.getSimpleValueType(), MVT::Other); 4106 4107 if (getGatherScatterIndexIsExtended(Index)) 4108 Index = Index.getOperand(0); 4109 4110 unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend); 4111 selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode, 4112 /*isGather=*/true, DAG); 4113 4114 if (ResNeedsSignExtend) 4115 Opcode = getSignExtendedGatherOpcode(Opcode); 4116 4117 SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT, PassThru}; 4118 SDValue Gather = DAG.getNode(Opcode, DL, VTs, Ops); 4119 4120 if (VT.isFloatingPoint()) { 4121 SDValue Cast = getSVESafeBitCast(VT, Gather, DAG); 4122 return DAG.getMergeValues({Cast, Gather.getValue(1)}, DL); 4123 } 4124 4125 return Gather; 4126 } 4127 4128 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op, 4129 SelectionDAG &DAG) const { 4130 SDLoc DL(Op); 4131 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op); 4132 assert(MSC && "Can only custom lower scatter store nodes"); 4133 4134 SDValue Index = MSC->getIndex(); 4135 SDValue Chain = MSC->getChain(); 4136 SDValue StoreVal = MSC->getValue(); 4137 SDValue Mask = MSC->getMask(); 4138 SDValue BasePtr = MSC->getBasePtr(); 4139 4140 ISD::MemIndexType IndexType = MSC->getIndexType(); 4141 bool IsScaled = 4142 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED; 4143 bool IsSigned = 4144 IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED; 4145 bool NeedsExtend = 4146 getGatherScatterIndexIsExtended(Index) || 4147 Index.getSimpleValueType().getVectorElementType() == MVT::i32; 4148 4149 EVT VT = StoreVal.getSimpleValueType(); 4150 SDVTList VTs = DAG.getVTList(MVT::Other); 4151 EVT MemVT = MSC->getMemoryVT(); 4152 SDValue InputVT = DAG.getValueType(MemVT); 4153 4154 if (VT.getVectorElementType() == MVT::bf16 && 4155 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 4156 return SDValue(); 4157 4158 // Handle FP data by casting the data so an integer scatter can be used. 4159 if (VT.isFloatingPoint()) { 4160 EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount()); 4161 StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG); 4162 InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger()); 4163 } 4164 4165 if (getGatherScatterIndexIsExtended(Index)) 4166 Index = Index.getOperand(0); 4167 4168 unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend); 4169 selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode, 4170 /*isGather=*/false, DAG); 4171 4172 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT}; 4173 return DAG.getNode(Opcode, DL, VTs, Ops); 4174 } 4175 4176 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 4177 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 4178 EVT VT, EVT MemVT, 4179 SelectionDAG &DAG) { 4180 assert(VT.isVector() && "VT should be a vector type"); 4181 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 4182 4183 SDValue Value = ST->getValue(); 4184 4185 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 4186 // the word lane which represent the v4i8 subvector. It optimizes the store 4187 // to: 4188 // 4189 // xtn v0.8b, v0.8h 4190 // str s0, [x0] 4191 4192 SDValue Undef = DAG.getUNDEF(MVT::i16); 4193 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 4194 {Undef, Undef, Undef, Undef}); 4195 4196 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 4197 Value, UndefVec); 4198 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 4199 4200 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 4201 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 4202 Trunc, DAG.getConstant(0, DL, MVT::i64)); 4203 4204 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 4205 ST->getBasePtr(), ST->getMemOperand()); 4206 } 4207 4208 // Custom lowering for any store, vector or scalar and/or default or with 4209 // a truncate operations. Currently only custom lower truncate operation 4210 // from vector v4i16 to v4i8 or volatile stores of i128. 4211 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 4212 SelectionDAG &DAG) const { 4213 SDLoc Dl(Op); 4214 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 4215 assert (StoreNode && "Can only custom lower store nodes"); 4216 4217 SDValue Value = StoreNode->getValue(); 4218 4219 EVT VT = Value.getValueType(); 4220 EVT MemVT = StoreNode->getMemoryVT(); 4221 4222 if (VT.isVector()) { 4223 if (useSVEForFixedLengthVectorVT(VT)) 4224 return LowerFixedLengthVectorStoreToSVE(Op, DAG); 4225 4226 unsigned AS = StoreNode->getAddressSpace(); 4227 Align Alignment = StoreNode->getAlign(); 4228 if (Alignment < MemVT.getStoreSize() && 4229 !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment, 4230 StoreNode->getMemOperand()->getFlags(), 4231 nullptr)) { 4232 return scalarizeVectorStore(StoreNode, DAG); 4233 } 4234 4235 if (StoreNode->isTruncatingStore()) { 4236 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 4237 } 4238 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of 4239 // the custom lowering, as there are no un-paired non-temporal stores and 4240 // legalization will break up 256 bit inputs. 4241 ElementCount EC = MemVT.getVectorElementCount(); 4242 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u && 4243 EC.isKnownEven() && 4244 ((MemVT.getScalarSizeInBits() == 8u || 4245 MemVT.getScalarSizeInBits() == 16u || 4246 MemVT.getScalarSizeInBits() == 32u || 4247 MemVT.getScalarSizeInBits() == 64u))) { 4248 SDValue Lo = 4249 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 4250 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 4251 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64)); 4252 SDValue Hi = 4253 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 4254 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 4255 StoreNode->getValue(), 4256 DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64)); 4257 SDValue Result = DAG.getMemIntrinsicNode( 4258 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other), 4259 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 4260 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 4261 return Result; 4262 } 4263 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) { 4264 assert(StoreNode->getValue()->getValueType(0) == MVT::i128); 4265 SDValue Lo = 4266 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 4267 DAG.getConstant(0, Dl, MVT::i64)); 4268 SDValue Hi = 4269 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 4270 DAG.getConstant(1, Dl, MVT::i64)); 4271 SDValue Result = DAG.getMemIntrinsicNode( 4272 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other), 4273 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 4274 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 4275 return Result; 4276 } 4277 4278 return SDValue(); 4279 } 4280 4281 // Generate SUBS and CSEL for integer abs. 4282 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 4283 MVT VT = Op.getSimpleValueType(); 4284 4285 if (VT.isVector()) 4286 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU); 4287 4288 SDLoc DL(Op); 4289 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 4290 Op.getOperand(0)); 4291 // Generate SUBS & CSEL. 4292 SDValue Cmp = 4293 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 4294 Op.getOperand(0), DAG.getConstant(0, DL, VT)); 4295 return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg, 4296 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 4297 Cmp.getValue(1)); 4298 } 4299 4300 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 4301 SelectionDAG &DAG) const { 4302 LLVM_DEBUG(dbgs() << "Custom lowering: "); 4303 LLVM_DEBUG(Op.dump()); 4304 4305 switch (Op.getOpcode()) { 4306 default: 4307 llvm_unreachable("unimplemented operand"); 4308 return SDValue(); 4309 case ISD::BITCAST: 4310 return LowerBITCAST(Op, DAG); 4311 case ISD::GlobalAddress: 4312 return LowerGlobalAddress(Op, DAG); 4313 case ISD::GlobalTLSAddress: 4314 return LowerGlobalTLSAddress(Op, DAG); 4315 case ISD::SETCC: 4316 case ISD::STRICT_FSETCC: 4317 case ISD::STRICT_FSETCCS: 4318 return LowerSETCC(Op, DAG); 4319 case ISD::BR_CC: 4320 return LowerBR_CC(Op, DAG); 4321 case ISD::SELECT: 4322 return LowerSELECT(Op, DAG); 4323 case ISD::SELECT_CC: 4324 return LowerSELECT_CC(Op, DAG); 4325 case ISD::JumpTable: 4326 return LowerJumpTable(Op, DAG); 4327 case ISD::BR_JT: 4328 return LowerBR_JT(Op, DAG); 4329 case ISD::ConstantPool: 4330 return LowerConstantPool(Op, DAG); 4331 case ISD::BlockAddress: 4332 return LowerBlockAddress(Op, DAG); 4333 case ISD::VASTART: 4334 return LowerVASTART(Op, DAG); 4335 case ISD::VACOPY: 4336 return LowerVACOPY(Op, DAG); 4337 case ISD::VAARG: 4338 return LowerVAARG(Op, DAG); 4339 case ISD::ADDC: 4340 case ISD::ADDE: 4341 case ISD::SUBC: 4342 case ISD::SUBE: 4343 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 4344 case ISD::SADDO: 4345 case ISD::UADDO: 4346 case ISD::SSUBO: 4347 case ISD::USUBO: 4348 case ISD::SMULO: 4349 case ISD::UMULO: 4350 return LowerXALUO(Op, DAG); 4351 case ISD::FADD: 4352 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED); 4353 case ISD::FSUB: 4354 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED); 4355 case ISD::FMUL: 4356 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED); 4357 case ISD::FMA: 4358 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED); 4359 case ISD::FDIV: 4360 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED); 4361 case ISD::FNEG: 4362 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU); 4363 case ISD::FCEIL: 4364 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU); 4365 case ISD::FFLOOR: 4366 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU); 4367 case ISD::FNEARBYINT: 4368 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU); 4369 case ISD::FRINT: 4370 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU); 4371 case ISD::FROUND: 4372 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU); 4373 case ISD::FROUNDEVEN: 4374 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU); 4375 case ISD::FTRUNC: 4376 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU); 4377 case ISD::FSQRT: 4378 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU); 4379 case ISD::FABS: 4380 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU); 4381 case ISD::FP_ROUND: 4382 case ISD::STRICT_FP_ROUND: 4383 return LowerFP_ROUND(Op, DAG); 4384 case ISD::FP_EXTEND: 4385 return LowerFP_EXTEND(Op, DAG); 4386 case ISD::FRAMEADDR: 4387 return LowerFRAMEADDR(Op, DAG); 4388 case ISD::SPONENTRY: 4389 return LowerSPONENTRY(Op, DAG); 4390 case ISD::RETURNADDR: 4391 return LowerRETURNADDR(Op, DAG); 4392 case ISD::ADDROFRETURNADDR: 4393 return LowerADDROFRETURNADDR(Op, DAG); 4394 case ISD::CONCAT_VECTORS: 4395 return LowerCONCAT_VECTORS(Op, DAG); 4396 case ISD::INSERT_VECTOR_ELT: 4397 return LowerINSERT_VECTOR_ELT(Op, DAG); 4398 case ISD::EXTRACT_VECTOR_ELT: 4399 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 4400 case ISD::BUILD_VECTOR: 4401 return LowerBUILD_VECTOR(Op, DAG); 4402 case ISD::VECTOR_SHUFFLE: 4403 return LowerVECTOR_SHUFFLE(Op, DAG); 4404 case ISD::SPLAT_VECTOR: 4405 return LowerSPLAT_VECTOR(Op, DAG); 4406 case ISD::STEP_VECTOR: 4407 return LowerSTEP_VECTOR(Op, DAG); 4408 case ISD::EXTRACT_SUBVECTOR: 4409 return LowerEXTRACT_SUBVECTOR(Op, DAG); 4410 case ISD::INSERT_SUBVECTOR: 4411 return LowerINSERT_SUBVECTOR(Op, DAG); 4412 case ISD::SDIV: 4413 case ISD::UDIV: 4414 return LowerDIV(Op, DAG); 4415 case ISD::SMIN: 4416 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED, 4417 /*OverrideNEON=*/true); 4418 case ISD::UMIN: 4419 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED, 4420 /*OverrideNEON=*/true); 4421 case ISD::SMAX: 4422 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED, 4423 /*OverrideNEON=*/true); 4424 case ISD::UMAX: 4425 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED, 4426 /*OverrideNEON=*/true); 4427 case ISD::SRA: 4428 case ISD::SRL: 4429 case ISD::SHL: 4430 return LowerVectorSRA_SRL_SHL(Op, DAG); 4431 case ISD::SHL_PARTS: 4432 return LowerShiftLeftParts(Op, DAG); 4433 case ISD::SRL_PARTS: 4434 case ISD::SRA_PARTS: 4435 return LowerShiftRightParts(Op, DAG); 4436 case ISD::CTPOP: 4437 return LowerCTPOP(Op, DAG); 4438 case ISD::FCOPYSIGN: 4439 return LowerFCOPYSIGN(Op, DAG); 4440 case ISD::OR: 4441 return LowerVectorOR(Op, DAG); 4442 case ISD::XOR: 4443 return LowerXOR(Op, DAG); 4444 case ISD::PREFETCH: 4445 return LowerPREFETCH(Op, DAG); 4446 case ISD::SINT_TO_FP: 4447 case ISD::UINT_TO_FP: 4448 case ISD::STRICT_SINT_TO_FP: 4449 case ISD::STRICT_UINT_TO_FP: 4450 return LowerINT_TO_FP(Op, DAG); 4451 case ISD::FP_TO_SINT: 4452 case ISD::FP_TO_UINT: 4453 case ISD::STRICT_FP_TO_SINT: 4454 case ISD::STRICT_FP_TO_UINT: 4455 return LowerFP_TO_INT(Op, DAG); 4456 case ISD::FSINCOS: 4457 return LowerFSINCOS(Op, DAG); 4458 case ISD::FLT_ROUNDS_: 4459 return LowerFLT_ROUNDS_(Op, DAG); 4460 case ISD::SET_ROUNDING: 4461 return LowerSET_ROUNDING(Op, DAG); 4462 case ISD::MUL: 4463 return LowerMUL(Op, DAG); 4464 case ISD::INTRINSIC_WO_CHAIN: 4465 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4466 case ISD::STORE: 4467 return LowerSTORE(Op, DAG); 4468 case ISD::MGATHER: 4469 return LowerMGATHER(Op, DAG); 4470 case ISD::MSCATTER: 4471 return LowerMSCATTER(Op, DAG); 4472 case ISD::VECREDUCE_SEQ_FADD: 4473 return LowerVECREDUCE_SEQ_FADD(Op, DAG); 4474 case ISD::VECREDUCE_ADD: 4475 case ISD::VECREDUCE_AND: 4476 case ISD::VECREDUCE_OR: 4477 case ISD::VECREDUCE_XOR: 4478 case ISD::VECREDUCE_SMAX: 4479 case ISD::VECREDUCE_SMIN: 4480 case ISD::VECREDUCE_UMAX: 4481 case ISD::VECREDUCE_UMIN: 4482 case ISD::VECREDUCE_FADD: 4483 case ISD::VECREDUCE_FMAX: 4484 case ISD::VECREDUCE_FMIN: 4485 return LowerVECREDUCE(Op, DAG); 4486 case ISD::ATOMIC_LOAD_SUB: 4487 return LowerATOMIC_LOAD_SUB(Op, DAG); 4488 case ISD::ATOMIC_LOAD_AND: 4489 return LowerATOMIC_LOAD_AND(Op, DAG); 4490 case ISD::DYNAMIC_STACKALLOC: 4491 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4492 case ISD::VSCALE: 4493 return LowerVSCALE(Op, DAG); 4494 case ISD::ANY_EXTEND: 4495 case ISD::SIGN_EXTEND: 4496 case ISD::ZERO_EXTEND: 4497 return LowerFixedLengthVectorIntExtendToSVE(Op, DAG); 4498 case ISD::SIGN_EXTEND_INREG: { 4499 // Only custom lower when ExtraVT has a legal byte based element type. 4500 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 4501 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 4502 if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) && 4503 (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64)) 4504 return SDValue(); 4505 4506 return LowerToPredicatedOp(Op, DAG, 4507 AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU); 4508 } 4509 case ISD::TRUNCATE: 4510 return LowerTRUNCATE(Op, DAG); 4511 case ISD::LOAD: 4512 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 4513 return LowerFixedLengthVectorLoadToSVE(Op, DAG); 4514 llvm_unreachable("Unexpected request to lower ISD::LOAD"); 4515 case ISD::ADD: 4516 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED); 4517 case ISD::AND: 4518 return LowerToScalableOp(Op, DAG); 4519 case ISD::SUB: 4520 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED); 4521 case ISD::FMAXIMUM: 4522 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED); 4523 case ISD::FMAXNUM: 4524 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED); 4525 case ISD::FMINIMUM: 4526 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED); 4527 case ISD::FMINNUM: 4528 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED); 4529 case ISD::VSELECT: 4530 return LowerFixedLengthVectorSelectToSVE(Op, DAG); 4531 case ISD::ABS: 4532 return LowerABS(Op, DAG); 4533 case ISD::BITREVERSE: 4534 return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU, 4535 /*OverrideNEON=*/true); 4536 case ISD::BSWAP: 4537 return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU); 4538 case ISD::CTLZ: 4539 return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU, 4540 /*OverrideNEON=*/true); 4541 case ISD::CTTZ: 4542 return LowerCTTZ(Op, DAG); 4543 } 4544 } 4545 4546 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const { 4547 return !Subtarget->useSVEForFixedLengthVectors(); 4548 } 4549 4550 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT( 4551 EVT VT, bool OverrideNEON) const { 4552 if (!Subtarget->useSVEForFixedLengthVectors()) 4553 return false; 4554 4555 if (!VT.isFixedLengthVector()) 4556 return false; 4557 4558 // Don't use SVE for vectors we cannot scalarize if required. 4559 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 4560 // Fixed length predicates should be promoted to i8. 4561 // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work. 4562 case MVT::i1: 4563 default: 4564 return false; 4565 case MVT::i8: 4566 case MVT::i16: 4567 case MVT::i32: 4568 case MVT::i64: 4569 case MVT::f16: 4570 case MVT::f32: 4571 case MVT::f64: 4572 break; 4573 } 4574 4575 // All SVE implementations support NEON sized vectors. 4576 if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector())) 4577 return true; 4578 4579 // Ensure NEON MVTs only belong to a single register class. 4580 if (VT.getFixedSizeInBits() <= 128) 4581 return false; 4582 4583 // Don't use SVE for types that don't fit. 4584 if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits()) 4585 return false; 4586 4587 // TODO: Perhaps an artificial restriction, but worth having whilst getting 4588 // the base fixed length SVE support in place. 4589 if (!VT.isPow2VectorType()) 4590 return false; 4591 4592 return true; 4593 } 4594 4595 //===----------------------------------------------------------------------===// 4596 // Calling Convention Implementation 4597 //===----------------------------------------------------------------------===// 4598 4599 /// Selects the correct CCAssignFn for a given CallingConvention value. 4600 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 4601 bool IsVarArg) const { 4602 switch (CC) { 4603 default: 4604 report_fatal_error("Unsupported calling convention."); 4605 case CallingConv::WebKit_JS: 4606 return CC_AArch64_WebKit_JS; 4607 case CallingConv::GHC: 4608 return CC_AArch64_GHC; 4609 case CallingConv::C: 4610 case CallingConv::Fast: 4611 case CallingConv::PreserveMost: 4612 case CallingConv::CXX_FAST_TLS: 4613 case CallingConv::Swift: 4614 if (Subtarget->isTargetWindows() && IsVarArg) 4615 return CC_AArch64_Win64_VarArg; 4616 if (!Subtarget->isTargetDarwin()) 4617 return CC_AArch64_AAPCS; 4618 if (!IsVarArg) 4619 return CC_AArch64_DarwinPCS; 4620 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 4621 : CC_AArch64_DarwinPCS_VarArg; 4622 case CallingConv::Win64: 4623 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 4624 case CallingConv::CFGuard_Check: 4625 return CC_AArch64_Win64_CFGuard_Check; 4626 case CallingConv::AArch64_VectorCall: 4627 case CallingConv::AArch64_SVE_VectorCall: 4628 return CC_AArch64_AAPCS; 4629 } 4630 } 4631 4632 CCAssignFn * 4633 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 4634 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 4635 : RetCC_AArch64_AAPCS; 4636 } 4637 4638 SDValue AArch64TargetLowering::LowerFormalArguments( 4639 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4640 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 4641 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4642 MachineFunction &MF = DAG.getMachineFunction(); 4643 MachineFrameInfo &MFI = MF.getFrameInfo(); 4644 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 4645 4646 // Assign locations to all of the incoming arguments. 4647 SmallVector<CCValAssign, 16> ArgLocs; 4648 DenseMap<unsigned, SDValue> CopiedRegs; 4649 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4650 *DAG.getContext()); 4651 4652 // At this point, Ins[].VT may already be promoted to i32. To correctly 4653 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 4654 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 4655 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 4656 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 4657 // LocVT. 4658 unsigned NumArgs = Ins.size(); 4659 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 4660 unsigned CurArgIdx = 0; 4661 for (unsigned i = 0; i != NumArgs; ++i) { 4662 MVT ValVT = Ins[i].VT; 4663 if (Ins[i].isOrigArg()) { 4664 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 4665 CurArgIdx = Ins[i].getOrigArgIndex(); 4666 4667 // Get type of the original argument. 4668 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 4669 /*AllowUnknown*/ true); 4670 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 4671 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 4672 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 4673 ValVT = MVT::i8; 4674 else if (ActualMVT == MVT::i16) 4675 ValVT = MVT::i16; 4676 } 4677 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 4678 bool Res = 4679 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 4680 assert(!Res && "Call operand has unhandled type"); 4681 (void)Res; 4682 } 4683 SmallVector<SDValue, 16> ArgValues; 4684 unsigned ExtraArgLocs = 0; 4685 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4686 CCValAssign &VA = ArgLocs[i - ExtraArgLocs]; 4687 4688 if (Ins[i].Flags.isByVal()) { 4689 // Byval is used for HFAs in the PCS, but the system should work in a 4690 // non-compliant manner for larger structs. 4691 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4692 int Size = Ins[i].Flags.getByValSize(); 4693 unsigned NumRegs = (Size + 7) / 8; 4694 4695 // FIXME: This works on big-endian for composite byvals, which are the common 4696 // case. It should also work for fundamental types too. 4697 unsigned FrameIdx = 4698 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 4699 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 4700 InVals.push_back(FrameIdxN); 4701 4702 continue; 4703 } 4704 4705 SDValue ArgValue; 4706 if (VA.isRegLoc()) { 4707 // Arguments stored in registers. 4708 EVT RegVT = VA.getLocVT(); 4709 const TargetRegisterClass *RC; 4710 4711 if (RegVT == MVT::i32) 4712 RC = &AArch64::GPR32RegClass; 4713 else if (RegVT == MVT::i64) 4714 RC = &AArch64::GPR64RegClass; 4715 else if (RegVT == MVT::f16 || RegVT == MVT::bf16) 4716 RC = &AArch64::FPR16RegClass; 4717 else if (RegVT == MVT::f32) 4718 RC = &AArch64::FPR32RegClass; 4719 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 4720 RC = &AArch64::FPR64RegClass; 4721 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 4722 RC = &AArch64::FPR128RegClass; 4723 else if (RegVT.isScalableVector() && 4724 RegVT.getVectorElementType() == MVT::i1) 4725 RC = &AArch64::PPRRegClass; 4726 else if (RegVT.isScalableVector()) 4727 RC = &AArch64::ZPRRegClass; 4728 else 4729 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 4730 4731 // Transform the arguments in physical registers into virtual ones. 4732 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 4733 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 4734 4735 // If this is an 8, 16 or 32-bit value, it is really passed promoted 4736 // to 64 bits. Insert an assert[sz]ext to capture this, then 4737 // truncate to the right size. 4738 switch (VA.getLocInfo()) { 4739 default: 4740 llvm_unreachable("Unknown loc info!"); 4741 case CCValAssign::Full: 4742 break; 4743 case CCValAssign::Indirect: 4744 assert(VA.getValVT().isScalableVector() && 4745 "Only scalable vectors can be passed indirectly"); 4746 break; 4747 case CCValAssign::BCvt: 4748 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 4749 break; 4750 case CCValAssign::AExt: 4751 case CCValAssign::SExt: 4752 case CCValAssign::ZExt: 4753 break; 4754 case CCValAssign::AExtUpper: 4755 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 4756 DAG.getConstant(32, DL, RegVT)); 4757 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 4758 break; 4759 } 4760 } else { // VA.isRegLoc() 4761 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 4762 unsigned ArgOffset = VA.getLocMemOffset(); 4763 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect 4764 ? VA.getLocVT().getSizeInBits() 4765 : VA.getValVT().getSizeInBits()) / 8; 4766 4767 uint32_t BEAlign = 0; 4768 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 4769 !Ins[i].Flags.isInConsecutiveRegs()) 4770 BEAlign = 8 - ArgSize; 4771 4772 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 4773 4774 // Create load nodes to retrieve arguments from the stack. 4775 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 4776 4777 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 4778 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 4779 MVT MemVT = VA.getValVT(); 4780 4781 switch (VA.getLocInfo()) { 4782 default: 4783 break; 4784 case CCValAssign::Trunc: 4785 case CCValAssign::BCvt: 4786 MemVT = VA.getLocVT(); 4787 break; 4788 case CCValAssign::Indirect: 4789 assert(VA.getValVT().isScalableVector() && 4790 "Only scalable vectors can be passed indirectly"); 4791 MemVT = VA.getLocVT(); 4792 break; 4793 case CCValAssign::SExt: 4794 ExtType = ISD::SEXTLOAD; 4795 break; 4796 case CCValAssign::ZExt: 4797 ExtType = ISD::ZEXTLOAD; 4798 break; 4799 case CCValAssign::AExt: 4800 ExtType = ISD::EXTLOAD; 4801 break; 4802 } 4803 4804 ArgValue = DAG.getExtLoad( 4805 ExtType, DL, VA.getLocVT(), Chain, FIN, 4806 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 4807 MemVT); 4808 4809 } 4810 4811 if (VA.getLocInfo() == CCValAssign::Indirect) { 4812 assert(VA.getValVT().isScalableVector() && 4813 "Only scalable vectors can be passed indirectly"); 4814 4815 uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize(); 4816 unsigned NumParts = 1; 4817 if (Ins[i].Flags.isInConsecutiveRegs()) { 4818 assert(!Ins[i].Flags.isInConsecutiveRegsLast()); 4819 while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast()) 4820 ++NumParts; 4821 } 4822 4823 MVT PartLoad = VA.getValVT(); 4824 SDValue Ptr = ArgValue; 4825 4826 // Ensure we generate all loads for each tuple part, whilst updating the 4827 // pointer after each load correctly using vscale. 4828 while (NumParts > 0) { 4829 ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo()); 4830 InVals.push_back(ArgValue); 4831 NumParts--; 4832 if (NumParts > 0) { 4833 SDValue BytesIncrement = DAG.getVScale( 4834 DL, Ptr.getValueType(), 4835 APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize)); 4836 SDNodeFlags Flags; 4837 Flags.setNoUnsignedWrap(true); 4838 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 4839 BytesIncrement, Flags); 4840 ExtraArgLocs++; 4841 i++; 4842 } 4843 } 4844 } else { 4845 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 4846 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 4847 ArgValue, DAG.getValueType(MVT::i32)); 4848 InVals.push_back(ArgValue); 4849 } 4850 } 4851 assert((ArgLocs.size() + ExtraArgLocs) == Ins.size()); 4852 4853 // varargs 4854 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4855 if (isVarArg) { 4856 if (!Subtarget->isTargetDarwin() || IsWin64) { 4857 // The AAPCS variadic function ABI is identical to the non-variadic 4858 // one. As a result there may be more arguments in registers and we should 4859 // save them for future reference. 4860 // Win64 variadic functions also pass arguments in registers, but all float 4861 // arguments are passed in integer registers. 4862 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 4863 } 4864 4865 // This will point to the next argument passed via stack. 4866 unsigned StackOffset = CCInfo.getNextStackOffset(); 4867 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 4868 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 4869 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 4870 4871 if (MFI.hasMustTailInVarArgFunc()) { 4872 SmallVector<MVT, 2> RegParmTypes; 4873 RegParmTypes.push_back(MVT::i64); 4874 RegParmTypes.push_back(MVT::f128); 4875 // Compute the set of forwarded registers. The rest are scratch. 4876 SmallVectorImpl<ForwardedRegister> &Forwards = 4877 FuncInfo->getForwardedMustTailRegParms(); 4878 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 4879 CC_AArch64_AAPCS); 4880 4881 // Conservatively forward X8, since it might be used for aggregate return. 4882 if (!CCInfo.isAllocated(AArch64::X8)) { 4883 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 4884 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 4885 } 4886 } 4887 } 4888 4889 // On Windows, InReg pointers must be returned, so record the pointer in a 4890 // virtual register at the start of the function so it can be returned in the 4891 // epilogue. 4892 if (IsWin64) { 4893 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 4894 if (Ins[I].Flags.isInReg()) { 4895 assert(!FuncInfo->getSRetReturnReg()); 4896 4897 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 4898 Register Reg = 4899 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 4900 FuncInfo->setSRetReturnReg(Reg); 4901 4902 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 4903 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 4904 break; 4905 } 4906 } 4907 } 4908 4909 unsigned StackArgSize = CCInfo.getNextStackOffset(); 4910 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 4911 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 4912 // This is a non-standard ABI so by fiat I say we're allowed to make full 4913 // use of the stack area to be popped, which must be aligned to 16 bytes in 4914 // any case: 4915 StackArgSize = alignTo(StackArgSize, 16); 4916 4917 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 4918 // a multiple of 16. 4919 FuncInfo->setArgumentStackToRestore(StackArgSize); 4920 4921 // This realignment carries over to the available bytes below. Our own 4922 // callers will guarantee the space is free by giving an aligned value to 4923 // CALLSEQ_START. 4924 } 4925 // Even if we're not expected to free up the space, it's useful to know how 4926 // much is there while considering tail calls (because we can reuse it). 4927 FuncInfo->setBytesInStackArgArea(StackArgSize); 4928 4929 if (Subtarget->hasCustomCallingConv()) 4930 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 4931 4932 return Chain; 4933 } 4934 4935 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 4936 SelectionDAG &DAG, 4937 const SDLoc &DL, 4938 SDValue &Chain) const { 4939 MachineFunction &MF = DAG.getMachineFunction(); 4940 MachineFrameInfo &MFI = MF.getFrameInfo(); 4941 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4942 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4943 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 4944 4945 SmallVector<SDValue, 8> MemOps; 4946 4947 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 4948 AArch64::X3, AArch64::X4, AArch64::X5, 4949 AArch64::X6, AArch64::X7 }; 4950 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 4951 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 4952 4953 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 4954 int GPRIdx = 0; 4955 if (GPRSaveSize != 0) { 4956 if (IsWin64) { 4957 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 4958 if (GPRSaveSize & 15) 4959 // The extra size here, if triggered, will always be 8. 4960 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 4961 } else 4962 GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false); 4963 4964 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 4965 4966 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 4967 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 4968 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 4969 SDValue Store = DAG.getStore( 4970 Val.getValue(1), DL, Val, FIN, 4971 IsWin64 4972 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 4973 GPRIdx, 4974 (i - FirstVariadicGPR) * 8) 4975 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 4976 MemOps.push_back(Store); 4977 FIN = 4978 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 4979 } 4980 } 4981 FuncInfo->setVarArgsGPRIndex(GPRIdx); 4982 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 4983 4984 if (Subtarget->hasFPARMv8() && !IsWin64) { 4985 static const MCPhysReg FPRArgRegs[] = { 4986 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 4987 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 4988 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 4989 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 4990 4991 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 4992 int FPRIdx = 0; 4993 if (FPRSaveSize != 0) { 4994 FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false); 4995 4996 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 4997 4998 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 4999 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 5000 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 5001 5002 SDValue Store = DAG.getStore( 5003 Val.getValue(1), DL, Val, FIN, 5004 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 5005 MemOps.push_back(Store); 5006 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 5007 DAG.getConstant(16, DL, PtrVT)); 5008 } 5009 } 5010 FuncInfo->setVarArgsFPRIndex(FPRIdx); 5011 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 5012 } 5013 5014 if (!MemOps.empty()) { 5015 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5016 } 5017 } 5018 5019 /// LowerCallResult - Lower the result values of a call into the 5020 /// appropriate copies out of appropriate physical registers. 5021 SDValue AArch64TargetLowering::LowerCallResult( 5022 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5023 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 5024 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 5025 SDValue ThisVal) const { 5026 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5027 // Assign locations to each value returned by this call. 5028 SmallVector<CCValAssign, 16> RVLocs; 5029 DenseMap<unsigned, SDValue> CopiedRegs; 5030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5031 *DAG.getContext()); 5032 CCInfo.AnalyzeCallResult(Ins, RetCC); 5033 5034 // Copy all of the result registers out of their specified physreg. 5035 for (unsigned i = 0; i != RVLocs.size(); ++i) { 5036 CCValAssign VA = RVLocs[i]; 5037 5038 // Pass 'this' value directly from the argument to return value, to avoid 5039 // reg unit interference 5040 if (i == 0 && isThisReturn) { 5041 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 5042 "unexpected return calling convention register assignment"); 5043 InVals.push_back(ThisVal); 5044 continue; 5045 } 5046 5047 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 5048 // allows one use of a physreg per block. 5049 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 5050 if (!Val) { 5051 Val = 5052 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 5053 Chain = Val.getValue(1); 5054 InFlag = Val.getValue(2); 5055 CopiedRegs[VA.getLocReg()] = Val; 5056 } 5057 5058 switch (VA.getLocInfo()) { 5059 default: 5060 llvm_unreachable("Unknown loc info!"); 5061 case CCValAssign::Full: 5062 break; 5063 case CCValAssign::BCvt: 5064 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 5065 break; 5066 case CCValAssign::AExtUpper: 5067 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 5068 DAG.getConstant(32, DL, VA.getLocVT())); 5069 LLVM_FALLTHROUGH; 5070 case CCValAssign::AExt: 5071 LLVM_FALLTHROUGH; 5072 case CCValAssign::ZExt: 5073 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 5074 break; 5075 } 5076 5077 InVals.push_back(Val); 5078 } 5079 5080 return Chain; 5081 } 5082 5083 /// Return true if the calling convention is one that we can guarantee TCO for. 5084 static bool canGuaranteeTCO(CallingConv::ID CC) { 5085 return CC == CallingConv::Fast; 5086 } 5087 5088 /// Return true if we might ever do TCO for calls with this calling convention. 5089 static bool mayTailCallThisCC(CallingConv::ID CC) { 5090 switch (CC) { 5091 case CallingConv::C: 5092 case CallingConv::AArch64_SVE_VectorCall: 5093 case CallingConv::PreserveMost: 5094 case CallingConv::Swift: 5095 return true; 5096 default: 5097 return canGuaranteeTCO(CC); 5098 } 5099 } 5100 5101 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 5102 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 5103 const SmallVectorImpl<ISD::OutputArg> &Outs, 5104 const SmallVectorImpl<SDValue> &OutVals, 5105 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 5106 if (!mayTailCallThisCC(CalleeCC)) 5107 return false; 5108 5109 MachineFunction &MF = DAG.getMachineFunction(); 5110 const Function &CallerF = MF.getFunction(); 5111 CallingConv::ID CallerCC = CallerF.getCallingConv(); 5112 5113 // If this function uses the C calling convention but has an SVE signature, 5114 // then it preserves more registers and should assume the SVE_VectorCall CC. 5115 // The check for matching callee-saved regs will determine whether it is 5116 // eligible for TCO. 5117 if (CallerCC == CallingConv::C && 5118 AArch64RegisterInfo::hasSVEArgsOrReturn(&MF)) 5119 CallerCC = CallingConv::AArch64_SVE_VectorCall; 5120 5121 bool CCMatch = CallerCC == CalleeCC; 5122 5123 // When using the Windows calling convention on a non-windows OS, we want 5124 // to back up and restore X18 in such functions; we can't do a tail call 5125 // from those functions. 5126 if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() && 5127 CalleeCC != CallingConv::Win64) 5128 return false; 5129 5130 // Byval parameters hand the function a pointer directly into the stack area 5131 // we want to reuse during a tail call. Working around this *is* possible (see 5132 // X86) but less efficient and uglier in LowerCall. 5133 for (Function::const_arg_iterator i = CallerF.arg_begin(), 5134 e = CallerF.arg_end(); 5135 i != e; ++i) { 5136 if (i->hasByValAttr()) 5137 return false; 5138 5139 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 5140 // In this case, it is necessary to save/restore X0 in the callee. Tail 5141 // call opt interferes with this. So we disable tail call opt when the 5142 // caller has an argument with "inreg" attribute. 5143 5144 // FIXME: Check whether the callee also has an "inreg" argument. 5145 if (i->hasInRegAttr()) 5146 return false; 5147 } 5148 5149 if (getTargetMachine().Options.GuaranteedTailCallOpt) 5150 return canGuaranteeTCO(CalleeCC) && CCMatch; 5151 5152 // Externally-defined functions with weak linkage should not be 5153 // tail-called on AArch64 when the OS does not support dynamic 5154 // pre-emption of symbols, as the AAELF spec requires normal calls 5155 // to undefined weak functions to be replaced with a NOP or jump to the 5156 // next instruction. The behaviour of branch instructions in this 5157 // situation (as used for tail calls) is implementation-defined, so we 5158 // cannot rely on the linker replacing the tail call with a return. 5159 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5160 const GlobalValue *GV = G->getGlobal(); 5161 const Triple &TT = getTargetMachine().getTargetTriple(); 5162 if (GV->hasExternalWeakLinkage() && 5163 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 5164 return false; 5165 } 5166 5167 // Now we search for cases where we can use a tail call without changing the 5168 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 5169 // concept. 5170 5171 // I want anyone implementing a new calling convention to think long and hard 5172 // about this assert. 5173 assert((!isVarArg || CalleeCC == CallingConv::C) && 5174 "Unexpected variadic calling convention"); 5175 5176 LLVMContext &C = *DAG.getContext(); 5177 if (isVarArg && !Outs.empty()) { 5178 // At least two cases here: if caller is fastcc then we can't have any 5179 // memory arguments (we'd be expected to clean up the stack afterwards). If 5180 // caller is C then we could potentially use its argument area. 5181 5182 // FIXME: for now we take the most conservative of these in both cases: 5183 // disallow all variadic memory operands. 5184 SmallVector<CCValAssign, 16> ArgLocs; 5185 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 5186 5187 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 5188 for (const CCValAssign &ArgLoc : ArgLocs) 5189 if (!ArgLoc.isRegLoc()) 5190 return false; 5191 } 5192 5193 // Check that the call results are passed in the same way. 5194 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 5195 CCAssignFnForCall(CalleeCC, isVarArg), 5196 CCAssignFnForCall(CallerCC, isVarArg))) 5197 return false; 5198 // The callee has to preserve all registers the caller needs to preserve. 5199 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5200 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 5201 if (!CCMatch) { 5202 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 5203 if (Subtarget->hasCustomCallingConv()) { 5204 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 5205 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 5206 } 5207 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 5208 return false; 5209 } 5210 5211 // Nothing more to check if the callee is taking no arguments 5212 if (Outs.empty()) 5213 return true; 5214 5215 SmallVector<CCValAssign, 16> ArgLocs; 5216 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 5217 5218 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 5219 5220 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5221 5222 // If any of the arguments is passed indirectly, it must be SVE, so the 5223 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to 5224 // allocate space on the stack. That is why we determine this explicitly here 5225 // the call cannot be a tailcall. 5226 if (llvm::any_of(ArgLocs, [](CCValAssign &A) { 5227 assert((A.getLocInfo() != CCValAssign::Indirect || 5228 A.getValVT().isScalableVector()) && 5229 "Expected value to be scalable"); 5230 return A.getLocInfo() == CCValAssign::Indirect; 5231 })) 5232 return false; 5233 5234 // If the stack arguments for this call do not fit into our own save area then 5235 // the call cannot be made tail. 5236 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 5237 return false; 5238 5239 const MachineRegisterInfo &MRI = MF.getRegInfo(); 5240 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 5241 return false; 5242 5243 return true; 5244 } 5245 5246 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 5247 SelectionDAG &DAG, 5248 MachineFrameInfo &MFI, 5249 int ClobberedFI) const { 5250 SmallVector<SDValue, 8> ArgChains; 5251 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 5252 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 5253 5254 // Include the original chain at the beginning of the list. When this is 5255 // used by target LowerCall hooks, this helps legalize find the 5256 // CALLSEQ_BEGIN node. 5257 ArgChains.push_back(Chain); 5258 5259 // Add a chain value for each stack argument corresponding 5260 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 5261 UE = DAG.getEntryNode().getNode()->use_end(); 5262 U != UE; ++U) 5263 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 5264 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 5265 if (FI->getIndex() < 0) { 5266 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 5267 int64_t InLastByte = InFirstByte; 5268 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 5269 5270 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 5271 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 5272 ArgChains.push_back(SDValue(L, 1)); 5273 } 5274 5275 // Build a tokenfactor for all the chains. 5276 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 5277 } 5278 5279 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 5280 bool TailCallOpt) const { 5281 return CallCC == CallingConv::Fast && TailCallOpt; 5282 } 5283 5284 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 5285 /// and add input and output parameter nodes. 5286 SDValue 5287 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 5288 SmallVectorImpl<SDValue> &InVals) const { 5289 SelectionDAG &DAG = CLI.DAG; 5290 SDLoc &DL = CLI.DL; 5291 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 5292 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 5293 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 5294 SDValue Chain = CLI.Chain; 5295 SDValue Callee = CLI.Callee; 5296 bool &IsTailCall = CLI.IsTailCall; 5297 CallingConv::ID CallConv = CLI.CallConv; 5298 bool IsVarArg = CLI.IsVarArg; 5299 5300 MachineFunction &MF = DAG.getMachineFunction(); 5301 MachineFunction::CallSiteInfo CSInfo; 5302 bool IsThisReturn = false; 5303 5304 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5305 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 5306 bool IsSibCall = false; 5307 5308 // Check callee args/returns for SVE registers and set calling convention 5309 // accordingly. 5310 if (CallConv == CallingConv::C) { 5311 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 5312 return Out.VT.isScalableVector(); 5313 }); 5314 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 5315 return In.VT.isScalableVector(); 5316 }); 5317 5318 if (CalleeInSVE || CalleeOutSVE) 5319 CallConv = CallingConv::AArch64_SVE_VectorCall; 5320 } 5321 5322 if (IsTailCall) { 5323 // Check if it's really possible to do a tail call. 5324 IsTailCall = isEligibleForTailCallOptimization( 5325 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 5326 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) 5327 report_fatal_error("failed to perform tail call elimination on a call " 5328 "site marked musttail"); 5329 5330 // A sibling call is one where we're under the usual C ABI and not planning 5331 // to change that but can still do a tail call: 5332 if (!TailCallOpt && IsTailCall) 5333 IsSibCall = true; 5334 5335 if (IsTailCall) 5336 ++NumTailCalls; 5337 } 5338 5339 // Analyze operands of the call, assigning locations to each operand. 5340 SmallVector<CCValAssign, 16> ArgLocs; 5341 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 5342 *DAG.getContext()); 5343 5344 if (IsVarArg) { 5345 // Handle fixed and variable vector arguments differently. 5346 // Variable vector arguments always go into memory. 5347 unsigned NumArgs = Outs.size(); 5348 5349 for (unsigned i = 0; i != NumArgs; ++i) { 5350 MVT ArgVT = Outs[i].VT; 5351 if (!Outs[i].IsFixed && ArgVT.isScalableVector()) 5352 report_fatal_error("Passing SVE types to variadic functions is " 5353 "currently not supported"); 5354 5355 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5356 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 5357 /*IsVarArg=*/ !Outs[i].IsFixed); 5358 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 5359 assert(!Res && "Call operand has unhandled type"); 5360 (void)Res; 5361 } 5362 } else { 5363 // At this point, Outs[].VT may already be promoted to i32. To correctly 5364 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 5365 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 5366 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 5367 // we use a special version of AnalyzeCallOperands to pass in ValVT and 5368 // LocVT. 5369 unsigned NumArgs = Outs.size(); 5370 for (unsigned i = 0; i != NumArgs; ++i) { 5371 MVT ValVT = Outs[i].VT; 5372 // Get type of the original argument. 5373 EVT ActualVT = getValueType(DAG.getDataLayout(), 5374 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 5375 /*AllowUnknown*/ true); 5376 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 5377 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5378 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 5379 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 5380 ValVT = MVT::i8; 5381 else if (ActualMVT == MVT::i16) 5382 ValVT = MVT::i16; 5383 5384 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 5385 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 5386 assert(!Res && "Call operand has unhandled type"); 5387 (void)Res; 5388 } 5389 } 5390 5391 // Get a count of how many bytes are to be pushed on the stack. 5392 unsigned NumBytes = CCInfo.getNextStackOffset(); 5393 5394 if (IsSibCall) { 5395 // Since we're not changing the ABI to make this a tail call, the memory 5396 // operands are already available in the caller's incoming argument space. 5397 NumBytes = 0; 5398 } 5399 5400 // FPDiff is the byte offset of the call's argument area from the callee's. 5401 // Stores to callee stack arguments will be placed in FixedStackSlots offset 5402 // by this amount for a tail call. In a sibling call it must be 0 because the 5403 // caller will deallocate the entire stack and the callee still expects its 5404 // arguments to begin at SP+0. Completely unused for non-tail calls. 5405 int FPDiff = 0; 5406 5407 if (IsTailCall && !IsSibCall) { 5408 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 5409 5410 // Since callee will pop argument stack as a tail call, we must keep the 5411 // popped size 16-byte aligned. 5412 NumBytes = alignTo(NumBytes, 16); 5413 5414 // FPDiff will be negative if this tail call requires more space than we 5415 // would automatically have in our incoming argument space. Positive if we 5416 // can actually shrink the stack. 5417 FPDiff = NumReusableBytes - NumBytes; 5418 5419 // The stack pointer must be 16-byte aligned at all times it's used for a 5420 // memory operation, which in practice means at *all* times and in 5421 // particular across call boundaries. Therefore our own arguments started at 5422 // a 16-byte aligned SP and the delta applied for the tail call should 5423 // satisfy the same constraint. 5424 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 5425 } 5426 5427 // Adjust the stack pointer for the new arguments... 5428 // These operations are automatically eliminated by the prolog/epilog pass 5429 if (!IsSibCall) 5430 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 5431 5432 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 5433 getPointerTy(DAG.getDataLayout())); 5434 5435 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5436 SmallSet<unsigned, 8> RegsUsed; 5437 SmallVector<SDValue, 8> MemOpChains; 5438 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5439 5440 if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) { 5441 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 5442 for (const auto &F : Forwards) { 5443 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 5444 RegsToPass.emplace_back(F.PReg, Val); 5445 } 5446 } 5447 5448 // Walk the register/memloc assignments, inserting copies/loads. 5449 unsigned ExtraArgLocs = 0; 5450 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 5451 CCValAssign &VA = ArgLocs[i - ExtraArgLocs]; 5452 SDValue Arg = OutVals[i]; 5453 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5454 5455 // Promote the value if needed. 5456 switch (VA.getLocInfo()) { 5457 default: 5458 llvm_unreachable("Unknown loc info!"); 5459 case CCValAssign::Full: 5460 break; 5461 case CCValAssign::SExt: 5462 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 5463 break; 5464 case CCValAssign::ZExt: 5465 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 5466 break; 5467 case CCValAssign::AExt: 5468 if (Outs[i].ArgVT == MVT::i1) { 5469 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 5470 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 5471 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 5472 } 5473 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 5474 break; 5475 case CCValAssign::AExtUpper: 5476 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 5477 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 5478 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 5479 DAG.getConstant(32, DL, VA.getLocVT())); 5480 break; 5481 case CCValAssign::BCvt: 5482 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 5483 break; 5484 case CCValAssign::Trunc: 5485 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5486 break; 5487 case CCValAssign::FPExt: 5488 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 5489 break; 5490 case CCValAssign::Indirect: 5491 assert(VA.getValVT().isScalableVector() && 5492 "Only scalable vectors can be passed indirectly"); 5493 5494 uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize(); 5495 uint64_t PartSize = StoreSize; 5496 unsigned NumParts = 1; 5497 if (Outs[i].Flags.isInConsecutiveRegs()) { 5498 assert(!Outs[i].Flags.isInConsecutiveRegsLast()); 5499 while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast()) 5500 ++NumParts; 5501 StoreSize *= NumParts; 5502 } 5503 5504 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5505 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext()); 5506 Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty); 5507 int FI = MFI.CreateStackObject(StoreSize, Alignment, false); 5508 MFI.setStackID(FI, TargetStackID::ScalableVector); 5509 5510 MachinePointerInfo MPI = 5511 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 5512 SDValue Ptr = DAG.getFrameIndex( 5513 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout())); 5514 SDValue SpillSlot = Ptr; 5515 5516 // Ensure we generate all stores for each tuple part, whilst updating the 5517 // pointer after each store correctly using vscale. 5518 while (NumParts) { 5519 Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI); 5520 NumParts--; 5521 if (NumParts > 0) { 5522 SDValue BytesIncrement = DAG.getVScale( 5523 DL, Ptr.getValueType(), 5524 APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize)); 5525 SDNodeFlags Flags; 5526 Flags.setNoUnsignedWrap(true); 5527 5528 MPI = MachinePointerInfo(MPI.getAddrSpace()); 5529 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5530 BytesIncrement, Flags); 5531 ExtraArgLocs++; 5532 i++; 5533 } 5534 } 5535 5536 Arg = SpillSlot; 5537 break; 5538 } 5539 5540 if (VA.isRegLoc()) { 5541 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 5542 Outs[0].VT == MVT::i64) { 5543 assert(VA.getLocVT() == MVT::i64 && 5544 "unexpected calling convention register assignment"); 5545 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 5546 "unexpected use of 'returned'"); 5547 IsThisReturn = true; 5548 } 5549 if (RegsUsed.count(VA.getLocReg())) { 5550 // If this register has already been used then we're trying to pack 5551 // parts of an [N x i32] into an X-register. The extension type will 5552 // take care of putting the two halves in the right place but we have to 5553 // combine them. 5554 SDValue &Bits = 5555 llvm::find_if(RegsToPass, 5556 [=](const std::pair<unsigned, SDValue> &Elt) { 5557 return Elt.first == VA.getLocReg(); 5558 }) 5559 ->second; 5560 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 5561 // Call site info is used for function's parameter entry value 5562 // tracking. For now we track only simple cases when parameter 5563 // is transferred through whole register. 5564 llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) { 5565 return ArgReg.Reg == VA.getLocReg(); 5566 }); 5567 } else { 5568 RegsToPass.emplace_back(VA.getLocReg(), Arg); 5569 RegsUsed.insert(VA.getLocReg()); 5570 const TargetOptions &Options = DAG.getTarget().Options; 5571 if (Options.EmitCallSiteInfo) 5572 CSInfo.emplace_back(VA.getLocReg(), i); 5573 } 5574 } else { 5575 assert(VA.isMemLoc()); 5576 5577 SDValue DstAddr; 5578 MachinePointerInfo DstInfo; 5579 5580 // FIXME: This works on big-endian for composite byvals, which are the 5581 // common case. It should also work for fundamental types too. 5582 uint32_t BEAlign = 0; 5583 unsigned OpSize; 5584 if (VA.getLocInfo() == CCValAssign::Indirect) 5585 OpSize = VA.getLocVT().getFixedSizeInBits(); 5586 else 5587 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 5588 : VA.getValVT().getSizeInBits(); 5589 OpSize = (OpSize + 7) / 8; 5590 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 5591 !Flags.isInConsecutiveRegs()) { 5592 if (OpSize < 8) 5593 BEAlign = 8 - OpSize; 5594 } 5595 unsigned LocMemOffset = VA.getLocMemOffset(); 5596 int32_t Offset = LocMemOffset + BEAlign; 5597 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 5598 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 5599 5600 if (IsTailCall) { 5601 Offset = Offset + FPDiff; 5602 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5603 5604 DstAddr = DAG.getFrameIndex(FI, PtrVT); 5605 DstInfo = 5606 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 5607 5608 // Make sure any stack arguments overlapping with where we're storing 5609 // are loaded before this eventual operation. Otherwise they'll be 5610 // clobbered. 5611 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 5612 } else { 5613 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 5614 5615 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 5616 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 5617 LocMemOffset); 5618 } 5619 5620 if (Outs[i].Flags.isByVal()) { 5621 SDValue SizeNode = 5622 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 5623 SDValue Cpy = DAG.getMemcpy( 5624 Chain, DL, DstAddr, Arg, SizeNode, 5625 Outs[i].Flags.getNonZeroByValAlign(), 5626 /*isVol = */ false, /*AlwaysInline = */ false, 5627 /*isTailCall = */ false, DstInfo, MachinePointerInfo()); 5628 5629 MemOpChains.push_back(Cpy); 5630 } else { 5631 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 5632 // promoted to a legal register type i32, we should truncate Arg back to 5633 // i1/i8/i16. 5634 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 5635 VA.getValVT() == MVT::i16) 5636 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 5637 5638 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 5639 MemOpChains.push_back(Store); 5640 } 5641 } 5642 } 5643 5644 if (!MemOpChains.empty()) 5645 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 5646 5647 // Build a sequence of copy-to-reg nodes chained together with token chain 5648 // and flag operands which copy the outgoing args into the appropriate regs. 5649 SDValue InFlag; 5650 for (auto &RegToPass : RegsToPass) { 5651 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 5652 RegToPass.second, InFlag); 5653 InFlag = Chain.getValue(1); 5654 } 5655 5656 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 5657 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 5658 // node so that legalize doesn't hack it. 5659 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5660 auto GV = G->getGlobal(); 5661 unsigned OpFlags = 5662 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()); 5663 if (OpFlags & AArch64II::MO_GOT) { 5664 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 5665 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 5666 } else { 5667 const GlobalValue *GV = G->getGlobal(); 5668 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 5669 } 5670 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5671 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5672 Subtarget->isTargetMachO()) { 5673 const char *Sym = S->getSymbol(); 5674 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 5675 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 5676 } else { 5677 const char *Sym = S->getSymbol(); 5678 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 5679 } 5680 } 5681 5682 // We don't usually want to end the call-sequence here because we would tidy 5683 // the frame up *after* the call, however in the ABI-changing tail-call case 5684 // we've carefully laid out the parameters so that when sp is reset they'll be 5685 // in the correct location. 5686 if (IsTailCall && !IsSibCall) { 5687 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 5688 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 5689 InFlag = Chain.getValue(1); 5690 } 5691 5692 std::vector<SDValue> Ops; 5693 Ops.push_back(Chain); 5694 Ops.push_back(Callee); 5695 5696 if (IsTailCall) { 5697 // Each tail call may have to adjust the stack by a different amount, so 5698 // this information must travel along with the operation for eventual 5699 // consumption by emitEpilogue. 5700 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 5701 } 5702 5703 // Add argument registers to the end of the list so that they are known live 5704 // into the call. 5705 for (auto &RegToPass : RegsToPass) 5706 Ops.push_back(DAG.getRegister(RegToPass.first, 5707 RegToPass.second.getValueType())); 5708 5709 // Add a register mask operand representing the call-preserved registers. 5710 const uint32_t *Mask; 5711 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5712 if (IsThisReturn) { 5713 // For 'this' returns, use the X0-preserving mask if applicable 5714 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 5715 if (!Mask) { 5716 IsThisReturn = false; 5717 Mask = TRI->getCallPreservedMask(MF, CallConv); 5718 } 5719 } else 5720 Mask = TRI->getCallPreservedMask(MF, CallConv); 5721 5722 if (Subtarget->hasCustomCallingConv()) 5723 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 5724 5725 if (TRI->isAnyArgRegReserved(MF)) 5726 TRI->emitReservedArgRegCallError(MF); 5727 5728 assert(Mask && "Missing call preserved mask for calling convention"); 5729 Ops.push_back(DAG.getRegisterMask(Mask)); 5730 5731 if (InFlag.getNode()) 5732 Ops.push_back(InFlag); 5733 5734 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 5735 5736 // If we're doing a tall call, use a TC_RETURN here rather than an 5737 // actual call instruction. 5738 if (IsTailCall) { 5739 MF.getFrameInfo().setHasTailCall(); 5740 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 5741 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 5742 return Ret; 5743 } 5744 5745 unsigned CallOpc = AArch64ISD::CALL; 5746 // Calls with operand bundle "clang.arc.attachedcall" are special. They should 5747 // be expanded to the call, directly followed by a special marker sequence. 5748 // Use the CALL_RVMARKER to do that. 5749 if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) { 5750 assert(!IsTailCall && 5751 "tail calls cannot be marked with clang.arc.attachedcall"); 5752 CallOpc = AArch64ISD::CALL_RVMARKER; 5753 } 5754 5755 // Returns a chain and a flag for retval copy to use. 5756 Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops); 5757 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 5758 InFlag = Chain.getValue(1); 5759 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 5760 5761 uint64_t CalleePopBytes = 5762 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 5763 5764 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 5765 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 5766 InFlag, DL); 5767 if (!Ins.empty()) 5768 InFlag = Chain.getValue(1); 5769 5770 // Handle result values, copying them out of physregs into vregs that we 5771 // return. 5772 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 5773 InVals, IsThisReturn, 5774 IsThisReturn ? OutVals[0] : SDValue()); 5775 } 5776 5777 bool AArch64TargetLowering::CanLowerReturn( 5778 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 5779 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 5780 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5781 SmallVector<CCValAssign, 16> RVLocs; 5782 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 5783 return CCInfo.CheckReturn(Outs, RetCC); 5784 } 5785 5786 SDValue 5787 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 5788 bool isVarArg, 5789 const SmallVectorImpl<ISD::OutputArg> &Outs, 5790 const SmallVectorImpl<SDValue> &OutVals, 5791 const SDLoc &DL, SelectionDAG &DAG) const { 5792 auto &MF = DAG.getMachineFunction(); 5793 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5794 5795 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv); 5796 SmallVector<CCValAssign, 16> RVLocs; 5797 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5798 *DAG.getContext()); 5799 CCInfo.AnalyzeReturn(Outs, RetCC); 5800 5801 // Copy the result values into the output registers. 5802 SDValue Flag; 5803 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 5804 SmallSet<unsigned, 4> RegsUsed; 5805 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 5806 ++i, ++realRVLocIdx) { 5807 CCValAssign &VA = RVLocs[i]; 5808 assert(VA.isRegLoc() && "Can only return in registers!"); 5809 SDValue Arg = OutVals[realRVLocIdx]; 5810 5811 switch (VA.getLocInfo()) { 5812 default: 5813 llvm_unreachable("Unknown loc info!"); 5814 case CCValAssign::Full: 5815 if (Outs[i].ArgVT == MVT::i1) { 5816 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 5817 // value. This is strictly redundant on Darwin (which uses "zeroext 5818 // i1"), but will be optimised out before ISel. 5819 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 5820 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 5821 } 5822 break; 5823 case CCValAssign::BCvt: 5824 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 5825 break; 5826 case CCValAssign::AExt: 5827 case CCValAssign::ZExt: 5828 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5829 break; 5830 case CCValAssign::AExtUpper: 5831 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 5832 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 5833 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 5834 DAG.getConstant(32, DL, VA.getLocVT())); 5835 break; 5836 } 5837 5838 if (RegsUsed.count(VA.getLocReg())) { 5839 SDValue &Bits = 5840 llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) { 5841 return Elt.first == VA.getLocReg(); 5842 })->second; 5843 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 5844 } else { 5845 RetVals.emplace_back(VA.getLocReg(), Arg); 5846 RegsUsed.insert(VA.getLocReg()); 5847 } 5848 } 5849 5850 SmallVector<SDValue, 4> RetOps(1, Chain); 5851 for (auto &RetVal : RetVals) { 5852 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 5853 Flag = Chain.getValue(1); 5854 RetOps.push_back( 5855 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 5856 } 5857 5858 // Windows AArch64 ABIs require that for returning structs by value we copy 5859 // the sret argument into X0 for the return. 5860 // We saved the argument into a virtual register in the entry block, 5861 // so now we copy the value out and into X0. 5862 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 5863 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 5864 getPointerTy(MF.getDataLayout())); 5865 5866 unsigned RetValReg = AArch64::X0; 5867 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 5868 Flag = Chain.getValue(1); 5869 5870 RetOps.push_back( 5871 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 5872 } 5873 5874 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 5875 const MCPhysReg *I = 5876 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 5877 if (I) { 5878 for (; *I; ++I) { 5879 if (AArch64::GPR64RegClass.contains(*I)) 5880 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 5881 else if (AArch64::FPR64RegClass.contains(*I)) 5882 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 5883 else 5884 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 5885 } 5886 } 5887 5888 RetOps[0] = Chain; // Update chain. 5889 5890 // Add the flag if we have it. 5891 if (Flag.getNode()) 5892 RetOps.push_back(Flag); 5893 5894 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 5895 } 5896 5897 //===----------------------------------------------------------------------===// 5898 // Other Lowering Code 5899 //===----------------------------------------------------------------------===// 5900 5901 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 5902 SelectionDAG &DAG, 5903 unsigned Flag) const { 5904 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 5905 N->getOffset(), Flag); 5906 } 5907 5908 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 5909 SelectionDAG &DAG, 5910 unsigned Flag) const { 5911 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 5912 } 5913 5914 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 5915 SelectionDAG &DAG, 5916 unsigned Flag) const { 5917 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 5918 N->getOffset(), Flag); 5919 } 5920 5921 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 5922 SelectionDAG &DAG, 5923 unsigned Flag) const { 5924 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 5925 } 5926 5927 // (loadGOT sym) 5928 template <class NodeTy> 5929 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 5930 unsigned Flags) const { 5931 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 5932 SDLoc DL(N); 5933 EVT Ty = getPointerTy(DAG.getDataLayout()); 5934 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 5935 // FIXME: Once remat is capable of dealing with instructions with register 5936 // operands, expand this into two nodes instead of using a wrapper node. 5937 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 5938 } 5939 5940 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 5941 template <class NodeTy> 5942 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 5943 unsigned Flags) const { 5944 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 5945 SDLoc DL(N); 5946 EVT Ty = getPointerTy(DAG.getDataLayout()); 5947 const unsigned char MO_NC = AArch64II::MO_NC; 5948 return DAG.getNode( 5949 AArch64ISD::WrapperLarge, DL, Ty, 5950 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 5951 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 5952 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 5953 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 5954 } 5955 5956 // (addlow (adrp %hi(sym)) %lo(sym)) 5957 template <class NodeTy> 5958 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 5959 unsigned Flags) const { 5960 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 5961 SDLoc DL(N); 5962 EVT Ty = getPointerTy(DAG.getDataLayout()); 5963 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 5964 SDValue Lo = getTargetNode(N, Ty, DAG, 5965 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 5966 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 5967 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 5968 } 5969 5970 // (adr sym) 5971 template <class NodeTy> 5972 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 5973 unsigned Flags) const { 5974 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 5975 SDLoc DL(N); 5976 EVT Ty = getPointerTy(DAG.getDataLayout()); 5977 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 5978 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 5979 } 5980 5981 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 5982 SelectionDAG &DAG) const { 5983 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 5984 const GlobalValue *GV = GN->getGlobal(); 5985 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 5986 5987 if (OpFlags != AArch64II::MO_NO_FLAG) 5988 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 5989 "unexpected offset in global node"); 5990 5991 // This also catches the large code model case for Darwin, and tiny code 5992 // model with got relocations. 5993 if ((OpFlags & AArch64II::MO_GOT) != 0) { 5994 return getGOT(GN, DAG, OpFlags); 5995 } 5996 5997 SDValue Result; 5998 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5999 Result = getAddrLarge(GN, DAG, OpFlags); 6000 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 6001 Result = getAddrTiny(GN, DAG, OpFlags); 6002 } else { 6003 Result = getAddr(GN, DAG, OpFlags); 6004 } 6005 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6006 SDLoc DL(GN); 6007 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 6008 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 6009 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 6010 return Result; 6011 } 6012 6013 /// Convert a TLS address reference into the correct sequence of loads 6014 /// and calls to compute the variable's address (for Darwin, currently) and 6015 /// return an SDValue containing the final node. 6016 6017 /// Darwin only has one TLS scheme which must be capable of dealing with the 6018 /// fully general situation, in the worst case. This means: 6019 /// + "extern __thread" declaration. 6020 /// + Defined in a possibly unknown dynamic library. 6021 /// 6022 /// The general system is that each __thread variable has a [3 x i64] descriptor 6023 /// which contains information used by the runtime to calculate the address. The 6024 /// only part of this the compiler needs to know about is the first xword, which 6025 /// contains a function pointer that must be called with the address of the 6026 /// entire descriptor in "x0". 6027 /// 6028 /// Since this descriptor may be in a different unit, in general even the 6029 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 6030 /// is: 6031 /// adrp x0, _var@TLVPPAGE 6032 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 6033 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 6034 /// ; the function pointer 6035 /// blr x1 ; Uses descriptor address in x0 6036 /// ; Address of _var is now in x0. 6037 /// 6038 /// If the address of _var's descriptor *is* known to the linker, then it can 6039 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 6040 /// a slight efficiency gain. 6041 SDValue 6042 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 6043 SelectionDAG &DAG) const { 6044 assert(Subtarget->isTargetDarwin() && 6045 "This function expects a Darwin target"); 6046 6047 SDLoc DL(Op); 6048 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 6049 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 6050 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 6051 6052 SDValue TLVPAddr = 6053 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6054 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 6055 6056 // The first entry in the descriptor is a function pointer that we must call 6057 // to obtain the address of the variable. 6058 SDValue Chain = DAG.getEntryNode(); 6059 SDValue FuncTLVGet = DAG.getLoad( 6060 PtrMemVT, DL, Chain, DescAddr, 6061 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 6062 Align(PtrMemVT.getSizeInBits() / 8), 6063 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 6064 Chain = FuncTLVGet.getValue(1); 6065 6066 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 6067 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 6068 6069 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6070 MFI.setAdjustsStack(true); 6071 6072 // TLS calls preserve all registers except those that absolutely must be 6073 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 6074 // silly). 6075 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 6076 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 6077 if (Subtarget->hasCustomCallingConv()) 6078 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 6079 6080 // Finally, we can make the call. This is just a degenerate version of a 6081 // normal AArch64 call node: x0 takes the address of the descriptor, and 6082 // returns the address of the variable in this thread. 6083 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 6084 Chain = 6085 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 6086 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 6087 DAG.getRegisterMask(Mask), Chain.getValue(1)); 6088 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 6089 } 6090 6091 /// Convert a thread-local variable reference into a sequence of instructions to 6092 /// compute the variable's address for the local exec TLS model of ELF targets. 6093 /// The sequence depends on the maximum TLS area size. 6094 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV, 6095 SDValue ThreadBase, 6096 const SDLoc &DL, 6097 SelectionDAG &DAG) const { 6098 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6099 SDValue TPOff, Addr; 6100 6101 switch (DAG.getTarget().Options.TLSSize) { 6102 default: 6103 llvm_unreachable("Unexpected TLS size"); 6104 6105 case 12: { 6106 // mrs x0, TPIDR_EL0 6107 // add x0, x0, :tprel_lo12:a 6108 SDValue Var = DAG.getTargetGlobalAddress( 6109 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF); 6110 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 6111 Var, 6112 DAG.getTargetConstant(0, DL, MVT::i32)), 6113 0); 6114 } 6115 6116 case 24: { 6117 // mrs x0, TPIDR_EL0 6118 // add x0, x0, :tprel_hi12:a 6119 // add x0, x0, :tprel_lo12_nc:a 6120 SDValue HiVar = DAG.getTargetGlobalAddress( 6121 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6122 SDValue LoVar = DAG.getTargetGlobalAddress( 6123 GV, DL, PtrVT, 0, 6124 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6125 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 6126 HiVar, 6127 DAG.getTargetConstant(0, DL, MVT::i32)), 6128 0); 6129 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr, 6130 LoVar, 6131 DAG.getTargetConstant(0, DL, MVT::i32)), 6132 0); 6133 } 6134 6135 case 32: { 6136 // mrs x1, TPIDR_EL0 6137 // movz x0, #:tprel_g1:a 6138 // movk x0, #:tprel_g0_nc:a 6139 // add x0, x1, x0 6140 SDValue HiVar = DAG.getTargetGlobalAddress( 6141 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1); 6142 SDValue LoVar = DAG.getTargetGlobalAddress( 6143 GV, DL, PtrVT, 0, 6144 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 6145 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 6146 DAG.getTargetConstant(16, DL, MVT::i32)), 6147 0); 6148 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 6149 DAG.getTargetConstant(0, DL, MVT::i32)), 6150 0); 6151 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6152 } 6153 6154 case 48: { 6155 // mrs x1, TPIDR_EL0 6156 // movz x0, #:tprel_g2:a 6157 // movk x0, #:tprel_g1_nc:a 6158 // movk x0, #:tprel_g0_nc:a 6159 // add x0, x1, x0 6160 SDValue HiVar = DAG.getTargetGlobalAddress( 6161 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2); 6162 SDValue MiVar = DAG.getTargetGlobalAddress( 6163 GV, DL, PtrVT, 0, 6164 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC); 6165 SDValue LoVar = DAG.getTargetGlobalAddress( 6166 GV, DL, PtrVT, 0, 6167 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 6168 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 6169 DAG.getTargetConstant(32, DL, MVT::i32)), 6170 0); 6171 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar, 6172 DAG.getTargetConstant(16, DL, MVT::i32)), 6173 0); 6174 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 6175 DAG.getTargetConstant(0, DL, MVT::i32)), 6176 0); 6177 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6178 } 6179 } 6180 } 6181 6182 /// When accessing thread-local variables under either the general-dynamic or 6183 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 6184 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 6185 /// is a function pointer to carry out the resolution. 6186 /// 6187 /// The sequence is: 6188 /// adrp x0, :tlsdesc:var 6189 /// ldr x1, [x0, #:tlsdesc_lo12:var] 6190 /// add x0, x0, #:tlsdesc_lo12:var 6191 /// .tlsdesccall var 6192 /// blr x1 6193 /// (TPIDR_EL0 offset now in x0) 6194 /// 6195 /// The above sequence must be produced unscheduled, to enable the linker to 6196 /// optimize/relax this sequence. 6197 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 6198 /// above sequence, and expanded really late in the compilation flow, to ensure 6199 /// the sequence is produced as per above. 6200 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 6201 const SDLoc &DL, 6202 SelectionDAG &DAG) const { 6203 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6204 6205 SDValue Chain = DAG.getEntryNode(); 6206 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6207 6208 Chain = 6209 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 6210 SDValue Glue = Chain.getValue(1); 6211 6212 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 6213 } 6214 6215 SDValue 6216 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 6217 SelectionDAG &DAG) const { 6218 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 6219 6220 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6221 6222 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 6223 6224 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 6225 if (Model == TLSModel::LocalDynamic) 6226 Model = TLSModel::GeneralDynamic; 6227 } 6228 6229 if (getTargetMachine().getCodeModel() == CodeModel::Large && 6230 Model != TLSModel::LocalExec) 6231 report_fatal_error("ELF TLS only supported in small memory model or " 6232 "in local exec TLS model"); 6233 // Different choices can be made for the maximum size of the TLS area for a 6234 // module. For the small address model, the default TLS size is 16MiB and the 6235 // maximum TLS size is 4GiB. 6236 // FIXME: add tiny and large code model support for TLS access models other 6237 // than local exec. We currently generate the same code as small for tiny, 6238 // which may be larger than needed. 6239 6240 SDValue TPOff; 6241 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6242 SDLoc DL(Op); 6243 const GlobalValue *GV = GA->getGlobal(); 6244 6245 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 6246 6247 if (Model == TLSModel::LocalExec) { 6248 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG); 6249 } else if (Model == TLSModel::InitialExec) { 6250 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6251 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 6252 } else if (Model == TLSModel::LocalDynamic) { 6253 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 6254 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 6255 // the beginning of the module's TLS region, followed by a DTPREL offset 6256 // calculation. 6257 6258 // These accesses will need deduplicating if there's more than one. 6259 AArch64FunctionInfo *MFI = 6260 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 6261 MFI->incNumLocalDynamicTLSAccesses(); 6262 6263 // The call needs a relocation too for linker relaxation. It doesn't make 6264 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 6265 // the address. 6266 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 6267 AArch64II::MO_TLS); 6268 6269 // Now we can calculate the offset from TPIDR_EL0 to this module's 6270 // thread-local area. 6271 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 6272 6273 // Now use :dtprel_whatever: operations to calculate this variable's offset 6274 // in its thread-storage area. 6275 SDValue HiVar = DAG.getTargetGlobalAddress( 6276 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6277 SDValue LoVar = DAG.getTargetGlobalAddress( 6278 GV, DL, MVT::i64, 0, 6279 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6280 6281 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 6282 DAG.getTargetConstant(0, DL, MVT::i32)), 6283 0); 6284 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 6285 DAG.getTargetConstant(0, DL, MVT::i32)), 6286 0); 6287 } else if (Model == TLSModel::GeneralDynamic) { 6288 // The call needs a relocation too for linker relaxation. It doesn't make 6289 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 6290 // the address. 6291 SDValue SymAddr = 6292 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 6293 6294 // Finally we can make a call to calculate the offset from tpidr_el0. 6295 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 6296 } else 6297 llvm_unreachable("Unsupported ELF TLS access model"); 6298 6299 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 6300 } 6301 6302 SDValue 6303 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 6304 SelectionDAG &DAG) const { 6305 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 6306 6307 SDValue Chain = DAG.getEntryNode(); 6308 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6309 SDLoc DL(Op); 6310 6311 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 6312 6313 // Load the ThreadLocalStoragePointer from the TEB 6314 // A pointer to the TLS array is located at offset 0x58 from the TEB. 6315 SDValue TLSArray = 6316 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 6317 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 6318 Chain = TLSArray.getValue(1); 6319 6320 // Load the TLS index from the C runtime; 6321 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 6322 // This also does the same as LOADgot, but using a generic i32 load, 6323 // while LOADgot only loads i64. 6324 SDValue TLSIndexHi = 6325 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 6326 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 6327 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6328 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 6329 SDValue TLSIndex = 6330 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 6331 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 6332 Chain = TLSIndex.getValue(1); 6333 6334 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 6335 // offset into the TLSArray. 6336 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 6337 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 6338 DAG.getConstant(3, DL, PtrVT)); 6339 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 6340 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 6341 MachinePointerInfo()); 6342 Chain = TLS.getValue(1); 6343 6344 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6345 const GlobalValue *GV = GA->getGlobal(); 6346 SDValue TGAHi = DAG.getTargetGlobalAddress( 6347 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 6348 SDValue TGALo = DAG.getTargetGlobalAddress( 6349 GV, DL, PtrVT, 0, 6350 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 6351 6352 // Add the offset from the start of the .tls section (section base). 6353 SDValue Addr = 6354 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 6355 DAG.getTargetConstant(0, DL, MVT::i32)), 6356 0); 6357 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 6358 return Addr; 6359 } 6360 6361 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 6362 SelectionDAG &DAG) const { 6363 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6364 if (DAG.getTarget().useEmulatedTLS()) 6365 return LowerToTLSEmulatedModel(GA, DAG); 6366 6367 if (Subtarget->isTargetDarwin()) 6368 return LowerDarwinGlobalTLSAddress(Op, DAG); 6369 if (Subtarget->isTargetELF()) 6370 return LowerELFGlobalTLSAddress(Op, DAG); 6371 if (Subtarget->isTargetWindows()) 6372 return LowerWindowsGlobalTLSAddress(Op, DAG); 6373 6374 llvm_unreachable("Unexpected platform trying to use TLS"); 6375 } 6376 6377 // Looks through \param Val to determine the bit that can be used to 6378 // check the sign of the value. It returns the unextended value and 6379 // the sign bit position. 6380 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) { 6381 if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG) 6382 return {Val.getOperand(0), 6383 cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() - 6384 1}; 6385 6386 if (Val.getOpcode() == ISD::SIGN_EXTEND) 6387 return {Val.getOperand(0), 6388 Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1}; 6389 6390 return {Val, Val.getValueSizeInBits() - 1}; 6391 } 6392 6393 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 6394 SDValue Chain = Op.getOperand(0); 6395 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 6396 SDValue LHS = Op.getOperand(2); 6397 SDValue RHS = Op.getOperand(3); 6398 SDValue Dest = Op.getOperand(4); 6399 SDLoc dl(Op); 6400 6401 MachineFunction &MF = DAG.getMachineFunction(); 6402 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 6403 // will not be produced, as they are conditional branch instructions that do 6404 // not set flags. 6405 bool ProduceNonFlagSettingCondBr = 6406 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 6407 6408 // Handle f128 first, since lowering it will result in comparing the return 6409 // value of a libcall against zero, which is just what the rest of LowerBR_CC 6410 // is expecting to deal with. 6411 if (LHS.getValueType() == MVT::f128) { 6412 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 6413 6414 // If softenSetCCOperands returned a scalar, we need to compare the result 6415 // against zero to select between true and false values. 6416 if (!RHS.getNode()) { 6417 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 6418 CC = ISD::SETNE; 6419 } 6420 } 6421 6422 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 6423 // instruction. 6424 if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 6425 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 6426 // Only lower legal XALUO ops. 6427 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 6428 return SDValue(); 6429 6430 // The actual operation with overflow check. 6431 AArch64CC::CondCode OFCC; 6432 SDValue Value, Overflow; 6433 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 6434 6435 if (CC == ISD::SETNE) 6436 OFCC = getInvertedCondCode(OFCC); 6437 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 6438 6439 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 6440 Overflow); 6441 } 6442 6443 if (LHS.getValueType().isInteger()) { 6444 assert((LHS.getValueType() == RHS.getValueType()) && 6445 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 6446 6447 // If the RHS of the comparison is zero, we can potentially fold this 6448 // to a specialized branch. 6449 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 6450 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 6451 if (CC == ISD::SETEQ) { 6452 // See if we can use a TBZ to fold in an AND as well. 6453 // TBZ has a smaller branch displacement than CBZ. If the offset is 6454 // out of bounds, a late MI-layer pass rewrites branches. 6455 // 403.gcc is an example that hits this case. 6456 if (LHS.getOpcode() == ISD::AND && 6457 isa<ConstantSDNode>(LHS.getOperand(1)) && 6458 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 6459 SDValue Test = LHS.getOperand(0); 6460 uint64_t Mask = LHS.getConstantOperandVal(1); 6461 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 6462 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 6463 Dest); 6464 } 6465 6466 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 6467 } else if (CC == ISD::SETNE) { 6468 // See if we can use a TBZ to fold in an AND as well. 6469 // TBZ has a smaller branch displacement than CBZ. If the offset is 6470 // out of bounds, a late MI-layer pass rewrites branches. 6471 // 403.gcc is an example that hits this case. 6472 if (LHS.getOpcode() == ISD::AND && 6473 isa<ConstantSDNode>(LHS.getOperand(1)) && 6474 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 6475 SDValue Test = LHS.getOperand(0); 6476 uint64_t Mask = LHS.getConstantOperandVal(1); 6477 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 6478 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 6479 Dest); 6480 } 6481 6482 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 6483 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 6484 // Don't combine AND since emitComparison converts the AND to an ANDS 6485 // (a.k.a. TST) and the test in the test bit and branch instruction 6486 // becomes redundant. This would also increase register pressure. 6487 uint64_t SignBitPos; 6488 std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS); 6489 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 6490 DAG.getConstant(SignBitPos, dl, MVT::i64), Dest); 6491 } 6492 } 6493 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 6494 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 6495 // Don't combine AND since emitComparison converts the AND to an ANDS 6496 // (a.k.a. TST) and the test in the test bit and branch instruction 6497 // becomes redundant. This would also increase register pressure. 6498 uint64_t SignBitPos; 6499 std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS); 6500 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 6501 DAG.getConstant(SignBitPos, dl, MVT::i64), Dest); 6502 } 6503 6504 SDValue CCVal; 6505 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 6506 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 6507 Cmp); 6508 } 6509 6510 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 || 6511 LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 6512 6513 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6514 // clean. Some of them require two branches to implement. 6515 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6516 AArch64CC::CondCode CC1, CC2; 6517 changeFPCCToAArch64CC(CC, CC1, CC2); 6518 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6519 SDValue BR1 = 6520 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 6521 if (CC2 != AArch64CC::AL) { 6522 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6523 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 6524 Cmp); 6525 } 6526 6527 return BR1; 6528 } 6529 6530 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 6531 SelectionDAG &DAG) const { 6532 EVT VT = Op.getValueType(); 6533 SDLoc DL(Op); 6534 6535 SDValue In1 = Op.getOperand(0); 6536 SDValue In2 = Op.getOperand(1); 6537 EVT SrcVT = In2.getValueType(); 6538 6539 if (SrcVT.bitsLT(VT)) 6540 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 6541 else if (SrcVT.bitsGT(VT)) 6542 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 6543 6544 EVT VecVT; 6545 uint64_t EltMask; 6546 SDValue VecVal1, VecVal2; 6547 6548 auto setVecVal = [&] (int Idx) { 6549 if (!VT.isVector()) { 6550 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 6551 DAG.getUNDEF(VecVT), In1); 6552 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 6553 DAG.getUNDEF(VecVT), In2); 6554 } else { 6555 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 6556 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 6557 } 6558 }; 6559 6560 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 6561 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 6562 EltMask = 0x80000000ULL; 6563 setVecVal(AArch64::ssub); 6564 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 6565 VecVT = MVT::v2i64; 6566 6567 // We want to materialize a mask with the high bit set, but the AdvSIMD 6568 // immediate moves cannot materialize that in a single instruction for 6569 // 64-bit elements. Instead, materialize zero and then negate it. 6570 EltMask = 0; 6571 6572 setVecVal(AArch64::dsub); 6573 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 6574 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 6575 EltMask = 0x8000ULL; 6576 setVecVal(AArch64::hsub); 6577 } else { 6578 llvm_unreachable("Invalid type for copysign!"); 6579 } 6580 6581 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 6582 6583 // If we couldn't materialize the mask above, then the mask vector will be 6584 // the zero vector, and we need to negate it here. 6585 if (VT == MVT::f64 || VT == MVT::v2f64) { 6586 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 6587 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 6588 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 6589 } 6590 6591 SDValue Sel = 6592 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 6593 6594 if (VT == MVT::f16) 6595 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 6596 if (VT == MVT::f32) 6597 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 6598 else if (VT == MVT::f64) 6599 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 6600 else 6601 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 6602 } 6603 6604 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 6605 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 6606 Attribute::NoImplicitFloat)) 6607 return SDValue(); 6608 6609 if (!Subtarget->hasNEON()) 6610 return SDValue(); 6611 6612 // While there is no integer popcount instruction, it can 6613 // be more efficiently lowered to the following sequence that uses 6614 // AdvSIMD registers/instructions as long as the copies to/from 6615 // the AdvSIMD registers are cheap. 6616 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 6617 // CNT V0.8B, V0.8B // 8xbyte pop-counts 6618 // ADDV B0, V0.8B // sum 8xbyte pop-counts 6619 // UMOV X0, V0.B[0] // copy byte result back to integer reg 6620 SDValue Val = Op.getOperand(0); 6621 SDLoc DL(Op); 6622 EVT VT = Op.getValueType(); 6623 6624 if (VT == MVT::i32 || VT == MVT::i64) { 6625 if (VT == MVT::i32) 6626 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 6627 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 6628 6629 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 6630 SDValue UaddLV = DAG.getNode( 6631 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 6632 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 6633 6634 if (VT == MVT::i64) 6635 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 6636 return UaddLV; 6637 } else if (VT == MVT::i128) { 6638 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val); 6639 6640 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val); 6641 SDValue UaddLV = DAG.getNode( 6642 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 6643 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 6644 6645 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV); 6646 } 6647 6648 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) 6649 return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU); 6650 6651 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 6652 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 6653 "Unexpected type for custom ctpop lowering"); 6654 6655 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 6656 Val = DAG.getBitcast(VT8Bit, Val); 6657 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 6658 6659 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 6660 unsigned EltSize = 8; 6661 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 6662 while (EltSize != VT.getScalarSizeInBits()) { 6663 EltSize *= 2; 6664 NumElts /= 2; 6665 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 6666 Val = DAG.getNode( 6667 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 6668 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 6669 } 6670 6671 return Val; 6672 } 6673 6674 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 6675 EVT VT = Op.getValueType(); 6676 assert(VT.isScalableVector() || 6677 useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)); 6678 6679 SDLoc DL(Op); 6680 SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0)); 6681 return DAG.getNode(ISD::CTLZ, DL, VT, RBIT); 6682 } 6683 6684 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 6685 6686 if (Op.getValueType().isVector()) 6687 return LowerVSETCC(Op, DAG); 6688 6689 bool IsStrict = Op->isStrictFPOpcode(); 6690 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 6691 unsigned OpNo = IsStrict ? 1 : 0; 6692 SDValue Chain; 6693 if (IsStrict) 6694 Chain = Op.getOperand(0); 6695 SDValue LHS = Op.getOperand(OpNo + 0); 6696 SDValue RHS = Op.getOperand(OpNo + 1); 6697 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get(); 6698 SDLoc dl(Op); 6699 6700 // We chose ZeroOrOneBooleanContents, so use zero and one. 6701 EVT VT = Op.getValueType(); 6702 SDValue TVal = DAG.getConstant(1, dl, VT); 6703 SDValue FVal = DAG.getConstant(0, dl, VT); 6704 6705 // Handle f128 first, since one possible outcome is a normal integer 6706 // comparison which gets picked up by the next if statement. 6707 if (LHS.getValueType() == MVT::f128) { 6708 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain, 6709 IsSignaling); 6710 6711 // If softenSetCCOperands returned a scalar, use it. 6712 if (!RHS.getNode()) { 6713 assert(LHS.getValueType() == Op.getValueType() && 6714 "Unexpected setcc expansion!"); 6715 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS; 6716 } 6717 } 6718 6719 if (LHS.getValueType().isInteger()) { 6720 SDValue CCVal; 6721 SDValue Cmp = getAArch64Cmp( 6722 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl); 6723 6724 // Note that we inverted the condition above, so we reverse the order of 6725 // the true and false operands here. This will allow the setcc to be 6726 // matched to a single CSINC instruction. 6727 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 6728 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res; 6729 } 6730 6731 // Now we know we're dealing with FP values. 6732 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 6733 LHS.getValueType() == MVT::f64); 6734 6735 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 6736 // and do the comparison. 6737 SDValue Cmp; 6738 if (IsStrict) 6739 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling); 6740 else 6741 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6742 6743 AArch64CC::CondCode CC1, CC2; 6744 changeFPCCToAArch64CC(CC, CC1, CC2); 6745 SDValue Res; 6746 if (CC2 == AArch64CC::AL) { 6747 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1, 6748 CC2); 6749 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6750 6751 // Note that we inverted the condition above, so we reverse the order of 6752 // the true and false operands here. This will allow the setcc to be 6753 // matched to a single CSINC instruction. 6754 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 6755 } else { 6756 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 6757 // totally clean. Some of them require two CSELs to implement. As is in 6758 // this case, we emit the first CSEL and then emit a second using the output 6759 // of the first as the RHS. We're effectively OR'ing the two CC's together. 6760 6761 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 6762 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6763 SDValue CS1 = 6764 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 6765 6766 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6767 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 6768 } 6769 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res; 6770 } 6771 6772 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 6773 SDValue RHS, SDValue TVal, 6774 SDValue FVal, const SDLoc &dl, 6775 SelectionDAG &DAG) const { 6776 // Handle f128 first, because it will result in a comparison of some RTLIB 6777 // call result against zero. 6778 if (LHS.getValueType() == MVT::f128) { 6779 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 6780 6781 // If softenSetCCOperands returned a scalar, we need to compare the result 6782 // against zero to select between true and false values. 6783 if (!RHS.getNode()) { 6784 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 6785 CC = ISD::SETNE; 6786 } 6787 } 6788 6789 // Also handle f16, for which we need to do a f32 comparison. 6790 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 6791 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 6792 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 6793 } 6794 6795 // Next, handle integers. 6796 if (LHS.getValueType().isInteger()) { 6797 assert((LHS.getValueType() == RHS.getValueType()) && 6798 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 6799 6800 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 6801 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 6802 ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 6803 // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform 6804 // into (OR (ASR lhs, N-1), 1), which requires less instructions for the 6805 // supported types. 6806 if (CC == ISD::SETGT && RHSC && RHSC->isAllOnesValue() && CTVal && CFVal && 6807 CTVal->isOne() && CFVal->isAllOnesValue() && 6808 LHS.getValueType() == TVal.getValueType()) { 6809 EVT VT = LHS.getValueType(); 6810 SDValue Shift = 6811 DAG.getNode(ISD::SRA, dl, VT, LHS, 6812 DAG.getConstant(VT.getSizeInBits() - 1, dl, VT)); 6813 return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT)); 6814 } 6815 6816 unsigned Opcode = AArch64ISD::CSEL; 6817 6818 // If both the TVal and the FVal are constants, see if we can swap them in 6819 // order to for a CSINV or CSINC out of them. 6820 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 6821 std::swap(TVal, FVal); 6822 std::swap(CTVal, CFVal); 6823 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6824 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 6825 std::swap(TVal, FVal); 6826 std::swap(CTVal, CFVal); 6827 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6828 } else if (TVal.getOpcode() == ISD::XOR) { 6829 // If TVal is a NOT we want to swap TVal and FVal so that we can match 6830 // with a CSINV rather than a CSEL. 6831 if (isAllOnesConstant(TVal.getOperand(1))) { 6832 std::swap(TVal, FVal); 6833 std::swap(CTVal, CFVal); 6834 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6835 } 6836 } else if (TVal.getOpcode() == ISD::SUB) { 6837 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 6838 // that we can match with a CSNEG rather than a CSEL. 6839 if (isNullConstant(TVal.getOperand(0))) { 6840 std::swap(TVal, FVal); 6841 std::swap(CTVal, CFVal); 6842 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6843 } 6844 } else if (CTVal && CFVal) { 6845 const int64_t TrueVal = CTVal->getSExtValue(); 6846 const int64_t FalseVal = CFVal->getSExtValue(); 6847 bool Swap = false; 6848 6849 // If both TVal and FVal are constants, see if FVal is the 6850 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 6851 // instead of a CSEL in that case. 6852 if (TrueVal == ~FalseVal) { 6853 Opcode = AArch64ISD::CSINV; 6854 } else if (FalseVal > std::numeric_limits<int64_t>::min() && 6855 TrueVal == -FalseVal) { 6856 Opcode = AArch64ISD::CSNEG; 6857 } else if (TVal.getValueType() == MVT::i32) { 6858 // If our operands are only 32-bit wide, make sure we use 32-bit 6859 // arithmetic for the check whether we can use CSINC. This ensures that 6860 // the addition in the check will wrap around properly in case there is 6861 // an overflow (which would not be the case if we do the check with 6862 // 64-bit arithmetic). 6863 const uint32_t TrueVal32 = CTVal->getZExtValue(); 6864 const uint32_t FalseVal32 = CFVal->getZExtValue(); 6865 6866 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 6867 Opcode = AArch64ISD::CSINC; 6868 6869 if (TrueVal32 > FalseVal32) { 6870 Swap = true; 6871 } 6872 } 6873 // 64-bit check whether we can use CSINC. 6874 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 6875 Opcode = AArch64ISD::CSINC; 6876 6877 if (TrueVal > FalseVal) { 6878 Swap = true; 6879 } 6880 } 6881 6882 // Swap TVal and FVal if necessary. 6883 if (Swap) { 6884 std::swap(TVal, FVal); 6885 std::swap(CTVal, CFVal); 6886 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 6887 } 6888 6889 if (Opcode != AArch64ISD::CSEL) { 6890 // Drop FVal since we can get its value by simply inverting/negating 6891 // TVal. 6892 FVal = TVal; 6893 } 6894 } 6895 6896 // Avoid materializing a constant when possible by reusing a known value in 6897 // a register. However, don't perform this optimization if the known value 6898 // is one, zero or negative one in the case of a CSEL. We can always 6899 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 6900 // FVal, respectively. 6901 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 6902 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 6903 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 6904 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6905 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 6906 // "a != C ? x : a" to avoid materializing C. 6907 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 6908 TVal = LHS; 6909 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 6910 FVal = LHS; 6911 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 6912 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 6913 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 6914 // avoid materializing C. 6915 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6916 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 6917 Opcode = AArch64ISD::CSINV; 6918 TVal = LHS; 6919 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 6920 } 6921 } 6922 6923 SDValue CCVal; 6924 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 6925 EVT VT = TVal.getValueType(); 6926 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 6927 } 6928 6929 // Now we know we're dealing with FP values. 6930 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 6931 LHS.getValueType() == MVT::f64); 6932 assert(LHS.getValueType() == RHS.getValueType()); 6933 EVT VT = TVal.getValueType(); 6934 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 6935 6936 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6937 // clean. Some of them require two CSELs to implement. 6938 AArch64CC::CondCode CC1, CC2; 6939 changeFPCCToAArch64CC(CC, CC1, CC2); 6940 6941 if (DAG.getTarget().Options.UnsafeFPMath) { 6942 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 6943 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 6944 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 6945 if (RHSVal && RHSVal->isZero()) { 6946 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 6947 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 6948 6949 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 6950 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 6951 TVal = LHS; 6952 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 6953 CFVal && CFVal->isZero() && 6954 FVal.getValueType() == LHS.getValueType()) 6955 FVal = LHS; 6956 } 6957 } 6958 6959 // Emit first, and possibly only, CSEL. 6960 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 6961 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 6962 6963 // If we need a second CSEL, emit it, using the output of the first as the 6964 // RHS. We're effectively OR'ing the two CC's together. 6965 if (CC2 != AArch64CC::AL) { 6966 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 6967 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 6968 } 6969 6970 // Otherwise, return the output of the first CSEL. 6971 return CS1; 6972 } 6973 6974 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 6975 SelectionDAG &DAG) const { 6976 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6977 SDValue LHS = Op.getOperand(0); 6978 SDValue RHS = Op.getOperand(1); 6979 SDValue TVal = Op.getOperand(2); 6980 SDValue FVal = Op.getOperand(3); 6981 SDLoc DL(Op); 6982 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 6983 } 6984 6985 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 6986 SelectionDAG &DAG) const { 6987 SDValue CCVal = Op->getOperand(0); 6988 SDValue TVal = Op->getOperand(1); 6989 SDValue FVal = Op->getOperand(2); 6990 SDLoc DL(Op); 6991 6992 EVT Ty = Op.getValueType(); 6993 if (Ty.isScalableVector()) { 6994 SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal); 6995 MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount()); 6996 SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC); 6997 return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal); 6998 } 6999 7000 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 7001 // instruction. 7002 if (ISD::isOverflowIntrOpRes(CCVal)) { 7003 // Only lower legal XALUO ops. 7004 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 7005 return SDValue(); 7006 7007 AArch64CC::CondCode OFCC; 7008 SDValue Value, Overflow; 7009 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 7010 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 7011 7012 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 7013 CCVal, Overflow); 7014 } 7015 7016 // Lower it the same way as we would lower a SELECT_CC node. 7017 ISD::CondCode CC; 7018 SDValue LHS, RHS; 7019 if (CCVal.getOpcode() == ISD::SETCC) { 7020 LHS = CCVal.getOperand(0); 7021 RHS = CCVal.getOperand(1); 7022 CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get(); 7023 } else { 7024 LHS = CCVal; 7025 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 7026 CC = ISD::SETNE; 7027 } 7028 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 7029 } 7030 7031 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 7032 SelectionDAG &DAG) const { 7033 // Jump table entries as PC relative offsets. No additional tweaking 7034 // is necessary here. Just get the address of the jump table. 7035 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7036 7037 if (getTargetMachine().getCodeModel() == CodeModel::Large && 7038 !Subtarget->isTargetMachO()) { 7039 return getAddrLarge(JT, DAG); 7040 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 7041 return getAddrTiny(JT, DAG); 7042 } 7043 return getAddr(JT, DAG); 7044 } 7045 7046 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 7047 SelectionDAG &DAG) const { 7048 // Jump table entries as PC relative offsets. No additional tweaking 7049 // is necessary here. Just get the address of the jump table. 7050 SDLoc DL(Op); 7051 SDValue JT = Op.getOperand(1); 7052 SDValue Entry = Op.getOperand(2); 7053 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 7054 7055 auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7056 AFI->setJumpTableEntryInfo(JTI, 4, nullptr); 7057 7058 SDNode *Dest = 7059 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 7060 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 7061 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 7062 SDValue(Dest, 0)); 7063 } 7064 7065 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 7066 SelectionDAG &DAG) const { 7067 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7068 7069 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 7070 // Use the GOT for the large code model on iOS. 7071 if (Subtarget->isTargetMachO()) { 7072 return getGOT(CP, DAG); 7073 } 7074 return getAddrLarge(CP, DAG); 7075 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 7076 return getAddrTiny(CP, DAG); 7077 } else { 7078 return getAddr(CP, DAG); 7079 } 7080 } 7081 7082 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 7083 SelectionDAG &DAG) const { 7084 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 7085 if (getTargetMachine().getCodeModel() == CodeModel::Large && 7086 !Subtarget->isTargetMachO()) { 7087 return getAddrLarge(BA, DAG); 7088 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 7089 return getAddrTiny(BA, DAG); 7090 } 7091 return getAddr(BA, DAG); 7092 } 7093 7094 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 7095 SelectionDAG &DAG) const { 7096 AArch64FunctionInfo *FuncInfo = 7097 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7098 7099 SDLoc DL(Op); 7100 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 7101 getPointerTy(DAG.getDataLayout())); 7102 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 7103 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7104 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7105 MachinePointerInfo(SV)); 7106 } 7107 7108 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 7109 SelectionDAG &DAG) const { 7110 AArch64FunctionInfo *FuncInfo = 7111 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 7112 7113 SDLoc DL(Op); 7114 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 7115 ? FuncInfo->getVarArgsGPRIndex() 7116 : FuncInfo->getVarArgsStackIndex(), 7117 getPointerTy(DAG.getDataLayout())); 7118 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7119 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7120 MachinePointerInfo(SV)); 7121 } 7122 7123 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 7124 SelectionDAG &DAG) const { 7125 // The layout of the va_list struct is specified in the AArch64 Procedure Call 7126 // Standard, section B.3. 7127 MachineFunction &MF = DAG.getMachineFunction(); 7128 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 7129 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 7130 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 7131 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7132 SDLoc DL(Op); 7133 7134 SDValue Chain = Op.getOperand(0); 7135 SDValue VAList = Op.getOperand(1); 7136 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7137 SmallVector<SDValue, 4> MemOps; 7138 7139 // void *__stack at offset 0 7140 unsigned Offset = 0; 7141 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 7142 Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT); 7143 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 7144 MachinePointerInfo(SV), Align(PtrSize))); 7145 7146 // void *__gr_top at offset 8 (4 on ILP32) 7147 Offset += PtrSize; 7148 int GPRSize = FuncInfo->getVarArgsGPRSize(); 7149 if (GPRSize > 0) { 7150 SDValue GRTop, GRTopAddr; 7151 7152 GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7153 DAG.getConstant(Offset, DL, PtrVT)); 7154 7155 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 7156 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 7157 DAG.getConstant(GPRSize, DL, PtrVT)); 7158 GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT); 7159 7160 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 7161 MachinePointerInfo(SV, Offset), 7162 Align(PtrSize))); 7163 } 7164 7165 // void *__vr_top at offset 16 (8 on ILP32) 7166 Offset += PtrSize; 7167 int FPRSize = FuncInfo->getVarArgsFPRSize(); 7168 if (FPRSize > 0) { 7169 SDValue VRTop, VRTopAddr; 7170 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7171 DAG.getConstant(Offset, DL, PtrVT)); 7172 7173 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 7174 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 7175 DAG.getConstant(FPRSize, DL, PtrVT)); 7176 VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT); 7177 7178 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 7179 MachinePointerInfo(SV, Offset), 7180 Align(PtrSize))); 7181 } 7182 7183 // int __gr_offs at offset 24 (12 on ILP32) 7184 Offset += PtrSize; 7185 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7186 DAG.getConstant(Offset, DL, PtrVT)); 7187 MemOps.push_back( 7188 DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), 7189 GROffsAddr, MachinePointerInfo(SV, Offset), Align(4))); 7190 7191 // int __vr_offs at offset 28 (16 on ILP32) 7192 Offset += 4; 7193 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7194 DAG.getConstant(Offset, DL, PtrVT)); 7195 MemOps.push_back( 7196 DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), 7197 VROffsAddr, MachinePointerInfo(SV, Offset), Align(4))); 7198 7199 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 7200 } 7201 7202 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 7203 SelectionDAG &DAG) const { 7204 MachineFunction &MF = DAG.getMachineFunction(); 7205 7206 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 7207 return LowerWin64_VASTART(Op, DAG); 7208 else if (Subtarget->isTargetDarwin()) 7209 return LowerDarwin_VASTART(Op, DAG); 7210 else 7211 return LowerAAPCS_VASTART(Op, DAG); 7212 } 7213 7214 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 7215 SelectionDAG &DAG) const { 7216 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 7217 // pointer. 7218 SDLoc DL(Op); 7219 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 7220 unsigned VaListSize = 7221 (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 7222 ? PtrSize 7223 : Subtarget->isTargetILP32() ? 20 : 32; 7224 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 7225 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 7226 7227 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 7228 DAG.getConstant(VaListSize, DL, MVT::i32), 7229 Align(PtrSize), false, false, false, 7230 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); 7231 } 7232 7233 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 7234 assert(Subtarget->isTargetDarwin() && 7235 "automatic va_arg instruction only works on Darwin"); 7236 7237 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7238 EVT VT = Op.getValueType(); 7239 SDLoc DL(Op); 7240 SDValue Chain = Op.getOperand(0); 7241 SDValue Addr = Op.getOperand(1); 7242 MaybeAlign Align(Op.getConstantOperandVal(3)); 7243 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 7244 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7245 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 7246 SDValue VAList = 7247 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 7248 Chain = VAList.getValue(1); 7249 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 7250 7251 if (VT.isScalableVector()) 7252 report_fatal_error("Passing SVE types to variadic functions is " 7253 "currently not supported"); 7254 7255 if (Align && *Align > MinSlotSize) { 7256 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7257 DAG.getConstant(Align->value() - 1, DL, PtrVT)); 7258 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 7259 DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT)); 7260 } 7261 7262 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7263 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 7264 7265 // Scalar integer and FP values smaller than 64 bits are implicitly extended 7266 // up to 64 bits. At the very least, we have to increase the striding of the 7267 // vaargs list to match this, and for FP values we need to introduce 7268 // FP_ROUND nodes as well. 7269 if (VT.isInteger() && !VT.isVector()) 7270 ArgSize = std::max(ArgSize, MinSlotSize); 7271 bool NeedFPTrunc = false; 7272 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 7273 ArgSize = 8; 7274 NeedFPTrunc = true; 7275 } 7276 7277 // Increment the pointer, VAList, to the next vaarg 7278 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 7279 DAG.getConstant(ArgSize, DL, PtrVT)); 7280 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 7281 7282 // Store the incremented VAList to the legalized pointer 7283 SDValue APStore = 7284 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 7285 7286 // Load the actual argument out of the pointer VAList 7287 if (NeedFPTrunc) { 7288 // Load the value as an f64. 7289 SDValue WideFP = 7290 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 7291 // Round the value down to an f32. 7292 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 7293 DAG.getIntPtrConstant(1, DL)); 7294 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 7295 // Merge the rounded value with the chain output of the load. 7296 return DAG.getMergeValues(Ops, DL); 7297 } 7298 7299 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 7300 } 7301 7302 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 7303 SelectionDAG &DAG) const { 7304 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7305 MFI.setFrameAddressIsTaken(true); 7306 7307 EVT VT = Op.getValueType(); 7308 SDLoc DL(Op); 7309 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7310 SDValue FrameAddr = 7311 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 7312 while (Depth--) 7313 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 7314 MachinePointerInfo()); 7315 7316 if (Subtarget->isTargetILP32()) 7317 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 7318 DAG.getValueType(VT)); 7319 7320 return FrameAddr; 7321 } 7322 7323 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 7324 SelectionDAG &DAG) const { 7325 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7326 7327 EVT VT = getPointerTy(DAG.getDataLayout()); 7328 SDLoc DL(Op); 7329 int FI = MFI.CreateFixedObject(4, 0, false); 7330 return DAG.getFrameIndex(FI, VT); 7331 } 7332 7333 #define GET_REGISTER_MATCHER 7334 #include "AArch64GenAsmMatcher.inc" 7335 7336 // FIXME? Maybe this could be a TableGen attribute on some registers and 7337 // this table could be generated automatically from RegInfo. 7338 Register AArch64TargetLowering:: 7339 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const { 7340 Register Reg = MatchRegisterName(RegName); 7341 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 7342 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 7343 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 7344 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 7345 Reg = 0; 7346 } 7347 if (Reg) 7348 return Reg; 7349 report_fatal_error(Twine("Invalid register name \"" 7350 + StringRef(RegName) + "\".")); 7351 } 7352 7353 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 7354 SelectionDAG &DAG) const { 7355 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 7356 7357 EVT VT = Op.getValueType(); 7358 SDLoc DL(Op); 7359 7360 SDValue FrameAddr = 7361 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 7362 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 7363 7364 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 7365 } 7366 7367 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 7368 SelectionDAG &DAG) const { 7369 MachineFunction &MF = DAG.getMachineFunction(); 7370 MachineFrameInfo &MFI = MF.getFrameInfo(); 7371 MFI.setReturnAddressIsTaken(true); 7372 7373 EVT VT = Op.getValueType(); 7374 SDLoc DL(Op); 7375 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 7376 SDValue ReturnAddress; 7377 if (Depth) { 7378 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 7379 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 7380 ReturnAddress = DAG.getLoad( 7381 VT, DL, DAG.getEntryNode(), 7382 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo()); 7383 } else { 7384 // Return LR, which contains the return address. Mark it an implicit 7385 // live-in. 7386 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 7387 ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 7388 } 7389 7390 // The XPACLRI instruction assembles to a hint-space instruction before 7391 // Armv8.3-A therefore this instruction can be safely used for any pre 7392 // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use 7393 // that instead. 7394 SDNode *St; 7395 if (Subtarget->hasPAuth()) { 7396 St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress); 7397 } else { 7398 // XPACLRI operates on LR therefore we must move the operand accordingly. 7399 SDValue Chain = 7400 DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress); 7401 St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain); 7402 } 7403 return SDValue(St, 0); 7404 } 7405 7406 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 7407 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 7408 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 7409 SelectionDAG &DAG) const { 7410 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7411 EVT VT = Op.getValueType(); 7412 unsigned VTBits = VT.getSizeInBits(); 7413 SDLoc dl(Op); 7414 SDValue ShOpLo = Op.getOperand(0); 7415 SDValue ShOpHi = Op.getOperand(1); 7416 SDValue ShAmt = Op.getOperand(2); 7417 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 7418 7419 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 7420 7421 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 7422 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 7423 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 7424 7425 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 7426 // is "undef". We wanted 0, so CSEL it directly. 7427 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 7428 ISD::SETEQ, dl, DAG); 7429 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 7430 HiBitsForLo = 7431 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 7432 HiBitsForLo, CCVal, Cmp); 7433 7434 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 7435 DAG.getConstant(VTBits, dl, MVT::i64)); 7436 7437 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 7438 SDValue LoForNormalShift = 7439 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 7440 7441 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 7442 dl, DAG); 7443 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 7444 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 7445 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 7446 LoForNormalShift, CCVal, Cmp); 7447 7448 // AArch64 shifts larger than the register width are wrapped rather than 7449 // clamped, so we can't just emit "hi >> x". 7450 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 7451 SDValue HiForBigShift = 7452 Opc == ISD::SRA 7453 ? DAG.getNode(Opc, dl, VT, ShOpHi, 7454 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 7455 : DAG.getConstant(0, dl, VT); 7456 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 7457 HiForNormalShift, CCVal, Cmp); 7458 7459 SDValue Ops[2] = { Lo, Hi }; 7460 return DAG.getMergeValues(Ops, dl); 7461 } 7462 7463 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 7464 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 7465 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 7466 SelectionDAG &DAG) const { 7467 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7468 EVT VT = Op.getValueType(); 7469 unsigned VTBits = VT.getSizeInBits(); 7470 SDLoc dl(Op); 7471 SDValue ShOpLo = Op.getOperand(0); 7472 SDValue ShOpHi = Op.getOperand(1); 7473 SDValue ShAmt = Op.getOperand(2); 7474 7475 assert(Op.getOpcode() == ISD::SHL_PARTS); 7476 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 7477 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 7478 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 7479 7480 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 7481 // is "undef". We wanted 0, so CSEL it directly. 7482 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 7483 ISD::SETEQ, dl, DAG); 7484 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 7485 LoBitsForHi = 7486 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 7487 LoBitsForHi, CCVal, Cmp); 7488 7489 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 7490 DAG.getConstant(VTBits, dl, MVT::i64)); 7491 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 7492 SDValue HiForNormalShift = 7493 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 7494 7495 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 7496 7497 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 7498 dl, DAG); 7499 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 7500 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 7501 HiForNormalShift, CCVal, Cmp); 7502 7503 // AArch64 shifts of larger than register sizes are wrapped rather than 7504 // clamped, so we can't just emit "lo << a" if a is too big. 7505 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 7506 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7507 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 7508 LoForNormalShift, CCVal, Cmp); 7509 7510 SDValue Ops[2] = { Lo, Hi }; 7511 return DAG.getMergeValues(Ops, dl); 7512 } 7513 7514 bool AArch64TargetLowering::isOffsetFoldingLegal( 7515 const GlobalAddressSDNode *GA) const { 7516 // Offsets are folded in the DAG combine rather than here so that we can 7517 // intelligently choose an offset based on the uses. 7518 return false; 7519 } 7520 7521 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 7522 bool OptForSize) const { 7523 bool IsLegal = false; 7524 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 7525 // 16-bit case when target has full fp16 support. 7526 // FIXME: We should be able to handle f128 as well with a clever lowering. 7527 const APInt ImmInt = Imm.bitcastToAPInt(); 7528 if (VT == MVT::f64) 7529 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 7530 else if (VT == MVT::f32) 7531 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 7532 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 7533 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 7534 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 7535 // generate that fmov. 7536 7537 // If we can not materialize in immediate field for fmov, check if the 7538 // value can be encoded as the immediate operand of a logical instruction. 7539 // The immediate value will be created with either MOVZ, MOVN, or ORR. 7540 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 7541 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 7542 // however the mov+fmov sequence is always better because of the reduced 7543 // cache pressure. The timings are still the same if you consider 7544 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 7545 // movw+movk is fused). So we limit up to 2 instrdduction at most. 7546 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 7547 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 7548 Insn); 7549 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 7550 IsLegal = Insn.size() <= Limit; 7551 } 7552 7553 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 7554 << " imm value: "; Imm.dump();); 7555 return IsLegal; 7556 } 7557 7558 //===----------------------------------------------------------------------===// 7559 // AArch64 Optimization Hooks 7560 //===----------------------------------------------------------------------===// 7561 7562 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 7563 SDValue Operand, SelectionDAG &DAG, 7564 int &ExtraSteps) { 7565 EVT VT = Operand.getValueType(); 7566 if (ST->hasNEON() && 7567 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 7568 VT == MVT::f32 || VT == MVT::v1f32 || 7569 VT == MVT::v2f32 || VT == MVT::v4f32)) { 7570 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 7571 // For the reciprocal estimates, convergence is quadratic, so the number 7572 // of digits is doubled after each iteration. In ARMv8, the accuracy of 7573 // the initial estimate is 2^-8. Thus the number of extra steps to refine 7574 // the result for float (23 mantissa bits) is 2 and for double (52 7575 // mantissa bits) is 3. 7576 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 7577 7578 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 7579 } 7580 7581 return SDValue(); 7582 } 7583 7584 SDValue 7585 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 7586 const DenormalMode &Mode) const { 7587 SDLoc DL(Op); 7588 EVT VT = Op.getValueType(); 7589 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7590 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 7591 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 7592 } 7593 7594 SDValue 7595 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op, 7596 SelectionDAG &DAG) const { 7597 return Op; 7598 } 7599 7600 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 7601 SelectionDAG &DAG, int Enabled, 7602 int &ExtraSteps, 7603 bool &UseOneConst, 7604 bool Reciprocal) const { 7605 if (Enabled == ReciprocalEstimate::Enabled || 7606 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 7607 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 7608 DAG, ExtraSteps)) { 7609 SDLoc DL(Operand); 7610 EVT VT = Operand.getValueType(); 7611 7612 SDNodeFlags Flags; 7613 Flags.setAllowReassociation(true); 7614 7615 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 7616 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 7617 for (int i = ExtraSteps; i > 0; --i) { 7618 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 7619 Flags); 7620 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 7621 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 7622 } 7623 if (!Reciprocal) 7624 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 7625 7626 ExtraSteps = 0; 7627 return Estimate; 7628 } 7629 7630 return SDValue(); 7631 } 7632 7633 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 7634 SelectionDAG &DAG, int Enabled, 7635 int &ExtraSteps) const { 7636 if (Enabled == ReciprocalEstimate::Enabled) 7637 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 7638 DAG, ExtraSteps)) { 7639 SDLoc DL(Operand); 7640 EVT VT = Operand.getValueType(); 7641 7642 SDNodeFlags Flags; 7643 Flags.setAllowReassociation(true); 7644 7645 // Newton reciprocal iteration: E * (2 - X * E) 7646 // AArch64 reciprocal iteration instruction: (2 - M * N) 7647 for (int i = ExtraSteps; i > 0; --i) { 7648 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 7649 Estimate, Flags); 7650 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 7651 } 7652 7653 ExtraSteps = 0; 7654 return Estimate; 7655 } 7656 7657 return SDValue(); 7658 } 7659 7660 //===----------------------------------------------------------------------===// 7661 // AArch64 Inline Assembly Support 7662 //===----------------------------------------------------------------------===// 7663 7664 // Table of Constraints 7665 // TODO: This is the current set of constraints supported by ARM for the 7666 // compiler, not all of them may make sense. 7667 // 7668 // r - A general register 7669 // w - An FP/SIMD register of some size in the range v0-v31 7670 // x - An FP/SIMD register of some size in the range v0-v15 7671 // I - Constant that can be used with an ADD instruction 7672 // J - Constant that can be used with a SUB instruction 7673 // K - Constant that can be used with a 32-bit logical instruction 7674 // L - Constant that can be used with a 64-bit logical instruction 7675 // M - Constant that can be used as a 32-bit MOV immediate 7676 // N - Constant that can be used as a 64-bit MOV immediate 7677 // Q - A memory reference with base register and no offset 7678 // S - A symbolic address 7679 // Y - Floating point constant zero 7680 // Z - Integer constant zero 7681 // 7682 // Note that general register operands will be output using their 64-bit x 7683 // register name, whatever the size of the variable, unless the asm operand 7684 // is prefixed by the %w modifier. Floating-point and SIMD register operands 7685 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 7686 // %q modifier. 7687 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 7688 // At this point, we have to lower this constraint to something else, so we 7689 // lower it to an "r" or "w". However, by doing this we will force the result 7690 // to be in register, while the X constraint is much more permissive. 7691 // 7692 // Although we are correct (we are free to emit anything, without 7693 // constraints), we might break use cases that would expect us to be more 7694 // efficient and emit something else. 7695 if (!Subtarget->hasFPARMv8()) 7696 return "r"; 7697 7698 if (ConstraintVT.isFloatingPoint()) 7699 return "w"; 7700 7701 if (ConstraintVT.isVector() && 7702 (ConstraintVT.getSizeInBits() == 64 || 7703 ConstraintVT.getSizeInBits() == 128)) 7704 return "w"; 7705 7706 return "r"; 7707 } 7708 7709 enum PredicateConstraint { 7710 Upl, 7711 Upa, 7712 Invalid 7713 }; 7714 7715 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 7716 PredicateConstraint P = PredicateConstraint::Invalid; 7717 if (Constraint == "Upa") 7718 P = PredicateConstraint::Upa; 7719 if (Constraint == "Upl") 7720 P = PredicateConstraint::Upl; 7721 return P; 7722 } 7723 7724 /// getConstraintType - Given a constraint letter, return the type of 7725 /// constraint it is for this target. 7726 AArch64TargetLowering::ConstraintType 7727 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 7728 if (Constraint.size() == 1) { 7729 switch (Constraint[0]) { 7730 default: 7731 break; 7732 case 'x': 7733 case 'w': 7734 case 'y': 7735 return C_RegisterClass; 7736 // An address with a single base register. Due to the way we 7737 // currently handle addresses it is the same as 'r'. 7738 case 'Q': 7739 return C_Memory; 7740 case 'I': 7741 case 'J': 7742 case 'K': 7743 case 'L': 7744 case 'M': 7745 case 'N': 7746 case 'Y': 7747 case 'Z': 7748 return C_Immediate; 7749 case 'z': 7750 case 'S': // A symbolic address 7751 return C_Other; 7752 } 7753 } else if (parsePredicateConstraint(Constraint) != 7754 PredicateConstraint::Invalid) 7755 return C_RegisterClass; 7756 return TargetLowering::getConstraintType(Constraint); 7757 } 7758 7759 /// Examine constraint type and operand type and determine a weight value. 7760 /// This object must already have been set up with the operand type 7761 /// and the current alternative constraint selected. 7762 TargetLowering::ConstraintWeight 7763 AArch64TargetLowering::getSingleConstraintMatchWeight( 7764 AsmOperandInfo &info, const char *constraint) const { 7765 ConstraintWeight weight = CW_Invalid; 7766 Value *CallOperandVal = info.CallOperandVal; 7767 // If we don't have a value, we can't do a match, 7768 // but allow it at the lowest weight. 7769 if (!CallOperandVal) 7770 return CW_Default; 7771 Type *type = CallOperandVal->getType(); 7772 // Look at the constraint type. 7773 switch (*constraint) { 7774 default: 7775 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 7776 break; 7777 case 'x': 7778 case 'w': 7779 case 'y': 7780 if (type->isFloatingPointTy() || type->isVectorTy()) 7781 weight = CW_Register; 7782 break; 7783 case 'z': 7784 weight = CW_Constant; 7785 break; 7786 case 'U': 7787 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 7788 weight = CW_Register; 7789 break; 7790 } 7791 return weight; 7792 } 7793 7794 std::pair<unsigned, const TargetRegisterClass *> 7795 AArch64TargetLowering::getRegForInlineAsmConstraint( 7796 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 7797 if (Constraint.size() == 1) { 7798 switch (Constraint[0]) { 7799 case 'r': 7800 if (VT.isScalableVector()) 7801 return std::make_pair(0U, nullptr); 7802 if (VT.getFixedSizeInBits() == 64) 7803 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 7804 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 7805 case 'w': { 7806 if (!Subtarget->hasFPARMv8()) 7807 break; 7808 if (VT.isScalableVector()) { 7809 if (VT.getVectorElementType() != MVT::i1) 7810 return std::make_pair(0U, &AArch64::ZPRRegClass); 7811 return std::make_pair(0U, nullptr); 7812 } 7813 uint64_t VTSize = VT.getFixedSizeInBits(); 7814 if (VTSize == 16) 7815 return std::make_pair(0U, &AArch64::FPR16RegClass); 7816 if (VTSize == 32) 7817 return std::make_pair(0U, &AArch64::FPR32RegClass); 7818 if (VTSize == 64) 7819 return std::make_pair(0U, &AArch64::FPR64RegClass); 7820 if (VTSize == 128) 7821 return std::make_pair(0U, &AArch64::FPR128RegClass); 7822 break; 7823 } 7824 // The instructions that this constraint is designed for can 7825 // only take 128-bit registers so just use that regclass. 7826 case 'x': 7827 if (!Subtarget->hasFPARMv8()) 7828 break; 7829 if (VT.isScalableVector()) 7830 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 7831 if (VT.getSizeInBits() == 128) 7832 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 7833 break; 7834 case 'y': 7835 if (!Subtarget->hasFPARMv8()) 7836 break; 7837 if (VT.isScalableVector()) 7838 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 7839 break; 7840 } 7841 } else { 7842 PredicateConstraint PC = parsePredicateConstraint(Constraint); 7843 if (PC != PredicateConstraint::Invalid) { 7844 if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1) 7845 return std::make_pair(0U, nullptr); 7846 bool restricted = (PC == PredicateConstraint::Upl); 7847 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 7848 : std::make_pair(0U, &AArch64::PPRRegClass); 7849 } 7850 } 7851 if (StringRef("{cc}").equals_lower(Constraint)) 7852 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 7853 7854 // Use the default implementation in TargetLowering to convert the register 7855 // constraint into a member of a register class. 7856 std::pair<unsigned, const TargetRegisterClass *> Res; 7857 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7858 7859 // Not found as a standard register? 7860 if (!Res.second) { 7861 unsigned Size = Constraint.size(); 7862 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 7863 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 7864 int RegNo; 7865 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 7866 if (!Failed && RegNo >= 0 && RegNo <= 31) { 7867 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 7868 // By default we'll emit v0-v31 for this unless there's a modifier where 7869 // we'll emit the correct register as well. 7870 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 7871 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 7872 Res.second = &AArch64::FPR64RegClass; 7873 } else { 7874 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 7875 Res.second = &AArch64::FPR128RegClass; 7876 } 7877 } 7878 } 7879 } 7880 7881 if (Res.second && !Subtarget->hasFPARMv8() && 7882 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 7883 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 7884 return std::make_pair(0U, nullptr); 7885 7886 return Res; 7887 } 7888 7889 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 7890 /// vector. If it is invalid, don't add anything to Ops. 7891 void AArch64TargetLowering::LowerAsmOperandForConstraint( 7892 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 7893 SelectionDAG &DAG) const { 7894 SDValue Result; 7895 7896 // Currently only support length 1 constraints. 7897 if (Constraint.length() != 1) 7898 return; 7899 7900 char ConstraintLetter = Constraint[0]; 7901 switch (ConstraintLetter) { 7902 default: 7903 break; 7904 7905 // This set of constraints deal with valid constants for various instructions. 7906 // Validate and return a target constant for them if we can. 7907 case 'z': { 7908 // 'z' maps to xzr or wzr so it needs an input of 0. 7909 if (!isNullConstant(Op)) 7910 return; 7911 7912 if (Op.getValueType() == MVT::i64) 7913 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 7914 else 7915 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 7916 break; 7917 } 7918 case 'S': { 7919 // An absolute symbolic address or label reference. 7920 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 7921 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 7922 GA->getValueType(0)); 7923 } else if (const BlockAddressSDNode *BA = 7924 dyn_cast<BlockAddressSDNode>(Op)) { 7925 Result = 7926 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 7927 } else if (const ExternalSymbolSDNode *ES = 7928 dyn_cast<ExternalSymbolSDNode>(Op)) { 7929 Result = 7930 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 7931 } else 7932 return; 7933 break; 7934 } 7935 7936 case 'I': 7937 case 'J': 7938 case 'K': 7939 case 'L': 7940 case 'M': 7941 case 'N': 7942 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 7943 if (!C) 7944 return; 7945 7946 // Grab the value and do some validation. 7947 uint64_t CVal = C->getZExtValue(); 7948 switch (ConstraintLetter) { 7949 // The I constraint applies only to simple ADD or SUB immediate operands: 7950 // i.e. 0 to 4095 with optional shift by 12 7951 // The J constraint applies only to ADD or SUB immediates that would be 7952 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 7953 // instruction [or vice versa], in other words -1 to -4095 with optional 7954 // left shift by 12. 7955 case 'I': 7956 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 7957 break; 7958 return; 7959 case 'J': { 7960 uint64_t NVal = -C->getSExtValue(); 7961 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 7962 CVal = C->getSExtValue(); 7963 break; 7964 } 7965 return; 7966 } 7967 // The K and L constraints apply *only* to logical immediates, including 7968 // what used to be the MOVI alias for ORR (though the MOVI alias has now 7969 // been removed and MOV should be used). So these constraints have to 7970 // distinguish between bit patterns that are valid 32-bit or 64-bit 7971 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 7972 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 7973 // versa. 7974 case 'K': 7975 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 7976 break; 7977 return; 7978 case 'L': 7979 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 7980 break; 7981 return; 7982 // The M and N constraints are a superset of K and L respectively, for use 7983 // with the MOV (immediate) alias. As well as the logical immediates they 7984 // also match 32 or 64-bit immediates that can be loaded either using a 7985 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 7986 // (M) or 64-bit 0x1234000000000000 (N) etc. 7987 // As a note some of this code is liberally stolen from the asm parser. 7988 case 'M': { 7989 if (!isUInt<32>(CVal)) 7990 return; 7991 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 7992 break; 7993 if ((CVal & 0xFFFF) == CVal) 7994 break; 7995 if ((CVal & 0xFFFF0000ULL) == CVal) 7996 break; 7997 uint64_t NCVal = ~(uint32_t)CVal; 7998 if ((NCVal & 0xFFFFULL) == NCVal) 7999 break; 8000 if ((NCVal & 0xFFFF0000ULL) == NCVal) 8001 break; 8002 return; 8003 } 8004 case 'N': { 8005 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 8006 break; 8007 if ((CVal & 0xFFFFULL) == CVal) 8008 break; 8009 if ((CVal & 0xFFFF0000ULL) == CVal) 8010 break; 8011 if ((CVal & 0xFFFF00000000ULL) == CVal) 8012 break; 8013 if ((CVal & 0xFFFF000000000000ULL) == CVal) 8014 break; 8015 uint64_t NCVal = ~CVal; 8016 if ((NCVal & 0xFFFFULL) == NCVal) 8017 break; 8018 if ((NCVal & 0xFFFF0000ULL) == NCVal) 8019 break; 8020 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 8021 break; 8022 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 8023 break; 8024 return; 8025 } 8026 default: 8027 return; 8028 } 8029 8030 // All assembler immediates are 64-bit integers. 8031 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 8032 break; 8033 } 8034 8035 if (Result.getNode()) { 8036 Ops.push_back(Result); 8037 return; 8038 } 8039 8040 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 8041 } 8042 8043 //===----------------------------------------------------------------------===// 8044 // AArch64 Advanced SIMD Support 8045 //===----------------------------------------------------------------------===// 8046 8047 /// WidenVector - Given a value in the V64 register class, produce the 8048 /// equivalent value in the V128 register class. 8049 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 8050 EVT VT = V64Reg.getValueType(); 8051 unsigned NarrowSize = VT.getVectorNumElements(); 8052 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 8053 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 8054 SDLoc DL(V64Reg); 8055 8056 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 8057 V64Reg, DAG.getConstant(0, DL, MVT::i64)); 8058 } 8059 8060 /// getExtFactor - Determine the adjustment factor for the position when 8061 /// generating an "extract from vector registers" instruction. 8062 static unsigned getExtFactor(SDValue &V) { 8063 EVT EltType = V.getValueType().getVectorElementType(); 8064 return EltType.getSizeInBits() / 8; 8065 } 8066 8067 /// NarrowVector - Given a value in the V128 register class, produce the 8068 /// equivalent value in the V64 register class. 8069 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 8070 EVT VT = V128Reg.getValueType(); 8071 unsigned WideSize = VT.getVectorNumElements(); 8072 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 8073 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 8074 SDLoc DL(V128Reg); 8075 8076 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 8077 } 8078 8079 // Gather data to see if the operation can be modelled as a 8080 // shuffle in combination with VEXTs. 8081 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 8082 SelectionDAG &DAG) const { 8083 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 8084 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 8085 SDLoc dl(Op); 8086 EVT VT = Op.getValueType(); 8087 assert(!VT.isScalableVector() && 8088 "Scalable vectors cannot be used with ISD::BUILD_VECTOR"); 8089 unsigned NumElts = VT.getVectorNumElements(); 8090 8091 struct ShuffleSourceInfo { 8092 SDValue Vec; 8093 unsigned MinElt; 8094 unsigned MaxElt; 8095 8096 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 8097 // be compatible with the shuffle we intend to construct. As a result 8098 // ShuffleVec will be some sliding window into the original Vec. 8099 SDValue ShuffleVec; 8100 8101 // Code should guarantee that element i in Vec starts at element "WindowBase 8102 // + i * WindowScale in ShuffleVec". 8103 int WindowBase; 8104 int WindowScale; 8105 8106 ShuffleSourceInfo(SDValue Vec) 8107 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 8108 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 8109 8110 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 8111 }; 8112 8113 // First gather all vectors used as an immediate source for this BUILD_VECTOR 8114 // node. 8115 SmallVector<ShuffleSourceInfo, 2> Sources; 8116 for (unsigned i = 0; i < NumElts; ++i) { 8117 SDValue V = Op.getOperand(i); 8118 if (V.isUndef()) 8119 continue; 8120 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8121 !isa<ConstantSDNode>(V.getOperand(1))) { 8122 LLVM_DEBUG( 8123 dbgs() << "Reshuffle failed: " 8124 "a shuffle can only come from building a vector from " 8125 "various elements of other vectors, provided their " 8126 "indices are constant\n"); 8127 return SDValue(); 8128 } 8129 8130 // Add this element source to the list if it's not already there. 8131 SDValue SourceVec = V.getOperand(0); 8132 auto Source = find(Sources, SourceVec); 8133 if (Source == Sources.end()) 8134 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 8135 8136 // Update the minimum and maximum lane number seen. 8137 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 8138 Source->MinElt = std::min(Source->MinElt, EltNo); 8139 Source->MaxElt = std::max(Source->MaxElt, EltNo); 8140 } 8141 8142 if (Sources.size() > 2) { 8143 LLVM_DEBUG( 8144 dbgs() << "Reshuffle failed: currently only do something sane when at " 8145 "most two source vectors are involved\n"); 8146 return SDValue(); 8147 } 8148 8149 // Find out the smallest element size among result and two sources, and use 8150 // it as element size to build the shuffle_vector. 8151 EVT SmallestEltTy = VT.getVectorElementType(); 8152 for (auto &Source : Sources) { 8153 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 8154 if (SrcEltTy.bitsLT(SmallestEltTy)) { 8155 SmallestEltTy = SrcEltTy; 8156 } 8157 } 8158 unsigned ResMultiplier = 8159 VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits(); 8160 uint64_t VTSize = VT.getFixedSizeInBits(); 8161 NumElts = VTSize / SmallestEltTy.getFixedSizeInBits(); 8162 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 8163 8164 // If the source vector is too wide or too narrow, we may nevertheless be able 8165 // to construct a compatible shuffle either by concatenating it with UNDEF or 8166 // extracting a suitable range of elements. 8167 for (auto &Src : Sources) { 8168 EVT SrcVT = Src.ShuffleVec.getValueType(); 8169 8170 uint64_t SrcVTSize = SrcVT.getFixedSizeInBits(); 8171 if (SrcVTSize == VTSize) 8172 continue; 8173 8174 // This stage of the search produces a source with the same element type as 8175 // the original, but with a total width matching the BUILD_VECTOR output. 8176 EVT EltVT = SrcVT.getVectorElementType(); 8177 unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits(); 8178 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 8179 8180 if (SrcVTSize < VTSize) { 8181 assert(2 * SrcVTSize == VTSize); 8182 // We can pad out the smaller vector for free, so if it's part of a 8183 // shuffle... 8184 Src.ShuffleVec = 8185 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 8186 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 8187 continue; 8188 } 8189 8190 if (SrcVTSize != 2 * VTSize) { 8191 LLVM_DEBUG( 8192 dbgs() << "Reshuffle failed: result vector too small to extract\n"); 8193 return SDValue(); 8194 } 8195 8196 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 8197 LLVM_DEBUG( 8198 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 8199 return SDValue(); 8200 } 8201 8202 if (Src.MinElt >= NumSrcElts) { 8203 // The extraction can just take the second half 8204 Src.ShuffleVec = 8205 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8206 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 8207 Src.WindowBase = -NumSrcElts; 8208 } else if (Src.MaxElt < NumSrcElts) { 8209 // The extraction can just take the first half 8210 Src.ShuffleVec = 8211 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8212 DAG.getConstant(0, dl, MVT::i64)); 8213 } else { 8214 // An actual VEXT is needed 8215 SDValue VEXTSrc1 = 8216 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8217 DAG.getConstant(0, dl, MVT::i64)); 8218 SDValue VEXTSrc2 = 8219 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 8220 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 8221 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 8222 8223 if (!SrcVT.is64BitVector()) { 8224 LLVM_DEBUG( 8225 dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT " 8226 "for SVE vectors."); 8227 return SDValue(); 8228 } 8229 8230 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 8231 VEXTSrc2, 8232 DAG.getConstant(Imm, dl, MVT::i32)); 8233 Src.WindowBase = -Src.MinElt; 8234 } 8235 } 8236 8237 // Another possible incompatibility occurs from the vector element types. We 8238 // can fix this by bitcasting the source vectors to the same type we intend 8239 // for the shuffle. 8240 for (auto &Src : Sources) { 8241 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 8242 if (SrcEltTy == SmallestEltTy) 8243 continue; 8244 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 8245 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 8246 Src.WindowScale = 8247 SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits(); 8248 Src.WindowBase *= Src.WindowScale; 8249 } 8250 8251 // Final sanity check before we try to actually produce a shuffle. 8252 LLVM_DEBUG(for (auto Src 8253 : Sources) 8254 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 8255 8256 // The stars all align, our next step is to produce the mask for the shuffle. 8257 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 8258 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 8259 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 8260 SDValue Entry = Op.getOperand(i); 8261 if (Entry.isUndef()) 8262 continue; 8263 8264 auto Src = find(Sources, Entry.getOperand(0)); 8265 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 8266 8267 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 8268 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 8269 // segment. 8270 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 8271 int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(), 8272 VT.getScalarSizeInBits()); 8273 int LanesDefined = BitsDefined / BitsPerShuffleLane; 8274 8275 // This source is expected to fill ResMultiplier lanes of the final shuffle, 8276 // starting at the appropriate offset. 8277 int *LaneMask = &Mask[i * ResMultiplier]; 8278 8279 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 8280 ExtractBase += NumElts * (Src - Sources.begin()); 8281 for (int j = 0; j < LanesDefined; ++j) 8282 LaneMask[j] = ExtractBase + j; 8283 } 8284 8285 // Final check before we try to produce nonsense... 8286 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 8287 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 8288 return SDValue(); 8289 } 8290 8291 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 8292 for (unsigned i = 0; i < Sources.size(); ++i) 8293 ShuffleOps[i] = Sources[i].ShuffleVec; 8294 8295 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 8296 ShuffleOps[1], Mask); 8297 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 8298 8299 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 8300 dbgs() << "Reshuffle, creating node: "; V.dump();); 8301 8302 return V; 8303 } 8304 8305 // check if an EXT instruction can handle the shuffle mask when the 8306 // vector sources of the shuffle are the same. 8307 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 8308 unsigned NumElts = VT.getVectorNumElements(); 8309 8310 // Assume that the first shuffle index is not UNDEF. Fail if it is. 8311 if (M[0] < 0) 8312 return false; 8313 8314 Imm = M[0]; 8315 8316 // If this is a VEXT shuffle, the immediate value is the index of the first 8317 // element. The other shuffle indices must be the successive elements after 8318 // the first one. 8319 unsigned ExpectedElt = Imm; 8320 for (unsigned i = 1; i < NumElts; ++i) { 8321 // Increment the expected index. If it wraps around, just follow it 8322 // back to index zero and keep going. 8323 ++ExpectedElt; 8324 if (ExpectedElt == NumElts) 8325 ExpectedElt = 0; 8326 8327 if (M[i] < 0) 8328 continue; // ignore UNDEF indices 8329 if (ExpectedElt != static_cast<unsigned>(M[i])) 8330 return false; 8331 } 8332 8333 return true; 8334 } 8335 8336 /// Check if a vector shuffle corresponds to a DUP instructions with a larger 8337 /// element width than the vector lane type. If that is the case the function 8338 /// returns true and writes the value of the DUP instruction lane operand into 8339 /// DupLaneOp 8340 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize, 8341 unsigned &DupLaneOp) { 8342 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 8343 "Only possible block sizes for wide DUP are: 16, 32, 64"); 8344 8345 if (BlockSize <= VT.getScalarSizeInBits()) 8346 return false; 8347 if (BlockSize % VT.getScalarSizeInBits() != 0) 8348 return false; 8349 if (VT.getSizeInBits() % BlockSize != 0) 8350 return false; 8351 8352 size_t SingleVecNumElements = VT.getVectorNumElements(); 8353 size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits(); 8354 size_t NumBlocks = VT.getSizeInBits() / BlockSize; 8355 8356 // We are looking for masks like 8357 // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element 8358 // might be replaced by 'undefined'. BlockIndices will eventually contain 8359 // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7] 8360 // for the above examples) 8361 SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1); 8362 for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++) 8363 for (size_t I = 0; I < NumEltsPerBlock; I++) { 8364 int Elt = M[BlockIndex * NumEltsPerBlock + I]; 8365 if (Elt < 0) 8366 continue; 8367 // For now we don't support shuffles that use the second operand 8368 if ((unsigned)Elt >= SingleVecNumElements) 8369 return false; 8370 if (BlockElts[I] < 0) 8371 BlockElts[I] = Elt; 8372 else if (BlockElts[I] != Elt) 8373 return false; 8374 } 8375 8376 // We found a candidate block (possibly with some undefs). It must be a 8377 // sequence of consecutive integers starting with a value divisible by 8378 // NumEltsPerBlock with some values possibly replaced by undef-s. 8379 8380 // Find first non-undef element 8381 auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; }); 8382 assert(FirstRealEltIter != BlockElts.end() && 8383 "Shuffle with all-undefs must have been caught by previous cases, " 8384 "e.g. isSplat()"); 8385 if (FirstRealEltIter == BlockElts.end()) { 8386 DupLaneOp = 0; 8387 return true; 8388 } 8389 8390 // Index of FirstRealElt in BlockElts 8391 size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin(); 8392 8393 if ((unsigned)*FirstRealEltIter < FirstRealIndex) 8394 return false; 8395 // BlockElts[0] must have the following value if it isn't undef: 8396 size_t Elt0 = *FirstRealEltIter - FirstRealIndex; 8397 8398 // Check the first element 8399 if (Elt0 % NumEltsPerBlock != 0) 8400 return false; 8401 // Check that the sequence indeed consists of consecutive integers (modulo 8402 // undefs) 8403 for (size_t I = 0; I < NumEltsPerBlock; I++) 8404 if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I) 8405 return false; 8406 8407 DupLaneOp = Elt0 / NumEltsPerBlock; 8408 return true; 8409 } 8410 8411 // check if an EXT instruction can handle the shuffle mask when the 8412 // vector sources of the shuffle are different. 8413 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 8414 unsigned &Imm) { 8415 // Look for the first non-undef element. 8416 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 8417 8418 // Benefit form APInt to handle overflow when calculating expected element. 8419 unsigned NumElts = VT.getVectorNumElements(); 8420 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 8421 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 8422 // The following shuffle indices must be the successive elements after the 8423 // first real element. 8424 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 8425 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 8426 if (FirstWrongElt != M.end()) 8427 return false; 8428 8429 // The index of an EXT is the first element if it is not UNDEF. 8430 // Watch out for the beginning UNDEFs. The EXT index should be the expected 8431 // value of the first element. E.g. 8432 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 8433 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 8434 // ExpectedElt is the last mask index plus 1. 8435 Imm = ExpectedElt.getZExtValue(); 8436 8437 // There are two difference cases requiring to reverse input vectors. 8438 // For example, for vector <4 x i32> we have the following cases, 8439 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 8440 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 8441 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 8442 // to reverse two input vectors. 8443 if (Imm < NumElts) 8444 ReverseEXT = true; 8445 else 8446 Imm -= NumElts; 8447 8448 return true; 8449 } 8450 8451 /// isREVMask - Check if a vector shuffle corresponds to a REV 8452 /// instruction with the specified blocksize. (The order of the elements 8453 /// within each block of the vector is reversed.) 8454 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 8455 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 8456 "Only possible block sizes for REV are: 16, 32, 64"); 8457 8458 unsigned EltSz = VT.getScalarSizeInBits(); 8459 if (EltSz == 64) 8460 return false; 8461 8462 unsigned NumElts = VT.getVectorNumElements(); 8463 unsigned BlockElts = M[0] + 1; 8464 // If the first shuffle index is UNDEF, be optimistic. 8465 if (M[0] < 0) 8466 BlockElts = BlockSize / EltSz; 8467 8468 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 8469 return false; 8470 8471 for (unsigned i = 0; i < NumElts; ++i) { 8472 if (M[i] < 0) 8473 continue; // ignore UNDEF indices 8474 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 8475 return false; 8476 } 8477 8478 return true; 8479 } 8480 8481 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8482 unsigned NumElts = VT.getVectorNumElements(); 8483 if (NumElts % 2 != 0) 8484 return false; 8485 WhichResult = (M[0] == 0 ? 0 : 1); 8486 unsigned Idx = WhichResult * NumElts / 2; 8487 for (unsigned i = 0; i != NumElts; i += 2) { 8488 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 8489 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 8490 return false; 8491 Idx += 1; 8492 } 8493 8494 return true; 8495 } 8496 8497 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8498 unsigned NumElts = VT.getVectorNumElements(); 8499 WhichResult = (M[0] == 0 ? 0 : 1); 8500 for (unsigned i = 0; i != NumElts; ++i) { 8501 if (M[i] < 0) 8502 continue; // ignore UNDEF indices 8503 if ((unsigned)M[i] != 2 * i + WhichResult) 8504 return false; 8505 } 8506 8507 return true; 8508 } 8509 8510 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8511 unsigned NumElts = VT.getVectorNumElements(); 8512 if (NumElts % 2 != 0) 8513 return false; 8514 WhichResult = (M[0] == 0 ? 0 : 1); 8515 for (unsigned i = 0; i < NumElts; i += 2) { 8516 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 8517 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 8518 return false; 8519 } 8520 return true; 8521 } 8522 8523 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 8524 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8525 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 8526 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8527 unsigned NumElts = VT.getVectorNumElements(); 8528 if (NumElts % 2 != 0) 8529 return false; 8530 WhichResult = (M[0] == 0 ? 0 : 1); 8531 unsigned Idx = WhichResult * NumElts / 2; 8532 for (unsigned i = 0; i != NumElts; i += 2) { 8533 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 8534 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 8535 return false; 8536 Idx += 1; 8537 } 8538 8539 return true; 8540 } 8541 8542 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 8543 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8544 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 8545 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8546 unsigned Half = VT.getVectorNumElements() / 2; 8547 WhichResult = (M[0] == 0 ? 0 : 1); 8548 for (unsigned j = 0; j != 2; ++j) { 8549 unsigned Idx = WhichResult; 8550 for (unsigned i = 0; i != Half; ++i) { 8551 int MIdx = M[i + j * Half]; 8552 if (MIdx >= 0 && (unsigned)MIdx != Idx) 8553 return false; 8554 Idx += 2; 8555 } 8556 } 8557 8558 return true; 8559 } 8560 8561 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 8562 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 8563 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 8564 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 8565 unsigned NumElts = VT.getVectorNumElements(); 8566 if (NumElts % 2 != 0) 8567 return false; 8568 WhichResult = (M[0] == 0 ? 0 : 1); 8569 for (unsigned i = 0; i < NumElts; i += 2) { 8570 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 8571 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 8572 return false; 8573 } 8574 return true; 8575 } 8576 8577 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 8578 bool &DstIsLeft, int &Anomaly) { 8579 if (M.size() != static_cast<size_t>(NumInputElements)) 8580 return false; 8581 8582 int NumLHSMatch = 0, NumRHSMatch = 0; 8583 int LastLHSMismatch = -1, LastRHSMismatch = -1; 8584 8585 for (int i = 0; i < NumInputElements; ++i) { 8586 if (M[i] == -1) { 8587 ++NumLHSMatch; 8588 ++NumRHSMatch; 8589 continue; 8590 } 8591 8592 if (M[i] == i) 8593 ++NumLHSMatch; 8594 else 8595 LastLHSMismatch = i; 8596 8597 if (M[i] == i + NumInputElements) 8598 ++NumRHSMatch; 8599 else 8600 LastRHSMismatch = i; 8601 } 8602 8603 if (NumLHSMatch == NumInputElements - 1) { 8604 DstIsLeft = true; 8605 Anomaly = LastLHSMismatch; 8606 return true; 8607 } else if (NumRHSMatch == NumInputElements - 1) { 8608 DstIsLeft = false; 8609 Anomaly = LastRHSMismatch; 8610 return true; 8611 } 8612 8613 return false; 8614 } 8615 8616 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 8617 if (VT.getSizeInBits() != 128) 8618 return false; 8619 8620 unsigned NumElts = VT.getVectorNumElements(); 8621 8622 for (int I = 0, E = NumElts / 2; I != E; I++) { 8623 if (Mask[I] != I) 8624 return false; 8625 } 8626 8627 int Offset = NumElts / 2; 8628 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 8629 if (Mask[I] != I + SplitLHS * Offset) 8630 return false; 8631 } 8632 8633 return true; 8634 } 8635 8636 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 8637 SDLoc DL(Op); 8638 EVT VT = Op.getValueType(); 8639 SDValue V0 = Op.getOperand(0); 8640 SDValue V1 = Op.getOperand(1); 8641 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 8642 8643 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 8644 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 8645 return SDValue(); 8646 8647 bool SplitV0 = V0.getValueSizeInBits() == 128; 8648 8649 if (!isConcatMask(Mask, VT, SplitV0)) 8650 return SDValue(); 8651 8652 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8653 if (SplitV0) { 8654 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 8655 DAG.getConstant(0, DL, MVT::i64)); 8656 } 8657 if (V1.getValueSizeInBits() == 128) { 8658 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 8659 DAG.getConstant(0, DL, MVT::i64)); 8660 } 8661 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 8662 } 8663 8664 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8665 /// the specified operations to build the shuffle. 8666 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8667 SDValue RHS, SelectionDAG &DAG, 8668 const SDLoc &dl) { 8669 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8670 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 8671 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 8672 8673 enum { 8674 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8675 OP_VREV, 8676 OP_VDUP0, 8677 OP_VDUP1, 8678 OP_VDUP2, 8679 OP_VDUP3, 8680 OP_VEXT1, 8681 OP_VEXT2, 8682 OP_VEXT3, 8683 OP_VUZPL, // VUZP, left result 8684 OP_VUZPR, // VUZP, right result 8685 OP_VZIPL, // VZIP, left result 8686 OP_VZIPR, // VZIP, right result 8687 OP_VTRNL, // VTRN, left result 8688 OP_VTRNR // VTRN, right result 8689 }; 8690 8691 if (OpNum == OP_COPY) { 8692 if (LHSID == (1 * 9 + 2) * 9 + 3) 8693 return LHS; 8694 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 8695 return RHS; 8696 } 8697 8698 SDValue OpLHS, OpRHS; 8699 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8700 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8701 EVT VT = OpLHS.getValueType(); 8702 8703 switch (OpNum) { 8704 default: 8705 llvm_unreachable("Unknown shuffle opcode!"); 8706 case OP_VREV: 8707 // VREV divides the vector in half and swaps within the half. 8708 if (VT.getVectorElementType() == MVT::i32 || 8709 VT.getVectorElementType() == MVT::f32) 8710 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 8711 // vrev <4 x i16> -> REV32 8712 if (VT.getVectorElementType() == MVT::i16 || 8713 VT.getVectorElementType() == MVT::f16 || 8714 VT.getVectorElementType() == MVT::bf16) 8715 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 8716 // vrev <4 x i8> -> REV16 8717 assert(VT.getVectorElementType() == MVT::i8); 8718 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 8719 case OP_VDUP0: 8720 case OP_VDUP1: 8721 case OP_VDUP2: 8722 case OP_VDUP3: { 8723 EVT EltTy = VT.getVectorElementType(); 8724 unsigned Opcode; 8725 if (EltTy == MVT::i8) 8726 Opcode = AArch64ISD::DUPLANE8; 8727 else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16) 8728 Opcode = AArch64ISD::DUPLANE16; 8729 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 8730 Opcode = AArch64ISD::DUPLANE32; 8731 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 8732 Opcode = AArch64ISD::DUPLANE64; 8733 else 8734 llvm_unreachable("Invalid vector element type?"); 8735 8736 if (VT.getSizeInBits() == 64) 8737 OpLHS = WidenVector(OpLHS, DAG); 8738 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 8739 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 8740 } 8741 case OP_VEXT1: 8742 case OP_VEXT2: 8743 case OP_VEXT3: { 8744 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 8745 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 8746 DAG.getConstant(Imm, dl, MVT::i32)); 8747 } 8748 case OP_VUZPL: 8749 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 8750 OpRHS); 8751 case OP_VUZPR: 8752 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 8753 OpRHS); 8754 case OP_VZIPL: 8755 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 8756 OpRHS); 8757 case OP_VZIPR: 8758 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 8759 OpRHS); 8760 case OP_VTRNL: 8761 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 8762 OpRHS); 8763 case OP_VTRNR: 8764 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 8765 OpRHS); 8766 } 8767 } 8768 8769 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 8770 SelectionDAG &DAG) { 8771 // Check to see if we can use the TBL instruction. 8772 SDValue V1 = Op.getOperand(0); 8773 SDValue V2 = Op.getOperand(1); 8774 SDLoc DL(Op); 8775 8776 EVT EltVT = Op.getValueType().getVectorElementType(); 8777 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 8778 8779 SmallVector<SDValue, 8> TBLMask; 8780 for (int Val : ShuffleMask) { 8781 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 8782 unsigned Offset = Byte + Val * BytesPerElt; 8783 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 8784 } 8785 } 8786 8787 MVT IndexVT = MVT::v8i8; 8788 unsigned IndexLen = 8; 8789 if (Op.getValueSizeInBits() == 128) { 8790 IndexVT = MVT::v16i8; 8791 IndexLen = 16; 8792 } 8793 8794 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 8795 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 8796 8797 SDValue Shuffle; 8798 if (V2.getNode()->isUndef()) { 8799 if (IndexLen == 8) 8800 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 8801 Shuffle = DAG.getNode( 8802 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8803 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 8804 DAG.getBuildVector(IndexVT, DL, 8805 makeArrayRef(TBLMask.data(), IndexLen))); 8806 } else { 8807 if (IndexLen == 8) { 8808 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 8809 Shuffle = DAG.getNode( 8810 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8811 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 8812 DAG.getBuildVector(IndexVT, DL, 8813 makeArrayRef(TBLMask.data(), IndexLen))); 8814 } else { 8815 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 8816 // cannot currently represent the register constraints on the input 8817 // table registers. 8818 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 8819 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 8820 // IndexLen)); 8821 Shuffle = DAG.getNode( 8822 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 8823 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 8824 V2Cst, DAG.getBuildVector(IndexVT, DL, 8825 makeArrayRef(TBLMask.data(), IndexLen))); 8826 } 8827 } 8828 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 8829 } 8830 8831 static unsigned getDUPLANEOp(EVT EltType) { 8832 if (EltType == MVT::i8) 8833 return AArch64ISD::DUPLANE8; 8834 if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16) 8835 return AArch64ISD::DUPLANE16; 8836 if (EltType == MVT::i32 || EltType == MVT::f32) 8837 return AArch64ISD::DUPLANE32; 8838 if (EltType == MVT::i64 || EltType == MVT::f64) 8839 return AArch64ISD::DUPLANE64; 8840 8841 llvm_unreachable("Invalid vector element type?"); 8842 } 8843 8844 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT, 8845 unsigned Opcode, SelectionDAG &DAG) { 8846 // Try to eliminate a bitcasted extract subvector before a DUPLANE. 8847 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) { 8848 // Match: dup (bitcast (extract_subv X, C)), LaneC 8849 if (BitCast.getOpcode() != ISD::BITCAST || 8850 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR) 8851 return false; 8852 8853 // The extract index must align in the destination type. That may not 8854 // happen if the bitcast is from narrow to wide type. 8855 SDValue Extract = BitCast.getOperand(0); 8856 unsigned ExtIdx = Extract.getConstantOperandVal(1); 8857 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits(); 8858 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth; 8859 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits(); 8860 if (ExtIdxInBits % CastedEltBitWidth != 0) 8861 return false; 8862 8863 // Update the lane value by offsetting with the scaled extract index. 8864 LaneC += ExtIdxInBits / CastedEltBitWidth; 8865 8866 // Determine the casted vector type of the wide vector input. 8867 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC' 8868 // Examples: 8869 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3 8870 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5 8871 unsigned SrcVecNumElts = 8872 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth; 8873 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(), 8874 SrcVecNumElts); 8875 return true; 8876 }; 8877 MVT CastVT; 8878 if (getScaledOffsetDup(V, Lane, CastVT)) { 8879 V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0)); 8880 } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8881 // The lane is incremented by the index of the extract. 8882 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3 8883 Lane += V.getConstantOperandVal(1); 8884 V = V.getOperand(0); 8885 } else if (V.getOpcode() == ISD::CONCAT_VECTORS) { 8886 // The lane is decremented if we are splatting from the 2nd operand. 8887 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1 8888 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 8889 Lane -= Idx * VT.getVectorNumElements() / 2; 8890 V = WidenVector(V.getOperand(Idx), DAG); 8891 } else if (VT.getSizeInBits() == 64) { 8892 // Widen the operand to 128-bit register with undef. 8893 V = WidenVector(V, DAG); 8894 } 8895 return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64)); 8896 } 8897 8898 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8899 SelectionDAG &DAG) const { 8900 SDLoc dl(Op); 8901 EVT VT = Op.getValueType(); 8902 8903 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 8904 8905 // Convert shuffles that are directly supported on NEON to target-specific 8906 // DAG nodes, instead of keeping them as shuffles and matching them again 8907 // during code selection. This is more efficient and avoids the possibility 8908 // of inconsistencies between legalization and selection. 8909 ArrayRef<int> ShuffleMask = SVN->getMask(); 8910 8911 SDValue V1 = Op.getOperand(0); 8912 SDValue V2 = Op.getOperand(1); 8913 8914 if (SVN->isSplat()) { 8915 int Lane = SVN->getSplatIndex(); 8916 // If this is undef splat, generate it via "just" vdup, if possible. 8917 if (Lane == -1) 8918 Lane = 0; 8919 8920 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 8921 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 8922 V1.getOperand(0)); 8923 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 8924 // constant. If so, we can just reference the lane's definition directly. 8925 if (V1.getOpcode() == ISD::BUILD_VECTOR && 8926 !isa<ConstantSDNode>(V1.getOperand(Lane))) 8927 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 8928 8929 // Otherwise, duplicate from the lane of the input vector. 8930 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 8931 return constructDup(V1, Lane, dl, VT, Opcode, DAG); 8932 } 8933 8934 // Check if the mask matches a DUP for a wider element 8935 for (unsigned LaneSize : {64U, 32U, 16U}) { 8936 unsigned Lane = 0; 8937 if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) { 8938 unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64 8939 : LaneSize == 32 ? AArch64ISD::DUPLANE32 8940 : AArch64ISD::DUPLANE16; 8941 // Cast V1 to an integer vector with required lane size 8942 MVT NewEltTy = MVT::getIntegerVT(LaneSize); 8943 unsigned NewEltCount = VT.getSizeInBits() / LaneSize; 8944 MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount); 8945 V1 = DAG.getBitcast(NewVecTy, V1); 8946 // Constuct the DUP instruction 8947 V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG); 8948 // Cast back to the original type 8949 return DAG.getBitcast(VT, V1); 8950 } 8951 } 8952 8953 if (isREVMask(ShuffleMask, VT, 64)) 8954 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 8955 if (isREVMask(ShuffleMask, VT, 32)) 8956 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 8957 if (isREVMask(ShuffleMask, VT, 16)) 8958 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 8959 8960 bool ReverseEXT = false; 8961 unsigned Imm; 8962 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 8963 if (ReverseEXT) 8964 std::swap(V1, V2); 8965 Imm *= getExtFactor(V1); 8966 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 8967 DAG.getConstant(Imm, dl, MVT::i32)); 8968 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 8969 Imm *= getExtFactor(V1); 8970 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 8971 DAG.getConstant(Imm, dl, MVT::i32)); 8972 } 8973 8974 unsigned WhichResult; 8975 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 8976 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 8977 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 8978 } 8979 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 8980 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 8981 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 8982 } 8983 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 8984 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 8985 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 8986 } 8987 8988 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 8989 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 8990 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 8991 } 8992 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 8993 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 8994 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 8995 } 8996 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 8997 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 8998 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 8999 } 9000 9001 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 9002 return Concat; 9003 9004 bool DstIsLeft; 9005 int Anomaly; 9006 int NumInputElements = V1.getValueType().getVectorNumElements(); 9007 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 9008 SDValue DstVec = DstIsLeft ? V1 : V2; 9009 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 9010 9011 SDValue SrcVec = V1; 9012 int SrcLane = ShuffleMask[Anomaly]; 9013 if (SrcLane >= NumInputElements) { 9014 SrcVec = V2; 9015 SrcLane -= VT.getVectorNumElements(); 9016 } 9017 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 9018 9019 EVT ScalarVT = VT.getVectorElementType(); 9020 9021 if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger()) 9022 ScalarVT = MVT::i32; 9023 9024 return DAG.getNode( 9025 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 9026 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 9027 DstLaneV); 9028 } 9029 9030 // If the shuffle is not directly supported and it has 4 elements, use 9031 // the PerfectShuffle-generated table to synthesize it from other shuffles. 9032 unsigned NumElts = VT.getVectorNumElements(); 9033 if (NumElts == 4) { 9034 unsigned PFIndexes[4]; 9035 for (unsigned i = 0; i != 4; ++i) { 9036 if (ShuffleMask[i] < 0) 9037 PFIndexes[i] = 8; 9038 else 9039 PFIndexes[i] = ShuffleMask[i]; 9040 } 9041 9042 // Compute the index in the perfect shuffle table. 9043 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 9044 PFIndexes[2] * 9 + PFIndexes[3]; 9045 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9046 unsigned Cost = (PFEntry >> 30); 9047 9048 if (Cost <= 4) 9049 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9050 } 9051 9052 return GenerateTBL(Op, ShuffleMask, DAG); 9053 } 9054 9055 SDValue AArch64TargetLowering::LowerSTEP_VECTOR(SDValue Op, 9056 SelectionDAG &DAG) const { 9057 SDLoc dl(Op); 9058 EVT VT = Op.getValueType(); 9059 assert(VT.isScalableVector() && 9060 "Only expect scalable vectors for STEP_VECTOR"); 9061 assert(VT.getScalarType() != MVT::i1 && 9062 "Vectors of i1 types not supported for STEP_VECTOR"); 9063 9064 SDValue StepVal = Op.getOperand(0); 9065 SDValue Zero = DAG.getConstant(0, dl, StepVal.getValueType()); 9066 return DAG.getNode(AArch64ISD::INDEX_VECTOR, dl, VT, Zero, StepVal); 9067 } 9068 9069 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 9070 SelectionDAG &DAG) const { 9071 SDLoc dl(Op); 9072 EVT VT = Op.getValueType(); 9073 EVT ElemVT = VT.getScalarType(); 9074 SDValue SplatVal = Op.getOperand(0); 9075 9076 if (useSVEForFixedLengthVectorVT(VT)) 9077 return LowerToScalableOp(Op, DAG); 9078 9079 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 9080 // FPRs don't have this restriction. 9081 switch (ElemVT.getSimpleVT().SimpleTy) { 9082 case MVT::i1: { 9083 // The only legal i1 vectors are SVE vectors, so we can use SVE-specific 9084 // lowering code. 9085 if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) { 9086 if (ConstVal->isOne()) 9087 return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all); 9088 // TODO: Add special case for constant false 9089 } 9090 // The general case of i1. There isn't any natural way to do this, 9091 // so we use some trickery with whilelo. 9092 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 9093 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal, 9094 DAG.getValueType(MVT::i1)); 9095 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, 9096 MVT::i64); 9097 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID, 9098 DAG.getConstant(0, dl, MVT::i64), SplatVal); 9099 } 9100 case MVT::i8: 9101 case MVT::i16: 9102 case MVT::i32: 9103 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 9104 break; 9105 case MVT::i64: 9106 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 9107 break; 9108 case MVT::f16: 9109 case MVT::bf16: 9110 case MVT::f32: 9111 case MVT::f64: 9112 // Fine as is 9113 break; 9114 default: 9115 report_fatal_error("Unsupported SPLAT_VECTOR input operand type"); 9116 } 9117 9118 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 9119 } 9120 9121 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op, 9122 SelectionDAG &DAG) const { 9123 SDLoc DL(Op); 9124 9125 EVT VT = Op.getValueType(); 9126 if (!isTypeLegal(VT) || !VT.isScalableVector()) 9127 return SDValue(); 9128 9129 // Current lowering only supports the SVE-ACLE types. 9130 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 9131 return SDValue(); 9132 9133 // The DUPQ operation is indepedent of element type so normalise to i64s. 9134 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1)); 9135 SDValue Idx128 = Op.getOperand(2); 9136 9137 // DUPQ can be used when idx is in range. 9138 auto *CIdx = dyn_cast<ConstantSDNode>(Idx128); 9139 if (CIdx && (CIdx->getZExtValue() <= 3)) { 9140 SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64); 9141 SDNode *DUPQ = 9142 DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI); 9143 return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0)); 9144 } 9145 9146 // The ACLE says this must produce the same result as: 9147 // svtbl(data, svadd_x(svptrue_b64(), 9148 // svand_x(svptrue_b64(), svindex_u64(0, 1), 1), 9149 // index * 2)) 9150 SDValue One = DAG.getConstant(1, DL, MVT::i64); 9151 SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One); 9152 9153 // create the vector 0,1,0,1,... 9154 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 9155 SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR, 9156 DL, MVT::nxv2i64, Zero, One); 9157 SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne); 9158 9159 // create the vector idx64,idx64+1,idx64,idx64+1,... 9160 SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128); 9161 SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64); 9162 SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64); 9163 9164 // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],... 9165 SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask); 9166 return DAG.getNode(ISD::BITCAST, DL, VT, TBL); 9167 } 9168 9169 9170 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 9171 APInt &UndefBits) { 9172 EVT VT = BVN->getValueType(0); 9173 APInt SplatBits, SplatUndef; 9174 unsigned SplatBitSize; 9175 bool HasAnyUndefs; 9176 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9177 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 9178 9179 for (unsigned i = 0; i < NumSplats; ++i) { 9180 CnstBits <<= SplatBitSize; 9181 UndefBits <<= SplatBitSize; 9182 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 9183 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 9184 } 9185 9186 return true; 9187 } 9188 9189 return false; 9190 } 9191 9192 // Try 64-bit splatted SIMD immediate. 9193 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9194 const APInt &Bits) { 9195 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9196 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9197 EVT VT = Op.getValueType(); 9198 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 9199 9200 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 9201 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 9202 9203 SDLoc dl(Op); 9204 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9205 DAG.getConstant(Value, dl, MVT::i32)); 9206 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9207 } 9208 } 9209 9210 return SDValue(); 9211 } 9212 9213 // Try 32-bit splatted SIMD immediate. 9214 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9215 const APInt &Bits, 9216 const SDValue *LHS = nullptr) { 9217 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9218 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9219 EVT VT = Op.getValueType(); 9220 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 9221 bool isAdvSIMDModImm = false; 9222 uint64_t Shift; 9223 9224 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 9225 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 9226 Shift = 0; 9227 } 9228 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 9229 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 9230 Shift = 8; 9231 } 9232 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 9233 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 9234 Shift = 16; 9235 } 9236 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 9237 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 9238 Shift = 24; 9239 } 9240 9241 if (isAdvSIMDModImm) { 9242 SDLoc dl(Op); 9243 SDValue Mov; 9244 9245 if (LHS) 9246 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 9247 DAG.getConstant(Value, dl, MVT::i32), 9248 DAG.getConstant(Shift, dl, MVT::i32)); 9249 else 9250 Mov = DAG.getNode(NewOp, dl, MovTy, 9251 DAG.getConstant(Value, dl, MVT::i32), 9252 DAG.getConstant(Shift, dl, MVT::i32)); 9253 9254 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9255 } 9256 } 9257 9258 return SDValue(); 9259 } 9260 9261 // Try 16-bit splatted SIMD immediate. 9262 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9263 const APInt &Bits, 9264 const SDValue *LHS = nullptr) { 9265 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9266 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9267 EVT VT = Op.getValueType(); 9268 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 9269 bool isAdvSIMDModImm = false; 9270 uint64_t Shift; 9271 9272 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 9273 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 9274 Shift = 0; 9275 } 9276 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 9277 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 9278 Shift = 8; 9279 } 9280 9281 if (isAdvSIMDModImm) { 9282 SDLoc dl(Op); 9283 SDValue Mov; 9284 9285 if (LHS) 9286 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 9287 DAG.getConstant(Value, dl, MVT::i32), 9288 DAG.getConstant(Shift, dl, MVT::i32)); 9289 else 9290 Mov = DAG.getNode(NewOp, dl, MovTy, 9291 DAG.getConstant(Value, dl, MVT::i32), 9292 DAG.getConstant(Shift, dl, MVT::i32)); 9293 9294 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9295 } 9296 } 9297 9298 return SDValue(); 9299 } 9300 9301 // Try 32-bit splatted SIMD immediate with shifted ones. 9302 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 9303 SelectionDAG &DAG, const APInt &Bits) { 9304 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9305 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9306 EVT VT = Op.getValueType(); 9307 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 9308 bool isAdvSIMDModImm = false; 9309 uint64_t Shift; 9310 9311 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 9312 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 9313 Shift = 264; 9314 } 9315 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 9316 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 9317 Shift = 272; 9318 } 9319 9320 if (isAdvSIMDModImm) { 9321 SDLoc dl(Op); 9322 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9323 DAG.getConstant(Value, dl, MVT::i32), 9324 DAG.getConstant(Shift, dl, MVT::i32)); 9325 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9326 } 9327 } 9328 9329 return SDValue(); 9330 } 9331 9332 // Try 8-bit splatted SIMD immediate. 9333 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9334 const APInt &Bits) { 9335 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9336 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9337 EVT VT = Op.getValueType(); 9338 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 9339 9340 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 9341 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 9342 9343 SDLoc dl(Op); 9344 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9345 DAG.getConstant(Value, dl, MVT::i32)); 9346 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9347 } 9348 } 9349 9350 return SDValue(); 9351 } 9352 9353 // Try FP splatted SIMD immediate. 9354 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 9355 const APInt &Bits) { 9356 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 9357 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 9358 EVT VT = Op.getValueType(); 9359 bool isWide = (VT.getSizeInBits() == 128); 9360 MVT MovTy; 9361 bool isAdvSIMDModImm = false; 9362 9363 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 9364 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 9365 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 9366 } 9367 else if (isWide && 9368 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 9369 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 9370 MovTy = MVT::v2f64; 9371 } 9372 9373 if (isAdvSIMDModImm) { 9374 SDLoc dl(Op); 9375 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 9376 DAG.getConstant(Value, dl, MVT::i32)); 9377 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 9378 } 9379 } 9380 9381 return SDValue(); 9382 } 9383 9384 // Specialized code to quickly find if PotentialBVec is a BuildVector that 9385 // consists of only the same constant int value, returned in reference arg 9386 // ConstVal 9387 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 9388 uint64_t &ConstVal) { 9389 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 9390 if (!Bvec) 9391 return false; 9392 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 9393 if (!FirstElt) 9394 return false; 9395 EVT VT = Bvec->getValueType(0); 9396 unsigned NumElts = VT.getVectorNumElements(); 9397 for (unsigned i = 1; i < NumElts; ++i) 9398 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 9399 return false; 9400 ConstVal = FirstElt->getZExtValue(); 9401 return true; 9402 } 9403 9404 static unsigned getIntrinsicID(const SDNode *N) { 9405 unsigned Opcode = N->getOpcode(); 9406 switch (Opcode) { 9407 default: 9408 return Intrinsic::not_intrinsic; 9409 case ISD::INTRINSIC_WO_CHAIN: { 9410 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 9411 if (IID < Intrinsic::num_intrinsics) 9412 return IID; 9413 return Intrinsic::not_intrinsic; 9414 } 9415 } 9416 } 9417 9418 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 9419 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 9420 // BUILD_VECTORs with constant element C1, C2 is a constant, and: 9421 // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2) 9422 // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2) 9423 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled. 9424 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 9425 EVT VT = N->getValueType(0); 9426 9427 if (!VT.isVector()) 9428 return SDValue(); 9429 9430 SDLoc DL(N); 9431 9432 SDValue And; 9433 SDValue Shift; 9434 9435 SDValue FirstOp = N->getOperand(0); 9436 unsigned FirstOpc = FirstOp.getOpcode(); 9437 SDValue SecondOp = N->getOperand(1); 9438 unsigned SecondOpc = SecondOp.getOpcode(); 9439 9440 // Is one of the operands an AND or a BICi? The AND may have been optimised to 9441 // a BICi in order to use an immediate instead of a register. 9442 // Is the other operand an shl or lshr? This will have been turned into: 9443 // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift. 9444 if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) && 9445 (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) { 9446 And = FirstOp; 9447 Shift = SecondOp; 9448 9449 } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) && 9450 (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) { 9451 And = SecondOp; 9452 Shift = FirstOp; 9453 } else 9454 return SDValue(); 9455 9456 bool IsAnd = And.getOpcode() == ISD::AND; 9457 bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR; 9458 9459 // Is the shift amount constant? 9460 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 9461 if (!C2node) 9462 return SDValue(); 9463 9464 uint64_t C1; 9465 if (IsAnd) { 9466 // Is the and mask vector all constant? 9467 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 9468 return SDValue(); 9469 } else { 9470 // Reconstruct the corresponding AND immediate from the two BICi immediates. 9471 ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1)); 9472 ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2)); 9473 assert(C1nodeImm && C1nodeShift); 9474 C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue()); 9475 } 9476 9477 // Is C1 == ~(Ones(ElemSizeInBits) << C2) or 9478 // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account 9479 // how much one can shift elements of a particular size? 9480 uint64_t C2 = C2node->getZExtValue(); 9481 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 9482 if (C2 > ElemSizeInBits) 9483 return SDValue(); 9484 9485 APInt C1AsAPInt(ElemSizeInBits, C1); 9486 APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2) 9487 : APInt::getLowBitsSet(ElemSizeInBits, C2); 9488 if (C1AsAPInt != RequiredC1) 9489 return SDValue(); 9490 9491 SDValue X = And.getOperand(0); 9492 SDValue Y = Shift.getOperand(0); 9493 9494 unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI; 9495 SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1)); 9496 9497 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 9498 LLVM_DEBUG(N->dump(&DAG)); 9499 LLVM_DEBUG(dbgs() << "into: \n"); 9500 LLVM_DEBUG(ResultSLI->dump(&DAG)); 9501 9502 ++NumShiftInserts; 9503 return ResultSLI; 9504 } 9505 9506 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 9507 SelectionDAG &DAG) const { 9508 if (useSVEForFixedLengthVectorVT(Op.getValueType())) 9509 return LowerToScalableOp(Op, DAG); 9510 9511 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 9512 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 9513 return Res; 9514 9515 EVT VT = Op.getValueType(); 9516 9517 SDValue LHS = Op.getOperand(0); 9518 BuildVectorSDNode *BVN = 9519 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 9520 if (!BVN) { 9521 // OR commutes, so try swapping the operands. 9522 LHS = Op.getOperand(1); 9523 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 9524 } 9525 if (!BVN) 9526 return Op; 9527 9528 APInt DefBits(VT.getSizeInBits(), 0); 9529 APInt UndefBits(VT.getSizeInBits(), 0); 9530 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9531 SDValue NewOp; 9532 9533 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 9534 DefBits, &LHS)) || 9535 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 9536 DefBits, &LHS))) 9537 return NewOp; 9538 9539 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 9540 UndefBits, &LHS)) || 9541 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 9542 UndefBits, &LHS))) 9543 return NewOp; 9544 } 9545 9546 // We can always fall back to a non-immediate OR. 9547 return Op; 9548 } 9549 9550 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 9551 // be truncated to fit element width. 9552 static SDValue NormalizeBuildVector(SDValue Op, 9553 SelectionDAG &DAG) { 9554 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 9555 SDLoc dl(Op); 9556 EVT VT = Op.getValueType(); 9557 EVT EltTy= VT.getVectorElementType(); 9558 9559 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 9560 return Op; 9561 9562 SmallVector<SDValue, 16> Ops; 9563 for (SDValue Lane : Op->ops()) { 9564 // For integer vectors, type legalization would have promoted the 9565 // operands already. Otherwise, if Op is a floating-point splat 9566 // (with operands cast to integers), then the only possibilities 9567 // are constants and UNDEFs. 9568 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 9569 APInt LowBits(EltTy.getSizeInBits(), 9570 CstLane->getZExtValue()); 9571 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 9572 } else if (Lane.getNode()->isUndef()) { 9573 Lane = DAG.getUNDEF(MVT::i32); 9574 } else { 9575 assert(Lane.getValueType() == MVT::i32 && 9576 "Unexpected BUILD_VECTOR operand type"); 9577 } 9578 Ops.push_back(Lane); 9579 } 9580 return DAG.getBuildVector(VT, dl, Ops); 9581 } 9582 9583 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 9584 EVT VT = Op.getValueType(); 9585 9586 APInt DefBits(VT.getSizeInBits(), 0); 9587 APInt UndefBits(VT.getSizeInBits(), 0); 9588 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 9589 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9590 SDValue NewOp; 9591 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 9592 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9593 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 9594 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9595 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 9596 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 9597 return NewOp; 9598 9599 DefBits = ~DefBits; 9600 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 9601 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 9602 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 9603 return NewOp; 9604 9605 DefBits = UndefBits; 9606 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 9607 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9608 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 9609 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 9610 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 9611 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 9612 return NewOp; 9613 9614 DefBits = ~UndefBits; 9615 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 9616 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 9617 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 9618 return NewOp; 9619 } 9620 9621 return SDValue(); 9622 } 9623 9624 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 9625 SelectionDAG &DAG) const { 9626 EVT VT = Op.getValueType(); 9627 9628 // Try to build a simple constant vector. 9629 Op = NormalizeBuildVector(Op, DAG); 9630 if (VT.isInteger()) { 9631 // Certain vector constants, used to express things like logical NOT and 9632 // arithmetic NEG, are passed through unmodified. This allows special 9633 // patterns for these operations to match, which will lower these constants 9634 // to whatever is proven necessary. 9635 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 9636 if (BVN->isConstant()) 9637 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 9638 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 9639 APInt Val(BitSize, 9640 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 9641 if (Val.isNullValue() || Val.isAllOnesValue()) 9642 return Op; 9643 } 9644 } 9645 9646 if (SDValue V = ConstantBuildVector(Op, DAG)) 9647 return V; 9648 9649 // Scan through the operands to find some interesting properties we can 9650 // exploit: 9651 // 1) If only one value is used, we can use a DUP, or 9652 // 2) if only the low element is not undef, we can just insert that, or 9653 // 3) if only one constant value is used (w/ some non-constant lanes), 9654 // we can splat the constant value into the whole vector then fill 9655 // in the non-constant lanes. 9656 // 4) FIXME: If different constant values are used, but we can intelligently 9657 // select the values we'll be overwriting for the non-constant 9658 // lanes such that we can directly materialize the vector 9659 // some other way (MOVI, e.g.), we can be sneaky. 9660 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 9661 SDLoc dl(Op); 9662 unsigned NumElts = VT.getVectorNumElements(); 9663 bool isOnlyLowElement = true; 9664 bool usesOnlyOneValue = true; 9665 bool usesOnlyOneConstantValue = true; 9666 bool isConstant = true; 9667 bool AllLanesExtractElt = true; 9668 unsigned NumConstantLanes = 0; 9669 unsigned NumDifferentLanes = 0; 9670 unsigned NumUndefLanes = 0; 9671 SDValue Value; 9672 SDValue ConstantValue; 9673 for (unsigned i = 0; i < NumElts; ++i) { 9674 SDValue V = Op.getOperand(i); 9675 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9676 AllLanesExtractElt = false; 9677 if (V.isUndef()) { 9678 ++NumUndefLanes; 9679 continue; 9680 } 9681 if (i > 0) 9682 isOnlyLowElement = false; 9683 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 9684 isConstant = false; 9685 9686 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 9687 ++NumConstantLanes; 9688 if (!ConstantValue.getNode()) 9689 ConstantValue = V; 9690 else if (ConstantValue != V) 9691 usesOnlyOneConstantValue = false; 9692 } 9693 9694 if (!Value.getNode()) 9695 Value = V; 9696 else if (V != Value) { 9697 usesOnlyOneValue = false; 9698 ++NumDifferentLanes; 9699 } 9700 } 9701 9702 if (!Value.getNode()) { 9703 LLVM_DEBUG( 9704 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 9705 return DAG.getUNDEF(VT); 9706 } 9707 9708 // Convert BUILD_VECTOR where all elements but the lowest are undef into 9709 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 9710 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 9711 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 9712 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 9713 "SCALAR_TO_VECTOR node\n"); 9714 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 9715 } 9716 9717 if (AllLanesExtractElt) { 9718 SDNode *Vector = nullptr; 9719 bool Even = false; 9720 bool Odd = false; 9721 // Check whether the extract elements match the Even pattern <0,2,4,...> or 9722 // the Odd pattern <1,3,5,...>. 9723 for (unsigned i = 0; i < NumElts; ++i) { 9724 SDValue V = Op.getOperand(i); 9725 const SDNode *N = V.getNode(); 9726 if (!isa<ConstantSDNode>(N->getOperand(1))) 9727 break; 9728 SDValue N0 = N->getOperand(0); 9729 9730 // All elements are extracted from the same vector. 9731 if (!Vector) { 9732 Vector = N0.getNode(); 9733 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 9734 // BUILD_VECTOR. 9735 if (VT.getVectorElementType() != 9736 N0.getValueType().getVectorElementType()) 9737 break; 9738 } else if (Vector != N0.getNode()) { 9739 Odd = false; 9740 Even = false; 9741 break; 9742 } 9743 9744 // Extracted values are either at Even indices <0,2,4,...> or at Odd 9745 // indices <1,3,5,...>. 9746 uint64_t Val = N->getConstantOperandVal(1); 9747 if (Val == 2 * i) { 9748 Even = true; 9749 continue; 9750 } 9751 if (Val - 1 == 2 * i) { 9752 Odd = true; 9753 continue; 9754 } 9755 9756 // Something does not match: abort. 9757 Odd = false; 9758 Even = false; 9759 break; 9760 } 9761 if (Even || Odd) { 9762 SDValue LHS = 9763 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 9764 DAG.getConstant(0, dl, MVT::i64)); 9765 SDValue RHS = 9766 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 9767 DAG.getConstant(NumElts, dl, MVT::i64)); 9768 9769 if (Even && !Odd) 9770 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 9771 RHS); 9772 if (Odd && !Even) 9773 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 9774 RHS); 9775 } 9776 } 9777 9778 // Use DUP for non-constant splats. For f32 constant splats, reduce to 9779 // i32 and try again. 9780 if (usesOnlyOneValue) { 9781 if (!isConstant) { 9782 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9783 Value.getValueType() != VT) { 9784 LLVM_DEBUG( 9785 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 9786 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 9787 } 9788 9789 // This is actually a DUPLANExx operation, which keeps everything vectory. 9790 9791 SDValue Lane = Value.getOperand(1); 9792 Value = Value.getOperand(0); 9793 if (Value.getValueSizeInBits() == 64) { 9794 LLVM_DEBUG( 9795 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 9796 "widening it\n"); 9797 Value = WidenVector(Value, DAG); 9798 } 9799 9800 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 9801 return DAG.getNode(Opcode, dl, VT, Value, Lane); 9802 } 9803 9804 if (VT.getVectorElementType().isFloatingPoint()) { 9805 SmallVector<SDValue, 8> Ops; 9806 EVT EltTy = VT.getVectorElementType(); 9807 assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 || 9808 EltTy == MVT::f64) && "Unsupported floating-point vector type"); 9809 LLVM_DEBUG( 9810 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 9811 "BITCASTS, and try again\n"); 9812 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 9813 for (unsigned i = 0; i < NumElts; ++i) 9814 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 9815 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 9816 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 9817 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 9818 Val.dump();); 9819 Val = LowerBUILD_VECTOR(Val, DAG); 9820 if (Val.getNode()) 9821 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 9822 } 9823 } 9824 9825 // If we need to insert a small number of different non-constant elements and 9826 // the vector width is sufficiently large, prefer using DUP with the common 9827 // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred, 9828 // skip the constant lane handling below. 9829 bool PreferDUPAndInsert = 9830 !isConstant && NumDifferentLanes >= 1 && 9831 NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) && 9832 NumDifferentLanes >= NumConstantLanes; 9833 9834 // If there was only one constant value used and for more than one lane, 9835 // start by splatting that value, then replace the non-constant lanes. This 9836 // is better than the default, which will perform a separate initialization 9837 // for each lane. 9838 if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) { 9839 // Firstly, try to materialize the splat constant. 9840 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 9841 Val = ConstantBuildVector(Vec, DAG); 9842 if (!Val) { 9843 // Otherwise, materialize the constant and splat it. 9844 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 9845 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 9846 } 9847 9848 // Now insert the non-constant lanes. 9849 for (unsigned i = 0; i < NumElts; ++i) { 9850 SDValue V = Op.getOperand(i); 9851 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 9852 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 9853 // Note that type legalization likely mucked about with the VT of the 9854 // source operand, so we may have to convert it here before inserting. 9855 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 9856 } 9857 return Val; 9858 } 9859 9860 // This will generate a load from the constant pool. 9861 if (isConstant) { 9862 LLVM_DEBUG( 9863 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 9864 "expansion\n"); 9865 return SDValue(); 9866 } 9867 9868 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 9869 if (NumElts >= 4) { 9870 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 9871 return shuffle; 9872 } 9873 9874 if (PreferDUPAndInsert) { 9875 // First, build a constant vector with the common element. 9876 SmallVector<SDValue, 8> Ops(NumElts, Value); 9877 SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG); 9878 // Next, insert the elements that do not match the common value. 9879 for (unsigned I = 0; I < NumElts; ++I) 9880 if (Op.getOperand(I) != Value) 9881 NewVector = 9882 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector, 9883 Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64)); 9884 9885 return NewVector; 9886 } 9887 9888 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 9889 // know the default expansion would otherwise fall back on something even 9890 // worse. For a vector with one or two non-undef values, that's 9891 // scalar_to_vector for the elements followed by a shuffle (provided the 9892 // shuffle is valid for the target) and materialization element by element 9893 // on the stack followed by a load for everything else. 9894 if (!isConstant && !usesOnlyOneValue) { 9895 LLVM_DEBUG( 9896 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 9897 "of INSERT_VECTOR_ELT\n"); 9898 9899 SDValue Vec = DAG.getUNDEF(VT); 9900 SDValue Op0 = Op.getOperand(0); 9901 unsigned i = 0; 9902 9903 // Use SCALAR_TO_VECTOR for lane zero to 9904 // a) Avoid a RMW dependency on the full vector register, and 9905 // b) Allow the register coalescer to fold away the copy if the 9906 // value is already in an S or D register, and we're forced to emit an 9907 // INSERT_SUBREG that we can't fold anywhere. 9908 // 9909 // We also allow types like i8 and i16 which are illegal scalar but legal 9910 // vector element types. After type-legalization the inserted value is 9911 // extended (i32) and it is safe to cast them to the vector type by ignoring 9912 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 9913 if (!Op0.isUndef()) { 9914 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 9915 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 9916 ++i; 9917 } 9918 LLVM_DEBUG(if (i < NumElts) dbgs() 9919 << "Creating nodes for the other vector elements:\n";); 9920 for (; i < NumElts; ++i) { 9921 SDValue V = Op.getOperand(i); 9922 if (V.isUndef()) 9923 continue; 9924 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 9925 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 9926 } 9927 return Vec; 9928 } 9929 9930 LLVM_DEBUG( 9931 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 9932 "better alternative\n"); 9933 return SDValue(); 9934 } 9935 9936 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op, 9937 SelectionDAG &DAG) const { 9938 assert(Op.getValueType().isScalableVector() && 9939 isTypeLegal(Op.getValueType()) && 9940 "Expected legal scalable vector type!"); 9941 9942 if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2) 9943 return Op; 9944 9945 return SDValue(); 9946 } 9947 9948 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9949 SelectionDAG &DAG) const { 9950 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 9951 9952 // Check for non-constant or out of range lane. 9953 EVT VT = Op.getOperand(0).getValueType(); 9954 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9955 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 9956 return SDValue(); 9957 9958 9959 // Insertion/extraction are legal for V128 types. 9960 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 9961 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 9962 VT == MVT::v8f16 || VT == MVT::v8bf16) 9963 return Op; 9964 9965 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 9966 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 9967 VT != MVT::v4bf16) 9968 return SDValue(); 9969 9970 // For V64 types, we perform insertion by expanding the value 9971 // to a V128 type and perform the insertion on that. 9972 SDLoc DL(Op); 9973 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 9974 EVT WideTy = WideVec.getValueType(); 9975 9976 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 9977 Op.getOperand(1), Op.getOperand(2)); 9978 // Re-narrow the resultant vector. 9979 return NarrowVector(Node, DAG); 9980 } 9981 9982 SDValue 9983 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9984 SelectionDAG &DAG) const { 9985 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 9986 9987 // Check for non-constant or out of range lane. 9988 EVT VT = Op.getOperand(0).getValueType(); 9989 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9990 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 9991 return SDValue(); 9992 9993 9994 // Insertion/extraction are legal for V128 types. 9995 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 9996 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 9997 VT == MVT::v8f16 || VT == MVT::v8bf16) 9998 return Op; 9999 10000 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 10001 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 && 10002 VT != MVT::v4bf16) 10003 return SDValue(); 10004 10005 // For V64 types, we perform extraction by expanding the value 10006 // to a V128 type and perform the extraction on that. 10007 SDLoc DL(Op); 10008 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 10009 EVT WideTy = WideVec.getValueType(); 10010 10011 EVT ExtrTy = WideTy.getVectorElementType(); 10012 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 10013 ExtrTy = MVT::i32; 10014 10015 // For extractions, we just return the result directly. 10016 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 10017 Op.getOperand(1)); 10018 } 10019 10020 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 10021 SelectionDAG &DAG) const { 10022 assert(Op.getValueType().isFixedLengthVector() && 10023 "Only cases that extract a fixed length vector are supported!"); 10024 10025 EVT InVT = Op.getOperand(0).getValueType(); 10026 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10027 unsigned Size = Op.getValueSizeInBits(); 10028 10029 if (InVT.isScalableVector()) { 10030 // This will be matched by custom code during ISelDAGToDAG. 10031 if (Idx == 0 && isPackedVectorType(InVT, DAG)) 10032 return Op; 10033 10034 return SDValue(); 10035 } 10036 10037 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 10038 if (Idx == 0 && InVT.getSizeInBits() <= 128) 10039 return Op; 10040 10041 // If this is extracting the upper 64-bits of a 128-bit vector, we match 10042 // that directly. 10043 if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 && 10044 InVT.getSizeInBits() == 128) 10045 return Op; 10046 10047 return SDValue(); 10048 } 10049 10050 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, 10051 SelectionDAG &DAG) const { 10052 assert(Op.getValueType().isScalableVector() && 10053 "Only expect to lower inserts into scalable vectors!"); 10054 10055 EVT InVT = Op.getOperand(1).getValueType(); 10056 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 10057 10058 if (InVT.isScalableVector()) { 10059 SDLoc DL(Op); 10060 EVT VT = Op.getValueType(); 10061 10062 if (!isTypeLegal(VT) || !VT.isInteger()) 10063 return SDValue(); 10064 10065 SDValue Vec0 = Op.getOperand(0); 10066 SDValue Vec1 = Op.getOperand(1); 10067 10068 // Ensure the subvector is half the size of the main vector. 10069 if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2)) 10070 return SDValue(); 10071 10072 // Extend elements of smaller vector... 10073 EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext())); 10074 SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1); 10075 10076 if (Idx == 0) { 10077 SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0); 10078 return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0); 10079 } else if (Idx == InVT.getVectorMinNumElements()) { 10080 SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0); 10081 return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec); 10082 } 10083 10084 return SDValue(); 10085 } 10086 10087 // This will be matched by custom code during ISelDAGToDAG. 10088 if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef()) 10089 return Op; 10090 10091 return SDValue(); 10092 } 10093 10094 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const { 10095 EVT VT = Op.getValueType(); 10096 10097 if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) 10098 return LowerFixedLengthVectorIntDivideToSVE(Op, DAG); 10099 10100 assert(VT.isScalableVector() && "Expected a scalable vector."); 10101 10102 bool Signed = Op.getOpcode() == ISD::SDIV; 10103 unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED; 10104 10105 if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64) 10106 return LowerToPredicatedOp(Op, DAG, PredOpcode); 10107 10108 // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit 10109 // operations, and truncate the result. 10110 EVT WidenedVT; 10111 if (VT == MVT::nxv16i8) 10112 WidenedVT = MVT::nxv8i16; 10113 else if (VT == MVT::nxv8i16) 10114 WidenedVT = MVT::nxv4i32; 10115 else 10116 llvm_unreachable("Unexpected Custom DIV operation"); 10117 10118 SDLoc dl(Op); 10119 unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 10120 unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI; 10121 SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0)); 10122 SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1)); 10123 SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0)); 10124 SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1)); 10125 SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo); 10126 SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi); 10127 return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi); 10128 } 10129 10130 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 10131 // Currently no fixed length shuffles that require SVE are legal. 10132 if (useSVEForFixedLengthVectorVT(VT)) 10133 return false; 10134 10135 if (VT.getVectorNumElements() == 4 && 10136 (VT.is128BitVector() || VT.is64BitVector())) { 10137 unsigned PFIndexes[4]; 10138 for (unsigned i = 0; i != 4; ++i) { 10139 if (M[i] < 0) 10140 PFIndexes[i] = 8; 10141 else 10142 PFIndexes[i] = M[i]; 10143 } 10144 10145 // Compute the index in the perfect shuffle table. 10146 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 10147 PFIndexes[2] * 9 + PFIndexes[3]; 10148 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10149 unsigned Cost = (PFEntry >> 30); 10150 10151 if (Cost <= 4) 10152 return true; 10153 } 10154 10155 bool DummyBool; 10156 int DummyInt; 10157 unsigned DummyUnsigned; 10158 10159 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 10160 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 10161 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 10162 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 10163 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 10164 isZIPMask(M, VT, DummyUnsigned) || 10165 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 10166 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 10167 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 10168 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 10169 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 10170 } 10171 10172 /// getVShiftImm - Check if this is a valid build_vector for the immediate 10173 /// operand of a vector shift operation, where all the elements of the 10174 /// build_vector must have the same constant integer value. 10175 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 10176 // Ignore bit_converts. 10177 while (Op.getOpcode() == ISD::BITCAST) 10178 Op = Op.getOperand(0); 10179 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 10180 APInt SplatBits, SplatUndef; 10181 unsigned SplatBitSize; 10182 bool HasAnyUndefs; 10183 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 10184 HasAnyUndefs, ElementBits) || 10185 SplatBitSize > ElementBits) 10186 return false; 10187 Cnt = SplatBits.getSExtValue(); 10188 return true; 10189 } 10190 10191 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 10192 /// operand of a vector shift left operation. That value must be in the range: 10193 /// 0 <= Value < ElementBits for a left shift; or 10194 /// 0 <= Value <= ElementBits for a long left shift. 10195 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 10196 assert(VT.isVector() && "vector shift count is not a vector type"); 10197 int64_t ElementBits = VT.getScalarSizeInBits(); 10198 if (!getVShiftImm(Op, ElementBits, Cnt)) 10199 return false; 10200 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 10201 } 10202 10203 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 10204 /// operand of a vector shift right operation. The value must be in the range: 10205 /// 1 <= Value <= ElementBits for a right shift; or 10206 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 10207 assert(VT.isVector() && "vector shift count is not a vector type"); 10208 int64_t ElementBits = VT.getScalarSizeInBits(); 10209 if (!getVShiftImm(Op, ElementBits, Cnt)) 10210 return false; 10211 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 10212 } 10213 10214 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op, 10215 SelectionDAG &DAG) const { 10216 EVT VT = Op.getValueType(); 10217 10218 if (VT.getScalarType() == MVT::i1) { 10219 // Lower i1 truncate to `(x & 1) != 0`. 10220 SDLoc dl(Op); 10221 EVT OpVT = Op.getOperand(0).getValueType(); 10222 SDValue Zero = DAG.getConstant(0, dl, OpVT); 10223 SDValue One = DAG.getConstant(1, dl, OpVT); 10224 SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One); 10225 return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE); 10226 } 10227 10228 if (!VT.isVector() || VT.isScalableVector()) 10229 return SDValue(); 10230 10231 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType())) 10232 return LowerFixedLengthVectorTruncateToSVE(Op, DAG); 10233 10234 return SDValue(); 10235 } 10236 10237 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 10238 SelectionDAG &DAG) const { 10239 EVT VT = Op.getValueType(); 10240 SDLoc DL(Op); 10241 int64_t Cnt; 10242 10243 if (!Op.getOperand(1).getValueType().isVector()) 10244 return Op; 10245 unsigned EltSize = VT.getScalarSizeInBits(); 10246 10247 switch (Op.getOpcode()) { 10248 default: 10249 llvm_unreachable("unexpected shift opcode"); 10250 10251 case ISD::SHL: 10252 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) 10253 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED); 10254 10255 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 10256 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 10257 DAG.getConstant(Cnt, DL, MVT::i32)); 10258 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 10259 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 10260 MVT::i32), 10261 Op.getOperand(0), Op.getOperand(1)); 10262 case ISD::SRA: 10263 case ISD::SRL: 10264 if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) { 10265 unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED 10266 : AArch64ISD::SRL_PRED; 10267 return LowerToPredicatedOp(Op, DAG, Opc); 10268 } 10269 10270 // Right shift immediate 10271 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 10272 unsigned Opc = 10273 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 10274 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 10275 DAG.getConstant(Cnt, DL, MVT::i32)); 10276 } 10277 10278 // Right shift register. Note, there is not a shift right register 10279 // instruction, but the shift left register instruction takes a signed 10280 // value, where negative numbers specify a right shift. 10281 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 10282 : Intrinsic::aarch64_neon_ushl; 10283 // negate the shift amount 10284 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 10285 SDValue NegShiftLeft = 10286 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 10287 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 10288 NegShift); 10289 return NegShiftLeft; 10290 } 10291 10292 return SDValue(); 10293 } 10294 10295 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 10296 AArch64CC::CondCode CC, bool NoNans, EVT VT, 10297 const SDLoc &dl, SelectionDAG &DAG) { 10298 EVT SrcVT = LHS.getValueType(); 10299 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 10300 "function only supposed to emit natural comparisons"); 10301 10302 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 10303 APInt CnstBits(VT.getSizeInBits(), 0); 10304 APInt UndefBits(VT.getSizeInBits(), 0); 10305 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 10306 bool IsZero = IsCnst && (CnstBits == 0); 10307 10308 if (SrcVT.getVectorElementType().isFloatingPoint()) { 10309 switch (CC) { 10310 default: 10311 return SDValue(); 10312 case AArch64CC::NE: { 10313 SDValue Fcmeq; 10314 if (IsZero) 10315 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 10316 else 10317 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 10318 return DAG.getNOT(dl, Fcmeq, VT); 10319 } 10320 case AArch64CC::EQ: 10321 if (IsZero) 10322 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 10323 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 10324 case AArch64CC::GE: 10325 if (IsZero) 10326 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 10327 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 10328 case AArch64CC::GT: 10329 if (IsZero) 10330 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 10331 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 10332 case AArch64CC::LS: 10333 if (IsZero) 10334 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 10335 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 10336 case AArch64CC::LT: 10337 if (!NoNans) 10338 return SDValue(); 10339 // If we ignore NaNs then we can use to the MI implementation. 10340 LLVM_FALLTHROUGH; 10341 case AArch64CC::MI: 10342 if (IsZero) 10343 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 10344 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 10345 } 10346 } 10347 10348 switch (CC) { 10349 default: 10350 return SDValue(); 10351 case AArch64CC::NE: { 10352 SDValue Cmeq; 10353 if (IsZero) 10354 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 10355 else 10356 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 10357 return DAG.getNOT(dl, Cmeq, VT); 10358 } 10359 case AArch64CC::EQ: 10360 if (IsZero) 10361 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 10362 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 10363 case AArch64CC::GE: 10364 if (IsZero) 10365 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 10366 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 10367 case AArch64CC::GT: 10368 if (IsZero) 10369 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 10370 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 10371 case AArch64CC::LE: 10372 if (IsZero) 10373 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 10374 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 10375 case AArch64CC::LS: 10376 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 10377 case AArch64CC::LO: 10378 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 10379 case AArch64CC::LT: 10380 if (IsZero) 10381 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 10382 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 10383 case AArch64CC::HI: 10384 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 10385 case AArch64CC::HS: 10386 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 10387 } 10388 } 10389 10390 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 10391 SelectionDAG &DAG) const { 10392 if (Op.getValueType().isScalableVector()) { 10393 if (Op.getOperand(0).getValueType().isFloatingPoint()) 10394 return Op; 10395 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO); 10396 } 10397 10398 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType())) 10399 return LowerFixedLengthVectorSetccToSVE(Op, DAG); 10400 10401 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10402 SDValue LHS = Op.getOperand(0); 10403 SDValue RHS = Op.getOperand(1); 10404 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 10405 SDLoc dl(Op); 10406 10407 if (LHS.getValueType().getVectorElementType().isInteger()) { 10408 assert(LHS.getValueType() == RHS.getValueType()); 10409 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 10410 SDValue Cmp = 10411 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 10412 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 10413 } 10414 10415 const bool FullFP16 = 10416 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 10417 10418 // Make v4f16 (only) fcmp operations utilise vector instructions 10419 // v8f16 support will be a litle more complicated 10420 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 10421 if (LHS.getValueType().getVectorNumElements() == 4) { 10422 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 10423 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 10424 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 10425 DAG.ReplaceAllUsesWith(Op, NewSetcc); 10426 CmpVT = MVT::v4i32; 10427 } else 10428 return SDValue(); 10429 } 10430 10431 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 10432 LHS.getValueType().getVectorElementType() != MVT::f128); 10433 10434 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 10435 // clean. Some of them require two branches to implement. 10436 AArch64CC::CondCode CC1, CC2; 10437 bool ShouldInvert; 10438 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 10439 10440 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 10441 SDValue Cmp = 10442 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 10443 if (!Cmp.getNode()) 10444 return SDValue(); 10445 10446 if (CC2 != AArch64CC::AL) { 10447 SDValue Cmp2 = 10448 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 10449 if (!Cmp2.getNode()) 10450 return SDValue(); 10451 10452 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 10453 } 10454 10455 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 10456 10457 if (ShouldInvert) 10458 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 10459 10460 return Cmp; 10461 } 10462 10463 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 10464 SelectionDAG &DAG) { 10465 SDValue VecOp = ScalarOp.getOperand(0); 10466 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 10467 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 10468 DAG.getConstant(0, DL, MVT::i64)); 10469 } 10470 10471 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 10472 SelectionDAG &DAG) const { 10473 SDValue Src = Op.getOperand(0); 10474 10475 // Try to lower fixed length reductions to SVE. 10476 EVT SrcVT = Src.getValueType(); 10477 bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND || 10478 Op.getOpcode() == ISD::VECREDUCE_OR || 10479 Op.getOpcode() == ISD::VECREDUCE_XOR || 10480 Op.getOpcode() == ISD::VECREDUCE_FADD || 10481 (Op.getOpcode() != ISD::VECREDUCE_ADD && 10482 SrcVT.getVectorElementType() == MVT::i64); 10483 if (SrcVT.isScalableVector() || 10484 useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) { 10485 10486 if (SrcVT.getVectorElementType() == MVT::i1) 10487 return LowerPredReductionToSVE(Op, DAG); 10488 10489 switch (Op.getOpcode()) { 10490 case ISD::VECREDUCE_ADD: 10491 return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG); 10492 case ISD::VECREDUCE_AND: 10493 return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG); 10494 case ISD::VECREDUCE_OR: 10495 return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG); 10496 case ISD::VECREDUCE_SMAX: 10497 return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG); 10498 case ISD::VECREDUCE_SMIN: 10499 return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG); 10500 case ISD::VECREDUCE_UMAX: 10501 return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG); 10502 case ISD::VECREDUCE_UMIN: 10503 return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG); 10504 case ISD::VECREDUCE_XOR: 10505 return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG); 10506 case ISD::VECREDUCE_FADD: 10507 return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG); 10508 case ISD::VECREDUCE_FMAX: 10509 return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG); 10510 case ISD::VECREDUCE_FMIN: 10511 return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG); 10512 default: 10513 llvm_unreachable("Unhandled fixed length reduction"); 10514 } 10515 } 10516 10517 // Lower NEON reductions. 10518 SDLoc dl(Op); 10519 switch (Op.getOpcode()) { 10520 case ISD::VECREDUCE_ADD: 10521 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 10522 case ISD::VECREDUCE_SMAX: 10523 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 10524 case ISD::VECREDUCE_SMIN: 10525 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 10526 case ISD::VECREDUCE_UMAX: 10527 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 10528 case ISD::VECREDUCE_UMIN: 10529 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 10530 case ISD::VECREDUCE_FMAX: { 10531 return DAG.getNode( 10532 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 10533 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 10534 Src); 10535 } 10536 case ISD::VECREDUCE_FMIN: { 10537 return DAG.getNode( 10538 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 10539 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 10540 Src); 10541 } 10542 default: 10543 llvm_unreachable("Unhandled reduction"); 10544 } 10545 } 10546 10547 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 10548 SelectionDAG &DAG) const { 10549 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 10550 if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics()) 10551 return SDValue(); 10552 10553 // LSE has an atomic load-add instruction, but not a load-sub. 10554 SDLoc dl(Op); 10555 MVT VT = Op.getSimpleValueType(); 10556 SDValue RHS = Op.getOperand(2); 10557 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 10558 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 10559 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 10560 Op.getOperand(0), Op.getOperand(1), RHS, 10561 AN->getMemOperand()); 10562 } 10563 10564 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 10565 SelectionDAG &DAG) const { 10566 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 10567 if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics()) 10568 return SDValue(); 10569 10570 // LSE has an atomic load-clear instruction, but not a load-and. 10571 SDLoc dl(Op); 10572 MVT VT = Op.getSimpleValueType(); 10573 SDValue RHS = Op.getOperand(2); 10574 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 10575 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 10576 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 10577 Op.getOperand(0), Op.getOperand(1), RHS, 10578 AN->getMemOperand()); 10579 } 10580 10581 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 10582 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 10583 SDLoc dl(Op); 10584 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10585 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 10586 10587 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10588 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 10589 if (Subtarget->hasCustomCallingConv()) 10590 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 10591 10592 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 10593 DAG.getConstant(4, dl, MVT::i64)); 10594 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 10595 Chain = 10596 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 10597 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 10598 DAG.getRegisterMask(Mask), Chain.getValue(1)); 10599 // To match the actual intent better, we should read the output from X15 here 10600 // again (instead of potentially spilling it to the stack), but rereading Size 10601 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 10602 // here. 10603 10604 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 10605 DAG.getConstant(4, dl, MVT::i64)); 10606 return Chain; 10607 } 10608 10609 SDValue 10610 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 10611 SelectionDAG &DAG) const { 10612 assert(Subtarget->isTargetWindows() && 10613 "Only Windows alloca probing supported"); 10614 SDLoc dl(Op); 10615 // Get the inputs. 10616 SDNode *Node = Op.getNode(); 10617 SDValue Chain = Op.getOperand(0); 10618 SDValue Size = Op.getOperand(1); 10619 MaybeAlign Align = 10620 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue(); 10621 EVT VT = Node->getValueType(0); 10622 10623 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 10624 "no-stack-arg-probe")) { 10625 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 10626 Chain = SP.getValue(1); 10627 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 10628 if (Align) 10629 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 10630 DAG.getConstant(-(uint64_t)Align->value(), dl, VT)); 10631 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 10632 SDValue Ops[2] = {SP, Chain}; 10633 return DAG.getMergeValues(Ops, dl); 10634 } 10635 10636 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 10637 10638 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 10639 10640 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 10641 Chain = SP.getValue(1); 10642 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 10643 if (Align) 10644 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 10645 DAG.getConstant(-(uint64_t)Align->value(), dl, VT)); 10646 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 10647 10648 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 10649 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 10650 10651 SDValue Ops[2] = {SP, Chain}; 10652 return DAG.getMergeValues(Ops, dl); 10653 } 10654 10655 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op, 10656 SelectionDAG &DAG) const { 10657 EVT VT = Op.getValueType(); 10658 assert(VT != MVT::i64 && "Expected illegal VSCALE node"); 10659 10660 SDLoc DL(Op); 10661 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue(); 10662 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)), 10663 DL, VT); 10664 } 10665 10666 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics. 10667 template <unsigned NumVecs> 10668 static bool 10669 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL, 10670 AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) { 10671 Info.opc = ISD::INTRINSIC_VOID; 10672 // Retrieve EC from first vector argument. 10673 const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType()); 10674 ElementCount EC = VT.getVectorElementCount(); 10675 #ifndef NDEBUG 10676 // Check the assumption that all input vectors are the same type. 10677 for (unsigned I = 0; I < NumVecs; ++I) 10678 assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) && 10679 "Invalid type."); 10680 #endif 10681 // memVT is `NumVecs * VT`. 10682 Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(), 10683 EC * NumVecs); 10684 Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1); 10685 Info.offset = 0; 10686 Info.align.reset(); 10687 Info.flags = MachineMemOperand::MOStore; 10688 return true; 10689 } 10690 10691 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 10692 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 10693 /// specified in the intrinsic calls. 10694 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 10695 const CallInst &I, 10696 MachineFunction &MF, 10697 unsigned Intrinsic) const { 10698 auto &DL = I.getModule()->getDataLayout(); 10699 switch (Intrinsic) { 10700 case Intrinsic::aarch64_sve_st2: 10701 return setInfoSVEStN<2>(*this, DL, Info, I); 10702 case Intrinsic::aarch64_sve_st3: 10703 return setInfoSVEStN<3>(*this, DL, Info, I); 10704 case Intrinsic::aarch64_sve_st4: 10705 return setInfoSVEStN<4>(*this, DL, Info, I); 10706 case Intrinsic::aarch64_neon_ld2: 10707 case Intrinsic::aarch64_neon_ld3: 10708 case Intrinsic::aarch64_neon_ld4: 10709 case Intrinsic::aarch64_neon_ld1x2: 10710 case Intrinsic::aarch64_neon_ld1x3: 10711 case Intrinsic::aarch64_neon_ld1x4: 10712 case Intrinsic::aarch64_neon_ld2lane: 10713 case Intrinsic::aarch64_neon_ld3lane: 10714 case Intrinsic::aarch64_neon_ld4lane: 10715 case Intrinsic::aarch64_neon_ld2r: 10716 case Intrinsic::aarch64_neon_ld3r: 10717 case Intrinsic::aarch64_neon_ld4r: { 10718 Info.opc = ISD::INTRINSIC_W_CHAIN; 10719 // Conservatively set memVT to the entire set of vectors loaded. 10720 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 10721 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10722 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 10723 Info.offset = 0; 10724 Info.align.reset(); 10725 // volatile loads with NEON intrinsics not supported 10726 Info.flags = MachineMemOperand::MOLoad; 10727 return true; 10728 } 10729 case Intrinsic::aarch64_neon_st2: 10730 case Intrinsic::aarch64_neon_st3: 10731 case Intrinsic::aarch64_neon_st4: 10732 case Intrinsic::aarch64_neon_st1x2: 10733 case Intrinsic::aarch64_neon_st1x3: 10734 case Intrinsic::aarch64_neon_st1x4: 10735 case Intrinsic::aarch64_neon_st2lane: 10736 case Intrinsic::aarch64_neon_st3lane: 10737 case Intrinsic::aarch64_neon_st4lane: { 10738 Info.opc = ISD::INTRINSIC_VOID; 10739 // Conservatively set memVT to the entire set of vectors stored. 10740 unsigned NumElts = 0; 10741 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 10742 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 10743 if (!ArgTy->isVectorTy()) 10744 break; 10745 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 10746 } 10747 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10748 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 10749 Info.offset = 0; 10750 Info.align.reset(); 10751 // volatile stores with NEON intrinsics not supported 10752 Info.flags = MachineMemOperand::MOStore; 10753 return true; 10754 } 10755 case Intrinsic::aarch64_ldaxr: 10756 case Intrinsic::aarch64_ldxr: { 10757 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 10758 Info.opc = ISD::INTRINSIC_W_CHAIN; 10759 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10760 Info.ptrVal = I.getArgOperand(0); 10761 Info.offset = 0; 10762 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10763 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 10764 return true; 10765 } 10766 case Intrinsic::aarch64_stlxr: 10767 case Intrinsic::aarch64_stxr: { 10768 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10769 Info.opc = ISD::INTRINSIC_W_CHAIN; 10770 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10771 Info.ptrVal = I.getArgOperand(1); 10772 Info.offset = 0; 10773 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10774 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 10775 return true; 10776 } 10777 case Intrinsic::aarch64_ldaxp: 10778 case Intrinsic::aarch64_ldxp: 10779 Info.opc = ISD::INTRINSIC_W_CHAIN; 10780 Info.memVT = MVT::i128; 10781 Info.ptrVal = I.getArgOperand(0); 10782 Info.offset = 0; 10783 Info.align = Align(16); 10784 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 10785 return true; 10786 case Intrinsic::aarch64_stlxp: 10787 case Intrinsic::aarch64_stxp: 10788 Info.opc = ISD::INTRINSIC_W_CHAIN; 10789 Info.memVT = MVT::i128; 10790 Info.ptrVal = I.getArgOperand(2); 10791 Info.offset = 0; 10792 Info.align = Align(16); 10793 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 10794 return true; 10795 case Intrinsic::aarch64_sve_ldnt1: { 10796 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10797 Info.opc = ISD::INTRINSIC_W_CHAIN; 10798 Info.memVT = MVT::getVT(I.getType()); 10799 Info.ptrVal = I.getArgOperand(1); 10800 Info.offset = 0; 10801 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10802 Info.flags = MachineMemOperand::MOLoad; 10803 if (Intrinsic == Intrinsic::aarch64_sve_ldnt1) 10804 Info.flags |= MachineMemOperand::MONonTemporal; 10805 return true; 10806 } 10807 case Intrinsic::aarch64_sve_stnt1: { 10808 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType()); 10809 Info.opc = ISD::INTRINSIC_W_CHAIN; 10810 Info.memVT = MVT::getVT(I.getOperand(0)->getType()); 10811 Info.ptrVal = I.getArgOperand(2); 10812 Info.offset = 0; 10813 Info.align = DL.getABITypeAlign(PtrTy->getElementType()); 10814 Info.flags = MachineMemOperand::MOStore; 10815 if (Intrinsic == Intrinsic::aarch64_sve_stnt1) 10816 Info.flags |= MachineMemOperand::MONonTemporal; 10817 return true; 10818 } 10819 default: 10820 break; 10821 } 10822 10823 return false; 10824 } 10825 10826 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 10827 ISD::LoadExtType ExtTy, 10828 EVT NewVT) const { 10829 // TODO: This may be worth removing. Check regression tests for diffs. 10830 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 10831 return false; 10832 10833 // If we're reducing the load width in order to avoid having to use an extra 10834 // instruction to do extension then it's probably a good idea. 10835 if (ExtTy != ISD::NON_EXTLOAD) 10836 return true; 10837 // Don't reduce load width if it would prevent us from combining a shift into 10838 // the offset. 10839 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 10840 assert(Mem); 10841 const SDValue &Base = Mem->getBasePtr(); 10842 if (Base.getOpcode() == ISD::ADD && 10843 Base.getOperand(1).getOpcode() == ISD::SHL && 10844 Base.getOperand(1).hasOneUse() && 10845 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 10846 // The shift can be combined if it matches the size of the value being 10847 // loaded (and so reducing the width would make it not match). 10848 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 10849 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 10850 if (ShiftAmount == Log2_32(LoadBytes)) 10851 return false; 10852 } 10853 // We have no reason to disallow reducing the load width, so allow it. 10854 return true; 10855 } 10856 10857 // Truncations from 64-bit GPR to 32-bit GPR is free. 10858 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 10859 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10860 return false; 10861 uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize(); 10862 uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize(); 10863 return NumBits1 > NumBits2; 10864 } 10865 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 10866 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 10867 return false; 10868 uint64_t NumBits1 = VT1.getFixedSizeInBits(); 10869 uint64_t NumBits2 = VT2.getFixedSizeInBits(); 10870 return NumBits1 > NumBits2; 10871 } 10872 10873 /// Check if it is profitable to hoist instruction in then/else to if. 10874 /// Not profitable if I and it's user can form a FMA instruction 10875 /// because we prefer FMSUB/FMADD. 10876 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 10877 if (I->getOpcode() != Instruction::FMul) 10878 return true; 10879 10880 if (!I->hasOneUse()) 10881 return true; 10882 10883 Instruction *User = I->user_back(); 10884 10885 if (User && 10886 !(User->getOpcode() == Instruction::FSub || 10887 User->getOpcode() == Instruction::FAdd)) 10888 return true; 10889 10890 const TargetOptions &Options = getTargetMachine().Options; 10891 const Function *F = I->getFunction(); 10892 const DataLayout &DL = F->getParent()->getDataLayout(); 10893 Type *Ty = User->getOperand(0)->getType(); 10894 10895 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) && 10896 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 10897 (Options.AllowFPOpFusion == FPOpFusion::Fast || 10898 Options.UnsafeFPMath)); 10899 } 10900 10901 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 10902 // 64-bit GPR. 10903 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 10904 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 10905 return false; 10906 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 10907 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 10908 return NumBits1 == 32 && NumBits2 == 64; 10909 } 10910 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 10911 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 10912 return false; 10913 unsigned NumBits1 = VT1.getSizeInBits(); 10914 unsigned NumBits2 = VT2.getSizeInBits(); 10915 return NumBits1 == 32 && NumBits2 == 64; 10916 } 10917 10918 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 10919 EVT VT1 = Val.getValueType(); 10920 if (isZExtFree(VT1, VT2)) { 10921 return true; 10922 } 10923 10924 if (Val.getOpcode() != ISD::LOAD) 10925 return false; 10926 10927 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 10928 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 10929 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 10930 VT1.getSizeInBits() <= 32); 10931 } 10932 10933 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 10934 if (isa<FPExtInst>(Ext)) 10935 return false; 10936 10937 // Vector types are not free. 10938 if (Ext->getType()->isVectorTy()) 10939 return false; 10940 10941 for (const Use &U : Ext->uses()) { 10942 // The extension is free if we can fold it with a left shift in an 10943 // addressing mode or an arithmetic operation: add, sub, and cmp. 10944 10945 // Is there a shift? 10946 const Instruction *Instr = cast<Instruction>(U.getUser()); 10947 10948 // Is this a constant shift? 10949 switch (Instr->getOpcode()) { 10950 case Instruction::Shl: 10951 if (!isa<ConstantInt>(Instr->getOperand(1))) 10952 return false; 10953 break; 10954 case Instruction::GetElementPtr: { 10955 gep_type_iterator GTI = gep_type_begin(Instr); 10956 auto &DL = Ext->getModule()->getDataLayout(); 10957 std::advance(GTI, U.getOperandNo()-1); 10958 Type *IdxTy = GTI.getIndexedType(); 10959 // This extension will end up with a shift because of the scaling factor. 10960 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 10961 // Get the shift amount based on the scaling factor: 10962 // log2(sizeof(IdxTy)) - log2(8). 10963 uint64_t ShiftAmt = 10964 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 10965 // Is the constant foldable in the shift of the addressing mode? 10966 // I.e., shift amount is between 1 and 4 inclusive. 10967 if (ShiftAmt == 0 || ShiftAmt > 4) 10968 return false; 10969 break; 10970 } 10971 case Instruction::Trunc: 10972 // Check if this is a noop. 10973 // trunc(sext ty1 to ty2) to ty1. 10974 if (Instr->getType() == Ext->getOperand(0)->getType()) 10975 continue; 10976 LLVM_FALLTHROUGH; 10977 default: 10978 return false; 10979 } 10980 10981 // At this point we can use the bfm family, so this extension is free 10982 // for that use. 10983 } 10984 return true; 10985 } 10986 10987 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 10988 /// or upper half of the vector elements. 10989 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 10990 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 10991 auto *FullTy = FullV->getType(); 10992 auto *HalfTy = HalfV->getType(); 10993 return FullTy->getPrimitiveSizeInBits().getFixedSize() == 10994 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize(); 10995 }; 10996 10997 auto extractHalf = [](Value *FullV, Value *HalfV) { 10998 auto *FullVT = cast<FixedVectorType>(FullV->getType()); 10999 auto *HalfVT = cast<FixedVectorType>(HalfV->getType()); 11000 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 11001 }; 11002 11003 ArrayRef<int> M1, M2; 11004 Value *S1Op1, *S2Op1; 11005 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) || 11006 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2)))) 11007 return false; 11008 11009 // Check that the operands are half as wide as the result and we extract 11010 // half of the elements of the input vectors. 11011 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 11012 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 11013 return false; 11014 11015 // Check the mask extracts either the lower or upper half of vector 11016 // elements. 11017 int M1Start = -1; 11018 int M2Start = -1; 11019 int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2; 11020 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 11021 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 11022 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 11023 return false; 11024 11025 return true; 11026 } 11027 11028 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 11029 /// of the vector elements. 11030 static bool areExtractExts(Value *Ext1, Value *Ext2) { 11031 auto areExtDoubled = [](Instruction *Ext) { 11032 return Ext->getType()->getScalarSizeInBits() == 11033 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 11034 }; 11035 11036 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 11037 !match(Ext2, m_ZExtOrSExt(m_Value())) || 11038 !areExtDoubled(cast<Instruction>(Ext1)) || 11039 !areExtDoubled(cast<Instruction>(Ext2))) 11040 return false; 11041 11042 return true; 11043 } 11044 11045 /// Check if Op could be used with vmull_high_p64 intrinsic. 11046 static bool isOperandOfVmullHighP64(Value *Op) { 11047 Value *VectorOperand = nullptr; 11048 ConstantInt *ElementIndex = nullptr; 11049 return match(Op, m_ExtractElt(m_Value(VectorOperand), 11050 m_ConstantInt(ElementIndex))) && 11051 ElementIndex->getValue() == 1 && 11052 isa<FixedVectorType>(VectorOperand->getType()) && 11053 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2; 11054 } 11055 11056 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic. 11057 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) { 11058 return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2); 11059 } 11060 11061 /// Check if sinking \p I's operands to I's basic block is profitable, because 11062 /// the operands can be folded into a target instruction, e.g. 11063 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 11064 bool AArch64TargetLowering::shouldSinkOperands( 11065 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 11066 if (!I->getType()->isVectorTy()) 11067 return false; 11068 11069 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 11070 switch (II->getIntrinsicID()) { 11071 case Intrinsic::aarch64_neon_umull: 11072 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 11073 return false; 11074 Ops.push_back(&II->getOperandUse(0)); 11075 Ops.push_back(&II->getOperandUse(1)); 11076 return true; 11077 11078 case Intrinsic::aarch64_neon_pmull64: 11079 if (!areOperandsOfVmullHighP64(II->getArgOperand(0), 11080 II->getArgOperand(1))) 11081 return false; 11082 Ops.push_back(&II->getArgOperandUse(0)); 11083 Ops.push_back(&II->getArgOperandUse(1)); 11084 return true; 11085 11086 default: 11087 return false; 11088 } 11089 } 11090 11091 switch (I->getOpcode()) { 11092 case Instruction::Sub: 11093 case Instruction::Add: { 11094 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 11095 return false; 11096 11097 // If the exts' operands extract either the lower or upper elements, we 11098 // can sink them too. 11099 auto Ext1 = cast<Instruction>(I->getOperand(0)); 11100 auto Ext2 = cast<Instruction>(I->getOperand(1)); 11101 if (areExtractShuffleVectors(Ext1, Ext2)) { 11102 Ops.push_back(&Ext1->getOperandUse(0)); 11103 Ops.push_back(&Ext2->getOperandUse(0)); 11104 } 11105 11106 Ops.push_back(&I->getOperandUse(0)); 11107 Ops.push_back(&I->getOperandUse(1)); 11108 11109 return true; 11110 } 11111 case Instruction::Mul: { 11112 bool IsProfitable = false; 11113 for (auto &Op : I->operands()) { 11114 // Make sure we are not already sinking this operand 11115 if (any_of(Ops, [&](Use *U) { return U->get() == Op; })) 11116 continue; 11117 11118 ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op); 11119 if (!Shuffle || !Shuffle->isZeroEltSplat()) 11120 continue; 11121 11122 Value *ShuffleOperand = Shuffle->getOperand(0); 11123 InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand); 11124 if (!Insert) 11125 continue; 11126 11127 Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1)); 11128 if (!OperandInstr) 11129 continue; 11130 11131 ConstantInt *ElementConstant = 11132 dyn_cast<ConstantInt>(Insert->getOperand(2)); 11133 // Check that the insertelement is inserting into element 0 11134 if (!ElementConstant || ElementConstant->getZExtValue() != 0) 11135 continue; 11136 11137 unsigned Opcode = OperandInstr->getOpcode(); 11138 if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt) 11139 continue; 11140 11141 Ops.push_back(&Shuffle->getOperandUse(0)); 11142 Ops.push_back(&Op); 11143 IsProfitable = true; 11144 } 11145 11146 return IsProfitable; 11147 } 11148 default: 11149 return false; 11150 } 11151 return false; 11152 } 11153 11154 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 11155 Align &RequiredAligment) const { 11156 if (!LoadedType.isSimple() || 11157 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 11158 return false; 11159 // Cyclone supports unaligned accesses. 11160 RequiredAligment = Align(1); 11161 unsigned NumBits = LoadedType.getSizeInBits(); 11162 return NumBits == 32 || NumBits == 64; 11163 } 11164 11165 /// A helper function for determining the number of interleaved accesses we 11166 /// will generate when lowering accesses of the given type. 11167 unsigned 11168 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 11169 const DataLayout &DL) const { 11170 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 11171 } 11172 11173 MachineMemOperand::Flags 11174 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const { 11175 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 11176 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 11177 return MOStridedAccess; 11178 return MachineMemOperand::MONone; 11179 } 11180 11181 bool AArch64TargetLowering::isLegalInterleavedAccessType( 11182 VectorType *VecTy, const DataLayout &DL) const { 11183 11184 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 11185 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 11186 11187 // Ensure the number of vector elements is greater than 1. 11188 if (cast<FixedVectorType>(VecTy)->getNumElements() < 2) 11189 return false; 11190 11191 // Ensure the element type is legal. 11192 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 11193 return false; 11194 11195 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 11196 // 128 will be split into multiple interleaved accesses. 11197 return VecSize == 64 || VecSize % 128 == 0; 11198 } 11199 11200 /// Lower an interleaved load into a ldN intrinsic. 11201 /// 11202 /// E.g. Lower an interleaved load (Factor = 2): 11203 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 11204 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 11205 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 11206 /// 11207 /// Into: 11208 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 11209 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 11210 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 11211 bool AArch64TargetLowering::lowerInterleavedLoad( 11212 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 11213 ArrayRef<unsigned> Indices, unsigned Factor) const { 11214 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11215 "Invalid interleave factor"); 11216 assert(!Shuffles.empty() && "Empty shufflevector input"); 11217 assert(Shuffles.size() == Indices.size() && 11218 "Unmatched number of shufflevectors and indices"); 11219 11220 const DataLayout &DL = LI->getModule()->getDataLayout(); 11221 11222 VectorType *VTy = Shuffles[0]->getType(); 11223 11224 // Skip if we do not have NEON and skip illegal vector types. We can 11225 // "legalize" wide vector types into multiple interleaved accesses as long as 11226 // the vector types are divisible by 128. 11227 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL)) 11228 return false; 11229 11230 unsigned NumLoads = getNumInterleavedAccesses(VTy, DL); 11231 11232 auto *FVTy = cast<FixedVectorType>(VTy); 11233 11234 // A pointer vector can not be the return type of the ldN intrinsics. Need to 11235 // load integer vectors first and then convert to pointer vectors. 11236 Type *EltTy = FVTy->getElementType(); 11237 if (EltTy->isPointerTy()) 11238 FVTy = 11239 FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements()); 11240 11241 IRBuilder<> Builder(LI); 11242 11243 // The base address of the load. 11244 Value *BaseAddr = LI->getPointerOperand(); 11245 11246 if (NumLoads > 1) { 11247 // If we're going to generate more than one load, reset the sub-vector type 11248 // to something legal. 11249 FVTy = FixedVectorType::get(FVTy->getElementType(), 11250 FVTy->getNumElements() / NumLoads); 11251 11252 // We will compute the pointer operand of each load from the original base 11253 // address using GEPs. Cast the base address to a pointer to the scalar 11254 // element type. 11255 BaseAddr = Builder.CreateBitCast( 11256 BaseAddr, 11257 FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())); 11258 } 11259 11260 Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace()); 11261 Type *Tys[2] = {FVTy, PtrTy}; 11262 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 11263 Intrinsic::aarch64_neon_ld3, 11264 Intrinsic::aarch64_neon_ld4}; 11265 Function *LdNFunc = 11266 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 11267 11268 // Holds sub-vectors extracted from the load intrinsic return values. The 11269 // sub-vectors are associated with the shufflevector instructions they will 11270 // replace. 11271 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 11272 11273 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 11274 11275 // If we're generating more than one load, compute the base address of 11276 // subsequent loads as an offset from the previous. 11277 if (LoadCount > 0) 11278 BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr, 11279 FVTy->getNumElements() * Factor); 11280 11281 CallInst *LdN = Builder.CreateCall( 11282 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 11283 11284 // Extract and store the sub-vectors returned by the load intrinsic. 11285 for (unsigned i = 0; i < Shuffles.size(); i++) { 11286 ShuffleVectorInst *SVI = Shuffles[i]; 11287 unsigned Index = Indices[i]; 11288 11289 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 11290 11291 // Convert the integer vector to pointer vector if the element is pointer. 11292 if (EltTy->isPointerTy()) 11293 SubVec = Builder.CreateIntToPtr( 11294 SubVec, FixedVectorType::get(SVI->getType()->getElementType(), 11295 FVTy->getNumElements())); 11296 SubVecs[SVI].push_back(SubVec); 11297 } 11298 } 11299 11300 // Replace uses of the shufflevector instructions with the sub-vectors 11301 // returned by the load intrinsic. If a shufflevector instruction is 11302 // associated with more than one sub-vector, those sub-vectors will be 11303 // concatenated into a single wide vector. 11304 for (ShuffleVectorInst *SVI : Shuffles) { 11305 auto &SubVec = SubVecs[SVI]; 11306 auto *WideVec = 11307 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 11308 SVI->replaceAllUsesWith(WideVec); 11309 } 11310 11311 return true; 11312 } 11313 11314 /// Lower an interleaved store into a stN intrinsic. 11315 /// 11316 /// E.g. Lower an interleaved store (Factor = 3): 11317 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 11318 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 11319 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 11320 /// 11321 /// Into: 11322 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 11323 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 11324 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 11325 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 11326 /// 11327 /// Note that the new shufflevectors will be removed and we'll only generate one 11328 /// st3 instruction in CodeGen. 11329 /// 11330 /// Example for a more general valid mask (Factor 3). Lower: 11331 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 11332 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 11333 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 11334 /// 11335 /// Into: 11336 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 11337 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 11338 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 11339 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 11340 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 11341 ShuffleVectorInst *SVI, 11342 unsigned Factor) const { 11343 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 11344 "Invalid interleave factor"); 11345 11346 auto *VecTy = cast<FixedVectorType>(SVI->getType()); 11347 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store"); 11348 11349 unsigned LaneLen = VecTy->getNumElements() / Factor; 11350 Type *EltTy = VecTy->getElementType(); 11351 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen); 11352 11353 const DataLayout &DL = SI->getModule()->getDataLayout(); 11354 11355 // Skip if we do not have NEON and skip illegal vector types. We can 11356 // "legalize" wide vector types into multiple interleaved accesses as long as 11357 // the vector types are divisible by 128. 11358 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 11359 return false; 11360 11361 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 11362 11363 Value *Op0 = SVI->getOperand(0); 11364 Value *Op1 = SVI->getOperand(1); 11365 IRBuilder<> Builder(SI); 11366 11367 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 11368 // vectors to integer vectors. 11369 if (EltTy->isPointerTy()) { 11370 Type *IntTy = DL.getIntPtrType(EltTy); 11371 unsigned NumOpElts = 11372 cast<FixedVectorType>(Op0->getType())->getNumElements(); 11373 11374 // Convert to the corresponding integer vector. 11375 auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts); 11376 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 11377 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 11378 11379 SubVecTy = FixedVectorType::get(IntTy, LaneLen); 11380 } 11381 11382 // The base address of the store. 11383 Value *BaseAddr = SI->getPointerOperand(); 11384 11385 if (NumStores > 1) { 11386 // If we're going to generate more than one store, reset the lane length 11387 // and sub-vector type to something legal. 11388 LaneLen /= NumStores; 11389 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen); 11390 11391 // We will compute the pointer operand of each store from the original base 11392 // address using GEPs. Cast the base address to a pointer to the scalar 11393 // element type. 11394 BaseAddr = Builder.CreateBitCast( 11395 BaseAddr, 11396 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())); 11397 } 11398 11399 auto Mask = SVI->getShuffleMask(); 11400 11401 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 11402 Type *Tys[2] = {SubVecTy, PtrTy}; 11403 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 11404 Intrinsic::aarch64_neon_st3, 11405 Intrinsic::aarch64_neon_st4}; 11406 Function *StNFunc = 11407 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 11408 11409 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 11410 11411 SmallVector<Value *, 5> Ops; 11412 11413 // Split the shufflevector operands into sub vectors for the new stN call. 11414 for (unsigned i = 0; i < Factor; i++) { 11415 unsigned IdxI = StoreCount * LaneLen * Factor + i; 11416 if (Mask[IdxI] >= 0) { 11417 Ops.push_back(Builder.CreateShuffleVector( 11418 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0))); 11419 } else { 11420 unsigned StartMask = 0; 11421 for (unsigned j = 1; j < LaneLen; j++) { 11422 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 11423 if (Mask[IdxJ * Factor + IdxI] >= 0) { 11424 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 11425 break; 11426 } 11427 } 11428 // Note: Filling undef gaps with random elements is ok, since 11429 // those elements were being written anyway (with undefs). 11430 // In the case of all undefs we're defaulting to using elems from 0 11431 // Note: StartMask cannot be negative, it's checked in 11432 // isReInterleaveMask 11433 Ops.push_back(Builder.CreateShuffleVector( 11434 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0))); 11435 } 11436 } 11437 11438 // If we generating more than one store, we compute the base address of 11439 // subsequent stores as an offset from the previous. 11440 if (StoreCount > 0) 11441 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(), 11442 BaseAddr, LaneLen * Factor); 11443 11444 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 11445 Builder.CreateCall(StNFunc, Ops); 11446 } 11447 return true; 11448 } 11449 11450 // Lower an SVE structured load intrinsic returning a tuple type to target 11451 // specific intrinsic taking the same input but returning a multi-result value 11452 // of the split tuple type. 11453 // 11454 // E.g. Lowering an LD3: 11455 // 11456 // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32( 11457 // <vscale x 4 x i1> %pred, 11458 // <vscale x 4 x i32>* %addr) 11459 // 11460 // Output DAG: 11461 // 11462 // t0: ch = EntryToken 11463 // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0 11464 // t4: i64,ch = CopyFromReg t0, Register:i64 %1 11465 // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4 11466 // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2 11467 // 11468 // This is called pre-legalization to avoid widening/splitting issues with 11469 // non-power-of-2 tuple types used for LD3, such as nxv12i32. 11470 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic, 11471 ArrayRef<SDValue> LoadOps, 11472 EVT VT, SelectionDAG &DAG, 11473 const SDLoc &DL) const { 11474 assert(VT.isScalableVector() && "Can only lower scalable vectors"); 11475 11476 unsigned N, Opcode; 11477 static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = { 11478 {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}}, 11479 {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}}, 11480 {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}}; 11481 11482 std::tie(N, Opcode) = IntrinsicMap[Intrinsic]; 11483 assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 && 11484 "invalid tuple vector type!"); 11485 11486 EVT SplitVT = 11487 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 11488 VT.getVectorElementCount().divideCoefficientBy(N)); 11489 assert(isTypeLegal(SplitVT)); 11490 11491 SmallVector<EVT, 5> VTs(N, SplitVT); 11492 VTs.push_back(MVT::Other); // Chain 11493 SDVTList NodeTys = DAG.getVTList(VTs); 11494 11495 SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps); 11496 SmallVector<SDValue, 4> PseudoLoadOps; 11497 for (unsigned I = 0; I < N; ++I) 11498 PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I)); 11499 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps); 11500 } 11501 11502 EVT AArch64TargetLowering::getOptimalMemOpType( 11503 const MemOp &Op, const AttributeList &FuncAttributes) const { 11504 bool CanImplicitFloat = 11505 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 11506 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 11507 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 11508 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 11509 // taken one instruction to materialize the v2i64 zero and one store (with 11510 // restrictive addressing mode). Just do i64 stores. 11511 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 11512 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 11513 if (Op.isAligned(AlignCheck)) 11514 return true; 11515 bool Fast; 11516 return allowsMisalignedMemoryAccesses(VT, 0, Align(1), 11517 MachineMemOperand::MONone, &Fast) && 11518 Fast; 11519 }; 11520 11521 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 11522 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 11523 return MVT::v2i64; 11524 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 11525 return MVT::f128; 11526 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 11527 return MVT::i64; 11528 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 11529 return MVT::i32; 11530 return MVT::Other; 11531 } 11532 11533 LLT AArch64TargetLowering::getOptimalMemOpLLT( 11534 const MemOp &Op, const AttributeList &FuncAttributes) const { 11535 bool CanImplicitFloat = 11536 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 11537 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 11538 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 11539 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 11540 // taken one instruction to materialize the v2i64 zero and one store (with 11541 // restrictive addressing mode). Just do i64 stores. 11542 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 11543 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 11544 if (Op.isAligned(AlignCheck)) 11545 return true; 11546 bool Fast; 11547 return allowsMisalignedMemoryAccesses(VT, 0, Align(1), 11548 MachineMemOperand::MONone, &Fast) && 11549 Fast; 11550 }; 11551 11552 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 11553 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 11554 return LLT::vector(2, 64); 11555 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 11556 return LLT::scalar(128); 11557 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 11558 return LLT::scalar(64); 11559 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 11560 return LLT::scalar(32); 11561 return LLT(); 11562 } 11563 11564 // 12-bit optionally shifted immediates are legal for adds. 11565 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 11566 if (Immed == std::numeric_limits<int64_t>::min()) { 11567 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 11568 << ": avoid UB for INT64_MIN\n"); 11569 return false; 11570 } 11571 // Same encoding for add/sub, just flip the sign. 11572 Immed = std::abs(Immed); 11573 bool IsLegal = ((Immed >> 12) == 0 || 11574 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 11575 LLVM_DEBUG(dbgs() << "Is " << Immed 11576 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 11577 return IsLegal; 11578 } 11579 11580 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 11581 // immediates is the same as for an add or a sub. 11582 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 11583 return isLegalAddImmediate(Immed); 11584 } 11585 11586 /// isLegalAddressingMode - Return true if the addressing mode represented 11587 /// by AM is legal for this target, for a load/store of the specified type. 11588 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 11589 const AddrMode &AM, Type *Ty, 11590 unsigned AS, Instruction *I) const { 11591 // AArch64 has five basic addressing modes: 11592 // reg 11593 // reg + 9-bit signed offset 11594 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 11595 // reg1 + reg2 11596 // reg + SIZE_IN_BYTES * reg 11597 11598 // No global is ever allowed as a base. 11599 if (AM.BaseGV) 11600 return false; 11601 11602 // No reg+reg+imm addressing. 11603 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 11604 return false; 11605 11606 // FIXME: Update this method to support scalable addressing modes. 11607 if (isa<ScalableVectorType>(Ty)) 11608 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale; 11609 11610 // check reg + imm case: 11611 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 11612 uint64_t NumBytes = 0; 11613 if (Ty->isSized()) { 11614 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 11615 NumBytes = NumBits / 8; 11616 if (!isPowerOf2_64(NumBits)) 11617 NumBytes = 0; 11618 } 11619 11620 if (!AM.Scale) { 11621 int64_t Offset = AM.BaseOffs; 11622 11623 // 9-bit signed offset 11624 if (isInt<9>(Offset)) 11625 return true; 11626 11627 // 12-bit unsigned offset 11628 unsigned shift = Log2_64(NumBytes); 11629 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 11630 // Must be a multiple of NumBytes (NumBytes is a power of 2) 11631 (Offset >> shift) << shift == Offset) 11632 return true; 11633 return false; 11634 } 11635 11636 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 11637 11638 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 11639 } 11640 11641 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 11642 // Consider splitting large offset of struct or array. 11643 return true; 11644 } 11645 11646 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 11647 const AddrMode &AM, Type *Ty, 11648 unsigned AS) const { 11649 // Scaling factors are not free at all. 11650 // Operands | Rt Latency 11651 // ------------------------------------------- 11652 // Rt, [Xn, Xm] | 4 11653 // ------------------------------------------- 11654 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 11655 // Rt, [Xn, Wm, <extend> #imm] | 11656 if (isLegalAddressingMode(DL, AM, Ty, AS)) 11657 // Scale represents reg2 * scale, thus account for 1 if 11658 // it is not equal to 0 or 1. 11659 return AM.Scale != 0 && AM.Scale != 1; 11660 return -1; 11661 } 11662 11663 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd( 11664 const MachineFunction &MF, EVT VT) const { 11665 VT = VT.getScalarType(); 11666 11667 if (!VT.isSimple()) 11668 return false; 11669 11670 switch (VT.getSimpleVT().SimpleTy) { 11671 case MVT::f16: 11672 return Subtarget->hasFullFP16(); 11673 case MVT::f32: 11674 case MVT::f64: 11675 return true; 11676 default: 11677 break; 11678 } 11679 11680 return false; 11681 } 11682 11683 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 11684 Type *Ty) const { 11685 switch (Ty->getScalarType()->getTypeID()) { 11686 case Type::FloatTyID: 11687 case Type::DoubleTyID: 11688 return true; 11689 default: 11690 return false; 11691 } 11692 } 11693 11694 bool AArch64TargetLowering::generateFMAsInMachineCombiner( 11695 EVT VT, CodeGenOpt::Level OptLevel) const { 11696 return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector(); 11697 } 11698 11699 const MCPhysReg * 11700 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 11701 // LR is a callee-save register, but we must treat it as clobbered by any call 11702 // site. Hence we include LR in the scratch registers, which are in turn added 11703 // as implicit-defs for stackmaps and patchpoints. 11704 static const MCPhysReg ScratchRegs[] = { 11705 AArch64::X16, AArch64::X17, AArch64::LR, 0 11706 }; 11707 return ScratchRegs; 11708 } 11709 11710 bool 11711 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 11712 CombineLevel Level) const { 11713 N = N->getOperand(0).getNode(); 11714 EVT VT = N->getValueType(0); 11715 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 11716 // it with shift to let it be lowered to UBFX. 11717 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 11718 isa<ConstantSDNode>(N->getOperand(1))) { 11719 uint64_t TruncMask = N->getConstantOperandVal(1); 11720 if (isMask_64(TruncMask) && 11721 N->getOperand(0).getOpcode() == ISD::SRL && 11722 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 11723 return false; 11724 } 11725 return true; 11726 } 11727 11728 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 11729 Type *Ty) const { 11730 assert(Ty->isIntegerTy()); 11731 11732 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 11733 if (BitSize == 0) 11734 return false; 11735 11736 int64_t Val = Imm.getSExtValue(); 11737 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 11738 return true; 11739 11740 if ((int64_t)Val < 0) 11741 Val = ~Val; 11742 if (BitSize == 32) 11743 Val &= (1LL << 32) - 1; 11744 11745 unsigned LZ = countLeadingZeros((uint64_t)Val); 11746 unsigned Shift = (63 - LZ) / 16; 11747 // MOVZ is free so return true for one or fewer MOVK. 11748 return Shift < 3; 11749 } 11750 11751 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 11752 unsigned Index) const { 11753 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 11754 return false; 11755 11756 return (Index == 0 || Index == ResVT.getVectorNumElements()); 11757 } 11758 11759 /// Turn vector tests of the signbit in the form of: 11760 /// xor (sra X, elt_size(X)-1), -1 11761 /// into: 11762 /// cmge X, X, #0 11763 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 11764 const AArch64Subtarget *Subtarget) { 11765 EVT VT = N->getValueType(0); 11766 if (!Subtarget->hasNEON() || !VT.isVector()) 11767 return SDValue(); 11768 11769 // There must be a shift right algebraic before the xor, and the xor must be a 11770 // 'not' operation. 11771 SDValue Shift = N->getOperand(0); 11772 SDValue Ones = N->getOperand(1); 11773 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 11774 !ISD::isBuildVectorAllOnes(Ones.getNode())) 11775 return SDValue(); 11776 11777 // The shift should be smearing the sign bit across each vector element. 11778 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 11779 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 11780 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 11781 return SDValue(); 11782 11783 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 11784 } 11785 11786 // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce 11787 // vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one)) 11788 // vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B)) 11789 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG, 11790 const AArch64Subtarget *ST) { 11791 SDValue Op0 = N->getOperand(0); 11792 if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32 || 11793 Op0.getValueType().getVectorElementType() != MVT::i32) 11794 return SDValue(); 11795 11796 unsigned ExtOpcode = Op0.getOpcode(); 11797 SDValue A = Op0; 11798 SDValue B; 11799 if (ExtOpcode == ISD::MUL) { 11800 A = Op0.getOperand(0); 11801 B = Op0.getOperand(1); 11802 if (A.getOpcode() != B.getOpcode() || 11803 A.getOperand(0).getValueType() != B.getOperand(0).getValueType()) 11804 return SDValue(); 11805 ExtOpcode = A.getOpcode(); 11806 } 11807 if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND) 11808 return SDValue(); 11809 11810 EVT Op0VT = A.getOperand(0).getValueType(); 11811 if (Op0VT != MVT::v8i8 && Op0VT != MVT::v16i8) 11812 return SDValue(); 11813 11814 SDLoc DL(Op0); 11815 // For non-mla reductions B can be set to 1. For MLA we take the operand of 11816 // the extend B. 11817 if (!B) 11818 B = DAG.getConstant(1, DL, Op0VT); 11819 else 11820 B = B.getOperand(0); 11821 11822 SDValue Zeros = 11823 DAG.getConstant(0, DL, Op0VT == MVT::v8i8 ? MVT::v2i32 : MVT::v4i32); 11824 auto DotOpcode = 11825 (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT; 11826 SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros, 11827 A.getOperand(0), B); 11828 return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot); 11829 } 11830 11831 // Given a ABS node, detect the following pattern: 11832 // (ABS (SUB (EXTEND a), (EXTEND b))). 11833 // Generates UABD/SABD instruction. 11834 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG, 11835 TargetLowering::DAGCombinerInfo &DCI, 11836 const AArch64Subtarget *Subtarget) { 11837 SDValue AbsOp1 = N->getOperand(0); 11838 SDValue Op0, Op1; 11839 11840 if (AbsOp1.getOpcode() != ISD::SUB) 11841 return SDValue(); 11842 11843 Op0 = AbsOp1.getOperand(0); 11844 Op1 = AbsOp1.getOperand(1); 11845 11846 unsigned Opc0 = Op0.getOpcode(); 11847 // Check if the operands of the sub are (zero|sign)-extended. 11848 if (Opc0 != Op1.getOpcode() || 11849 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND)) 11850 return SDValue(); 11851 11852 EVT VectorT1 = Op0.getOperand(0).getValueType(); 11853 EVT VectorT2 = Op1.getOperand(0).getValueType(); 11854 // Check if vectors are of same type and valid size. 11855 uint64_t Size = VectorT1.getFixedSizeInBits(); 11856 if (VectorT1 != VectorT2 || (Size != 64 && Size != 128)) 11857 return SDValue(); 11858 11859 // Check if vector element types are valid. 11860 EVT VT1 = VectorT1.getVectorElementType(); 11861 if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32) 11862 return SDValue(); 11863 11864 Op0 = Op0.getOperand(0); 11865 Op1 = Op1.getOperand(0); 11866 unsigned ABDOpcode = 11867 (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD; 11868 SDValue ABD = 11869 DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1); 11870 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD); 11871 } 11872 11873 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 11874 TargetLowering::DAGCombinerInfo &DCI, 11875 const AArch64Subtarget *Subtarget) { 11876 if (DCI.isBeforeLegalizeOps()) 11877 return SDValue(); 11878 11879 return foldVectorXorShiftIntoCmp(N, DAG, Subtarget); 11880 } 11881 11882 SDValue 11883 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11884 SelectionDAG &DAG, 11885 SmallVectorImpl<SDNode *> &Created) const { 11886 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11887 if (isIntDivCheap(N->getValueType(0), Attr)) 11888 return SDValue(N,0); // Lower SDIV as SDIV 11889 11890 // fold (sdiv X, pow2) 11891 EVT VT = N->getValueType(0); 11892 if ((VT != MVT::i32 && VT != MVT::i64) || 11893 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 11894 return SDValue(); 11895 11896 SDLoc DL(N); 11897 SDValue N0 = N->getOperand(0); 11898 unsigned Lg2 = Divisor.countTrailingZeros(); 11899 SDValue Zero = DAG.getConstant(0, DL, VT); 11900 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11901 11902 // Add (N0 < 0) ? Pow2 - 1 : 0; 11903 SDValue CCVal; 11904 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 11905 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11906 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 11907 11908 Created.push_back(Cmp.getNode()); 11909 Created.push_back(Add.getNode()); 11910 Created.push_back(CSel.getNode()); 11911 11912 // Divide by pow2. 11913 SDValue SRA = 11914 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 11915 11916 // If we're dividing by a positive value, we're done. Otherwise, we must 11917 // negate the result. 11918 if (Divisor.isNonNegative()) 11919 return SRA; 11920 11921 Created.push_back(SRA.getNode()); 11922 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11923 } 11924 11925 static bool IsSVECntIntrinsic(SDValue S) { 11926 switch(getIntrinsicID(S.getNode())) { 11927 default: 11928 break; 11929 case Intrinsic::aarch64_sve_cntb: 11930 case Intrinsic::aarch64_sve_cnth: 11931 case Intrinsic::aarch64_sve_cntw: 11932 case Intrinsic::aarch64_sve_cntd: 11933 return true; 11934 } 11935 return false; 11936 } 11937 11938 /// Calculates what the pre-extend type is, based on the extension 11939 /// operation node provided by \p Extend. 11940 /// 11941 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the 11942 /// pre-extend type is pulled directly from the operand, while other extend 11943 /// operations need a bit more inspection to get this information. 11944 /// 11945 /// \param Extend The SDNode from the DAG that represents the extend operation 11946 /// \param DAG The SelectionDAG hosting the \p Extend node 11947 /// 11948 /// \returns The type representing the \p Extend source type, or \p MVT::Other 11949 /// if no valid type can be determined 11950 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) { 11951 switch (Extend.getOpcode()) { 11952 case ISD::SIGN_EXTEND: 11953 case ISD::ZERO_EXTEND: 11954 return Extend.getOperand(0).getValueType(); 11955 case ISD::AssertSext: 11956 case ISD::AssertZext: 11957 case ISD::SIGN_EXTEND_INREG: { 11958 VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1)); 11959 if (!TypeNode) 11960 return MVT::Other; 11961 return TypeNode->getVT(); 11962 } 11963 case ISD::AND: { 11964 ConstantSDNode *Constant = 11965 dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode()); 11966 if (!Constant) 11967 return MVT::Other; 11968 11969 uint32_t Mask = Constant->getZExtValue(); 11970 11971 if (Mask == UCHAR_MAX) 11972 return MVT::i8; 11973 else if (Mask == USHRT_MAX) 11974 return MVT::i16; 11975 else if (Mask == UINT_MAX) 11976 return MVT::i32; 11977 11978 return MVT::Other; 11979 } 11980 default: 11981 return MVT::Other; 11982 } 11983 11984 llvm_unreachable("Code path unhandled in calculatePreExtendType!"); 11985 } 11986 11987 /// Combines a dup(sext/zext) node pattern into sext/zext(dup) 11988 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt 11989 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle, 11990 SelectionDAG &DAG) { 11991 11992 ShuffleVectorSDNode *ShuffleNode = 11993 dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode()); 11994 if (!ShuffleNode) 11995 return SDValue(); 11996 11997 // Ensuring the mask is zero before continuing 11998 if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0) 11999 return SDValue(); 12000 12001 SDValue InsertVectorElt = VectorShuffle.getOperand(0); 12002 12003 if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT) 12004 return SDValue(); 12005 12006 SDValue InsertLane = InsertVectorElt.getOperand(2); 12007 ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode()); 12008 // Ensures the insert is inserting into lane 0 12009 if (!Constant || Constant->getZExtValue() != 0) 12010 return SDValue(); 12011 12012 SDValue Extend = InsertVectorElt.getOperand(1); 12013 unsigned ExtendOpcode = Extend.getOpcode(); 12014 12015 bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND || 12016 ExtendOpcode == ISD::SIGN_EXTEND_INREG || 12017 ExtendOpcode == ISD::AssertSext; 12018 if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND && 12019 ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND) 12020 return SDValue(); 12021 12022 EVT TargetType = VectorShuffle.getValueType(); 12023 EVT PreExtendType = calculatePreExtendType(Extend, DAG); 12024 12025 if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 && 12026 TargetType != MVT::v2i64) || 12027 (PreExtendType == MVT::Other)) 12028 return SDValue(); 12029 12030 // Restrict valid pre-extend data type 12031 if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 && 12032 PreExtendType != MVT::i32) 12033 return SDValue(); 12034 12035 EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType); 12036 12037 if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount()) 12038 return SDValue(); 12039 12040 if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2) 12041 return SDValue(); 12042 12043 SDLoc DL(VectorShuffle); 12044 12045 SDValue InsertVectorNode = DAG.getNode( 12046 InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT), 12047 DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType), 12048 DAG.getConstant(0, DL, MVT::i64)); 12049 12050 std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue()); 12051 12052 SDValue VectorShuffleNode = 12053 DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode, 12054 DAG.getUNDEF(PreExtendVT), ShuffleMask); 12055 12056 SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12057 DL, TargetType, VectorShuffleNode); 12058 12059 return ExtendNode; 12060 } 12061 12062 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup)) 12063 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt 12064 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) { 12065 // If the value type isn't a vector, none of the operands are going to be dups 12066 if (!Mul->getValueType(0).isVector()) 12067 return SDValue(); 12068 12069 SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG); 12070 SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG); 12071 12072 // Neither operands have been changed, don't make any further changes 12073 if (!Op0 && !Op1) 12074 return SDValue(); 12075 12076 SDLoc DL(Mul); 12077 return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0), 12078 Op0 ? Op0 : Mul->getOperand(0), 12079 Op1 ? Op1 : Mul->getOperand(1)); 12080 } 12081 12082 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 12083 TargetLowering::DAGCombinerInfo &DCI, 12084 const AArch64Subtarget *Subtarget) { 12085 12086 if (SDValue Ext = performMulVectorExtendCombine(N, DAG)) 12087 return Ext; 12088 12089 if (DCI.isBeforeLegalizeOps()) 12090 return SDValue(); 12091 12092 // The below optimizations require a constant RHS. 12093 if (!isa<ConstantSDNode>(N->getOperand(1))) 12094 return SDValue(); 12095 12096 SDValue N0 = N->getOperand(0); 12097 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 12098 const APInt &ConstValue = C->getAPIntValue(); 12099 12100 // Allow the scaling to be folded into the `cnt` instruction by preventing 12101 // the scaling to be obscured here. This makes it easier to pattern match. 12102 if (IsSVECntIntrinsic(N0) || 12103 (N0->getOpcode() == ISD::TRUNCATE && 12104 (IsSVECntIntrinsic(N0->getOperand(0))))) 12105 if (ConstValue.sge(1) && ConstValue.sle(16)) 12106 return SDValue(); 12107 12108 // Multiplication of a power of two plus/minus one can be done more 12109 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 12110 // future CPUs have a cheaper MADD instruction, this may need to be 12111 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 12112 // 64-bit is 5 cycles, so this is always a win. 12113 // More aggressively, some multiplications N0 * C can be lowered to 12114 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 12115 // e.g. 6=3*2=(2+1)*2. 12116 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 12117 // which equals to (1+2)*16-(1+2). 12118 // TrailingZeroes is used to test if the mul can be lowered to 12119 // shift+add+shift. 12120 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 12121 if (TrailingZeroes) { 12122 // Conservatively do not lower to shift+add+shift if the mul might be 12123 // folded into smul or umul. 12124 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 12125 isZeroExtended(N0.getNode(), DAG))) 12126 return SDValue(); 12127 // Conservatively do not lower to shift+add+shift if the mul might be 12128 // folded into madd or msub. 12129 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 12130 N->use_begin()->getOpcode() == ISD::SUB)) 12131 return SDValue(); 12132 } 12133 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 12134 // and shift+add+shift. 12135 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 12136 12137 unsigned ShiftAmt, AddSubOpc; 12138 // Is the shifted value the LHS operand of the add/sub? 12139 bool ShiftValUseIsN0 = true; 12140 // Do we need to negate the result? 12141 bool NegateResult = false; 12142 12143 if (ConstValue.isNonNegative()) { 12144 // (mul x, 2^N + 1) => (add (shl x, N), x) 12145 // (mul x, 2^N - 1) => (sub (shl x, N), x) 12146 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 12147 APInt SCVMinus1 = ShiftedConstValue - 1; 12148 APInt CVPlus1 = ConstValue + 1; 12149 if (SCVMinus1.isPowerOf2()) { 12150 ShiftAmt = SCVMinus1.logBase2(); 12151 AddSubOpc = ISD::ADD; 12152 } else if (CVPlus1.isPowerOf2()) { 12153 ShiftAmt = CVPlus1.logBase2(); 12154 AddSubOpc = ISD::SUB; 12155 } else 12156 return SDValue(); 12157 } else { 12158 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 12159 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 12160 APInt CVNegPlus1 = -ConstValue + 1; 12161 APInt CVNegMinus1 = -ConstValue - 1; 12162 if (CVNegPlus1.isPowerOf2()) { 12163 ShiftAmt = CVNegPlus1.logBase2(); 12164 AddSubOpc = ISD::SUB; 12165 ShiftValUseIsN0 = false; 12166 } else if (CVNegMinus1.isPowerOf2()) { 12167 ShiftAmt = CVNegMinus1.logBase2(); 12168 AddSubOpc = ISD::ADD; 12169 NegateResult = true; 12170 } else 12171 return SDValue(); 12172 } 12173 12174 SDLoc DL(N); 12175 EVT VT = N->getValueType(0); 12176 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 12177 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 12178 12179 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 12180 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 12181 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 12182 assert(!(NegateResult && TrailingZeroes) && 12183 "NegateResult and TrailingZeroes cannot both be true for now."); 12184 // Negate the result. 12185 if (NegateResult) 12186 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 12187 // Shift the result. 12188 if (TrailingZeroes) 12189 return DAG.getNode(ISD::SHL, DL, VT, Res, 12190 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 12191 return Res; 12192 } 12193 12194 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 12195 SelectionDAG &DAG) { 12196 // Take advantage of vector comparisons producing 0 or -1 in each lane to 12197 // optimize away operation when it's from a constant. 12198 // 12199 // The general transformation is: 12200 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 12201 // AND(VECTOR_CMP(x,y), constant2) 12202 // constant2 = UNARYOP(constant) 12203 12204 // Early exit if this isn't a vector operation, the operand of the 12205 // unary operation isn't a bitwise AND, or if the sizes of the operations 12206 // aren't the same. 12207 EVT VT = N->getValueType(0); 12208 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 12209 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 12210 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 12211 return SDValue(); 12212 12213 // Now check that the other operand of the AND is a constant. We could 12214 // make the transformation for non-constant splats as well, but it's unclear 12215 // that would be a benefit as it would not eliminate any operations, just 12216 // perform one more step in scalar code before moving to the vector unit. 12217 if (BuildVectorSDNode *BV = 12218 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 12219 // Bail out if the vector isn't a constant. 12220 if (!BV->isConstant()) 12221 return SDValue(); 12222 12223 // Everything checks out. Build up the new and improved node. 12224 SDLoc DL(N); 12225 EVT IntVT = BV->getValueType(0); 12226 // Create a new constant of the appropriate type for the transformed 12227 // DAG. 12228 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 12229 // The AND node needs bitcasts to/from an integer vector type around it. 12230 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 12231 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 12232 N->getOperand(0)->getOperand(0), MaskConst); 12233 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 12234 return Res; 12235 } 12236 12237 return SDValue(); 12238 } 12239 12240 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 12241 const AArch64Subtarget *Subtarget) { 12242 // First try to optimize away the conversion when it's conditionally from 12243 // a constant. Vectors only. 12244 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 12245 return Res; 12246 12247 EVT VT = N->getValueType(0); 12248 if (VT != MVT::f32 && VT != MVT::f64) 12249 return SDValue(); 12250 12251 // Only optimize when the source and destination types have the same width. 12252 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 12253 return SDValue(); 12254 12255 // If the result of an integer load is only used by an integer-to-float 12256 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 12257 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 12258 SDValue N0 = N->getOperand(0); 12259 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12260 // Do not change the width of a volatile load. 12261 !cast<LoadSDNode>(N0)->isVolatile()) { 12262 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12263 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 12264 LN0->getPointerInfo(), LN0->getAlignment(), 12265 LN0->getMemOperand()->getFlags()); 12266 12267 // Make sure successors of the original load stay after it by updating them 12268 // to use the new Chain. 12269 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 12270 12271 unsigned Opcode = 12272 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 12273 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 12274 } 12275 12276 return SDValue(); 12277 } 12278 12279 /// Fold a floating-point multiply by power of two into floating-point to 12280 /// fixed-point conversion. 12281 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 12282 TargetLowering::DAGCombinerInfo &DCI, 12283 const AArch64Subtarget *Subtarget) { 12284 if (!Subtarget->hasNEON()) 12285 return SDValue(); 12286 12287 if (!N->getValueType(0).isSimple()) 12288 return SDValue(); 12289 12290 SDValue Op = N->getOperand(0); 12291 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12292 Op.getOpcode() != ISD::FMUL) 12293 return SDValue(); 12294 12295 SDValue ConstVec = Op->getOperand(1); 12296 if (!isa<BuildVectorSDNode>(ConstVec)) 12297 return SDValue(); 12298 12299 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12300 uint32_t FloatBits = FloatTy.getSizeInBits(); 12301 if (FloatBits != 32 && FloatBits != 64) 12302 return SDValue(); 12303 12304 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12305 uint32_t IntBits = IntTy.getSizeInBits(); 12306 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 12307 return SDValue(); 12308 12309 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 12310 if (IntBits > FloatBits) 12311 return SDValue(); 12312 12313 BitVector UndefElements; 12314 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12315 int32_t Bits = IntBits == 64 ? 64 : 32; 12316 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 12317 if (C == -1 || C == 0 || C > Bits) 12318 return SDValue(); 12319 12320 MVT ResTy; 12321 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12322 switch (NumLanes) { 12323 default: 12324 return SDValue(); 12325 case 2: 12326 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 12327 break; 12328 case 4: 12329 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 12330 break; 12331 } 12332 12333 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 12334 return SDValue(); 12335 12336 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 12337 "Illegal vector type after legalization"); 12338 12339 SDLoc DL(N); 12340 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 12341 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 12342 : Intrinsic::aarch64_neon_vcvtfp2fxu; 12343 SDValue FixConv = 12344 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 12345 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 12346 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 12347 // We can handle smaller integers by generating an extra trunc. 12348 if (IntBits < FloatBits) 12349 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 12350 12351 return FixConv; 12352 } 12353 12354 /// Fold a floating-point divide by power of two into fixed-point to 12355 /// floating-point conversion. 12356 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 12357 TargetLowering::DAGCombinerInfo &DCI, 12358 const AArch64Subtarget *Subtarget) { 12359 if (!Subtarget->hasNEON()) 12360 return SDValue(); 12361 12362 SDValue Op = N->getOperand(0); 12363 unsigned Opc = Op->getOpcode(); 12364 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12365 !Op.getOperand(0).getValueType().isSimple() || 12366 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 12367 return SDValue(); 12368 12369 SDValue ConstVec = N->getOperand(1); 12370 if (!isa<BuildVectorSDNode>(ConstVec)) 12371 return SDValue(); 12372 12373 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12374 int32_t IntBits = IntTy.getSizeInBits(); 12375 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 12376 return SDValue(); 12377 12378 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12379 int32_t FloatBits = FloatTy.getSizeInBits(); 12380 if (FloatBits != 32 && FloatBits != 64) 12381 return SDValue(); 12382 12383 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 12384 if (IntBits > FloatBits) 12385 return SDValue(); 12386 12387 BitVector UndefElements; 12388 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12389 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 12390 if (C == -1 || C == 0 || C > FloatBits) 12391 return SDValue(); 12392 12393 MVT ResTy; 12394 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12395 switch (NumLanes) { 12396 default: 12397 return SDValue(); 12398 case 2: 12399 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 12400 break; 12401 case 4: 12402 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 12403 break; 12404 } 12405 12406 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 12407 return SDValue(); 12408 12409 SDLoc DL(N); 12410 SDValue ConvInput = Op.getOperand(0); 12411 bool IsSigned = Opc == ISD::SINT_TO_FP; 12412 if (IntBits < FloatBits) 12413 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 12414 ResTy, ConvInput); 12415 12416 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 12417 : Intrinsic::aarch64_neon_vcvtfxu2fp; 12418 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 12419 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 12420 DAG.getConstant(C, DL, MVT::i32)); 12421 } 12422 12423 /// An EXTR instruction is made up of two shifts, ORed together. This helper 12424 /// searches for and classifies those shifts. 12425 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 12426 bool &FromHi) { 12427 if (N.getOpcode() == ISD::SHL) 12428 FromHi = false; 12429 else if (N.getOpcode() == ISD::SRL) 12430 FromHi = true; 12431 else 12432 return false; 12433 12434 if (!isa<ConstantSDNode>(N.getOperand(1))) 12435 return false; 12436 12437 ShiftAmount = N->getConstantOperandVal(1); 12438 Src = N->getOperand(0); 12439 return true; 12440 } 12441 12442 /// EXTR instruction extracts a contiguous chunk of bits from two existing 12443 /// registers viewed as a high/low pair. This function looks for the pattern: 12444 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 12445 /// with an EXTR. Can't quite be done in TableGen because the two immediates 12446 /// aren't independent. 12447 static SDValue tryCombineToEXTR(SDNode *N, 12448 TargetLowering::DAGCombinerInfo &DCI) { 12449 SelectionDAG &DAG = DCI.DAG; 12450 SDLoc DL(N); 12451 EVT VT = N->getValueType(0); 12452 12453 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 12454 12455 if (VT != MVT::i32 && VT != MVT::i64) 12456 return SDValue(); 12457 12458 SDValue LHS; 12459 uint32_t ShiftLHS = 0; 12460 bool LHSFromHi = false; 12461 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 12462 return SDValue(); 12463 12464 SDValue RHS; 12465 uint32_t ShiftRHS = 0; 12466 bool RHSFromHi = false; 12467 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 12468 return SDValue(); 12469 12470 // If they're both trying to come from the high part of the register, they're 12471 // not really an EXTR. 12472 if (LHSFromHi == RHSFromHi) 12473 return SDValue(); 12474 12475 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 12476 return SDValue(); 12477 12478 if (LHSFromHi) { 12479 std::swap(LHS, RHS); 12480 std::swap(ShiftLHS, ShiftRHS); 12481 } 12482 12483 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 12484 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 12485 } 12486 12487 static SDValue tryCombineToBSL(SDNode *N, 12488 TargetLowering::DAGCombinerInfo &DCI) { 12489 EVT VT = N->getValueType(0); 12490 SelectionDAG &DAG = DCI.DAG; 12491 SDLoc DL(N); 12492 12493 if (!VT.isVector()) 12494 return SDValue(); 12495 12496 SDValue N0 = N->getOperand(0); 12497 if (N0.getOpcode() != ISD::AND) 12498 return SDValue(); 12499 12500 SDValue N1 = N->getOperand(1); 12501 if (N1.getOpcode() != ISD::AND) 12502 return SDValue(); 12503 12504 // We only have to look for constant vectors here since the general, variable 12505 // case can be handled in TableGen. 12506 unsigned Bits = VT.getScalarSizeInBits(); 12507 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 12508 for (int i = 1; i >= 0; --i) 12509 for (int j = 1; j >= 0; --j) { 12510 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 12511 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 12512 if (!BVN0 || !BVN1) 12513 continue; 12514 12515 bool FoundMatch = true; 12516 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 12517 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 12518 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 12519 if (!CN0 || !CN1 || 12520 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 12521 FoundMatch = false; 12522 break; 12523 } 12524 } 12525 12526 if (FoundMatch) 12527 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0), 12528 N0->getOperand(1 - i), N1->getOperand(1 - j)); 12529 } 12530 12531 return SDValue(); 12532 } 12533 12534 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12535 const AArch64Subtarget *Subtarget) { 12536 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 12537 SelectionDAG &DAG = DCI.DAG; 12538 EVT VT = N->getValueType(0); 12539 12540 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12541 return SDValue(); 12542 12543 if (SDValue Res = tryCombineToEXTR(N, DCI)) 12544 return Res; 12545 12546 if (SDValue Res = tryCombineToBSL(N, DCI)) 12547 return Res; 12548 12549 return SDValue(); 12550 } 12551 12552 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) { 12553 if (!MemVT.getVectorElementType().isSimple()) 12554 return false; 12555 12556 uint64_t MaskForTy = 0ull; 12557 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) { 12558 case MVT::i8: 12559 MaskForTy = 0xffull; 12560 break; 12561 case MVT::i16: 12562 MaskForTy = 0xffffull; 12563 break; 12564 case MVT::i32: 12565 MaskForTy = 0xffffffffull; 12566 break; 12567 default: 12568 return false; 12569 break; 12570 } 12571 12572 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR) 12573 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) 12574 return Op0->getAPIntValue().getLimitedValue() == MaskForTy; 12575 12576 return false; 12577 } 12578 12579 static SDValue performSVEAndCombine(SDNode *N, 12580 TargetLowering::DAGCombinerInfo &DCI) { 12581 if (DCI.isBeforeLegalizeOps()) 12582 return SDValue(); 12583 12584 SelectionDAG &DAG = DCI.DAG; 12585 SDValue Src = N->getOperand(0); 12586 unsigned Opc = Src->getOpcode(); 12587 12588 // Zero/any extend of an unsigned unpack 12589 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 12590 SDValue UnpkOp = Src->getOperand(0); 12591 SDValue Dup = N->getOperand(1); 12592 12593 if (Dup.getOpcode() != AArch64ISD::DUP) 12594 return SDValue(); 12595 12596 SDLoc DL(N); 12597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0)); 12598 uint64_t ExtVal = C->getZExtValue(); 12599 12600 // If the mask is fully covered by the unpack, we don't need to push 12601 // a new AND onto the operand 12602 EVT EltTy = UnpkOp->getValueType(0).getVectorElementType(); 12603 if ((ExtVal == 0xFF && EltTy == MVT::i8) || 12604 (ExtVal == 0xFFFF && EltTy == MVT::i16) || 12605 (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32)) 12606 return Src; 12607 12608 // Truncate to prevent a DUP with an over wide constant 12609 APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits()); 12610 12611 // Otherwise, make sure we propagate the AND to the operand 12612 // of the unpack 12613 Dup = DAG.getNode(AArch64ISD::DUP, DL, 12614 UnpkOp->getValueType(0), 12615 DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32)); 12616 12617 SDValue And = DAG.getNode(ISD::AND, DL, 12618 UnpkOp->getValueType(0), UnpkOp, Dup); 12619 12620 return DAG.getNode(Opc, DL, N->getValueType(0), And); 12621 } 12622 12623 if (!EnableCombineMGatherIntrinsics) 12624 return SDValue(); 12625 12626 SDValue Mask = N->getOperand(1); 12627 12628 if (!Src.hasOneUse()) 12629 return SDValue(); 12630 12631 EVT MemVT; 12632 12633 // SVE load instructions perform an implicit zero-extend, which makes them 12634 // perfect candidates for combining. 12635 switch (Opc) { 12636 case AArch64ISD::LD1_MERGE_ZERO: 12637 case AArch64ISD::LDNF1_MERGE_ZERO: 12638 case AArch64ISD::LDFF1_MERGE_ZERO: 12639 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT(); 12640 break; 12641 case AArch64ISD::GLD1_MERGE_ZERO: 12642 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 12643 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 12644 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 12645 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 12646 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 12647 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 12648 case AArch64ISD::GLDFF1_MERGE_ZERO: 12649 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO: 12650 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO: 12651 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO: 12652 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO: 12653 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO: 12654 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO: 12655 case AArch64ISD::GLDNT1_MERGE_ZERO: 12656 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT(); 12657 break; 12658 default: 12659 return SDValue(); 12660 } 12661 12662 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT)) 12663 return Src; 12664 12665 return SDValue(); 12666 } 12667 12668 static SDValue performANDCombine(SDNode *N, 12669 TargetLowering::DAGCombinerInfo &DCI) { 12670 SelectionDAG &DAG = DCI.DAG; 12671 SDValue LHS = N->getOperand(0); 12672 EVT VT = N->getValueType(0); 12673 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12674 return SDValue(); 12675 12676 if (VT.isScalableVector()) 12677 return performSVEAndCombine(N, DCI); 12678 12679 // The combining code below works only for NEON vectors. In particular, it 12680 // does not work for SVE when dealing with vectors wider than 128 bits. 12681 if (!(VT.is64BitVector() || VT.is128BitVector())) 12682 return SDValue(); 12683 12684 BuildVectorSDNode *BVN = 12685 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 12686 if (!BVN) 12687 return SDValue(); 12688 12689 // AND does not accept an immediate, so check if we can use a BIC immediate 12690 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 12691 // pattern in isel, because some immediates may be lowered to the preferred 12692 // (and x, (movi imm)) form, even though an mvni representation also exists. 12693 APInt DefBits(VT.getSizeInBits(), 0); 12694 APInt UndefBits(VT.getSizeInBits(), 0); 12695 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 12696 SDValue NewOp; 12697 12698 DefBits = ~DefBits; 12699 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 12700 DefBits, &LHS)) || 12701 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 12702 DefBits, &LHS))) 12703 return NewOp; 12704 12705 UndefBits = ~UndefBits; 12706 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 12707 UndefBits, &LHS)) || 12708 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 12709 UndefBits, &LHS))) 12710 return NewOp; 12711 } 12712 12713 return SDValue(); 12714 } 12715 12716 static SDValue performSRLCombine(SDNode *N, 12717 TargetLowering::DAGCombinerInfo &DCI) { 12718 SelectionDAG &DAG = DCI.DAG; 12719 EVT VT = N->getValueType(0); 12720 if (VT != MVT::i32 && VT != MVT::i64) 12721 return SDValue(); 12722 12723 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 12724 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 12725 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 12726 SDValue N0 = N->getOperand(0); 12727 if (N0.getOpcode() == ISD::BSWAP) { 12728 SDLoc DL(N); 12729 SDValue N1 = N->getOperand(1); 12730 SDValue N00 = N0.getOperand(0); 12731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12732 uint64_t ShiftAmt = C->getZExtValue(); 12733 if (VT == MVT::i32 && ShiftAmt == 16 && 12734 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 12735 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 12736 if (VT == MVT::i64 && ShiftAmt == 32 && 12737 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 12738 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 12739 } 12740 } 12741 return SDValue(); 12742 } 12743 12744 // Attempt to form urhadd(OpA, OpB) from 12745 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1)) 12746 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)). 12747 // The original form of the first expression is 12748 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the 12749 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)). 12750 // Before this function is called the srl will have been lowered to 12751 // AArch64ISD::VLSHR. 12752 // This pass can also recognize signed variants of the patterns that use sign 12753 // extension instead of zero extension and form a srhadd(OpA, OpB) or a 12754 // shadd(OpA, OpB) from them. 12755 static SDValue 12756 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12757 SelectionDAG &DAG) { 12758 EVT VT = N->getValueType(0); 12759 12760 // Since we are looking for a right shift by a constant value of 1 and we are 12761 // operating on types at least 16 bits in length (sign/zero extended OpA and 12762 // OpB, which are at least 8 bits), it follows that the truncate will always 12763 // discard the shifted-in bit and therefore the right shift will be logical 12764 // regardless of the signedness of OpA and OpB. 12765 SDValue Shift = N->getOperand(0); 12766 if (Shift.getOpcode() != AArch64ISD::VLSHR) 12767 return SDValue(); 12768 12769 // Is the right shift using an immediate value of 1? 12770 uint64_t ShiftAmount = Shift.getConstantOperandVal(1); 12771 if (ShiftAmount != 1) 12772 return SDValue(); 12773 12774 SDValue ExtendOpA, ExtendOpB; 12775 SDValue ShiftOp0 = Shift.getOperand(0); 12776 unsigned ShiftOp0Opc = ShiftOp0.getOpcode(); 12777 if (ShiftOp0Opc == ISD::SUB) { 12778 12779 SDValue Xor = ShiftOp0.getOperand(1); 12780 if (Xor.getOpcode() != ISD::XOR) 12781 return SDValue(); 12782 12783 // Is the XOR using a constant amount of all ones in the right hand side? 12784 uint64_t C; 12785 if (!isAllConstantBuildVector(Xor.getOperand(1), C)) 12786 return SDValue(); 12787 12788 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 12789 APInt CAsAPInt(ElemSizeInBits, C); 12790 if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits)) 12791 return SDValue(); 12792 12793 ExtendOpA = Xor.getOperand(0); 12794 ExtendOpB = ShiftOp0.getOperand(0); 12795 } else if (ShiftOp0Opc == ISD::ADD) { 12796 ExtendOpA = ShiftOp0.getOperand(0); 12797 ExtendOpB = ShiftOp0.getOperand(1); 12798 } else 12799 return SDValue(); 12800 12801 unsigned ExtendOpAOpc = ExtendOpA.getOpcode(); 12802 unsigned ExtendOpBOpc = ExtendOpB.getOpcode(); 12803 if (!(ExtendOpAOpc == ExtendOpBOpc && 12804 (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND))) 12805 return SDValue(); 12806 12807 // Is the result of the right shift being truncated to the same value type as 12808 // the original operands, OpA and OpB? 12809 SDValue OpA = ExtendOpA.getOperand(0); 12810 SDValue OpB = ExtendOpB.getOperand(0); 12811 EVT OpAVT = OpA.getValueType(); 12812 assert(ExtendOpA.getValueType() == ExtendOpB.getValueType()); 12813 if (!(VT == OpAVT && OpAVT == OpB.getValueType())) 12814 return SDValue(); 12815 12816 SDLoc DL(N); 12817 bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND; 12818 bool IsRHADD = ShiftOp0Opc == ISD::SUB; 12819 unsigned HADDOpc = IsSignExtend 12820 ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD) 12821 : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD); 12822 SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB); 12823 12824 return ResultHADD; 12825 } 12826 12827 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) { 12828 switch (Opcode) { 12829 case ISD::FADD: 12830 return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64; 12831 case ISD::ADD: 12832 return VT == MVT::i64; 12833 default: 12834 return false; 12835 } 12836 } 12837 12838 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) { 12839 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 12840 ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1); 12841 12842 EVT VT = N->getValueType(0); 12843 const bool FullFP16 = 12844 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 12845 12846 // Rewrite for pairwise fadd pattern 12847 // (f32 (extract_vector_elt 12848 // (fadd (vXf32 Other) 12849 // (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0)) 12850 // -> 12851 // (f32 (fadd (extract_vector_elt (vXf32 Other) 0) 12852 // (extract_vector_elt (vXf32 Other) 1)) 12853 if (ConstantN1 && ConstantN1->getZExtValue() == 0 && 12854 hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) { 12855 SDLoc DL(N0); 12856 SDValue N00 = N0->getOperand(0); 12857 SDValue N01 = N0->getOperand(1); 12858 12859 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01); 12860 SDValue Other = N00; 12861 12862 // And handle the commutative case. 12863 if (!Shuffle) { 12864 Shuffle = dyn_cast<ShuffleVectorSDNode>(N00); 12865 Other = N01; 12866 } 12867 12868 if (Shuffle && Shuffle->getMaskElt(0) == 1 && 12869 Other == Shuffle->getOperand(0)) { 12870 return DAG.getNode(N0->getOpcode(), DL, VT, 12871 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other, 12872 DAG.getConstant(0, DL, MVT::i64)), 12873 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other, 12874 DAG.getConstant(1, DL, MVT::i64))); 12875 } 12876 } 12877 12878 return SDValue(); 12879 } 12880 12881 static SDValue performConcatVectorsCombine(SDNode *N, 12882 TargetLowering::DAGCombinerInfo &DCI, 12883 SelectionDAG &DAG) { 12884 SDLoc dl(N); 12885 EVT VT = N->getValueType(0); 12886 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 12887 unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode(); 12888 12889 // Optimize concat_vectors of truncated vectors, where the intermediate 12890 // type is illegal, to avoid said illegality, e.g., 12891 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 12892 // (v2i16 (truncate (v2i64))))) 12893 // -> 12894 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 12895 // (v4i32 (bitcast (v2i64))), 12896 // <0, 2, 4, 6>))) 12897 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 12898 // on both input and result type, so we might generate worse code. 12899 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 12900 if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE && 12901 N1Opc == ISD::TRUNCATE) { 12902 SDValue N00 = N0->getOperand(0); 12903 SDValue N10 = N1->getOperand(0); 12904 EVT N00VT = N00.getValueType(); 12905 12906 if (N00VT == N10.getValueType() && 12907 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 12908 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 12909 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 12910 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 12911 for (size_t i = 0; i < Mask.size(); ++i) 12912 Mask[i] = i * 2; 12913 return DAG.getNode(ISD::TRUNCATE, dl, VT, 12914 DAG.getVectorShuffle( 12915 MidVT, dl, 12916 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 12917 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 12918 } 12919 } 12920 12921 // Wait 'til after everything is legalized to try this. That way we have 12922 // legal vector types and such. 12923 if (DCI.isBeforeLegalizeOps()) 12924 return SDValue(); 12925 12926 // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted 12927 // subvectors from the same original vectors. Combine these into a single 12928 // [us]rhadd or [us]hadd that operates on the two original vectors. Example: 12929 // (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>), 12930 // extract_subvector (v16i8 OpB, 12931 // <0>))), 12932 // (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>), 12933 // extract_subvector (v16i8 OpB, 12934 // <8>))))) 12935 // -> 12936 // (v16i8(urhadd(v16i8 OpA, v16i8 OpB))) 12937 if (N->getNumOperands() == 2 && N0Opc == N1Opc && 12938 (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD || 12939 N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) { 12940 SDValue N00 = N0->getOperand(0); 12941 SDValue N01 = N0->getOperand(1); 12942 SDValue N10 = N1->getOperand(0); 12943 SDValue N11 = N1->getOperand(1); 12944 12945 EVT N00VT = N00.getValueType(); 12946 EVT N10VT = N10.getValueType(); 12947 12948 if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR && 12949 N01->getOpcode() == ISD::EXTRACT_SUBVECTOR && 12950 N10->getOpcode() == ISD::EXTRACT_SUBVECTOR && 12951 N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) { 12952 SDValue N00Source = N00->getOperand(0); 12953 SDValue N01Source = N01->getOperand(0); 12954 SDValue N10Source = N10->getOperand(0); 12955 SDValue N11Source = N11->getOperand(0); 12956 12957 if (N00Source == N10Source && N01Source == N11Source && 12958 N00Source.getValueType() == VT && N01Source.getValueType() == VT) { 12959 assert(N0.getValueType() == N1.getValueType()); 12960 12961 uint64_t N00Index = N00.getConstantOperandVal(1); 12962 uint64_t N01Index = N01.getConstantOperandVal(1); 12963 uint64_t N10Index = N10.getConstantOperandVal(1); 12964 uint64_t N11Index = N11.getConstantOperandVal(1); 12965 12966 if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 && 12967 N10Index == N00VT.getVectorNumElements()) 12968 return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source); 12969 } 12970 } 12971 } 12972 12973 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 12974 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 12975 // canonicalise to that. 12976 if (N0 == N1 && VT.getVectorNumElements() == 2) { 12977 assert(VT.getScalarSizeInBits() == 64); 12978 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 12979 DAG.getConstant(0, dl, MVT::i64)); 12980 } 12981 12982 // Canonicalise concat_vectors so that the right-hand vector has as few 12983 // bit-casts as possible before its real operation. The primary matching 12984 // destination for these operations will be the narrowing "2" instructions, 12985 // which depend on the operation being performed on this right-hand vector. 12986 // For example, 12987 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 12988 // becomes 12989 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 12990 12991 if (N1Opc != ISD::BITCAST) 12992 return SDValue(); 12993 SDValue RHS = N1->getOperand(0); 12994 MVT RHSTy = RHS.getValueType().getSimpleVT(); 12995 // If the RHS is not a vector, this is not the pattern we're looking for. 12996 if (!RHSTy.isVector()) 12997 return SDValue(); 12998 12999 LLVM_DEBUG( 13000 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 13001 13002 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 13003 RHSTy.getVectorNumElements() * 2); 13004 return DAG.getNode(ISD::BITCAST, dl, VT, 13005 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 13006 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 13007 RHS)); 13008 } 13009 13010 static SDValue tryCombineFixedPointConvert(SDNode *N, 13011 TargetLowering::DAGCombinerInfo &DCI, 13012 SelectionDAG &DAG) { 13013 // Wait until after everything is legalized to try this. That way we have 13014 // legal vector types and such. 13015 if (DCI.isBeforeLegalizeOps()) 13016 return SDValue(); 13017 // Transform a scalar conversion of a value from a lane extract into a 13018 // lane extract of a vector conversion. E.g., from foo1 to foo2: 13019 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 13020 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 13021 // 13022 // The second form interacts better with instruction selection and the 13023 // register allocator to avoid cross-class register copies that aren't 13024 // coalescable due to a lane reference. 13025 13026 // Check the operand and see if it originates from a lane extract. 13027 SDValue Op1 = N->getOperand(1); 13028 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13029 // Yep, no additional predication needed. Perform the transform. 13030 SDValue IID = N->getOperand(0); 13031 SDValue Shift = N->getOperand(2); 13032 SDValue Vec = Op1.getOperand(0); 13033 SDValue Lane = Op1.getOperand(1); 13034 EVT ResTy = N->getValueType(0); 13035 EVT VecResTy; 13036 SDLoc DL(N); 13037 13038 // The vector width should be 128 bits by the time we get here, even 13039 // if it started as 64 bits (the extract_vector handling will have 13040 // done so). 13041 assert(Vec.getValueSizeInBits() == 128 && 13042 "unexpected vector size on extract_vector_elt!"); 13043 if (Vec.getValueType() == MVT::v4i32) 13044 VecResTy = MVT::v4f32; 13045 else if (Vec.getValueType() == MVT::v2i64) 13046 VecResTy = MVT::v2f64; 13047 else 13048 llvm_unreachable("unexpected vector type!"); 13049 13050 SDValue Convert = 13051 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 13052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 13053 } 13054 return SDValue(); 13055 } 13056 13057 // AArch64 high-vector "long" operations are formed by performing the non-high 13058 // version on an extract_subvector of each operand which gets the high half: 13059 // 13060 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 13061 // 13062 // However, there are cases which don't have an extract_high explicitly, but 13063 // have another operation that can be made compatible with one for free. For 13064 // example: 13065 // 13066 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 13067 // 13068 // This routine does the actual conversion of such DUPs, once outer routines 13069 // have determined that everything else is in order. 13070 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 13071 // similarly here. 13072 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 13073 switch (N.getOpcode()) { 13074 case AArch64ISD::DUP: 13075 case AArch64ISD::DUPLANE8: 13076 case AArch64ISD::DUPLANE16: 13077 case AArch64ISD::DUPLANE32: 13078 case AArch64ISD::DUPLANE64: 13079 case AArch64ISD::MOVI: 13080 case AArch64ISD::MOVIshift: 13081 case AArch64ISD::MOVIedit: 13082 case AArch64ISD::MOVImsl: 13083 case AArch64ISD::MVNIshift: 13084 case AArch64ISD::MVNImsl: 13085 break; 13086 default: 13087 // FMOV could be supported, but isn't very useful, as it would only occur 13088 // if you passed a bitcast' floating point immediate to an eligible long 13089 // integer op (addl, smull, ...). 13090 return SDValue(); 13091 } 13092 13093 MVT NarrowTy = N.getSimpleValueType(); 13094 if (!NarrowTy.is64BitVector()) 13095 return SDValue(); 13096 13097 MVT ElementTy = NarrowTy.getVectorElementType(); 13098 unsigned NumElems = NarrowTy.getVectorNumElements(); 13099 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 13100 13101 SDLoc dl(N); 13102 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 13103 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 13104 DAG.getConstant(NumElems, dl, MVT::i64)); 13105 } 13106 13107 static bool isEssentiallyExtractHighSubvector(SDValue N) { 13108 if (N.getOpcode() == ISD::BITCAST) 13109 N = N.getOperand(0); 13110 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13111 return false; 13112 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 13113 N.getOperand(0).getValueType().getVectorNumElements() / 2; 13114 } 13115 13116 /// Helper structure to keep track of ISD::SET_CC operands. 13117 struct GenericSetCCInfo { 13118 const SDValue *Opnd0; 13119 const SDValue *Opnd1; 13120 ISD::CondCode CC; 13121 }; 13122 13123 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 13124 struct AArch64SetCCInfo { 13125 const SDValue *Cmp; 13126 AArch64CC::CondCode CC; 13127 }; 13128 13129 /// Helper structure to keep track of SetCC information. 13130 union SetCCInfo { 13131 GenericSetCCInfo Generic; 13132 AArch64SetCCInfo AArch64; 13133 }; 13134 13135 /// Helper structure to be able to read SetCC information. If set to 13136 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 13137 /// GenericSetCCInfo. 13138 struct SetCCInfoAndKind { 13139 SetCCInfo Info; 13140 bool IsAArch64; 13141 }; 13142 13143 /// Check whether or not \p Op is a SET_CC operation, either a generic or 13144 /// an 13145 /// AArch64 lowered one. 13146 /// \p SetCCInfo is filled accordingly. 13147 /// \post SetCCInfo is meanginfull only when this function returns true. 13148 /// \return True when Op is a kind of SET_CC operation. 13149 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 13150 // If this is a setcc, this is straight forward. 13151 if (Op.getOpcode() == ISD::SETCC) { 13152 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 13153 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 13154 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 13155 SetCCInfo.IsAArch64 = false; 13156 return true; 13157 } 13158 // Otherwise, check if this is a matching csel instruction. 13159 // In other words: 13160 // - csel 1, 0, cc 13161 // - csel 0, 1, !cc 13162 if (Op.getOpcode() != AArch64ISD::CSEL) 13163 return false; 13164 // Set the information about the operands. 13165 // TODO: we want the operands of the Cmp not the csel 13166 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 13167 SetCCInfo.IsAArch64 = true; 13168 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 13169 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 13170 13171 // Check that the operands matches the constraints: 13172 // (1) Both operands must be constants. 13173 // (2) One must be 1 and the other must be 0. 13174 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 13175 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13176 13177 // Check (1). 13178 if (!TValue || !FValue) 13179 return false; 13180 13181 // Check (2). 13182 if (!TValue->isOne()) { 13183 // Update the comparison when we are interested in !cc. 13184 std::swap(TValue, FValue); 13185 SetCCInfo.Info.AArch64.CC = 13186 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 13187 } 13188 return TValue->isOne() && FValue->isNullValue(); 13189 } 13190 13191 // Returns true if Op is setcc or zext of setcc. 13192 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 13193 if (isSetCC(Op, Info)) 13194 return true; 13195 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 13196 isSetCC(Op->getOperand(0), Info)); 13197 } 13198 13199 // The folding we want to perform is: 13200 // (add x, [zext] (setcc cc ...) ) 13201 // --> 13202 // (csel x, (add x, 1), !cc ...) 13203 // 13204 // The latter will get matched to a CSINC instruction. 13205 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 13206 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 13207 SDValue LHS = Op->getOperand(0); 13208 SDValue RHS = Op->getOperand(1); 13209 SetCCInfoAndKind InfoAndKind; 13210 13211 // If both operands are a SET_CC, then we don't want to perform this 13212 // folding and create another csel as this results in more instructions 13213 // (and higher register usage). 13214 if (isSetCCOrZExtSetCC(LHS, InfoAndKind) && 13215 isSetCCOrZExtSetCC(RHS, InfoAndKind)) 13216 return SDValue(); 13217 13218 // If neither operand is a SET_CC, give up. 13219 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 13220 std::swap(LHS, RHS); 13221 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 13222 return SDValue(); 13223 } 13224 13225 // FIXME: This could be generatized to work for FP comparisons. 13226 EVT CmpVT = InfoAndKind.IsAArch64 13227 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 13228 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 13229 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 13230 return SDValue(); 13231 13232 SDValue CCVal; 13233 SDValue Cmp; 13234 SDLoc dl(Op); 13235 if (InfoAndKind.IsAArch64) { 13236 CCVal = DAG.getConstant( 13237 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 13238 MVT::i32); 13239 Cmp = *InfoAndKind.Info.AArch64.Cmp; 13240 } else 13241 Cmp = getAArch64Cmp( 13242 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, 13243 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG, 13244 dl); 13245 13246 EVT VT = Op->getValueType(0); 13247 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 13248 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 13249 } 13250 13251 // ADD(UADDV a, UADDV b) --> UADDV(ADD a, b) 13252 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) { 13253 EVT VT = N->getValueType(0); 13254 // Only scalar integer and vector types. 13255 if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger()) 13256 return SDValue(); 13257 13258 SDValue LHS = N->getOperand(0); 13259 SDValue RHS = N->getOperand(1); 13260 if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13261 RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT) 13262 return SDValue(); 13263 13264 auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 13265 auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1)); 13266 if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue()) 13267 return SDValue(); 13268 13269 SDValue Op1 = LHS->getOperand(0); 13270 SDValue Op2 = RHS->getOperand(0); 13271 EVT OpVT1 = Op1.getValueType(); 13272 EVT OpVT2 = Op2.getValueType(); 13273 if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 || 13274 Op2.getOpcode() != AArch64ISD::UADDV || 13275 OpVT1.getVectorElementType() != VT) 13276 return SDValue(); 13277 13278 SDValue Val1 = Op1.getOperand(0); 13279 SDValue Val2 = Op2.getOperand(0); 13280 EVT ValVT = Val1->getValueType(0); 13281 SDLoc DL(N); 13282 SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2); 13283 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 13284 DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal), 13285 DAG.getConstant(0, DL, MVT::i64)); 13286 } 13287 13288 // ADD(UDOT(zero, x, y), A) --> UDOT(A, x, y) 13289 static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) { 13290 EVT VT = N->getValueType(0); 13291 if (N->getOpcode() != ISD::ADD) 13292 return SDValue(); 13293 13294 SDValue Dot = N->getOperand(0); 13295 SDValue A = N->getOperand(1); 13296 // Handle commutivity 13297 auto isZeroDot = [](SDValue Dot) { 13298 return (Dot.getOpcode() == AArch64ISD::UDOT || 13299 Dot.getOpcode() == AArch64ISD::SDOT) && 13300 ISD::isBuildVectorAllZeros(Dot.getOperand(0).getNode()); 13301 }; 13302 if (!isZeroDot(Dot)) 13303 std::swap(Dot, A); 13304 if (!isZeroDot(Dot)) 13305 return SDValue(); 13306 13307 return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1), 13308 Dot.getOperand(2)); 13309 } 13310 13311 // The basic add/sub long vector instructions have variants with "2" on the end 13312 // which act on the high-half of their inputs. They are normally matched by 13313 // patterns like: 13314 // 13315 // (add (zeroext (extract_high LHS)), 13316 // (zeroext (extract_high RHS))) 13317 // -> uaddl2 vD, vN, vM 13318 // 13319 // However, if one of the extracts is something like a duplicate, this 13320 // instruction can still be used profitably. This function puts the DAG into a 13321 // more appropriate form for those patterns to trigger. 13322 static SDValue performAddSubLongCombine(SDNode *N, 13323 TargetLowering::DAGCombinerInfo &DCI, 13324 SelectionDAG &DAG) { 13325 if (DCI.isBeforeLegalizeOps()) 13326 return SDValue(); 13327 13328 MVT VT = N->getSimpleValueType(0); 13329 if (!VT.is128BitVector()) { 13330 if (N->getOpcode() == ISD::ADD) 13331 return performSetccAddFolding(N, DAG); 13332 return SDValue(); 13333 } 13334 13335 // Make sure both branches are extended in the same way. 13336 SDValue LHS = N->getOperand(0); 13337 SDValue RHS = N->getOperand(1); 13338 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 13339 LHS.getOpcode() != ISD::SIGN_EXTEND) || 13340 LHS.getOpcode() != RHS.getOpcode()) 13341 return SDValue(); 13342 13343 unsigned ExtType = LHS.getOpcode(); 13344 13345 // It's not worth doing if at least one of the inputs isn't already an 13346 // extract, but we don't know which it'll be so we have to try both. 13347 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 13348 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 13349 if (!RHS.getNode()) 13350 return SDValue(); 13351 13352 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 13353 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 13354 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 13355 if (!LHS.getNode()) 13356 return SDValue(); 13357 13358 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 13359 } 13360 13361 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 13362 } 13363 13364 static SDValue performAddSubCombine(SDNode *N, 13365 TargetLowering::DAGCombinerInfo &DCI, 13366 SelectionDAG &DAG) { 13367 // Try to change sum of two reductions. 13368 if (SDValue Val = performUADDVCombine(N, DAG)) 13369 return Val; 13370 if (SDValue Val = performAddDotCombine(N, DAG)) 13371 return Val; 13372 13373 return performAddSubLongCombine(N, DCI, DAG); 13374 } 13375 13376 // Massage DAGs which we can use the high-half "long" operations on into 13377 // something isel will recognize better. E.g. 13378 // 13379 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 13380 // (aarch64_neon_umull (extract_high (v2i64 vec))) 13381 // (extract_high (v2i64 (dup128 scalar))))) 13382 // 13383 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 13384 TargetLowering::DAGCombinerInfo &DCI, 13385 SelectionDAG &DAG) { 13386 if (DCI.isBeforeLegalizeOps()) 13387 return SDValue(); 13388 13389 SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1); 13390 SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2); 13391 assert(LHS.getValueType().is64BitVector() && 13392 RHS.getValueType().is64BitVector() && 13393 "unexpected shape for long operation"); 13394 13395 // Either node could be a DUP, but it's not worth doing both of them (you'd 13396 // just as well use the non-high version) so look for a corresponding extract 13397 // operation on the other "wing". 13398 if (isEssentiallyExtractHighSubvector(LHS)) { 13399 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 13400 if (!RHS.getNode()) 13401 return SDValue(); 13402 } else if (isEssentiallyExtractHighSubvector(RHS)) { 13403 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 13404 if (!LHS.getNode()) 13405 return SDValue(); 13406 } 13407 13408 if (IID == Intrinsic::not_intrinsic) 13409 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS); 13410 13411 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 13412 N->getOperand(0), LHS, RHS); 13413 } 13414 13415 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 13416 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 13417 unsigned ElemBits = ElemTy.getSizeInBits(); 13418 13419 int64_t ShiftAmount; 13420 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 13421 APInt SplatValue, SplatUndef; 13422 unsigned SplatBitSize; 13423 bool HasAnyUndefs; 13424 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 13425 HasAnyUndefs, ElemBits) || 13426 SplatBitSize != ElemBits) 13427 return SDValue(); 13428 13429 ShiftAmount = SplatValue.getSExtValue(); 13430 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 13431 ShiftAmount = CVN->getSExtValue(); 13432 } else 13433 return SDValue(); 13434 13435 unsigned Opcode; 13436 bool IsRightShift; 13437 switch (IID) { 13438 default: 13439 llvm_unreachable("Unknown shift intrinsic"); 13440 case Intrinsic::aarch64_neon_sqshl: 13441 Opcode = AArch64ISD::SQSHL_I; 13442 IsRightShift = false; 13443 break; 13444 case Intrinsic::aarch64_neon_uqshl: 13445 Opcode = AArch64ISD::UQSHL_I; 13446 IsRightShift = false; 13447 break; 13448 case Intrinsic::aarch64_neon_srshl: 13449 Opcode = AArch64ISD::SRSHR_I; 13450 IsRightShift = true; 13451 break; 13452 case Intrinsic::aarch64_neon_urshl: 13453 Opcode = AArch64ISD::URSHR_I; 13454 IsRightShift = true; 13455 break; 13456 case Intrinsic::aarch64_neon_sqshlu: 13457 Opcode = AArch64ISD::SQSHLU_I; 13458 IsRightShift = false; 13459 break; 13460 case Intrinsic::aarch64_neon_sshl: 13461 case Intrinsic::aarch64_neon_ushl: 13462 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 13463 // left shift for positive shift amounts. Below, we only replace the current 13464 // node with VSHL, if this condition is met. 13465 Opcode = AArch64ISD::VSHL; 13466 IsRightShift = false; 13467 break; 13468 } 13469 13470 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 13471 SDLoc dl(N); 13472 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 13473 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 13474 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 13475 SDLoc dl(N); 13476 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 13477 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 13478 } 13479 13480 return SDValue(); 13481 } 13482 13483 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 13484 // the intrinsics must be legal and take an i32, this means there's almost 13485 // certainly going to be a zext in the DAG which we can eliminate. 13486 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 13487 SDValue AndN = N->getOperand(2); 13488 if (AndN.getOpcode() != ISD::AND) 13489 return SDValue(); 13490 13491 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 13492 if (!CMask || CMask->getZExtValue() != Mask) 13493 return SDValue(); 13494 13495 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 13496 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 13497 } 13498 13499 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 13500 SelectionDAG &DAG) { 13501 SDLoc dl(N); 13502 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 13503 DAG.getNode(Opc, dl, 13504 N->getOperand(1).getSimpleValueType(), 13505 N->getOperand(1)), 13506 DAG.getConstant(0, dl, MVT::i64)); 13507 } 13508 13509 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) { 13510 SDLoc DL(N); 13511 SDValue Op1 = N->getOperand(1); 13512 SDValue Op2 = N->getOperand(2); 13513 EVT ScalarTy = Op1.getValueType(); 13514 13515 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) { 13516 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1); 13517 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2); 13518 } 13519 13520 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0), 13521 Op1, Op2); 13522 } 13523 13524 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) { 13525 SDLoc dl(N); 13526 SDValue Scalar = N->getOperand(3); 13527 EVT ScalarTy = Scalar.getValueType(); 13528 13529 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 13530 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 13531 13532 SDValue Passthru = N->getOperand(1); 13533 SDValue Pred = N->getOperand(2); 13534 return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0), 13535 Pred, Scalar, Passthru); 13536 } 13537 13538 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) { 13539 SDLoc dl(N); 13540 LLVMContext &Ctx = *DAG.getContext(); 13541 EVT VT = N->getValueType(0); 13542 13543 assert(VT.isScalableVector() && "Expected a scalable vector."); 13544 13545 // Current lowering only supports the SVE-ACLE types. 13546 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 13547 return SDValue(); 13548 13549 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8; 13550 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8; 13551 EVT ByteVT = 13552 EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize)); 13553 13554 // Convert everything to the domain of EXT (i.e bytes). 13555 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1)); 13556 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2)); 13557 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3), 13558 DAG.getConstant(ElemSize, dl, MVT::i32)); 13559 13560 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2); 13561 return DAG.getNode(ISD::BITCAST, dl, VT, EXT); 13562 } 13563 13564 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC, 13565 TargetLowering::DAGCombinerInfo &DCI, 13566 SelectionDAG &DAG) { 13567 if (DCI.isBeforeLegalize()) 13568 return SDValue(); 13569 13570 SDValue Comparator = N->getOperand(3); 13571 if (Comparator.getOpcode() == AArch64ISD::DUP || 13572 Comparator.getOpcode() == ISD::SPLAT_VECTOR) { 13573 unsigned IID = getIntrinsicID(N); 13574 EVT VT = N->getValueType(0); 13575 EVT CmpVT = N->getOperand(2).getValueType(); 13576 SDValue Pred = N->getOperand(1); 13577 SDValue Imm; 13578 SDLoc DL(N); 13579 13580 switch (IID) { 13581 default: 13582 llvm_unreachable("Called with wrong intrinsic!"); 13583 break; 13584 13585 // Signed comparisons 13586 case Intrinsic::aarch64_sve_cmpeq_wide: 13587 case Intrinsic::aarch64_sve_cmpne_wide: 13588 case Intrinsic::aarch64_sve_cmpge_wide: 13589 case Intrinsic::aarch64_sve_cmpgt_wide: 13590 case Intrinsic::aarch64_sve_cmplt_wide: 13591 case Intrinsic::aarch64_sve_cmple_wide: { 13592 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 13593 int64_t ImmVal = CN->getSExtValue(); 13594 if (ImmVal >= -16 && ImmVal <= 15) 13595 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 13596 else 13597 return SDValue(); 13598 } 13599 break; 13600 } 13601 // Unsigned comparisons 13602 case Intrinsic::aarch64_sve_cmphs_wide: 13603 case Intrinsic::aarch64_sve_cmphi_wide: 13604 case Intrinsic::aarch64_sve_cmplo_wide: 13605 case Intrinsic::aarch64_sve_cmpls_wide: { 13606 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 13607 uint64_t ImmVal = CN->getZExtValue(); 13608 if (ImmVal <= 127) 13609 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 13610 else 13611 return SDValue(); 13612 } 13613 break; 13614 } 13615 } 13616 13617 if (!Imm) 13618 return SDValue(); 13619 13620 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm); 13621 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred, 13622 N->getOperand(2), Splat, DAG.getCondCode(CC)); 13623 } 13624 13625 return SDValue(); 13626 } 13627 13628 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op, 13629 AArch64CC::CondCode Cond) { 13630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13631 13632 SDLoc DL(Op); 13633 assert(Op.getValueType().isScalableVector() && 13634 TLI.isTypeLegal(Op.getValueType()) && 13635 "Expected legal scalable vector type!"); 13636 13637 // Ensure target specific opcodes are using legal type. 13638 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 13639 SDValue TVal = DAG.getConstant(1, DL, OutVT); 13640 SDValue FVal = DAG.getConstant(0, DL, OutVT); 13641 13642 // Set condition code (CC) flags. 13643 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op); 13644 13645 // Convert CC to integer based on requested condition. 13646 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare. 13647 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32); 13648 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test); 13649 return DAG.getZExtOrTrunc(Res, DL, VT); 13650 } 13651 13652 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc, 13653 SelectionDAG &DAG) { 13654 SDLoc DL(N); 13655 13656 SDValue Pred = N->getOperand(1); 13657 SDValue VecToReduce = N->getOperand(2); 13658 13659 // NOTE: The integer reduction's result type is not always linked to the 13660 // operand's element type so we construct it from the intrinsic's result type. 13661 EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0)); 13662 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 13663 13664 // SVE reductions set the whole vector register with the first element 13665 // containing the reduction result, which we'll now extract. 13666 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13667 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13668 Zero); 13669 } 13670 13671 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc, 13672 SelectionDAG &DAG) { 13673 SDLoc DL(N); 13674 13675 SDValue Pred = N->getOperand(1); 13676 SDValue VecToReduce = N->getOperand(2); 13677 13678 EVT ReduceVT = VecToReduce.getValueType(); 13679 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce); 13680 13681 // SVE reductions set the whole vector register with the first element 13682 // containing the reduction result, which we'll now extract. 13683 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13684 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13685 Zero); 13686 } 13687 13688 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc, 13689 SelectionDAG &DAG) { 13690 SDLoc DL(N); 13691 13692 SDValue Pred = N->getOperand(1); 13693 SDValue InitVal = N->getOperand(2); 13694 SDValue VecToReduce = N->getOperand(3); 13695 EVT ReduceVT = VecToReduce.getValueType(); 13696 13697 // Ordered reductions use the first lane of the result vector as the 13698 // reduction's initial value. 13699 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 13700 InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT, 13701 DAG.getUNDEF(ReduceVT), InitVal, Zero); 13702 13703 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce); 13704 13705 // SVE reductions set the whole vector register with the first element 13706 // containing the reduction result, which we'll now extract. 13707 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce, 13708 Zero); 13709 } 13710 13711 // If a merged operation has no inactive lanes we can relax it to a predicated 13712 // or unpredicated operation, which potentially allows better isel (perhaps 13713 // using immediate forms) or relaxing register reuse requirements. 13714 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc, 13715 SelectionDAG &DAG) { 13716 assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!"); 13717 assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!"); 13718 SDValue Pg = N->getOperand(1); 13719 13720 // ISD way to specify an all active predicate. 13721 if ((Pg.getOpcode() == AArch64ISD::PTRUE) && 13722 (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all)) 13723 return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg, 13724 N->getOperand(2), N->getOperand(3)); 13725 13726 // FUTURE: SplatVector(true) 13727 return SDValue(); 13728 } 13729 13730 static SDValue performIntrinsicCombine(SDNode *N, 13731 TargetLowering::DAGCombinerInfo &DCI, 13732 const AArch64Subtarget *Subtarget) { 13733 SelectionDAG &DAG = DCI.DAG; 13734 unsigned IID = getIntrinsicID(N); 13735 switch (IID) { 13736 default: 13737 break; 13738 case Intrinsic::aarch64_neon_vcvtfxs2fp: 13739 case Intrinsic::aarch64_neon_vcvtfxu2fp: 13740 return tryCombineFixedPointConvert(N, DCI, DAG); 13741 case Intrinsic::aarch64_neon_saddv: 13742 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 13743 case Intrinsic::aarch64_neon_uaddv: 13744 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 13745 case Intrinsic::aarch64_neon_sminv: 13746 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 13747 case Intrinsic::aarch64_neon_uminv: 13748 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 13749 case Intrinsic::aarch64_neon_smaxv: 13750 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 13751 case Intrinsic::aarch64_neon_umaxv: 13752 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 13753 case Intrinsic::aarch64_neon_fmax: 13754 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 13755 N->getOperand(1), N->getOperand(2)); 13756 case Intrinsic::aarch64_neon_fmin: 13757 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 13758 N->getOperand(1), N->getOperand(2)); 13759 case Intrinsic::aarch64_neon_fmaxnm: 13760 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 13761 N->getOperand(1), N->getOperand(2)); 13762 case Intrinsic::aarch64_neon_fminnm: 13763 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 13764 N->getOperand(1), N->getOperand(2)); 13765 case Intrinsic::aarch64_neon_smull: 13766 case Intrinsic::aarch64_neon_umull: 13767 case Intrinsic::aarch64_neon_pmull: 13768 case Intrinsic::aarch64_neon_sqdmull: 13769 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 13770 case Intrinsic::aarch64_neon_sqshl: 13771 case Intrinsic::aarch64_neon_uqshl: 13772 case Intrinsic::aarch64_neon_sqshlu: 13773 case Intrinsic::aarch64_neon_srshl: 13774 case Intrinsic::aarch64_neon_urshl: 13775 case Intrinsic::aarch64_neon_sshl: 13776 case Intrinsic::aarch64_neon_ushl: 13777 return tryCombineShiftImm(IID, N, DAG); 13778 case Intrinsic::aarch64_crc32b: 13779 case Intrinsic::aarch64_crc32cb: 13780 return tryCombineCRC32(0xff, N, DAG); 13781 case Intrinsic::aarch64_crc32h: 13782 case Intrinsic::aarch64_crc32ch: 13783 return tryCombineCRC32(0xffff, N, DAG); 13784 case Intrinsic::aarch64_sve_saddv: 13785 // There is no i64 version of SADDV because the sign is irrelevant. 13786 if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64) 13787 return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG); 13788 else 13789 return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG); 13790 case Intrinsic::aarch64_sve_uaddv: 13791 return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG); 13792 case Intrinsic::aarch64_sve_smaxv: 13793 return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG); 13794 case Intrinsic::aarch64_sve_umaxv: 13795 return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG); 13796 case Intrinsic::aarch64_sve_sminv: 13797 return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG); 13798 case Intrinsic::aarch64_sve_uminv: 13799 return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG); 13800 case Intrinsic::aarch64_sve_orv: 13801 return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG); 13802 case Intrinsic::aarch64_sve_eorv: 13803 return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG); 13804 case Intrinsic::aarch64_sve_andv: 13805 return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG); 13806 case Intrinsic::aarch64_sve_index: 13807 return LowerSVEIntrinsicIndex(N, DAG); 13808 case Intrinsic::aarch64_sve_dup: 13809 return LowerSVEIntrinsicDUP(N, DAG); 13810 case Intrinsic::aarch64_sve_dup_x: 13811 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0), 13812 N->getOperand(1)); 13813 case Intrinsic::aarch64_sve_ext: 13814 return LowerSVEIntrinsicEXT(N, DAG); 13815 case Intrinsic::aarch64_sve_smin: 13816 return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG); 13817 case Intrinsic::aarch64_sve_umin: 13818 return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG); 13819 case Intrinsic::aarch64_sve_smax: 13820 return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG); 13821 case Intrinsic::aarch64_sve_umax: 13822 return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG); 13823 case Intrinsic::aarch64_sve_lsl: 13824 return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG); 13825 case Intrinsic::aarch64_sve_lsr: 13826 return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG); 13827 case Intrinsic::aarch64_sve_asr: 13828 return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG); 13829 case Intrinsic::aarch64_sve_cmphs: 13830 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13831 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13832 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13833 N->getOperand(3), DAG.getCondCode(ISD::SETUGE)); 13834 break; 13835 case Intrinsic::aarch64_sve_cmphi: 13836 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13837 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13838 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13839 N->getOperand(3), DAG.getCondCode(ISD::SETUGT)); 13840 break; 13841 case Intrinsic::aarch64_sve_cmpge: 13842 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13843 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13844 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13845 N->getOperand(3), DAG.getCondCode(ISD::SETGE)); 13846 break; 13847 case Intrinsic::aarch64_sve_cmpgt: 13848 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13849 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13850 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13851 N->getOperand(3), DAG.getCondCode(ISD::SETGT)); 13852 break; 13853 case Intrinsic::aarch64_sve_cmpeq: 13854 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13855 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13856 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13857 N->getOperand(3), DAG.getCondCode(ISD::SETEQ)); 13858 break; 13859 case Intrinsic::aarch64_sve_cmpne: 13860 if (!N->getOperand(2).getValueType().isFloatingPoint()) 13861 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N), 13862 N->getValueType(0), N->getOperand(1), N->getOperand(2), 13863 N->getOperand(3), DAG.getCondCode(ISD::SETNE)); 13864 break; 13865 case Intrinsic::aarch64_sve_fadda: 13866 return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG); 13867 case Intrinsic::aarch64_sve_faddv: 13868 return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG); 13869 case Intrinsic::aarch64_sve_fmaxnmv: 13870 return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG); 13871 case Intrinsic::aarch64_sve_fmaxv: 13872 return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG); 13873 case Intrinsic::aarch64_sve_fminnmv: 13874 return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG); 13875 case Intrinsic::aarch64_sve_fminv: 13876 return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG); 13877 case Intrinsic::aarch64_sve_sel: 13878 return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0), 13879 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 13880 case Intrinsic::aarch64_sve_cmpeq_wide: 13881 return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG); 13882 case Intrinsic::aarch64_sve_cmpne_wide: 13883 return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG); 13884 case Intrinsic::aarch64_sve_cmpge_wide: 13885 return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG); 13886 case Intrinsic::aarch64_sve_cmpgt_wide: 13887 return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG); 13888 case Intrinsic::aarch64_sve_cmplt_wide: 13889 return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG); 13890 case Intrinsic::aarch64_sve_cmple_wide: 13891 return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG); 13892 case Intrinsic::aarch64_sve_cmphs_wide: 13893 return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG); 13894 case Intrinsic::aarch64_sve_cmphi_wide: 13895 return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG); 13896 case Intrinsic::aarch64_sve_cmplo_wide: 13897 return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG); 13898 case Intrinsic::aarch64_sve_cmpls_wide: 13899 return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG); 13900 case Intrinsic::aarch64_sve_ptest_any: 13901 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13902 AArch64CC::ANY_ACTIVE); 13903 case Intrinsic::aarch64_sve_ptest_first: 13904 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13905 AArch64CC::FIRST_ACTIVE); 13906 case Intrinsic::aarch64_sve_ptest_last: 13907 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 13908 AArch64CC::LAST_ACTIVE); 13909 } 13910 return SDValue(); 13911 } 13912 13913 static SDValue performExtendCombine(SDNode *N, 13914 TargetLowering::DAGCombinerInfo &DCI, 13915 SelectionDAG &DAG) { 13916 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 13917 // we can convert that DUP into another extract_high (of a bigger DUP), which 13918 // helps the backend to decide that an sabdl2 would be useful, saving a real 13919 // extract_high operation. 13920 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 13921 (N->getOperand(0).getOpcode() == AArch64ISD::UABD || 13922 N->getOperand(0).getOpcode() == AArch64ISD::SABD)) { 13923 SDNode *ABDNode = N->getOperand(0).getNode(); 13924 SDValue NewABD = 13925 tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG); 13926 if (!NewABD.getNode()) 13927 return SDValue(); 13928 13929 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD); 13930 } 13931 13932 // This is effectively a custom type legalization for AArch64. 13933 // 13934 // Type legalization will split an extend of a small, legal, type to a larger 13935 // illegal type by first splitting the destination type, often creating 13936 // illegal source types, which then get legalized in isel-confusing ways, 13937 // leading to really terrible codegen. E.g., 13938 // %result = v8i32 sext v8i8 %value 13939 // becomes 13940 // %losrc = extract_subreg %value, ... 13941 // %hisrc = extract_subreg %value, ... 13942 // %lo = v4i32 sext v4i8 %losrc 13943 // %hi = v4i32 sext v4i8 %hisrc 13944 // Things go rapidly downhill from there. 13945 // 13946 // For AArch64, the [sz]ext vector instructions can only go up one element 13947 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 13948 // take two instructions. 13949 // 13950 // This implies that the most efficient way to do the extend from v8i8 13951 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 13952 // the normal splitting to happen for the v8i16->v8i32. 13953 13954 // This is pre-legalization to catch some cases where the default 13955 // type legalization will create ill-tempered code. 13956 if (!DCI.isBeforeLegalizeOps()) 13957 return SDValue(); 13958 13959 // We're only interested in cleaning things up for non-legal vector types 13960 // here. If both the source and destination are legal, things will just 13961 // work naturally without any fiddling. 13962 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13963 EVT ResVT = N->getValueType(0); 13964 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 13965 return SDValue(); 13966 // If the vector type isn't a simple VT, it's beyond the scope of what 13967 // we're worried about here. Let legalization do its thing and hope for 13968 // the best. 13969 SDValue Src = N->getOperand(0); 13970 EVT SrcVT = Src->getValueType(0); 13971 if (!ResVT.isSimple() || !SrcVT.isSimple()) 13972 return SDValue(); 13973 13974 // If the source VT is a 64-bit fixed or scalable vector, we can play games 13975 // and get the better results we want. 13976 if (SrcVT.getSizeInBits().getKnownMinSize() != 64) 13977 return SDValue(); 13978 13979 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 13980 ElementCount SrcEC = SrcVT.getVectorElementCount(); 13981 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC); 13982 SDLoc DL(N); 13983 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 13984 13985 // Now split the rest of the operation into two halves, each with a 64 13986 // bit source. 13987 EVT LoVT, HiVT; 13988 SDValue Lo, Hi; 13989 LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext()); 13990 13991 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 13992 LoVT.getVectorElementCount()); 13993 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 13994 DAG.getConstant(0, DL, MVT::i64)); 13995 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 13996 DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64)); 13997 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 13998 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 13999 14000 // Now combine the parts back together so we still have a single result 14001 // like the combiner expects. 14002 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 14003 } 14004 14005 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 14006 SDValue SplatVal, unsigned NumVecElts) { 14007 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 14008 unsigned OrigAlignment = St.getAlignment(); 14009 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 14010 14011 // Create scalar stores. This is at least as good as the code sequence for a 14012 // split unaligned store which is a dup.s, ext.b, and two stores. 14013 // Most of the time the three stores should be replaced by store pair 14014 // instructions (stp). 14015 SDLoc DL(&St); 14016 SDValue BasePtr = St.getBasePtr(); 14017 uint64_t BaseOffset = 0; 14018 14019 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 14020 SDValue NewST1 = 14021 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 14022 OrigAlignment, St.getMemOperand()->getFlags()); 14023 14024 // As this in ISel, we will not merge this add which may degrade results. 14025 if (BasePtr->getOpcode() == ISD::ADD && 14026 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 14027 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 14028 BasePtr = BasePtr->getOperand(0); 14029 } 14030 14031 unsigned Offset = EltOffset; 14032 while (--NumVecElts) { 14033 unsigned Alignment = MinAlign(OrigAlignment, Offset); 14034 SDValue OffsetPtr = 14035 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 14036 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 14037 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 14038 PtrInfo.getWithOffset(Offset), Alignment, 14039 St.getMemOperand()->getFlags()); 14040 Offset += EltOffset; 14041 } 14042 return NewST1; 14043 } 14044 14045 // Returns an SVE type that ContentTy can be trivially sign or zero extended 14046 // into. 14047 static MVT getSVEContainerType(EVT ContentTy) { 14048 assert(ContentTy.isSimple() && "No SVE containers for extended types"); 14049 14050 switch (ContentTy.getSimpleVT().SimpleTy) { 14051 default: 14052 llvm_unreachable("No known SVE container for this MVT type"); 14053 case MVT::nxv2i8: 14054 case MVT::nxv2i16: 14055 case MVT::nxv2i32: 14056 case MVT::nxv2i64: 14057 case MVT::nxv2f32: 14058 case MVT::nxv2f64: 14059 return MVT::nxv2i64; 14060 case MVT::nxv4i8: 14061 case MVT::nxv4i16: 14062 case MVT::nxv4i32: 14063 case MVT::nxv4f32: 14064 return MVT::nxv4i32; 14065 case MVT::nxv8i8: 14066 case MVT::nxv8i16: 14067 case MVT::nxv8f16: 14068 case MVT::nxv8bf16: 14069 return MVT::nxv8i16; 14070 case MVT::nxv16i8: 14071 return MVT::nxv16i8; 14072 } 14073 } 14074 14075 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) { 14076 SDLoc DL(N); 14077 EVT VT = N->getValueType(0); 14078 14079 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 14080 return SDValue(); 14081 14082 EVT ContainerVT = VT; 14083 if (ContainerVT.isInteger()) 14084 ContainerVT = getSVEContainerType(ContainerVT); 14085 14086 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other); 14087 SDValue Ops[] = { N->getOperand(0), // Chain 14088 N->getOperand(2), // Pg 14089 N->getOperand(3), // Base 14090 DAG.getValueType(VT) }; 14091 14092 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops); 14093 SDValue LoadChain = SDValue(Load.getNode(), 1); 14094 14095 if (ContainerVT.isInteger() && (VT != ContainerVT)) 14096 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0)); 14097 14098 return DAG.getMergeValues({ Load, LoadChain }, DL); 14099 } 14100 14101 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) { 14102 SDLoc DL(N); 14103 EVT VT = N->getValueType(0); 14104 EVT PtrTy = N->getOperand(3).getValueType(); 14105 14106 if (VT == MVT::nxv8bf16 && 14107 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14108 return SDValue(); 14109 14110 EVT LoadVT = VT; 14111 if (VT.isFloatingPoint()) 14112 LoadVT = VT.changeTypeToInteger(); 14113 14114 auto *MINode = cast<MemIntrinsicSDNode>(N); 14115 SDValue PassThru = DAG.getConstant(0, DL, LoadVT); 14116 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(), 14117 MINode->getOperand(3), DAG.getUNDEF(PtrTy), 14118 MINode->getOperand(2), PassThru, 14119 MINode->getMemoryVT(), MINode->getMemOperand(), 14120 ISD::UNINDEXED, ISD::NON_EXTLOAD, false); 14121 14122 if (VT.isFloatingPoint()) { 14123 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) }; 14124 return DAG.getMergeValues(Ops, DL); 14125 } 14126 14127 return L; 14128 } 14129 14130 template <unsigned Opcode> 14131 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) { 14132 static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO || 14133 Opcode == AArch64ISD::LD1RO_MERGE_ZERO, 14134 "Unsupported opcode."); 14135 SDLoc DL(N); 14136 EVT VT = N->getValueType(0); 14137 if (VT == MVT::nxv8bf16 && 14138 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14139 return SDValue(); 14140 14141 EVT LoadVT = VT; 14142 if (VT.isFloatingPoint()) 14143 LoadVT = VT.changeTypeToInteger(); 14144 14145 SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)}; 14146 SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops); 14147 SDValue LoadChain = SDValue(Load.getNode(), 1); 14148 14149 if (VT.isFloatingPoint()) 14150 Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0)); 14151 14152 return DAG.getMergeValues({Load, LoadChain}, DL); 14153 } 14154 14155 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) { 14156 SDLoc DL(N); 14157 SDValue Data = N->getOperand(2); 14158 EVT DataVT = Data.getValueType(); 14159 EVT HwSrcVt = getSVEContainerType(DataVT); 14160 SDValue InputVT = DAG.getValueType(DataVT); 14161 14162 if (DataVT == MVT::nxv8bf16 && 14163 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14164 return SDValue(); 14165 14166 if (DataVT.isFloatingPoint()) 14167 InputVT = DAG.getValueType(HwSrcVt); 14168 14169 SDValue SrcNew; 14170 if (Data.getValueType().isFloatingPoint()) 14171 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data); 14172 else 14173 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data); 14174 14175 SDValue Ops[] = { N->getOperand(0), // Chain 14176 SrcNew, 14177 N->getOperand(4), // Base 14178 N->getOperand(3), // Pg 14179 InputVT 14180 }; 14181 14182 return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops); 14183 } 14184 14185 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) { 14186 SDLoc DL(N); 14187 14188 SDValue Data = N->getOperand(2); 14189 EVT DataVT = Data.getValueType(); 14190 EVT PtrTy = N->getOperand(4).getValueType(); 14191 14192 if (DataVT == MVT::nxv8bf16 && 14193 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16()) 14194 return SDValue(); 14195 14196 if (DataVT.isFloatingPoint()) 14197 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data); 14198 14199 auto *MINode = cast<MemIntrinsicSDNode>(N); 14200 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4), 14201 DAG.getUNDEF(PtrTy), MINode->getOperand(3), 14202 MINode->getMemoryVT(), MINode->getMemOperand(), 14203 ISD::UNINDEXED, false, false); 14204 } 14205 14206 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 14207 /// load store optimizer pass will merge them to store pair stores. This should 14208 /// be better than a movi to create the vector zero followed by a vector store 14209 /// if the zero constant is not re-used, since one instructions and one register 14210 /// live range will be removed. 14211 /// 14212 /// For example, the final generated code should be: 14213 /// 14214 /// stp xzr, xzr, [x0] 14215 /// 14216 /// instead of: 14217 /// 14218 /// movi v0.2d, #0 14219 /// str q0, [x0] 14220 /// 14221 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 14222 SDValue StVal = St.getValue(); 14223 EVT VT = StVal.getValueType(); 14224 14225 // Avoid scalarizing zero splat stores for scalable vectors. 14226 if (VT.isScalableVector()) 14227 return SDValue(); 14228 14229 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 14230 // 2, 3 or 4 i32 elements. 14231 int NumVecElts = VT.getVectorNumElements(); 14232 if (!(((NumVecElts == 2 || NumVecElts == 3) && 14233 VT.getVectorElementType().getSizeInBits() == 64) || 14234 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 14235 VT.getVectorElementType().getSizeInBits() == 32))) 14236 return SDValue(); 14237 14238 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 14239 return SDValue(); 14240 14241 // If the zero constant has more than one use then the vector store could be 14242 // better since the constant mov will be amortized and stp q instructions 14243 // should be able to be formed. 14244 if (!StVal.hasOneUse()) 14245 return SDValue(); 14246 14247 // If the store is truncating then it's going down to i16 or smaller, which 14248 // means it can be implemented in a single store anyway. 14249 if (St.isTruncatingStore()) 14250 return SDValue(); 14251 14252 // If the immediate offset of the address operand is too large for the stp 14253 // instruction, then bail out. 14254 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 14255 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 14256 if (Offset < -512 || Offset > 504) 14257 return SDValue(); 14258 } 14259 14260 for (int I = 0; I < NumVecElts; ++I) { 14261 SDValue EltVal = StVal.getOperand(I); 14262 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 14263 return SDValue(); 14264 } 14265 14266 // Use a CopyFromReg WZR/XZR here to prevent 14267 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 14268 SDLoc DL(&St); 14269 unsigned ZeroReg; 14270 EVT ZeroVT; 14271 if (VT.getVectorElementType().getSizeInBits() == 32) { 14272 ZeroReg = AArch64::WZR; 14273 ZeroVT = MVT::i32; 14274 } else { 14275 ZeroReg = AArch64::XZR; 14276 ZeroVT = MVT::i64; 14277 } 14278 SDValue SplatVal = 14279 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 14280 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 14281 } 14282 14283 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 14284 /// value. The load store optimizer pass will merge them to store pair stores. 14285 /// This has better performance than a splat of the scalar followed by a split 14286 /// vector store. Even if the stores are not merged it is four stores vs a dup, 14287 /// followed by an ext.b and two stores. 14288 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 14289 SDValue StVal = St.getValue(); 14290 EVT VT = StVal.getValueType(); 14291 14292 // Don't replace floating point stores, they possibly won't be transformed to 14293 // stp because of the store pair suppress pass. 14294 if (VT.isFloatingPoint()) 14295 return SDValue(); 14296 14297 // We can express a splat as store pair(s) for 2 or 4 elements. 14298 unsigned NumVecElts = VT.getVectorNumElements(); 14299 if (NumVecElts != 4 && NumVecElts != 2) 14300 return SDValue(); 14301 14302 // If the store is truncating then it's going down to i16 or smaller, which 14303 // means it can be implemented in a single store anyway. 14304 if (St.isTruncatingStore()) 14305 return SDValue(); 14306 14307 // Check that this is a splat. 14308 // Make sure that each of the relevant vector element locations are inserted 14309 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 14310 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 14311 SDValue SplatVal; 14312 for (unsigned I = 0; I < NumVecElts; ++I) { 14313 // Check for insert vector elements. 14314 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 14315 return SDValue(); 14316 14317 // Check that same value is inserted at each vector element. 14318 if (I == 0) 14319 SplatVal = StVal.getOperand(1); 14320 else if (StVal.getOperand(1) != SplatVal) 14321 return SDValue(); 14322 14323 // Check insert element index. 14324 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 14325 if (!CIndex) 14326 return SDValue(); 14327 uint64_t IndexVal = CIndex->getZExtValue(); 14328 if (IndexVal >= NumVecElts) 14329 return SDValue(); 14330 IndexNotInserted.reset(IndexVal); 14331 14332 StVal = StVal.getOperand(0); 14333 } 14334 // Check that all vector element locations were inserted to. 14335 if (IndexNotInserted.any()) 14336 return SDValue(); 14337 14338 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 14339 } 14340 14341 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 14342 SelectionDAG &DAG, 14343 const AArch64Subtarget *Subtarget) { 14344 14345 StoreSDNode *S = cast<StoreSDNode>(N); 14346 if (S->isVolatile() || S->isIndexed()) 14347 return SDValue(); 14348 14349 SDValue StVal = S->getValue(); 14350 EVT VT = StVal.getValueType(); 14351 14352 if (!VT.isFixedLengthVector()) 14353 return SDValue(); 14354 14355 // If we get a splat of zeros, convert this vector store to a store of 14356 // scalars. They will be merged into store pairs of xzr thereby removing one 14357 // instruction and one register. 14358 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 14359 return ReplacedZeroSplat; 14360 14361 // FIXME: The logic for deciding if an unaligned store should be split should 14362 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 14363 // a call to that function here. 14364 14365 if (!Subtarget->isMisaligned128StoreSlow()) 14366 return SDValue(); 14367 14368 // Don't split at -Oz. 14369 if (DAG.getMachineFunction().getFunction().hasMinSize()) 14370 return SDValue(); 14371 14372 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 14373 // those up regresses performance on micro-benchmarks and olden/bh. 14374 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 14375 return SDValue(); 14376 14377 // Split unaligned 16B stores. They are terrible for performance. 14378 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 14379 // extensions can use this to mark that it does not want splitting to happen 14380 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 14381 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 14382 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 14383 S->getAlignment() <= 2) 14384 return SDValue(); 14385 14386 // If we get a splat of a scalar convert this vector store to a store of 14387 // scalars. They will be merged into store pairs thereby removing two 14388 // instructions. 14389 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 14390 return ReplacedSplat; 14391 14392 SDLoc DL(S); 14393 14394 // Split VT into two. 14395 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 14396 unsigned NumElts = HalfVT.getVectorNumElements(); 14397 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 14398 DAG.getConstant(0, DL, MVT::i64)); 14399 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 14400 DAG.getConstant(NumElts, DL, MVT::i64)); 14401 SDValue BasePtr = S->getBasePtr(); 14402 SDValue NewST1 = 14403 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 14404 S->getAlignment(), S->getMemOperand()->getFlags()); 14405 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 14406 DAG.getConstant(8, DL, MVT::i64)); 14407 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 14408 S->getPointerInfo(), S->getAlignment(), 14409 S->getMemOperand()->getFlags()); 14410 } 14411 14412 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) { 14413 SDLoc DL(N); 14414 SDValue Op0 = N->getOperand(0); 14415 SDValue Op1 = N->getOperand(1); 14416 EVT ResVT = N->getValueType(0); 14417 14418 // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z) 14419 if (Op0.getOpcode() == AArch64ISD::UUNPKLO) { 14420 if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) { 14421 SDValue X = Op0.getOperand(0).getOperand(0); 14422 return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1); 14423 } 14424 } 14425 14426 // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z) 14427 if (Op1.getOpcode() == AArch64ISD::UUNPKHI) { 14428 if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) { 14429 SDValue Z = Op1.getOperand(0).getOperand(1); 14430 return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z); 14431 } 14432 } 14433 14434 return SDValue(); 14435 } 14436 14437 static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) { 14438 unsigned Opc = N->getOpcode(); 14439 14440 assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads 14441 Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) || 14442 (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads 14443 Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) && 14444 "Invalid opcode."); 14445 14446 const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO || 14447 Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 14448 const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO || 14449 Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 14450 const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO || 14451 Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO || 14452 Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO || 14453 Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO; 14454 14455 SDLoc DL(N); 14456 SDValue Chain = N->getOperand(0); 14457 SDValue Pg = N->getOperand(1); 14458 SDValue Base = N->getOperand(2); 14459 SDValue Offset = N->getOperand(3); 14460 SDValue Ty = N->getOperand(4); 14461 14462 EVT ResVT = N->getValueType(0); 14463 14464 const auto OffsetOpc = Offset.getOpcode(); 14465 const bool OffsetIsZExt = 14466 OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU; 14467 const bool OffsetIsSExt = 14468 OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU; 14469 14470 // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible. 14471 if (!Extended && (OffsetIsSExt || OffsetIsZExt)) { 14472 SDValue ExtPg = Offset.getOperand(0); 14473 VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode()); 14474 EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType(); 14475 14476 // If the predicate for the sign- or zero-extended offset is the 14477 // same as the predicate used for this load and the sign-/zero-extension 14478 // was from a 32-bits... 14479 if (ExtPg == Pg && ExtFromEVT == MVT::i32) { 14480 SDValue UnextendedOffset = Offset.getOperand(1); 14481 14482 unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true); 14483 if (Signed) 14484 NewOpc = getSignExtendedGatherOpcode(NewOpc); 14485 14486 return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other}, 14487 {Chain, Pg, Base, UnextendedOffset, Ty}); 14488 } 14489 } 14490 14491 return SDValue(); 14492 } 14493 14494 /// Target-specific DAG combine function for post-increment LD1 (lane) and 14495 /// post-increment LD1R. 14496 static SDValue performPostLD1Combine(SDNode *N, 14497 TargetLowering::DAGCombinerInfo &DCI, 14498 bool IsLaneOp) { 14499 if (DCI.isBeforeLegalizeOps()) 14500 return SDValue(); 14501 14502 SelectionDAG &DAG = DCI.DAG; 14503 EVT VT = N->getValueType(0); 14504 14505 if (VT.isScalableVector()) 14506 return SDValue(); 14507 14508 unsigned LoadIdx = IsLaneOp ? 1 : 0; 14509 SDNode *LD = N->getOperand(LoadIdx).getNode(); 14510 // If it is not LOAD, can not do such combine. 14511 if (LD->getOpcode() != ISD::LOAD) 14512 return SDValue(); 14513 14514 // The vector lane must be a constant in the LD1LANE opcode. 14515 SDValue Lane; 14516 if (IsLaneOp) { 14517 Lane = N->getOperand(2); 14518 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 14519 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 14520 return SDValue(); 14521 } 14522 14523 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 14524 EVT MemVT = LoadSDN->getMemoryVT(); 14525 // Check if memory operand is the same type as the vector element. 14526 if (MemVT != VT.getVectorElementType()) 14527 return SDValue(); 14528 14529 // Check if there are other uses. If so, do not combine as it will introduce 14530 // an extra load. 14531 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 14532 ++UI) { 14533 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 14534 continue; 14535 if (*UI != N) 14536 return SDValue(); 14537 } 14538 14539 SDValue Addr = LD->getOperand(1); 14540 SDValue Vector = N->getOperand(0); 14541 // Search for a use of the address operand that is an increment. 14542 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 14543 Addr.getNode()->use_end(); UI != UE; ++UI) { 14544 SDNode *User = *UI; 14545 if (User->getOpcode() != ISD::ADD 14546 || UI.getUse().getResNo() != Addr.getResNo()) 14547 continue; 14548 14549 // If the increment is a constant, it must match the memory ref size. 14550 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14551 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 14552 uint32_t IncVal = CInc->getZExtValue(); 14553 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 14554 if (IncVal != NumBytes) 14555 continue; 14556 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 14557 } 14558 14559 // To avoid cycle construction make sure that neither the load nor the add 14560 // are predecessors to each other or the Vector. 14561 SmallPtrSet<const SDNode *, 32> Visited; 14562 SmallVector<const SDNode *, 16> Worklist; 14563 Visited.insert(Addr.getNode()); 14564 Worklist.push_back(User); 14565 Worklist.push_back(LD); 14566 Worklist.push_back(Vector.getNode()); 14567 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 14568 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14569 continue; 14570 14571 SmallVector<SDValue, 8> Ops; 14572 Ops.push_back(LD->getOperand(0)); // Chain 14573 if (IsLaneOp) { 14574 Ops.push_back(Vector); // The vector to be inserted 14575 Ops.push_back(Lane); // The lane to be inserted in the vector 14576 } 14577 Ops.push_back(Addr); 14578 Ops.push_back(Inc); 14579 14580 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 14581 SDVTList SDTys = DAG.getVTList(Tys); 14582 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 14583 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 14584 MemVT, 14585 LoadSDN->getMemOperand()); 14586 14587 // Update the uses. 14588 SDValue NewResults[] = { 14589 SDValue(LD, 0), // The result of load 14590 SDValue(UpdN.getNode(), 2) // Chain 14591 }; 14592 DCI.CombineTo(LD, NewResults); 14593 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 14594 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 14595 14596 break; 14597 } 14598 return SDValue(); 14599 } 14600 14601 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 14602 /// address translation. 14603 static bool performTBISimplification(SDValue Addr, 14604 TargetLowering::DAGCombinerInfo &DCI, 14605 SelectionDAG &DAG) { 14606 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 14607 KnownBits Known; 14608 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 14609 !DCI.isBeforeLegalizeOps()); 14610 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14611 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 14612 DCI.CommitTargetLoweringOpt(TLO); 14613 return true; 14614 } 14615 return false; 14616 } 14617 14618 static SDValue performSTORECombine(SDNode *N, 14619 TargetLowering::DAGCombinerInfo &DCI, 14620 SelectionDAG &DAG, 14621 const AArch64Subtarget *Subtarget) { 14622 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 14623 return Split; 14624 14625 if (Subtarget->supportsAddressTopByteIgnored() && 14626 performTBISimplification(N->getOperand(2), DCI, DAG)) 14627 return SDValue(N, 0); 14628 14629 return SDValue(); 14630 } 14631 14632 /// Target-specific DAG combine function for NEON load/store intrinsics 14633 /// to merge base address updates. 14634 static SDValue performNEONPostLDSTCombine(SDNode *N, 14635 TargetLowering::DAGCombinerInfo &DCI, 14636 SelectionDAG &DAG) { 14637 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 14638 return SDValue(); 14639 14640 unsigned AddrOpIdx = N->getNumOperands() - 1; 14641 SDValue Addr = N->getOperand(AddrOpIdx); 14642 14643 // Search for a use of the address operand that is an increment. 14644 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 14645 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 14646 SDNode *User = *UI; 14647 if (User->getOpcode() != ISD::ADD || 14648 UI.getUse().getResNo() != Addr.getResNo()) 14649 continue; 14650 14651 // Check that the add is independent of the load/store. Otherwise, folding 14652 // it would create a cycle. 14653 SmallPtrSet<const SDNode *, 32> Visited; 14654 SmallVector<const SDNode *, 16> Worklist; 14655 Visited.insert(Addr.getNode()); 14656 Worklist.push_back(N); 14657 Worklist.push_back(User); 14658 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 14659 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 14660 continue; 14661 14662 // Find the new opcode for the updating load/store. 14663 bool IsStore = false; 14664 bool IsLaneOp = false; 14665 bool IsDupOp = false; 14666 unsigned NewOpc = 0; 14667 unsigned NumVecs = 0; 14668 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 14669 switch (IntNo) { 14670 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 14671 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 14672 NumVecs = 2; break; 14673 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 14674 NumVecs = 3; break; 14675 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 14676 NumVecs = 4; break; 14677 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 14678 NumVecs = 2; IsStore = true; break; 14679 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 14680 NumVecs = 3; IsStore = true; break; 14681 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 14682 NumVecs = 4; IsStore = true; break; 14683 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 14684 NumVecs = 2; break; 14685 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 14686 NumVecs = 3; break; 14687 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 14688 NumVecs = 4; break; 14689 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 14690 NumVecs = 2; IsStore = true; break; 14691 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 14692 NumVecs = 3; IsStore = true; break; 14693 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 14694 NumVecs = 4; IsStore = true; break; 14695 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 14696 NumVecs = 2; IsDupOp = true; break; 14697 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 14698 NumVecs = 3; IsDupOp = true; break; 14699 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 14700 NumVecs = 4; IsDupOp = true; break; 14701 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 14702 NumVecs = 2; IsLaneOp = true; break; 14703 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 14704 NumVecs = 3; IsLaneOp = true; break; 14705 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 14706 NumVecs = 4; IsLaneOp = true; break; 14707 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 14708 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 14709 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 14710 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 14711 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 14712 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 14713 } 14714 14715 EVT VecTy; 14716 if (IsStore) 14717 VecTy = N->getOperand(2).getValueType(); 14718 else 14719 VecTy = N->getValueType(0); 14720 14721 // If the increment is a constant, it must match the memory ref size. 14722 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 14723 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 14724 uint32_t IncVal = CInc->getZExtValue(); 14725 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 14726 if (IsLaneOp || IsDupOp) 14727 NumBytes /= VecTy.getVectorNumElements(); 14728 if (IncVal != NumBytes) 14729 continue; 14730 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 14731 } 14732 SmallVector<SDValue, 8> Ops; 14733 Ops.push_back(N->getOperand(0)); // Incoming chain 14734 // Load lane and store have vector list as input. 14735 if (IsLaneOp || IsStore) 14736 for (unsigned i = 2; i < AddrOpIdx; ++i) 14737 Ops.push_back(N->getOperand(i)); 14738 Ops.push_back(Addr); // Base register 14739 Ops.push_back(Inc); 14740 14741 // Return Types. 14742 EVT Tys[6]; 14743 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 14744 unsigned n; 14745 for (n = 0; n < NumResultVecs; ++n) 14746 Tys[n] = VecTy; 14747 Tys[n++] = MVT::i64; // Type of write back register 14748 Tys[n] = MVT::Other; // Type of the chain 14749 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 14750 14751 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 14752 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 14753 MemInt->getMemoryVT(), 14754 MemInt->getMemOperand()); 14755 14756 // Update the uses. 14757 std::vector<SDValue> NewResults; 14758 for (unsigned i = 0; i < NumResultVecs; ++i) { 14759 NewResults.push_back(SDValue(UpdN.getNode(), i)); 14760 } 14761 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 14762 DCI.CombineTo(N, NewResults); 14763 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 14764 14765 break; 14766 } 14767 return SDValue(); 14768 } 14769 14770 // Checks to see if the value is the prescribed width and returns information 14771 // about its extension mode. 14772 static 14773 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 14774 ExtType = ISD::NON_EXTLOAD; 14775 switch(V.getNode()->getOpcode()) { 14776 default: 14777 return false; 14778 case ISD::LOAD: { 14779 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 14780 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 14781 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 14782 ExtType = LoadNode->getExtensionType(); 14783 return true; 14784 } 14785 return false; 14786 } 14787 case ISD::AssertSext: { 14788 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 14789 if ((TypeNode->getVT() == MVT::i8 && width == 8) 14790 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 14791 ExtType = ISD::SEXTLOAD; 14792 return true; 14793 } 14794 return false; 14795 } 14796 case ISD::AssertZext: { 14797 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 14798 if ((TypeNode->getVT() == MVT::i8 && width == 8) 14799 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 14800 ExtType = ISD::ZEXTLOAD; 14801 return true; 14802 } 14803 return false; 14804 } 14805 case ISD::Constant: 14806 case ISD::TargetConstant: { 14807 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 14808 1LL << (width - 1); 14809 } 14810 } 14811 14812 return true; 14813 } 14814 14815 // This function does a whole lot of voodoo to determine if the tests are 14816 // equivalent without and with a mask. Essentially what happens is that given a 14817 // DAG resembling: 14818 // 14819 // +-------------+ +-------------+ +-------------+ +-------------+ 14820 // | Input | | AddConstant | | CompConstant| | CC | 14821 // +-------------+ +-------------+ +-------------+ +-------------+ 14822 // | | | | 14823 // V V | +----------+ 14824 // +-------------+ +----+ | | 14825 // | ADD | |0xff| | | 14826 // +-------------+ +----+ | | 14827 // | | | | 14828 // V V | | 14829 // +-------------+ | | 14830 // | AND | | | 14831 // +-------------+ | | 14832 // | | | 14833 // +-----+ | | 14834 // | | | 14835 // V V V 14836 // +-------------+ 14837 // | CMP | 14838 // +-------------+ 14839 // 14840 // The AND node may be safely removed for some combinations of inputs. In 14841 // particular we need to take into account the extension type of the Input, 14842 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 14843 // width of the input (this can work for any width inputs, the above graph is 14844 // specific to 8 bits. 14845 // 14846 // The specific equations were worked out by generating output tables for each 14847 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 14848 // problem was simplified by working with 4 bit inputs, which means we only 14849 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 14850 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 14851 // patterns present in both extensions (0,7). For every distinct set of 14852 // AddConstant and CompConstants bit patterns we can consider the masked and 14853 // unmasked versions to be equivalent if the result of this function is true for 14854 // all 16 distinct bit patterns of for the current extension type of Input (w0). 14855 // 14856 // sub w8, w0, w1 14857 // and w10, w8, #0x0f 14858 // cmp w8, w2 14859 // cset w9, AArch64CC 14860 // cmp w10, w2 14861 // cset w11, AArch64CC 14862 // cmp w9, w11 14863 // cset w0, eq 14864 // ret 14865 // 14866 // Since the above function shows when the outputs are equivalent it defines 14867 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 14868 // would be expensive to run during compiles. The equations below were written 14869 // in a test harness that confirmed they gave equivalent outputs to the above 14870 // for all inputs function, so they can be used determine if the removal is 14871 // legal instead. 14872 // 14873 // isEquivalentMaskless() is the code for testing if the AND can be removed 14874 // factored out of the DAG recognition as the DAG can take several forms. 14875 14876 static bool isEquivalentMaskless(unsigned CC, unsigned width, 14877 ISD::LoadExtType ExtType, int AddConstant, 14878 int CompConstant) { 14879 // By being careful about our equations and only writing the in term 14880 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 14881 // make them generally applicable to all bit widths. 14882 int MaxUInt = (1 << width); 14883 14884 // For the purposes of these comparisons sign extending the type is 14885 // equivalent to zero extending the add and displacing it by half the integer 14886 // width. Provided we are careful and make sure our equations are valid over 14887 // the whole range we can just adjust the input and avoid writing equations 14888 // for sign extended inputs. 14889 if (ExtType == ISD::SEXTLOAD) 14890 AddConstant -= (1 << (width-1)); 14891 14892 switch(CC) { 14893 case AArch64CC::LE: 14894 case AArch64CC::GT: 14895 if ((AddConstant == 0) || 14896 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 14897 (AddConstant >= 0 && CompConstant < 0) || 14898 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 14899 return true; 14900 break; 14901 case AArch64CC::LT: 14902 case AArch64CC::GE: 14903 if ((AddConstant == 0) || 14904 (AddConstant >= 0 && CompConstant <= 0) || 14905 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 14906 return true; 14907 break; 14908 case AArch64CC::HI: 14909 case AArch64CC::LS: 14910 if ((AddConstant >= 0 && CompConstant < 0) || 14911 (AddConstant <= 0 && CompConstant >= -1 && 14912 CompConstant < AddConstant + MaxUInt)) 14913 return true; 14914 break; 14915 case AArch64CC::PL: 14916 case AArch64CC::MI: 14917 if ((AddConstant == 0) || 14918 (AddConstant > 0 && CompConstant <= 0) || 14919 (AddConstant < 0 && CompConstant <= AddConstant)) 14920 return true; 14921 break; 14922 case AArch64CC::LO: 14923 case AArch64CC::HS: 14924 if ((AddConstant >= 0 && CompConstant <= 0) || 14925 (AddConstant <= 0 && CompConstant >= 0 && 14926 CompConstant <= AddConstant + MaxUInt)) 14927 return true; 14928 break; 14929 case AArch64CC::EQ: 14930 case AArch64CC::NE: 14931 if ((AddConstant > 0 && CompConstant < 0) || 14932 (AddConstant < 0 && CompConstant >= 0 && 14933 CompConstant < AddConstant + MaxUInt) || 14934 (AddConstant >= 0 && CompConstant >= 0 && 14935 CompConstant >= AddConstant) || 14936 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 14937 return true; 14938 break; 14939 case AArch64CC::VS: 14940 case AArch64CC::VC: 14941 case AArch64CC::AL: 14942 case AArch64CC::NV: 14943 return true; 14944 case AArch64CC::Invalid: 14945 break; 14946 } 14947 14948 return false; 14949 } 14950 14951 static 14952 SDValue performCONDCombine(SDNode *N, 14953 TargetLowering::DAGCombinerInfo &DCI, 14954 SelectionDAG &DAG, unsigned CCIndex, 14955 unsigned CmpIndex) { 14956 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 14957 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 14958 unsigned CondOpcode = SubsNode->getOpcode(); 14959 14960 if (CondOpcode != AArch64ISD::SUBS) 14961 return SDValue(); 14962 14963 // There is a SUBS feeding this condition. Is it fed by a mask we can 14964 // use? 14965 14966 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 14967 unsigned MaskBits = 0; 14968 14969 if (AndNode->getOpcode() != ISD::AND) 14970 return SDValue(); 14971 14972 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 14973 uint32_t CNV = CN->getZExtValue(); 14974 if (CNV == 255) 14975 MaskBits = 8; 14976 else if (CNV == 65535) 14977 MaskBits = 16; 14978 } 14979 14980 if (!MaskBits) 14981 return SDValue(); 14982 14983 SDValue AddValue = AndNode->getOperand(0); 14984 14985 if (AddValue.getOpcode() != ISD::ADD) 14986 return SDValue(); 14987 14988 // The basic dag structure is correct, grab the inputs and validate them. 14989 14990 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 14991 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 14992 SDValue SubsInputValue = SubsNode->getOperand(1); 14993 14994 // The mask is present and the provenance of all the values is a smaller type, 14995 // lets see if the mask is superfluous. 14996 14997 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 14998 !isa<ConstantSDNode>(SubsInputValue.getNode())) 14999 return SDValue(); 15000 15001 ISD::LoadExtType ExtType; 15002 15003 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 15004 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 15005 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 15006 return SDValue(); 15007 15008 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 15009 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 15010 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 15011 return SDValue(); 15012 15013 // The AND is not necessary, remove it. 15014 15015 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 15016 SubsNode->getValueType(1)); 15017 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 15018 15019 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 15020 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 15021 15022 return SDValue(N, 0); 15023 } 15024 15025 // Optimize compare with zero and branch. 15026 static SDValue performBRCONDCombine(SDNode *N, 15027 TargetLowering::DAGCombinerInfo &DCI, 15028 SelectionDAG &DAG) { 15029 MachineFunction &MF = DAG.getMachineFunction(); 15030 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 15031 // will not be produced, as they are conditional branch instructions that do 15032 // not set flags. 15033 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 15034 return SDValue(); 15035 15036 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 15037 N = NV.getNode(); 15038 SDValue Chain = N->getOperand(0); 15039 SDValue Dest = N->getOperand(1); 15040 SDValue CCVal = N->getOperand(2); 15041 SDValue Cmp = N->getOperand(3); 15042 15043 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 15044 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 15045 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 15046 return SDValue(); 15047 15048 unsigned CmpOpc = Cmp.getOpcode(); 15049 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 15050 return SDValue(); 15051 15052 // Only attempt folding if there is only one use of the flag and no use of the 15053 // value. 15054 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 15055 return SDValue(); 15056 15057 SDValue LHS = Cmp.getOperand(0); 15058 SDValue RHS = Cmp.getOperand(1); 15059 15060 assert(LHS.getValueType() == RHS.getValueType() && 15061 "Expected the value type to be the same for both operands!"); 15062 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 15063 return SDValue(); 15064 15065 if (isNullConstant(LHS)) 15066 std::swap(LHS, RHS); 15067 15068 if (!isNullConstant(RHS)) 15069 return SDValue(); 15070 15071 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 15072 LHS.getOpcode() == ISD::SRL) 15073 return SDValue(); 15074 15075 // Fold the compare into the branch instruction. 15076 SDValue BR; 15077 if (CC == AArch64CC::EQ) 15078 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 15079 else 15080 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 15081 15082 // Do not add new nodes to DAG combiner worklist. 15083 DCI.CombineTo(N, BR, false); 15084 15085 return SDValue(); 15086 } 15087 15088 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 15089 // as well as whether the test should be inverted. This code is required to 15090 // catch these cases (as opposed to standard dag combines) because 15091 // AArch64ISD::TBZ is matched during legalization. 15092 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 15093 SelectionDAG &DAG) { 15094 15095 if (!Op->hasOneUse()) 15096 return Op; 15097 15098 // We don't handle undef/constant-fold cases below, as they should have 15099 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 15100 // etc.) 15101 15102 // (tbz (trunc x), b) -> (tbz x, b) 15103 // This case is just here to enable more of the below cases to be caught. 15104 if (Op->getOpcode() == ISD::TRUNCATE && 15105 Bit < Op->getValueType(0).getSizeInBits()) { 15106 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15107 } 15108 15109 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 15110 if (Op->getOpcode() == ISD::ANY_EXTEND && 15111 Bit < Op->getOperand(0).getValueSizeInBits()) { 15112 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15113 } 15114 15115 if (Op->getNumOperands() != 2) 15116 return Op; 15117 15118 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 15119 if (!C) 15120 return Op; 15121 15122 switch (Op->getOpcode()) { 15123 default: 15124 return Op; 15125 15126 // (tbz (and x, m), b) -> (tbz x, b) 15127 case ISD::AND: 15128 if ((C->getZExtValue() >> Bit) & 1) 15129 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15130 return Op; 15131 15132 // (tbz (shl x, c), b) -> (tbz x, b-c) 15133 case ISD::SHL: 15134 if (C->getZExtValue() <= Bit && 15135 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 15136 Bit = Bit - C->getZExtValue(); 15137 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15138 } 15139 return Op; 15140 15141 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 15142 case ISD::SRA: 15143 Bit = Bit + C->getZExtValue(); 15144 if (Bit >= Op->getValueType(0).getSizeInBits()) 15145 Bit = Op->getValueType(0).getSizeInBits() - 1; 15146 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15147 15148 // (tbz (srl x, c), b) -> (tbz x, b+c) 15149 case ISD::SRL: 15150 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 15151 Bit = Bit + C->getZExtValue(); 15152 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15153 } 15154 return Op; 15155 15156 // (tbz (xor x, -1), b) -> (tbnz x, b) 15157 case ISD::XOR: 15158 if ((C->getZExtValue() >> Bit) & 1) 15159 Invert = !Invert; 15160 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 15161 } 15162 } 15163 15164 // Optimize test single bit zero/non-zero and branch. 15165 static SDValue performTBZCombine(SDNode *N, 15166 TargetLowering::DAGCombinerInfo &DCI, 15167 SelectionDAG &DAG) { 15168 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 15169 bool Invert = false; 15170 SDValue TestSrc = N->getOperand(1); 15171 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 15172 15173 if (TestSrc == NewTestSrc) 15174 return SDValue(); 15175 15176 unsigned NewOpc = N->getOpcode(); 15177 if (Invert) { 15178 if (NewOpc == AArch64ISD::TBZ) 15179 NewOpc = AArch64ISD::TBNZ; 15180 else { 15181 assert(NewOpc == AArch64ISD::TBNZ); 15182 NewOpc = AArch64ISD::TBZ; 15183 } 15184 } 15185 15186 SDLoc DL(N); 15187 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 15188 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 15189 } 15190 15191 // vselect (v1i1 setcc) -> 15192 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 15193 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 15194 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 15195 // such VSELECT. 15196 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 15197 SDValue N0 = N->getOperand(0); 15198 EVT CCVT = N0.getValueType(); 15199 15200 // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform 15201 // into (OR (ASR lhs, N-1), 1), which requires less instructions for the 15202 // supported types. 15203 SDValue SetCC = N->getOperand(0); 15204 if (SetCC.getOpcode() == ISD::SETCC && 15205 SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) { 15206 SDValue CmpLHS = SetCC.getOperand(0); 15207 EVT VT = CmpLHS.getValueType(); 15208 SDNode *CmpRHS = SetCC.getOperand(1).getNode(); 15209 SDNode *SplatLHS = N->getOperand(1).getNode(); 15210 SDNode *SplatRHS = N->getOperand(2).getNode(); 15211 APInt SplatLHSVal; 15212 if (CmpLHS.getValueType() == N->getOperand(1).getValueType() && 15213 VT.isSimple() && 15214 is_contained( 15215 makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16, 15216 MVT::v2i32, MVT::v4i32, MVT::v2i64}), 15217 VT.getSimpleVT().SimpleTy) && 15218 ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) && 15219 SplatLHSVal.isOneValue() && ISD::isConstantSplatVectorAllOnes(CmpRHS) && 15220 ISD::isConstantSplatVectorAllOnes(SplatRHS)) { 15221 unsigned NumElts = VT.getVectorNumElements(); 15222 SmallVector<SDValue, 8> Ops( 15223 NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N), 15224 VT.getScalarType())); 15225 SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops); 15226 15227 auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val); 15228 auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1)); 15229 return Or; 15230 } 15231 } 15232 15233 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 15234 CCVT.getVectorElementType() != MVT::i1) 15235 return SDValue(); 15236 15237 EVT ResVT = N->getValueType(0); 15238 EVT CmpVT = N0.getOperand(0).getValueType(); 15239 // Only combine when the result type is of the same size as the compared 15240 // operands. 15241 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 15242 return SDValue(); 15243 15244 SDValue IfTrue = N->getOperand(1); 15245 SDValue IfFalse = N->getOperand(2); 15246 SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 15247 N0.getOperand(0), N0.getOperand(1), 15248 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15249 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 15250 IfTrue, IfFalse); 15251 } 15252 15253 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 15254 /// the compare-mask instructions rather than going via NZCV, even if LHS and 15255 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 15256 /// with a vector one followed by a DUP shuffle on the result. 15257 static SDValue performSelectCombine(SDNode *N, 15258 TargetLowering::DAGCombinerInfo &DCI) { 15259 SelectionDAG &DAG = DCI.DAG; 15260 SDValue N0 = N->getOperand(0); 15261 EVT ResVT = N->getValueType(0); 15262 15263 if (N0.getOpcode() != ISD::SETCC) 15264 return SDValue(); 15265 15266 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 15267 // scalar SetCCResultType. We also don't expect vectors, because we assume 15268 // that selects fed by vector SETCCs are canonicalized to VSELECT. 15269 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 15270 "Scalar-SETCC feeding SELECT has unexpected result type!"); 15271 15272 // If NumMaskElts == 0, the comparison is larger than select result. The 15273 // largest real NEON comparison is 64-bits per lane, which means the result is 15274 // at most 32-bits and an illegal vector. Just bail out for now. 15275 EVT SrcVT = N0.getOperand(0).getValueType(); 15276 15277 // Don't try to do this optimization when the setcc itself has i1 operands. 15278 // There are no legal vectors of i1, so this would be pointless. 15279 if (SrcVT == MVT::i1) 15280 return SDValue(); 15281 15282 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 15283 if (!ResVT.isVector() || NumMaskElts == 0) 15284 return SDValue(); 15285 15286 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 15287 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 15288 15289 // Also bail out if the vector CCVT isn't the same size as ResVT. 15290 // This can happen if the SETCC operand size doesn't divide the ResVT size 15291 // (e.g., f64 vs v3f32). 15292 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 15293 return SDValue(); 15294 15295 // Make sure we didn't create illegal types, if we're not supposed to. 15296 assert(DCI.isBeforeLegalize() || 15297 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 15298 15299 // First perform a vector comparison, where lane 0 is the one we're interested 15300 // in. 15301 SDLoc DL(N0); 15302 SDValue LHS = 15303 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 15304 SDValue RHS = 15305 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 15306 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 15307 15308 // Now duplicate the comparison mask we want across all other lanes. 15309 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 15310 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 15311 Mask = DAG.getNode(ISD::BITCAST, DL, 15312 ResVT.changeVectorElementTypeToInteger(), Mask); 15313 15314 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 15315 } 15316 15317 /// Get rid of unnecessary NVCASTs (that don't change the type). 15318 static SDValue performNVCASTCombine(SDNode *N) { 15319 if (N->getValueType(0) == N->getOperand(0).getValueType()) 15320 return N->getOperand(0); 15321 15322 return SDValue(); 15323 } 15324 15325 // If all users of the globaladdr are of the form (globaladdr + constant), find 15326 // the smallest constant, fold it into the globaladdr's offset and rewrite the 15327 // globaladdr as (globaladdr + constant) - constant. 15328 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 15329 const AArch64Subtarget *Subtarget, 15330 const TargetMachine &TM) { 15331 auto *GN = cast<GlobalAddressSDNode>(N); 15332 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 15333 AArch64II::MO_NO_FLAG) 15334 return SDValue(); 15335 15336 uint64_t MinOffset = -1ull; 15337 for (SDNode *N : GN->uses()) { 15338 if (N->getOpcode() != ISD::ADD) 15339 return SDValue(); 15340 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 15341 if (!C) 15342 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15343 if (!C) 15344 return SDValue(); 15345 MinOffset = std::min(MinOffset, C->getZExtValue()); 15346 } 15347 uint64_t Offset = MinOffset + GN->getOffset(); 15348 15349 // Require that the new offset is larger than the existing one. Otherwise, we 15350 // can end up oscillating between two possible DAGs, for example, 15351 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 15352 if (Offset <= uint64_t(GN->getOffset())) 15353 return SDValue(); 15354 15355 // Check whether folding this offset is legal. It must not go out of bounds of 15356 // the referenced object to avoid violating the code model, and must be 15357 // smaller than 2^21 because this is the largest offset expressible in all 15358 // object formats. 15359 // 15360 // This check also prevents us from folding negative offsets, which will end 15361 // up being treated in the same way as large positive ones. They could also 15362 // cause code model violations, and aren't really common enough to matter. 15363 if (Offset >= (1 << 21)) 15364 return SDValue(); 15365 15366 const GlobalValue *GV = GN->getGlobal(); 15367 Type *T = GV->getValueType(); 15368 if (!T->isSized() || 15369 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 15370 return SDValue(); 15371 15372 SDLoc DL(GN); 15373 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 15374 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 15375 DAG.getConstant(MinOffset, DL, MVT::i64)); 15376 } 15377 15378 // Turns the vector of indices into a vector of byte offstes by scaling Offset 15379 // by (BitWidth / 8). 15380 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset, 15381 SDLoc DL, unsigned BitWidth) { 15382 assert(Offset.getValueType().isScalableVector() && 15383 "This method is only for scalable vectors of offsets"); 15384 15385 SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64); 15386 SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift); 15387 15388 return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift); 15389 } 15390 15391 /// Check if the value of \p OffsetInBytes can be used as an immediate for 15392 /// the gather load/prefetch and scatter store instructions with vector base and 15393 /// immediate offset addressing mode: 15394 /// 15395 /// [<Zn>.[S|D]{, #<imm>}] 15396 /// 15397 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 15398 15399 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes, 15400 unsigned ScalarSizeInBytes) { 15401 // The immediate is not a multiple of the scalar size. 15402 if (OffsetInBytes % ScalarSizeInBytes) 15403 return false; 15404 15405 // The immediate is out of range. 15406 if (OffsetInBytes / ScalarSizeInBytes > 31) 15407 return false; 15408 15409 return true; 15410 } 15411 15412 /// Check if the value of \p Offset represents a valid immediate for the SVE 15413 /// gather load/prefetch and scatter store instructiona with vector base and 15414 /// immediate offset addressing mode: 15415 /// 15416 /// [<Zn>.[S|D]{, #<imm>}] 15417 /// 15418 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 15419 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset, 15420 unsigned ScalarSizeInBytes) { 15421 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 15422 return OffsetConst && isValidImmForSVEVecImmAddrMode( 15423 OffsetConst->getZExtValue(), ScalarSizeInBytes); 15424 } 15425 15426 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG, 15427 unsigned Opcode, 15428 bool OnlyPackedOffsets = true) { 15429 const SDValue Src = N->getOperand(2); 15430 const EVT SrcVT = Src->getValueType(0); 15431 assert(SrcVT.isScalableVector() && 15432 "Scatter stores are only possible for SVE vectors"); 15433 15434 SDLoc DL(N); 15435 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT(); 15436 15437 // Make sure that source data will fit into an SVE register 15438 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 15439 return SDValue(); 15440 15441 // For FPs, ACLE only supports _packed_ single and double precision types. 15442 if (SrcElVT.isFloatingPoint()) 15443 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64)) 15444 return SDValue(); 15445 15446 // Depending on the addressing mode, this is either a pointer or a vector of 15447 // pointers (that fits into one register) 15448 SDValue Base = N->getOperand(4); 15449 // Depending on the addressing mode, this is either a single offset or a 15450 // vector of offsets (that fits into one register) 15451 SDValue Offset = N->getOperand(5); 15452 15453 // For "scalar + vector of indices", just scale the indices. This only 15454 // applies to non-temporal scatters because there's no instruction that takes 15455 // indicies. 15456 if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) { 15457 Offset = 15458 getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits()); 15459 Opcode = AArch64ISD::SSTNT1_PRED; 15460 } 15461 15462 // In the case of non-temporal gather loads there's only one SVE instruction 15463 // per data-size: "scalar + vector", i.e. 15464 // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 15465 // Since we do have intrinsics that allow the arguments to be in a different 15466 // order, we may need to swap them to match the spec. 15467 if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector()) 15468 std::swap(Base, Offset); 15469 15470 // SST1_IMM requires that the offset is an immediate that is: 15471 // * a multiple of #SizeInBytes, 15472 // * in the range [0, 31 x #SizeInBytes], 15473 // where #SizeInBytes is the size in bytes of the stored items. For 15474 // immediates outside that range and non-immediate scalar offsets use SST1 or 15475 // SST1_UXTW instead. 15476 if (Opcode == AArch64ISD::SST1_IMM_PRED) { 15477 if (!isValidImmForSVEVecImmAddrMode(Offset, 15478 SrcVT.getScalarSizeInBits() / 8)) { 15479 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 15480 Opcode = AArch64ISD::SST1_UXTW_PRED; 15481 else 15482 Opcode = AArch64ISD::SST1_PRED; 15483 15484 std::swap(Base, Offset); 15485 } 15486 } 15487 15488 auto &TLI = DAG.getTargetLoweringInfo(); 15489 if (!TLI.isTypeLegal(Base.getValueType())) 15490 return SDValue(); 15491 15492 // Some scatter store variants allow unpacked offsets, but only as nxv2i32 15493 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 15494 // nxv2i64. Legalize accordingly. 15495 if (!OnlyPackedOffsets && 15496 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 15497 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 15498 15499 if (!TLI.isTypeLegal(Offset.getValueType())) 15500 return SDValue(); 15501 15502 // Source value type that is representable in hardware 15503 EVT HwSrcVt = getSVEContainerType(SrcVT); 15504 15505 // Keep the original type of the input data to store - this is needed to be 15506 // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For 15507 // FP values we want the integer equivalent, so just use HwSrcVt. 15508 SDValue InputVT = DAG.getValueType(SrcVT); 15509 if (SrcVT.isFloatingPoint()) 15510 InputVT = DAG.getValueType(HwSrcVt); 15511 15512 SDVTList VTs = DAG.getVTList(MVT::Other); 15513 SDValue SrcNew; 15514 15515 if (Src.getValueType().isFloatingPoint()) 15516 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src); 15517 else 15518 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src); 15519 15520 SDValue Ops[] = {N->getOperand(0), // Chain 15521 SrcNew, 15522 N->getOperand(3), // Pg 15523 Base, 15524 Offset, 15525 InputVT}; 15526 15527 return DAG.getNode(Opcode, DL, VTs, Ops); 15528 } 15529 15530 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG, 15531 unsigned Opcode, 15532 bool OnlyPackedOffsets = true) { 15533 const EVT RetVT = N->getValueType(0); 15534 assert(RetVT.isScalableVector() && 15535 "Gather loads are only possible for SVE vectors"); 15536 15537 SDLoc DL(N); 15538 15539 // Make sure that the loaded data will fit into an SVE register 15540 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 15541 return SDValue(); 15542 15543 // Depending on the addressing mode, this is either a pointer or a vector of 15544 // pointers (that fits into one register) 15545 SDValue Base = N->getOperand(3); 15546 // Depending on the addressing mode, this is either a single offset or a 15547 // vector of offsets (that fits into one register) 15548 SDValue Offset = N->getOperand(4); 15549 15550 // For "scalar + vector of indices", just scale the indices. This only 15551 // applies to non-temporal gathers because there's no instruction that takes 15552 // indicies. 15553 if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) { 15554 Offset = getScaledOffsetForBitWidth(DAG, Offset, DL, 15555 RetVT.getScalarSizeInBits()); 15556 Opcode = AArch64ISD::GLDNT1_MERGE_ZERO; 15557 } 15558 15559 // In the case of non-temporal gather loads there's only one SVE instruction 15560 // per data-size: "scalar + vector", i.e. 15561 // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 15562 // Since we do have intrinsics that allow the arguments to be in a different 15563 // order, we may need to swap them to match the spec. 15564 if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO && 15565 Offset.getValueType().isVector()) 15566 std::swap(Base, Offset); 15567 15568 // GLD{FF}1_IMM requires that the offset is an immediate that is: 15569 // * a multiple of #SizeInBytes, 15570 // * in the range [0, 31 x #SizeInBytes], 15571 // where #SizeInBytes is the size in bytes of the loaded items. For 15572 // immediates outside that range and non-immediate scalar offsets use 15573 // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead. 15574 if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO || 15575 Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) { 15576 if (!isValidImmForSVEVecImmAddrMode(Offset, 15577 RetVT.getScalarSizeInBits() / 8)) { 15578 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 15579 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO) 15580 ? AArch64ISD::GLD1_UXTW_MERGE_ZERO 15581 : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO; 15582 else 15583 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO) 15584 ? AArch64ISD::GLD1_MERGE_ZERO 15585 : AArch64ISD::GLDFF1_MERGE_ZERO; 15586 15587 std::swap(Base, Offset); 15588 } 15589 } 15590 15591 auto &TLI = DAG.getTargetLoweringInfo(); 15592 if (!TLI.isTypeLegal(Base.getValueType())) 15593 return SDValue(); 15594 15595 // Some gather load variants allow unpacked offsets, but only as nxv2i32 15596 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 15597 // nxv2i64. Legalize accordingly. 15598 if (!OnlyPackedOffsets && 15599 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 15600 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 15601 15602 // Return value type that is representable in hardware 15603 EVT HwRetVt = getSVEContainerType(RetVT); 15604 15605 // Keep the original output value type around - this is needed to be able to 15606 // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP 15607 // values we want the integer equivalent, so just use HwRetVT. 15608 SDValue OutVT = DAG.getValueType(RetVT); 15609 if (RetVT.isFloatingPoint()) 15610 OutVT = DAG.getValueType(HwRetVt); 15611 15612 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other); 15613 SDValue Ops[] = {N->getOperand(0), // Chain 15614 N->getOperand(2), // Pg 15615 Base, Offset, OutVT}; 15616 15617 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops); 15618 SDValue LoadChain = SDValue(Load.getNode(), 1); 15619 15620 if (RetVT.isInteger() && (RetVT != HwRetVt)) 15621 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0)); 15622 15623 // If the original return value was FP, bitcast accordingly. Doing it here 15624 // means that we can avoid adding TableGen patterns for FPs. 15625 if (RetVT.isFloatingPoint()) 15626 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0)); 15627 15628 return DAG.getMergeValues({Load, LoadChain}, DL); 15629 } 15630 15631 static SDValue 15632 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 15633 SelectionDAG &DAG) { 15634 SDLoc DL(N); 15635 SDValue Src = N->getOperand(0); 15636 unsigned Opc = Src->getOpcode(); 15637 15638 // Sign extend of an unsigned unpack -> signed unpack 15639 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) { 15640 15641 unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI 15642 : AArch64ISD::SUNPKLO; 15643 15644 // Push the sign extend to the operand of the unpack 15645 // This is necessary where, for example, the operand of the unpack 15646 // is another unpack: 15647 // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8) 15648 // -> 15649 // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8) 15650 // -> 15651 // 4i32 sunpklo(8i16 sunpklo(16i8 opnd)) 15652 SDValue ExtOp = Src->getOperand(0); 15653 auto VT = cast<VTSDNode>(N->getOperand(1))->getVT(); 15654 EVT EltTy = VT.getVectorElementType(); 15655 (void)EltTy; 15656 15657 assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) && 15658 "Sign extending from an invalid type"); 15659 15660 EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext()); 15661 15662 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(), 15663 ExtOp, DAG.getValueType(ExtVT)); 15664 15665 return DAG.getNode(SOpc, DL, N->getValueType(0), Ext); 15666 } 15667 15668 if (DCI.isBeforeLegalizeOps()) 15669 return SDValue(); 15670 15671 if (!EnableCombineMGatherIntrinsics) 15672 return SDValue(); 15673 15674 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates 15675 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes. 15676 unsigned NewOpc; 15677 unsigned MemVTOpNum = 4; 15678 switch (Opc) { 15679 case AArch64ISD::LD1_MERGE_ZERO: 15680 NewOpc = AArch64ISD::LD1S_MERGE_ZERO; 15681 MemVTOpNum = 3; 15682 break; 15683 case AArch64ISD::LDNF1_MERGE_ZERO: 15684 NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO; 15685 MemVTOpNum = 3; 15686 break; 15687 case AArch64ISD::LDFF1_MERGE_ZERO: 15688 NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO; 15689 MemVTOpNum = 3; 15690 break; 15691 case AArch64ISD::GLD1_MERGE_ZERO: 15692 NewOpc = AArch64ISD::GLD1S_MERGE_ZERO; 15693 break; 15694 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 15695 NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO; 15696 break; 15697 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 15698 NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO; 15699 break; 15700 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 15701 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO; 15702 break; 15703 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 15704 NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO; 15705 break; 15706 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 15707 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO; 15708 break; 15709 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 15710 NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO; 15711 break; 15712 case AArch64ISD::GLDFF1_MERGE_ZERO: 15713 NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO; 15714 break; 15715 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO: 15716 NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO; 15717 break; 15718 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO: 15719 NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO; 15720 break; 15721 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO: 15722 NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO; 15723 break; 15724 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO: 15725 NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO; 15726 break; 15727 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO: 15728 NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO; 15729 break; 15730 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO: 15731 NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO; 15732 break; 15733 case AArch64ISD::GLDNT1_MERGE_ZERO: 15734 NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO; 15735 break; 15736 default: 15737 return SDValue(); 15738 } 15739 15740 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 15741 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT(); 15742 15743 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse()) 15744 return SDValue(); 15745 15746 EVT DstVT = N->getValueType(0); 15747 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other); 15748 15749 SmallVector<SDValue, 5> Ops; 15750 for (unsigned I = 0; I < Src->getNumOperands(); ++I) 15751 Ops.push_back(Src->getOperand(I)); 15752 15753 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops); 15754 DCI.CombineTo(N, ExtLoad); 15755 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1)); 15756 15757 // Return N so it doesn't get rechecked 15758 return SDValue(N, 0); 15759 } 15760 15761 /// Legalize the gather prefetch (scalar + vector addressing mode) when the 15762 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset 15763 /// != nxv2i32) do not need legalization. 15764 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) { 15765 const unsigned OffsetPos = 4; 15766 SDValue Offset = N->getOperand(OffsetPos); 15767 15768 // Not an unpacked vector, bail out. 15769 if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32) 15770 return SDValue(); 15771 15772 // Extend the unpacked offset vector to 64-bit lanes. 15773 SDLoc DL(N); 15774 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset); 15775 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 15776 // Replace the offset operand with the 64-bit one. 15777 Ops[OffsetPos] = Offset; 15778 15779 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 15780 } 15781 15782 /// Combines a node carrying the intrinsic 15783 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses 15784 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to 15785 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the 15786 /// sve gather prefetch instruction with vector plus immediate addressing mode. 15787 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG, 15788 unsigned ScalarSizeInBytes) { 15789 const unsigned ImmPos = 4, OffsetPos = 3; 15790 // No need to combine the node if the immediate is valid... 15791 if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes)) 15792 return SDValue(); 15793 15794 // ...otherwise swap the offset base with the offset... 15795 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 15796 std::swap(Ops[ImmPos], Ops[OffsetPos]); 15797 // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to 15798 // `aarch64_sve_prfb_gather_uxtw_index`. 15799 SDLoc DL(N); 15800 Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL, 15801 MVT::i64); 15802 15803 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 15804 } 15805 15806 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 15807 DAGCombinerInfo &DCI) const { 15808 SelectionDAG &DAG = DCI.DAG; 15809 switch (N->getOpcode()) { 15810 default: 15811 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 15812 break; 15813 case ISD::ABS: 15814 return performABSCombine(N, DAG, DCI, Subtarget); 15815 case ISD::ADD: 15816 case ISD::SUB: 15817 return performAddSubCombine(N, DCI, DAG); 15818 case ISD::XOR: 15819 return performXorCombine(N, DAG, DCI, Subtarget); 15820 case ISD::MUL: 15821 return performMulCombine(N, DAG, DCI, Subtarget); 15822 case ISD::SINT_TO_FP: 15823 case ISD::UINT_TO_FP: 15824 return performIntToFpCombine(N, DAG, Subtarget); 15825 case ISD::FP_TO_SINT: 15826 case ISD::FP_TO_UINT: 15827 return performFpToIntCombine(N, DAG, DCI, Subtarget); 15828 case ISD::FDIV: 15829 return performFDivCombine(N, DAG, DCI, Subtarget); 15830 case ISD::OR: 15831 return performORCombine(N, DCI, Subtarget); 15832 case ISD::AND: 15833 return performANDCombine(N, DCI); 15834 case ISD::SRL: 15835 return performSRLCombine(N, DCI); 15836 case ISD::INTRINSIC_WO_CHAIN: 15837 return performIntrinsicCombine(N, DCI, Subtarget); 15838 case ISD::ANY_EXTEND: 15839 case ISD::ZERO_EXTEND: 15840 case ISD::SIGN_EXTEND: 15841 return performExtendCombine(N, DCI, DAG); 15842 case ISD::SIGN_EXTEND_INREG: 15843 return performSignExtendInRegCombine(N, DCI, DAG); 15844 case ISD::TRUNCATE: 15845 return performVectorTruncateCombine(N, DCI, DAG); 15846 case ISD::CONCAT_VECTORS: 15847 return performConcatVectorsCombine(N, DCI, DAG); 15848 case ISD::SELECT: 15849 return performSelectCombine(N, DCI); 15850 case ISD::VSELECT: 15851 return performVSelectCombine(N, DCI.DAG); 15852 case ISD::LOAD: 15853 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 15854 return SDValue(N, 0); 15855 break; 15856 case ISD::STORE: 15857 return performSTORECombine(N, DCI, DAG, Subtarget); 15858 case AArch64ISD::BRCOND: 15859 return performBRCONDCombine(N, DCI, DAG); 15860 case AArch64ISD::TBNZ: 15861 case AArch64ISD::TBZ: 15862 return performTBZCombine(N, DCI, DAG); 15863 case AArch64ISD::CSEL: 15864 return performCONDCombine(N, DCI, DAG, 2, 3); 15865 case AArch64ISD::DUP: 15866 return performPostLD1Combine(N, DCI, false); 15867 case AArch64ISD::NVCAST: 15868 return performNVCASTCombine(N); 15869 case AArch64ISD::UZP1: 15870 return performUzpCombine(N, DAG); 15871 case AArch64ISD::GLD1_MERGE_ZERO: 15872 case AArch64ISD::GLD1_SCALED_MERGE_ZERO: 15873 case AArch64ISD::GLD1_UXTW_MERGE_ZERO: 15874 case AArch64ISD::GLD1_SXTW_MERGE_ZERO: 15875 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO: 15876 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO: 15877 case AArch64ISD::GLD1_IMM_MERGE_ZERO: 15878 case AArch64ISD::GLD1S_MERGE_ZERO: 15879 case AArch64ISD::GLD1S_SCALED_MERGE_ZERO: 15880 case AArch64ISD::GLD1S_UXTW_MERGE_ZERO: 15881 case AArch64ISD::GLD1S_SXTW_MERGE_ZERO: 15882 case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO: 15883 case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO: 15884 case AArch64ISD::GLD1S_IMM_MERGE_ZERO: 15885 return performGLD1Combine(N, DAG); 15886 case ISD::INSERT_VECTOR_ELT: 15887 return performPostLD1Combine(N, DCI, true); 15888 case ISD::EXTRACT_VECTOR_ELT: 15889 return performExtractVectorEltCombine(N, DAG); 15890 case ISD::VECREDUCE_ADD: 15891 return performVecReduceAddCombine(N, DCI.DAG, Subtarget); 15892 case ISD::INTRINSIC_VOID: 15893 case ISD::INTRINSIC_W_CHAIN: 15894 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15895 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset: 15896 return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/); 15897 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset: 15898 return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/); 15899 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset: 15900 return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/); 15901 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset: 15902 return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/); 15903 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index: 15904 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index: 15905 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index: 15906 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index: 15907 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index: 15908 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index: 15909 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index: 15910 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index: 15911 return legalizeSVEGatherPrefetchOffsVec(N, DAG); 15912 case Intrinsic::aarch64_neon_ld2: 15913 case Intrinsic::aarch64_neon_ld3: 15914 case Intrinsic::aarch64_neon_ld4: 15915 case Intrinsic::aarch64_neon_ld1x2: 15916 case Intrinsic::aarch64_neon_ld1x3: 15917 case Intrinsic::aarch64_neon_ld1x4: 15918 case Intrinsic::aarch64_neon_ld2lane: 15919 case Intrinsic::aarch64_neon_ld3lane: 15920 case Intrinsic::aarch64_neon_ld4lane: 15921 case Intrinsic::aarch64_neon_ld2r: 15922 case Intrinsic::aarch64_neon_ld3r: 15923 case Intrinsic::aarch64_neon_ld4r: 15924 case Intrinsic::aarch64_neon_st2: 15925 case Intrinsic::aarch64_neon_st3: 15926 case Intrinsic::aarch64_neon_st4: 15927 case Intrinsic::aarch64_neon_st1x2: 15928 case Intrinsic::aarch64_neon_st1x3: 15929 case Intrinsic::aarch64_neon_st1x4: 15930 case Intrinsic::aarch64_neon_st2lane: 15931 case Intrinsic::aarch64_neon_st3lane: 15932 case Intrinsic::aarch64_neon_st4lane: 15933 return performNEONPostLDSTCombine(N, DCI, DAG); 15934 case Intrinsic::aarch64_sve_ldnt1: 15935 return performLDNT1Combine(N, DAG); 15936 case Intrinsic::aarch64_sve_ld1rq: 15937 return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG); 15938 case Intrinsic::aarch64_sve_ld1ro: 15939 return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG); 15940 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset: 15941 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15942 case Intrinsic::aarch64_sve_ldnt1_gather: 15943 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15944 case Intrinsic::aarch64_sve_ldnt1_gather_index: 15945 return performGatherLoadCombine(N, DAG, 15946 AArch64ISD::GLDNT1_INDEX_MERGE_ZERO); 15947 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw: 15948 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO); 15949 case Intrinsic::aarch64_sve_ld1: 15950 return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO); 15951 case Intrinsic::aarch64_sve_ldnf1: 15952 return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO); 15953 case Intrinsic::aarch64_sve_ldff1: 15954 return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO); 15955 case Intrinsic::aarch64_sve_st1: 15956 return performST1Combine(N, DAG); 15957 case Intrinsic::aarch64_sve_stnt1: 15958 return performSTNT1Combine(N, DAG); 15959 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset: 15960 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15961 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw: 15962 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15963 case Intrinsic::aarch64_sve_stnt1_scatter: 15964 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED); 15965 case Intrinsic::aarch64_sve_stnt1_scatter_index: 15966 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED); 15967 case Intrinsic::aarch64_sve_ld1_gather: 15968 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO); 15969 case Intrinsic::aarch64_sve_ld1_gather_index: 15970 return performGatherLoadCombine(N, DAG, 15971 AArch64ISD::GLD1_SCALED_MERGE_ZERO); 15972 case Intrinsic::aarch64_sve_ld1_gather_sxtw: 15973 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO, 15974 /*OnlyPackedOffsets=*/false); 15975 case Intrinsic::aarch64_sve_ld1_gather_uxtw: 15976 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO, 15977 /*OnlyPackedOffsets=*/false); 15978 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index: 15979 return performGatherLoadCombine(N, DAG, 15980 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO, 15981 /*OnlyPackedOffsets=*/false); 15982 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index: 15983 return performGatherLoadCombine(N, DAG, 15984 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO, 15985 /*OnlyPackedOffsets=*/false); 15986 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset: 15987 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO); 15988 case Intrinsic::aarch64_sve_ldff1_gather: 15989 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO); 15990 case Intrinsic::aarch64_sve_ldff1_gather_index: 15991 return performGatherLoadCombine(N, DAG, 15992 AArch64ISD::GLDFF1_SCALED_MERGE_ZERO); 15993 case Intrinsic::aarch64_sve_ldff1_gather_sxtw: 15994 return performGatherLoadCombine(N, DAG, 15995 AArch64ISD::GLDFF1_SXTW_MERGE_ZERO, 15996 /*OnlyPackedOffsets=*/false); 15997 case Intrinsic::aarch64_sve_ldff1_gather_uxtw: 15998 return performGatherLoadCombine(N, DAG, 15999 AArch64ISD::GLDFF1_UXTW_MERGE_ZERO, 16000 /*OnlyPackedOffsets=*/false); 16001 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index: 16002 return performGatherLoadCombine(N, DAG, 16003 AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO, 16004 /*OnlyPackedOffsets=*/false); 16005 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index: 16006 return performGatherLoadCombine(N, DAG, 16007 AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO, 16008 /*OnlyPackedOffsets=*/false); 16009 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset: 16010 return performGatherLoadCombine(N, DAG, 16011 AArch64ISD::GLDFF1_IMM_MERGE_ZERO); 16012 case Intrinsic::aarch64_sve_st1_scatter: 16013 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED); 16014 case Intrinsic::aarch64_sve_st1_scatter_index: 16015 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED); 16016 case Intrinsic::aarch64_sve_st1_scatter_sxtw: 16017 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED, 16018 /*OnlyPackedOffsets=*/false); 16019 case Intrinsic::aarch64_sve_st1_scatter_uxtw: 16020 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED, 16021 /*OnlyPackedOffsets=*/false); 16022 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index: 16023 return performScatterStoreCombine(N, DAG, 16024 AArch64ISD::SST1_SXTW_SCALED_PRED, 16025 /*OnlyPackedOffsets=*/false); 16026 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index: 16027 return performScatterStoreCombine(N, DAG, 16028 AArch64ISD::SST1_UXTW_SCALED_PRED, 16029 /*OnlyPackedOffsets=*/false); 16030 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset: 16031 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED); 16032 case Intrinsic::aarch64_sve_tuple_get: { 16033 SDLoc DL(N); 16034 SDValue Chain = N->getOperand(0); 16035 SDValue Src1 = N->getOperand(2); 16036 SDValue Idx = N->getOperand(3); 16037 16038 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 16039 EVT ResVT = N->getValueType(0); 16040 uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue(); 16041 SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL); 16042 SDValue Val = 16043 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx); 16044 return DAG.getMergeValues({Val, Chain}, DL); 16045 } 16046 case Intrinsic::aarch64_sve_tuple_set: { 16047 SDLoc DL(N); 16048 SDValue Chain = N->getOperand(0); 16049 SDValue Tuple = N->getOperand(2); 16050 SDValue Idx = N->getOperand(3); 16051 SDValue Vec = N->getOperand(4); 16052 16053 EVT TupleVT = Tuple.getValueType(); 16054 uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue(); 16055 16056 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue(); 16057 uint64_t NumLanes = 16058 Vec.getValueType().getVectorElementCount().getKnownMinValue(); 16059 16060 if ((TupleLanes % NumLanes) != 0) 16061 report_fatal_error("invalid tuple vector!"); 16062 16063 uint64_t NumVecs = TupleLanes / NumLanes; 16064 16065 SmallVector<SDValue, 4> Opnds; 16066 for (unsigned I = 0; I < NumVecs; ++I) { 16067 if (I == IdxConst) 16068 Opnds.push_back(Vec); 16069 else { 16070 SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL); 16071 Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, 16072 Vec.getValueType(), Tuple, ExtIdx)); 16073 } 16074 } 16075 SDValue Concat = 16076 DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds); 16077 return DAG.getMergeValues({Concat, Chain}, DL); 16078 } 16079 case Intrinsic::aarch64_sve_tuple_create2: 16080 case Intrinsic::aarch64_sve_tuple_create3: 16081 case Intrinsic::aarch64_sve_tuple_create4: { 16082 SDLoc DL(N); 16083 SDValue Chain = N->getOperand(0); 16084 16085 SmallVector<SDValue, 4> Opnds; 16086 for (unsigned I = 2; I < N->getNumOperands(); ++I) 16087 Opnds.push_back(N->getOperand(I)); 16088 16089 EVT VT = Opnds[0].getValueType(); 16090 EVT EltVT = VT.getVectorElementType(); 16091 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, 16092 VT.getVectorElementCount() * 16093 (N->getNumOperands() - 2)); 16094 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds); 16095 return DAG.getMergeValues({Concat, Chain}, DL); 16096 } 16097 case Intrinsic::aarch64_sve_ld2: 16098 case Intrinsic::aarch64_sve_ld3: 16099 case Intrinsic::aarch64_sve_ld4: { 16100 SDLoc DL(N); 16101 SDValue Chain = N->getOperand(0); 16102 SDValue Mask = N->getOperand(2); 16103 SDValue BasePtr = N->getOperand(3); 16104 SDValue LoadOps[] = {Chain, Mask, BasePtr}; 16105 unsigned IntrinsicID = 16106 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 16107 SDValue Result = 16108 LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL); 16109 return DAG.getMergeValues({Result, Chain}, DL); 16110 } 16111 case Intrinsic::aarch64_rndr: 16112 case Intrinsic::aarch64_rndrrs: { 16113 unsigned IntrinsicID = 16114 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 16115 auto Register = 16116 (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR 16117 : AArch64SysReg::RNDRRS); 16118 SDLoc DL(N); 16119 SDValue A = DAG.getNode( 16120 AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other), 16121 N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64)); 16122 SDValue B = DAG.getNode( 16123 AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32), 16124 DAG.getConstant(0, DL, MVT::i32), 16125 DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1)); 16126 return DAG.getMergeValues( 16127 {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL); 16128 } 16129 default: 16130 break; 16131 } 16132 break; 16133 case ISD::GlobalAddress: 16134 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 16135 } 16136 return SDValue(); 16137 } 16138 16139 // Check if the return value is used as only a return value, as otherwise 16140 // we can't perform a tail-call. In particular, we need to check for 16141 // target ISD nodes that are returns and any other "odd" constructs 16142 // that the generic analysis code won't necessarily catch. 16143 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 16144 SDValue &Chain) const { 16145 if (N->getNumValues() != 1) 16146 return false; 16147 if (!N->hasNUsesOfValue(1, 0)) 16148 return false; 16149 16150 SDValue TCChain = Chain; 16151 SDNode *Copy = *N->use_begin(); 16152 if (Copy->getOpcode() == ISD::CopyToReg) { 16153 // If the copy has a glue operand, we conservatively assume it isn't safe to 16154 // perform a tail call. 16155 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 16156 MVT::Glue) 16157 return false; 16158 TCChain = Copy->getOperand(0); 16159 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 16160 return false; 16161 16162 bool HasRet = false; 16163 for (SDNode *Node : Copy->uses()) { 16164 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 16165 return false; 16166 HasRet = true; 16167 } 16168 16169 if (!HasRet) 16170 return false; 16171 16172 Chain = TCChain; 16173 return true; 16174 } 16175 16176 // Return whether the an instruction can potentially be optimized to a tail 16177 // call. This will cause the optimizers to attempt to move, or duplicate, 16178 // return instructions to help enable tail call optimizations for this 16179 // instruction. 16180 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16181 return CI->isTailCall(); 16182 } 16183 16184 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 16185 SDValue &Offset, 16186 ISD::MemIndexedMode &AM, 16187 bool &IsInc, 16188 SelectionDAG &DAG) const { 16189 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 16190 return false; 16191 16192 Base = Op->getOperand(0); 16193 // All of the indexed addressing mode instructions take a signed 16194 // 9 bit immediate offset. 16195 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 16196 int64_t RHSC = RHS->getSExtValue(); 16197 if (Op->getOpcode() == ISD::SUB) 16198 RHSC = -(uint64_t)RHSC; 16199 if (!isInt<9>(RHSC)) 16200 return false; 16201 IsInc = (Op->getOpcode() == ISD::ADD); 16202 Offset = Op->getOperand(1); 16203 return true; 16204 } 16205 return false; 16206 } 16207 16208 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 16209 SDValue &Offset, 16210 ISD::MemIndexedMode &AM, 16211 SelectionDAG &DAG) const { 16212 EVT VT; 16213 SDValue Ptr; 16214 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16215 VT = LD->getMemoryVT(); 16216 Ptr = LD->getBasePtr(); 16217 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 16218 VT = ST->getMemoryVT(); 16219 Ptr = ST->getBasePtr(); 16220 } else 16221 return false; 16222 16223 bool IsInc; 16224 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 16225 return false; 16226 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 16227 return true; 16228 } 16229 16230 bool AArch64TargetLowering::getPostIndexedAddressParts( 16231 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 16232 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 16233 EVT VT; 16234 SDValue Ptr; 16235 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 16236 VT = LD->getMemoryVT(); 16237 Ptr = LD->getBasePtr(); 16238 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 16239 VT = ST->getMemoryVT(); 16240 Ptr = ST->getBasePtr(); 16241 } else 16242 return false; 16243 16244 bool IsInc; 16245 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 16246 return false; 16247 // Post-indexing updates the base, so it's not a valid transform 16248 // if that's not the same as the load's pointer. 16249 if (Ptr != Base) 16250 return false; 16251 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 16252 return true; 16253 } 16254 16255 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 16256 SelectionDAG &DAG) { 16257 SDLoc DL(N); 16258 SDValue Op = N->getOperand(0); 16259 16260 if (N->getValueType(0) != MVT::i16 || 16261 (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16)) 16262 return; 16263 16264 Op = SDValue( 16265 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 16266 DAG.getUNDEF(MVT::i32), Op, 16267 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 16268 0); 16269 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 16270 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 16271 } 16272 16273 static void ReplaceReductionResults(SDNode *N, 16274 SmallVectorImpl<SDValue> &Results, 16275 SelectionDAG &DAG, unsigned InterOp, 16276 unsigned AcrossOp) { 16277 EVT LoVT, HiVT; 16278 SDValue Lo, Hi; 16279 SDLoc dl(N); 16280 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 16281 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 16282 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 16283 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 16284 Results.push_back(SplitVal); 16285 } 16286 16287 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 16288 SDLoc DL(N); 16289 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 16290 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 16291 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 16292 DAG.getConstant(64, DL, MVT::i64))); 16293 return std::make_pair(Lo, Hi); 16294 } 16295 16296 void AArch64TargetLowering::ReplaceExtractSubVectorResults( 16297 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 16298 SDValue In = N->getOperand(0); 16299 EVT InVT = In.getValueType(); 16300 16301 // Common code will handle these just fine. 16302 if (!InVT.isScalableVector() || !InVT.isInteger()) 16303 return; 16304 16305 SDLoc DL(N); 16306 EVT VT = N->getValueType(0); 16307 16308 // The following checks bail if this is not a halving operation. 16309 16310 ElementCount ResEC = VT.getVectorElementCount(); 16311 16312 if (InVT.getVectorElementCount() != (ResEC * 2)) 16313 return; 16314 16315 auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16316 if (!CIndex) 16317 return; 16318 16319 unsigned Index = CIndex->getZExtValue(); 16320 if ((Index != 0) && (Index != ResEC.getKnownMinValue())) 16321 return; 16322 16323 unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI; 16324 EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext()); 16325 16326 SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0)); 16327 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half)); 16328 } 16329 16330 // Create an even/odd pair of X registers holding integer value V. 16331 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 16332 SDLoc dl(V.getNode()); 16333 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 16334 SDValue VHi = DAG.getAnyExtOrTrunc( 16335 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 16336 dl, MVT::i64); 16337 if (DAG.getDataLayout().isBigEndian()) 16338 std::swap (VLo, VHi); 16339 SDValue RegClass = 16340 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 16341 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 16342 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 16343 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 16344 return SDValue( 16345 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 16346 } 16347 16348 static void ReplaceCMP_SWAP_128Results(SDNode *N, 16349 SmallVectorImpl<SDValue> &Results, 16350 SelectionDAG &DAG, 16351 const AArch64Subtarget *Subtarget) { 16352 assert(N->getValueType(0) == MVT::i128 && 16353 "AtomicCmpSwap on types less than 128 should be legal"); 16354 16355 if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) { 16356 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 16357 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 16358 SDValue Ops[] = { 16359 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 16360 createGPRPairNode(DAG, N->getOperand(3)), // Store value 16361 N->getOperand(1), // Ptr 16362 N->getOperand(0), // Chain in 16363 }; 16364 16365 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 16366 16367 unsigned Opcode; 16368 switch (MemOp->getOrdering()) { 16369 case AtomicOrdering::Monotonic: 16370 Opcode = AArch64::CASPX; 16371 break; 16372 case AtomicOrdering::Acquire: 16373 Opcode = AArch64::CASPAX; 16374 break; 16375 case AtomicOrdering::Release: 16376 Opcode = AArch64::CASPLX; 16377 break; 16378 case AtomicOrdering::AcquireRelease: 16379 case AtomicOrdering::SequentiallyConsistent: 16380 Opcode = AArch64::CASPALX; 16381 break; 16382 default: 16383 llvm_unreachable("Unexpected ordering!"); 16384 } 16385 16386 MachineSDNode *CmpSwap = DAG.getMachineNode( 16387 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 16388 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 16389 16390 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 16391 if (DAG.getDataLayout().isBigEndian()) 16392 std::swap(SubReg1, SubReg2); 16393 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 16394 SDValue(CmpSwap, 0)); 16395 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 16396 SDValue(CmpSwap, 0)); 16397 Results.push_back( 16398 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi)); 16399 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 16400 return; 16401 } 16402 16403 auto Desired = splitInt128(N->getOperand(2), DAG); 16404 auto New = splitInt128(N->getOperand(3), DAG); 16405 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 16406 New.first, New.second, N->getOperand(0)}; 16407 SDNode *CmpSwap = DAG.getMachineNode( 16408 AArch64::CMP_SWAP_128, SDLoc(N), 16409 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 16410 16411 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 16412 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 16413 16414 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 16415 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1))); 16416 Results.push_back(SDValue(CmpSwap, 3)); 16417 } 16418 16419 void AArch64TargetLowering::ReplaceNodeResults( 16420 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 16421 switch (N->getOpcode()) { 16422 default: 16423 llvm_unreachable("Don't know how to custom expand this"); 16424 case ISD::BITCAST: 16425 ReplaceBITCASTResults(N, Results, DAG); 16426 return; 16427 case ISD::VECREDUCE_ADD: 16428 case ISD::VECREDUCE_SMAX: 16429 case ISD::VECREDUCE_SMIN: 16430 case ISD::VECREDUCE_UMAX: 16431 case ISD::VECREDUCE_UMIN: 16432 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 16433 return; 16434 16435 case ISD::CTPOP: 16436 if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG)) 16437 Results.push_back(Result); 16438 return; 16439 case AArch64ISD::SADDV: 16440 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 16441 return; 16442 case AArch64ISD::UADDV: 16443 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 16444 return; 16445 case AArch64ISD::SMINV: 16446 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 16447 return; 16448 case AArch64ISD::UMINV: 16449 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 16450 return; 16451 case AArch64ISD::SMAXV: 16452 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 16453 return; 16454 case AArch64ISD::UMAXV: 16455 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 16456 return; 16457 case ISD::FP_TO_UINT: 16458 case ISD::FP_TO_SINT: 16459 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 16460 // Let normal code take care of it by not adding anything to Results. 16461 return; 16462 case ISD::ATOMIC_CMP_SWAP: 16463 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 16464 return; 16465 case ISD::LOAD: { 16466 assert(SDValue(N, 0).getValueType() == MVT::i128 && 16467 "unexpected load's value type"); 16468 LoadSDNode *LoadNode = cast<LoadSDNode>(N); 16469 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) { 16470 // Non-volatile loads are optimized later in AArch64's load/store 16471 // optimizer. 16472 return; 16473 } 16474 16475 SDValue Result = DAG.getMemIntrinsicNode( 16476 AArch64ISD::LDP, SDLoc(N), 16477 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}), 16478 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(), 16479 LoadNode->getMemOperand()); 16480 16481 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 16482 Result.getValue(0), Result.getValue(1)); 16483 Results.append({Pair, Result.getValue(2) /* Chain */}); 16484 return; 16485 } 16486 case ISD::EXTRACT_SUBVECTOR: 16487 ReplaceExtractSubVectorResults(N, Results, DAG); 16488 return; 16489 case ISD::INTRINSIC_WO_CHAIN: { 16490 EVT VT = N->getValueType(0); 16491 assert((VT == MVT::i8 || VT == MVT::i16) && 16492 "custom lowering for unexpected type"); 16493 16494 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0)); 16495 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 16496 switch (IntID) { 16497 default: 16498 return; 16499 case Intrinsic::aarch64_sve_clasta_n: { 16500 SDLoc DL(N); 16501 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 16502 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32, 16503 N->getOperand(1), Op2, N->getOperand(3)); 16504 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16505 return; 16506 } 16507 case Intrinsic::aarch64_sve_clastb_n: { 16508 SDLoc DL(N); 16509 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 16510 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32, 16511 N->getOperand(1), Op2, N->getOperand(3)); 16512 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16513 return; 16514 } 16515 case Intrinsic::aarch64_sve_lasta: { 16516 SDLoc DL(N); 16517 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32, 16518 N->getOperand(1), N->getOperand(2)); 16519 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16520 return; 16521 } 16522 case Intrinsic::aarch64_sve_lastb: { 16523 SDLoc DL(N); 16524 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32, 16525 N->getOperand(1), N->getOperand(2)); 16526 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 16527 return; 16528 } 16529 } 16530 } 16531 } 16532 } 16533 16534 bool AArch64TargetLowering::useLoadStackGuardNode() const { 16535 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 16536 return TargetLowering::useLoadStackGuardNode(); 16537 return true; 16538 } 16539 16540 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 16541 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 16542 // reciprocal if there are three or more FDIVs. 16543 return 3; 16544 } 16545 16546 TargetLoweringBase::LegalizeTypeAction 16547 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 16548 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 16549 // v4i16, v2i32 instead of to promote. 16550 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 16551 VT == MVT::v1f32) 16552 return TypeWidenVector; 16553 16554 return TargetLoweringBase::getPreferredVectorAction(VT); 16555 } 16556 16557 // Loads and stores less than 128-bits are already atomic; ones above that 16558 // are doomed anyway, so defer to the default libcall and blame the OS when 16559 // things go wrong. 16560 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 16561 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 16562 return Size == 128; 16563 } 16564 16565 // Loads and stores less than 128-bits are already atomic; ones above that 16566 // are doomed anyway, so defer to the default libcall and blame the OS when 16567 // things go wrong. 16568 TargetLowering::AtomicExpansionKind 16569 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 16570 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 16571 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 16572 } 16573 16574 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 16575 TargetLowering::AtomicExpansionKind 16576 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 16577 if (AI->isFloatingPointOperation()) 16578 return AtomicExpansionKind::CmpXChg; 16579 16580 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 16581 if (Size > 128) return AtomicExpansionKind::None; 16582 // Nand not supported in LSE. 16583 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 16584 // Leave 128 bits to LLSC. 16585 if (Subtarget->hasLSE() && Size < 128) 16586 return AtomicExpansionKind::None; 16587 if (Subtarget->outlineAtomics() && Size < 128) { 16588 // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far. 16589 // Don't outline them unless 16590 // (1) high level <atomic> support approved: 16591 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf 16592 // (2) low level libgcc and compiler-rt support implemented by: 16593 // min/max outline atomics helpers 16594 if (AI->getOperation() != AtomicRMWInst::Min && 16595 AI->getOperation() != AtomicRMWInst::Max && 16596 AI->getOperation() != AtomicRMWInst::UMin && 16597 AI->getOperation() != AtomicRMWInst::UMax) { 16598 return AtomicExpansionKind::None; 16599 } 16600 } 16601 return AtomicExpansionKind::LLSC; 16602 } 16603 16604 TargetLowering::AtomicExpansionKind 16605 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 16606 AtomicCmpXchgInst *AI) const { 16607 // If subtarget has LSE, leave cmpxchg intact for codegen. 16608 if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) 16609 return AtomicExpansionKind::None; 16610 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 16611 // implement cmpxchg without spilling. If the address being exchanged is also 16612 // on the stack and close enough to the spill slot, this can lead to a 16613 // situation where the monitor always gets cleared and the atomic operation 16614 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 16615 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 16616 return AtomicExpansionKind::None; 16617 return AtomicExpansionKind::LLSC; 16618 } 16619 16620 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 16621 AtomicOrdering Ord) const { 16622 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16623 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 16624 bool IsAcquire = isAcquireOrStronger(Ord); 16625 16626 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 16627 // intrinsic must return {i64, i64} and we have to recombine them into a 16628 // single i128 here. 16629 if (ValTy->getPrimitiveSizeInBits() == 128) { 16630 Intrinsic::ID Int = 16631 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 16632 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 16633 16634 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16635 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 16636 16637 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 16638 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 16639 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 16640 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 16641 return Builder.CreateOr( 16642 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 16643 } 16644 16645 Type *Tys[] = { Addr->getType() }; 16646 Intrinsic::ID Int = 16647 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 16648 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 16649 16650 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 16651 16652 const DataLayout &DL = M->getDataLayout(); 16653 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 16654 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 16655 16656 return Builder.CreateBitCast(Trunc, EltTy); 16657 } 16658 16659 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 16660 IRBuilder<> &Builder) const { 16661 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16662 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 16663 } 16664 16665 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 16666 Value *Val, Value *Addr, 16667 AtomicOrdering Ord) const { 16668 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 16669 bool IsRelease = isReleaseOrStronger(Ord); 16670 16671 // Since the intrinsics must have legal type, the i128 intrinsics take two 16672 // parameters: "i64, i64". We must marshal Val into the appropriate form 16673 // before the call. 16674 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 16675 Intrinsic::ID Int = 16676 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 16677 Function *Stxr = Intrinsic::getDeclaration(M, Int); 16678 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 16679 16680 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 16681 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 16682 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 16683 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 16684 } 16685 16686 Intrinsic::ID Int = 16687 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 16688 Type *Tys[] = { Addr->getType() }; 16689 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 16690 16691 const DataLayout &DL = M->getDataLayout(); 16692 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 16693 Val = Builder.CreateBitCast(Val, IntValTy); 16694 16695 return Builder.CreateCall(Stxr, 16696 {Builder.CreateZExtOrBitCast( 16697 Val, Stxr->getFunctionType()->getParamType(0)), 16698 Addr}); 16699 } 16700 16701 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 16702 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 16703 if (Ty->isArrayTy()) 16704 return true; 16705 16706 const TypeSize &TySize = Ty->getPrimitiveSizeInBits(); 16707 if (TySize.isScalable() && TySize.getKnownMinSize() > 128) 16708 return true; 16709 16710 return false; 16711 } 16712 16713 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 16714 EVT) const { 16715 return false; 16716 } 16717 16718 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 16719 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 16720 Function *ThreadPointerFunc = 16721 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 16722 return IRB.CreatePointerCast( 16723 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 16724 Offset), 16725 IRB.getInt8PtrTy()->getPointerTo(0)); 16726 } 16727 16728 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 16729 // Android provides a fixed TLS slot for the stack cookie. See the definition 16730 // of TLS_SLOT_STACK_GUARD in 16731 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 16732 if (Subtarget->isTargetAndroid()) 16733 return UseTlsOffset(IRB, 0x28); 16734 16735 // Fuchsia is similar. 16736 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 16737 if (Subtarget->isTargetFuchsia()) 16738 return UseTlsOffset(IRB, -0x10); 16739 16740 return TargetLowering::getIRStackGuard(IRB); 16741 } 16742 16743 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 16744 // MSVC CRT provides functionalities for stack protection. 16745 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 16746 // MSVC CRT has a global variable holding security cookie. 16747 M.getOrInsertGlobal("__security_cookie", 16748 Type::getInt8PtrTy(M.getContext())); 16749 16750 // MSVC CRT has a function to validate security cookie. 16751 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 16752 "__security_check_cookie", Type::getVoidTy(M.getContext()), 16753 Type::getInt8PtrTy(M.getContext())); 16754 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 16755 F->setCallingConv(CallingConv::Win64); 16756 F->addAttribute(1, Attribute::AttrKind::InReg); 16757 } 16758 return; 16759 } 16760 TargetLowering::insertSSPDeclarations(M); 16761 } 16762 16763 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 16764 // MSVC CRT has a global variable holding security cookie. 16765 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16766 return M.getGlobalVariable("__security_cookie"); 16767 return TargetLowering::getSDagStackGuard(M); 16768 } 16769 16770 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 16771 // MSVC CRT has a function to validate security cookie. 16772 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 16773 return M.getFunction("__security_check_cookie"); 16774 return TargetLowering::getSSPStackGuardCheck(M); 16775 } 16776 16777 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 16778 // Android provides a fixed TLS slot for the SafeStack pointer. See the 16779 // definition of TLS_SLOT_SAFESTACK in 16780 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 16781 if (Subtarget->isTargetAndroid()) 16782 return UseTlsOffset(IRB, 0x48); 16783 16784 // Fuchsia is similar. 16785 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 16786 if (Subtarget->isTargetFuchsia()) 16787 return UseTlsOffset(IRB, -0x8); 16788 16789 return TargetLowering::getSafeStackPointerLocation(IRB); 16790 } 16791 16792 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 16793 const Instruction &AndI) const { 16794 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 16795 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 16796 // may be beneficial to sink in other cases, but we would have to check that 16797 // the cmp would not get folded into the br to form a cbz for these to be 16798 // beneficial. 16799 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 16800 if (!Mask) 16801 return false; 16802 return Mask->getValue().isPowerOf2(); 16803 } 16804 16805 bool AArch64TargetLowering:: 16806 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 16807 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 16808 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 16809 SelectionDAG &DAG) const { 16810 // Does baseline recommend not to perform the fold by default? 16811 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 16812 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 16813 return false; 16814 // Else, if this is a vector shift, prefer 'shl'. 16815 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 16816 } 16817 16818 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 16819 SDNode *N) const { 16820 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16821 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin()) 16822 return false; 16823 return true; 16824 } 16825 16826 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 16827 // Update IsSplitCSR in AArch64unctionInfo. 16828 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 16829 AFI->setIsSplitCSR(true); 16830 } 16831 16832 void AArch64TargetLowering::insertCopiesSplitCSR( 16833 MachineBasicBlock *Entry, 16834 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 16835 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 16836 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 16837 if (!IStart) 16838 return; 16839 16840 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 16841 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 16842 MachineBasicBlock::iterator MBBI = Entry->begin(); 16843 for (const MCPhysReg *I = IStart; *I; ++I) { 16844 const TargetRegisterClass *RC = nullptr; 16845 if (AArch64::GPR64RegClass.contains(*I)) 16846 RC = &AArch64::GPR64RegClass; 16847 else if (AArch64::FPR64RegClass.contains(*I)) 16848 RC = &AArch64::FPR64RegClass; 16849 else 16850 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 16851 16852 Register NewVR = MRI->createVirtualRegister(RC); 16853 // Create copy from CSR to a virtual register. 16854 // FIXME: this currently does not emit CFI pseudo-instructions, it works 16855 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 16856 // nounwind. If we want to generalize this later, we may need to emit 16857 // CFI pseudo-instructions. 16858 assert(Entry->getParent()->getFunction().hasFnAttribute( 16859 Attribute::NoUnwind) && 16860 "Function should be nounwind in insertCopiesSplitCSR!"); 16861 Entry->addLiveIn(*I); 16862 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 16863 .addReg(*I); 16864 16865 // Insert the copy-back instructions right before the terminator. 16866 for (auto *Exit : Exits) 16867 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 16868 TII->get(TargetOpcode::COPY), *I) 16869 .addReg(NewVR); 16870 } 16871 } 16872 16873 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 16874 // Integer division on AArch64 is expensive. However, when aggressively 16875 // optimizing for code size, we prefer to use a div instruction, as it is 16876 // usually smaller than the alternative sequence. 16877 // The exception to this is vector division. Since AArch64 doesn't have vector 16878 // integer division, leaving the division as-is is a loss even in terms of 16879 // size, because it will have to be scalarized, while the alternative code 16880 // sequence can be performed in vector form. 16881 bool OptSize = Attr.hasFnAttribute(Attribute::MinSize); 16882 return OptSize && !VT.isVector(); 16883 } 16884 16885 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 16886 // We want inc-of-add for scalars and sub-of-not for vectors. 16887 return VT.isScalarInteger(); 16888 } 16889 16890 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 16891 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 16892 } 16893 16894 unsigned 16895 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 16896 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 16897 return getPointerTy(DL).getSizeInBits(); 16898 16899 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 16900 } 16901 16902 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 16903 MF.getFrameInfo().computeMaxCallFrameSize(MF); 16904 TargetLoweringBase::finalizeLowering(MF); 16905 } 16906 16907 // Unlike X86, we let frame lowering assign offsets to all catch objects. 16908 bool AArch64TargetLowering::needsFixedCatchObjects() const { 16909 return false; 16910 } 16911 16912 bool AArch64TargetLowering::shouldLocalize( 16913 const MachineInstr &MI, const TargetTransformInfo *TTI) const { 16914 switch (MI.getOpcode()) { 16915 case TargetOpcode::G_GLOBAL_VALUE: { 16916 // On Darwin, TLS global vars get selected into function calls, which 16917 // we don't want localized, as they can get moved into the middle of a 16918 // another call sequence. 16919 const GlobalValue &GV = *MI.getOperand(1).getGlobal(); 16920 if (GV.isThreadLocal() && Subtarget->isTargetMachO()) 16921 return false; 16922 break; 16923 } 16924 // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being 16925 // localizable. 16926 case AArch64::ADRP: 16927 case AArch64::G_ADD_LOW: 16928 return true; 16929 default: 16930 break; 16931 } 16932 return TargetLoweringBase::shouldLocalize(MI, TTI); 16933 } 16934 16935 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const { 16936 if (isa<ScalableVectorType>(Inst.getType())) 16937 return true; 16938 16939 for (unsigned i = 0; i < Inst.getNumOperands(); ++i) 16940 if (isa<ScalableVectorType>(Inst.getOperand(i)->getType())) 16941 return true; 16942 16943 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) { 16944 if (isa<ScalableVectorType>(AI->getAllocatedType())) 16945 return true; 16946 } 16947 16948 return false; 16949 } 16950 16951 // Return the largest legal scalable vector type that matches VT's element type. 16952 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) { 16953 assert(VT.isFixedLengthVector() && 16954 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16955 "Expected legal fixed length vector!"); 16956 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 16957 default: 16958 llvm_unreachable("unexpected element type for SVE container"); 16959 case MVT::i8: 16960 return EVT(MVT::nxv16i8); 16961 case MVT::i16: 16962 return EVT(MVT::nxv8i16); 16963 case MVT::i32: 16964 return EVT(MVT::nxv4i32); 16965 case MVT::i64: 16966 return EVT(MVT::nxv2i64); 16967 case MVT::f16: 16968 return EVT(MVT::nxv8f16); 16969 case MVT::f32: 16970 return EVT(MVT::nxv4f32); 16971 case MVT::f64: 16972 return EVT(MVT::nxv2f64); 16973 } 16974 } 16975 16976 // Return a PTRUE with active lanes corresponding to the extent of VT. 16977 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL, 16978 EVT VT) { 16979 assert(VT.isFixedLengthVector() && 16980 DAG.getTargetLoweringInfo().isTypeLegal(VT) && 16981 "Expected legal fixed length vector!"); 16982 16983 int PgPattern; 16984 switch (VT.getVectorNumElements()) { 16985 default: 16986 llvm_unreachable("unexpected element count for SVE predicate"); 16987 case 1: 16988 PgPattern = AArch64SVEPredPattern::vl1; 16989 break; 16990 case 2: 16991 PgPattern = AArch64SVEPredPattern::vl2; 16992 break; 16993 case 4: 16994 PgPattern = AArch64SVEPredPattern::vl4; 16995 break; 16996 case 8: 16997 PgPattern = AArch64SVEPredPattern::vl8; 16998 break; 16999 case 16: 17000 PgPattern = AArch64SVEPredPattern::vl16; 17001 break; 17002 case 32: 17003 PgPattern = AArch64SVEPredPattern::vl32; 17004 break; 17005 case 64: 17006 PgPattern = AArch64SVEPredPattern::vl64; 17007 break; 17008 case 128: 17009 PgPattern = AArch64SVEPredPattern::vl128; 17010 break; 17011 case 256: 17012 PgPattern = AArch64SVEPredPattern::vl256; 17013 break; 17014 } 17015 17016 // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can 17017 // use AArch64SVEPredPattern::all, which can enable the use of unpredicated 17018 // variants of instructions when available. 17019 17020 MVT MaskVT; 17021 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 17022 default: 17023 llvm_unreachable("unexpected element type for SVE predicate"); 17024 case MVT::i8: 17025 MaskVT = MVT::nxv16i1; 17026 break; 17027 case MVT::i16: 17028 case MVT::f16: 17029 MaskVT = MVT::nxv8i1; 17030 break; 17031 case MVT::i32: 17032 case MVT::f32: 17033 MaskVT = MVT::nxv4i1; 17034 break; 17035 case MVT::i64: 17036 case MVT::f64: 17037 MaskVT = MVT::nxv2i1; 17038 break; 17039 } 17040 17041 return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT, 17042 DAG.getTargetConstant(PgPattern, DL, MVT::i64)); 17043 } 17044 17045 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL, 17046 EVT VT) { 17047 assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 17048 "Expected legal scalable vector!"); 17049 auto PredTy = VT.changeVectorElementType(MVT::i1); 17050 return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all); 17051 } 17052 17053 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) { 17054 if (VT.isFixedLengthVector()) 17055 return getPredicateForFixedLengthVector(DAG, DL, VT); 17056 17057 return getPredicateForScalableVector(DAG, DL, VT); 17058 } 17059 17060 // Grow V to consume an entire SVE register. 17061 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) { 17062 assert(VT.isScalableVector() && 17063 "Expected to convert into a scalable vector!"); 17064 assert(V.getValueType().isFixedLengthVector() && 17065 "Expected a fixed length vector operand!"); 17066 SDLoc DL(V); 17067 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17068 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 17069 } 17070 17071 // Shrink V so it's just big enough to maintain a VT's worth of data. 17072 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) { 17073 assert(VT.isFixedLengthVector() && 17074 "Expected to convert into a fixed length vector!"); 17075 assert(V.getValueType().isScalableVector() && 17076 "Expected a scalable vector operand!"); 17077 SDLoc DL(V); 17078 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17079 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 17080 } 17081 17082 // Convert all fixed length vector loads larger than NEON to masked_loads. 17083 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE( 17084 SDValue Op, SelectionDAG &DAG) const { 17085 auto Load = cast<LoadSDNode>(Op); 17086 17087 SDLoc DL(Op); 17088 EVT VT = Op.getValueType(); 17089 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17090 17091 auto NewLoad = DAG.getMaskedLoad( 17092 ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(), 17093 getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT), 17094 Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(), 17095 Load->getExtensionType()); 17096 17097 auto Result = convertFromScalableVector(DAG, VT, NewLoad); 17098 SDValue MergedValues[2] = {Result, Load->getChain()}; 17099 return DAG.getMergeValues(MergedValues, DL); 17100 } 17101 17102 // Convert all fixed length vector stores larger than NEON to masked_stores. 17103 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE( 17104 SDValue Op, SelectionDAG &DAG) const { 17105 auto Store = cast<StoreSDNode>(Op); 17106 17107 SDLoc DL(Op); 17108 EVT VT = Store->getValue().getValueType(); 17109 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17110 17111 auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue()); 17112 return DAG.getMaskedStore( 17113 Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(), 17114 getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(), 17115 Store->getMemOperand(), Store->getAddressingMode(), 17116 Store->isTruncatingStore()); 17117 } 17118 17119 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE( 17120 SDValue Op, SelectionDAG &DAG) const { 17121 SDLoc dl(Op); 17122 EVT VT = Op.getValueType(); 17123 EVT EltVT = VT.getVectorElementType(); 17124 17125 bool Signed = Op.getOpcode() == ISD::SDIV; 17126 unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED; 17127 17128 // Scalable vector i32/i64 DIV is supported. 17129 if (EltVT == MVT::i32 || EltVT == MVT::i64) 17130 return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true); 17131 17132 // Scalable vector i8/i16 DIV is not supported. Promote it to i32. 17133 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17134 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 17135 EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext()); 17136 EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT); 17137 17138 // Convert the operands to scalable vectors. 17139 SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0)); 17140 SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1)); 17141 17142 // Extend the scalable operands. 17143 unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 17144 unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI; 17145 SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0); 17146 SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1); 17147 SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0); 17148 SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1); 17149 17150 // Convert back to fixed vectors so the DIV can be further lowered. 17151 Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo); 17152 Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo); 17153 Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi); 17154 Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi); 17155 SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT, 17156 Op0Lo, Op1Lo); 17157 SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT, 17158 Op0Hi, Op1Hi); 17159 17160 // Convert again to scalable vectors to truncate. 17161 ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo); 17162 ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi); 17163 SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT, 17164 ResultLo, ResultHi); 17165 17166 return convertFromScalableVector(DAG, VT, ScalableResult); 17167 } 17168 17169 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE( 17170 SDValue Op, SelectionDAG &DAG) const { 17171 EVT VT = Op.getValueType(); 17172 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 17173 17174 SDLoc DL(Op); 17175 SDValue Val = Op.getOperand(0); 17176 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType()); 17177 Val = convertToScalableVector(DAG, ContainerVT, Val); 17178 17179 bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND; 17180 unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO; 17181 17182 // Repeatedly unpack Val until the result is of the desired element type. 17183 switch (ContainerVT.getSimpleVT().SimpleTy) { 17184 default: 17185 llvm_unreachable("unimplemented container type"); 17186 case MVT::nxv16i8: 17187 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val); 17188 if (VT.getVectorElementType() == MVT::i16) 17189 break; 17190 LLVM_FALLTHROUGH; 17191 case MVT::nxv8i16: 17192 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val); 17193 if (VT.getVectorElementType() == MVT::i32) 17194 break; 17195 LLVM_FALLTHROUGH; 17196 case MVT::nxv4i32: 17197 Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val); 17198 assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!"); 17199 break; 17200 } 17201 17202 return convertFromScalableVector(DAG, VT, Val); 17203 } 17204 17205 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE( 17206 SDValue Op, SelectionDAG &DAG) const { 17207 EVT VT = Op.getValueType(); 17208 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!"); 17209 17210 SDLoc DL(Op); 17211 SDValue Val = Op.getOperand(0); 17212 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType()); 17213 Val = convertToScalableVector(DAG, ContainerVT, Val); 17214 17215 // Repeatedly truncate Val until the result is of the desired element type. 17216 switch (ContainerVT.getSimpleVT().SimpleTy) { 17217 default: 17218 llvm_unreachable("unimplemented container type"); 17219 case MVT::nxv2i64: 17220 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val); 17221 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val); 17222 if (VT.getVectorElementType() == MVT::i32) 17223 break; 17224 LLVM_FALLTHROUGH; 17225 case MVT::nxv4i32: 17226 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val); 17227 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val); 17228 if (VT.getVectorElementType() == MVT::i16) 17229 break; 17230 LLVM_FALLTHROUGH; 17231 case MVT::nxv8i16: 17232 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val); 17233 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val); 17234 assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!"); 17235 break; 17236 } 17237 17238 return convertFromScalableVector(DAG, VT, Val); 17239 } 17240 17241 // Convert vector operation 'Op' to an equivalent predicated operation whereby 17242 // the original operation's type is used to construct a suitable predicate. 17243 // NOTE: The results for inactive lanes are undefined. 17244 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op, 17245 SelectionDAG &DAG, 17246 unsigned NewOp, 17247 bool OverrideNEON) const { 17248 EVT VT = Op.getValueType(); 17249 SDLoc DL(Op); 17250 auto Pg = getPredicateForVector(DAG, DL, VT); 17251 17252 if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) { 17253 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17254 17255 // Create list of operands by converting existing ones to scalable types. 17256 SmallVector<SDValue, 4> Operands = {Pg}; 17257 for (const SDValue &V : Op->op_values()) { 17258 if (isa<CondCodeSDNode>(V)) { 17259 Operands.push_back(V); 17260 continue; 17261 } 17262 17263 if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) { 17264 EVT VTArg = VTNode->getVT().getVectorElementType(); 17265 EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg); 17266 Operands.push_back(DAG.getValueType(NewVTArg)); 17267 continue; 17268 } 17269 17270 assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) && 17271 "Only fixed length vectors are supported!"); 17272 Operands.push_back(convertToScalableVector(DAG, ContainerVT, V)); 17273 } 17274 17275 if (isMergePassthruOpcode(NewOp)) 17276 Operands.push_back(DAG.getUNDEF(ContainerVT)); 17277 17278 auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands); 17279 return convertFromScalableVector(DAG, VT, ScalableRes); 17280 } 17281 17282 assert(VT.isScalableVector() && "Only expect to lower scalable vector op!"); 17283 17284 SmallVector<SDValue, 4> Operands = {Pg}; 17285 for (const SDValue &V : Op->op_values()) { 17286 assert((!V.getValueType().isVector() || 17287 V.getValueType().isScalableVector()) && 17288 "Only scalable vectors are supported!"); 17289 Operands.push_back(V); 17290 } 17291 17292 if (isMergePassthruOpcode(NewOp)) 17293 Operands.push_back(DAG.getUNDEF(VT)); 17294 17295 return DAG.getNode(NewOp, DL, VT, Operands); 17296 } 17297 17298 // If a fixed length vector operation has no side effects when applied to 17299 // undefined elements, we can safely use scalable vectors to perform the same 17300 // operation without needing to worry about predication. 17301 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op, 17302 SelectionDAG &DAG) const { 17303 EVT VT = Op.getValueType(); 17304 assert(useSVEForFixedLengthVectorVT(VT) && 17305 "Only expected to lower fixed length vector operation!"); 17306 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT); 17307 17308 // Create list of operands by converting existing ones to scalable types. 17309 SmallVector<SDValue, 4> Ops; 17310 for (const SDValue &V : Op->op_values()) { 17311 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 17312 17313 // Pass through non-vector operands. 17314 if (!V.getValueType().isVector()) { 17315 Ops.push_back(V); 17316 continue; 17317 } 17318 17319 // "cast" fixed length vector to a scalable vector. 17320 assert(useSVEForFixedLengthVectorVT(V.getValueType()) && 17321 "Only fixed length vectors are supported!"); 17322 Ops.push_back(convertToScalableVector(DAG, ContainerVT, V)); 17323 } 17324 17325 auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops); 17326 return convertFromScalableVector(DAG, VT, ScalableRes); 17327 } 17328 17329 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp, 17330 SelectionDAG &DAG) const { 17331 SDLoc DL(ScalarOp); 17332 SDValue AccOp = ScalarOp.getOperand(0); 17333 SDValue VecOp = ScalarOp.getOperand(1); 17334 EVT SrcVT = VecOp.getValueType(); 17335 EVT ResVT = SrcVT.getVectorElementType(); 17336 17337 EVT ContainerVT = SrcVT; 17338 if (SrcVT.isFixedLengthVector()) { 17339 ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT); 17340 VecOp = convertToScalableVector(DAG, ContainerVT, VecOp); 17341 } 17342 17343 SDValue Pg = getPredicateForVector(DAG, DL, SrcVT); 17344 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 17345 17346 // Convert operands to Scalable. 17347 AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, 17348 DAG.getUNDEF(ContainerVT), AccOp, Zero); 17349 17350 // Perform reduction. 17351 SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT, 17352 Pg, AccOp, VecOp); 17353 17354 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero); 17355 } 17356 17357 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp, 17358 SelectionDAG &DAG) const { 17359 SDLoc DL(ReduceOp); 17360 SDValue Op = ReduceOp.getOperand(0); 17361 EVT OpVT = Op.getValueType(); 17362 EVT VT = ReduceOp.getValueType(); 17363 17364 if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1) 17365 return SDValue(); 17366 17367 SDValue Pg = getPredicateForVector(DAG, DL, OpVT); 17368 17369 switch (ReduceOp.getOpcode()) { 17370 default: 17371 return SDValue(); 17372 case ISD::VECREDUCE_OR: 17373 return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE); 17374 case ISD::VECREDUCE_AND: { 17375 Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg); 17376 return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE); 17377 } 17378 case ISD::VECREDUCE_XOR: { 17379 SDValue ID = 17380 DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64); 17381 SDValue Cntp = 17382 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op); 17383 return DAG.getAnyExtOrTrunc(Cntp, DL, VT); 17384 } 17385 } 17386 17387 return SDValue(); 17388 } 17389 17390 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode, 17391 SDValue ScalarOp, 17392 SelectionDAG &DAG) const { 17393 SDLoc DL(ScalarOp); 17394 SDValue VecOp = ScalarOp.getOperand(0); 17395 EVT SrcVT = VecOp.getValueType(); 17396 17397 if (useSVEForFixedLengthVectorVT(SrcVT, true)) { 17398 EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT); 17399 VecOp = convertToScalableVector(DAG, ContainerVT, VecOp); 17400 } 17401 17402 // UADDV always returns an i64 result. 17403 EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 : 17404 SrcVT.getVectorElementType(); 17405 EVT RdxVT = SrcVT; 17406 if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED) 17407 RdxVT = getPackedSVEVectorVT(ResVT); 17408 17409 SDValue Pg = getPredicateForVector(DAG, DL, SrcVT); 17410 SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp); 17411 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, 17412 Rdx, DAG.getConstant(0, DL, MVT::i64)); 17413 17414 // The VEC_REDUCE nodes expect an element size result. 17415 if (ResVT != ScalarOp.getValueType()) 17416 Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType()); 17417 17418 return Res; 17419 } 17420 17421 SDValue 17422 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op, 17423 SelectionDAG &DAG) const { 17424 EVT VT = Op.getValueType(); 17425 SDLoc DL(Op); 17426 17427 EVT InVT = Op.getOperand(1).getValueType(); 17428 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17429 SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1)); 17430 SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2)); 17431 17432 // Convert the mask to a predicated (NOTE: We don't need to worry about 17433 // inactive lanes since VSELECT is safe when given undefined elements). 17434 EVT MaskVT = Op.getOperand(0).getValueType(); 17435 EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT); 17436 auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0)); 17437 Mask = DAG.getNode(ISD::TRUNCATE, DL, 17438 MaskContainerVT.changeVectorElementType(MVT::i1), Mask); 17439 17440 auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT, 17441 Mask, Op1, Op2); 17442 17443 return convertFromScalableVector(DAG, VT, ScalableRes); 17444 } 17445 17446 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE( 17447 SDValue Op, SelectionDAG &DAG) const { 17448 SDLoc DL(Op); 17449 EVT InVT = Op.getOperand(0).getValueType(); 17450 EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT); 17451 17452 assert(useSVEForFixedLengthVectorVT(InVT) && 17453 "Only expected to lower fixed length vector operation!"); 17454 assert(Op.getValueType() == InVT.changeTypeToInteger() && 17455 "Expected integer result of the same bit length as the inputs!"); 17456 17457 // Expand floating point vector comparisons. 17458 if (InVT.isFloatingPoint()) 17459 return SDValue(); 17460 17461 auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0)); 17462 auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1)); 17463 auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT); 17464 17465 EVT CmpVT = Pg.getValueType(); 17466 auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT, 17467 {Pg, Op1, Op2, Op.getOperand(2)}); 17468 17469 EVT PromoteVT = ContainerVT.changeTypeToInteger(); 17470 auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT); 17471 return convertFromScalableVector(DAG, Op.getValueType(), Promote); 17472 } 17473 17474 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op, 17475 SelectionDAG &DAG) const { 17476 SDLoc DL(Op); 17477 EVT InVT = Op.getValueType(); 17478 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17479 (void)TLI; 17480 17481 assert(VT.isScalableVector() && TLI.isTypeLegal(VT) && 17482 InVT.isScalableVector() && TLI.isTypeLegal(InVT) && 17483 "Only expect to cast between legal scalable vector types!"); 17484 assert((VT.getVectorElementType() == MVT::i1) == 17485 (InVT.getVectorElementType() == MVT::i1) && 17486 "Cannot cast between data and predicate scalable vector types!"); 17487 17488 if (InVT == VT) 17489 return Op; 17490 17491 if (VT.getVectorElementType() == MVT::i1) 17492 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op); 17493 17494 EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType()); 17495 EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType()); 17496 assert((VT == PackedVT || InVT == PackedInVT) && 17497 "Cannot cast between unpacked scalable vector types!"); 17498 17499 // Pack input if required. 17500 if (InVT != PackedInVT) 17501 Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op); 17502 17503 Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op); 17504 17505 // Unpack result if required. 17506 if (VT != PackedVT) 17507 Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op); 17508 17509 return Op; 17510 } 17511