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/StringSwitch.h" 31 #include "llvm/ADT/Triple.h" 32 #include "llvm/ADT/Twine.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 static cl::opt<bool> 103 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 104 cl::desc("Allow AArch64 SLI/SRI formation"), 105 cl::init(false)); 106 107 // FIXME: The necessary dtprel relocations don't seem to be supported 108 // well in the GNU bfd and gold linkers at the moment. Therefore, by 109 // default, for now, fall back to GeneralDynamic code generation. 110 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 111 "aarch64-elf-ldtls-generation", cl::Hidden, 112 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 113 cl::init(false)); 114 115 static cl::opt<bool> 116 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 117 cl::desc("Enable AArch64 logical imm instruction " 118 "optimization"), 119 cl::init(true)); 120 121 /// Value type used for condition codes. 122 static const MVT MVT_CC = MVT::i32; 123 124 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 125 const AArch64Subtarget &STI) 126 : TargetLowering(TM), Subtarget(&STI) { 127 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 128 // we have to make something up. Arbitrarily, choose ZeroOrOne. 129 setBooleanContents(ZeroOrOneBooleanContent); 130 // When comparing vectors the result sets the different elements in the 131 // vector to all-one or all-zero. 132 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 133 134 // Set up the register classes. 135 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 136 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 137 138 if (Subtarget->hasFPARMv8()) { 139 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 140 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 141 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 142 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 143 } 144 145 if (Subtarget->hasNEON()) { 146 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 147 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 148 // Someone set us up the NEON. 149 addDRTypeForNEON(MVT::v2f32); 150 addDRTypeForNEON(MVT::v8i8); 151 addDRTypeForNEON(MVT::v4i16); 152 addDRTypeForNEON(MVT::v2i32); 153 addDRTypeForNEON(MVT::v1i64); 154 addDRTypeForNEON(MVT::v1f64); 155 addDRTypeForNEON(MVT::v4f16); 156 157 addQRTypeForNEON(MVT::v4f32); 158 addQRTypeForNEON(MVT::v2f64); 159 addQRTypeForNEON(MVT::v16i8); 160 addQRTypeForNEON(MVT::v8i16); 161 addQRTypeForNEON(MVT::v4i32); 162 addQRTypeForNEON(MVT::v2i64); 163 addQRTypeForNEON(MVT::v8f16); 164 } 165 166 if (Subtarget->hasSVE()) { 167 // Add legal sve predicate types 168 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 169 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 170 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 171 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 172 173 // Add legal sve data types 174 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 175 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 176 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 177 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 178 179 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 180 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 181 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 182 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 183 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 184 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 185 186 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) { 187 setOperationAction(ISD::SADDSAT, VT, Legal); 188 setOperationAction(ISD::UADDSAT, VT, Legal); 189 setOperationAction(ISD::SSUBSAT, VT, Legal); 190 setOperationAction(ISD::USUBSAT, VT, Legal); 191 setOperationAction(ISD::SMAX, VT, Legal); 192 setOperationAction(ISD::UMAX, VT, Legal); 193 setOperationAction(ISD::SMIN, VT, Legal); 194 setOperationAction(ISD::UMIN, VT, Legal); 195 } 196 197 for (auto VT : 198 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8, 199 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 }) 200 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal); 201 } 202 203 // Compute derived properties from the register classes 204 computeRegisterProperties(Subtarget->getRegisterInfo()); 205 206 // Provide all sorts of operation actions 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 209 setOperationAction(ISD::SETCC, MVT::i32, Custom); 210 setOperationAction(ISD::SETCC, MVT::i64, Custom); 211 setOperationAction(ISD::SETCC, MVT::f16, Custom); 212 setOperationAction(ISD::SETCC, MVT::f32, Custom); 213 setOperationAction(ISD::SETCC, MVT::f64, Custom); 214 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 215 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 216 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 217 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 218 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 219 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 220 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 221 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 222 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 223 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 224 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 225 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 226 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 227 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 228 setOperationAction(ISD::SELECT, MVT::i32, Custom); 229 setOperationAction(ISD::SELECT, MVT::i64, Custom); 230 setOperationAction(ISD::SELECT, MVT::f16, Custom); 231 setOperationAction(ISD::SELECT, MVT::f32, Custom); 232 setOperationAction(ISD::SELECT, MVT::f64, Custom); 233 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 234 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 235 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 236 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 237 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 238 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 239 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 240 241 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 242 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 243 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 244 245 setOperationAction(ISD::FREM, MVT::f32, Expand); 246 setOperationAction(ISD::FREM, MVT::f64, Expand); 247 setOperationAction(ISD::FREM, MVT::f80, Expand); 248 249 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 250 251 // Custom lowering hooks are needed for XOR 252 // to fold it into CSINC/CSINV. 253 setOperationAction(ISD::XOR, MVT::i32, Custom); 254 setOperationAction(ISD::XOR, MVT::i64, Custom); 255 256 // Virtually no operation on f128 is legal, but LLVM can't expand them when 257 // there's a valid register class, so we need custom operations in most cases. 258 setOperationAction(ISD::FABS, MVT::f128, Expand); 259 setOperationAction(ISD::FADD, MVT::f128, Custom); 260 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 261 setOperationAction(ISD::FCOS, MVT::f128, Expand); 262 setOperationAction(ISD::FDIV, MVT::f128, Custom); 263 setOperationAction(ISD::FMA, MVT::f128, Expand); 264 setOperationAction(ISD::FMUL, MVT::f128, Custom); 265 setOperationAction(ISD::FNEG, MVT::f128, Expand); 266 setOperationAction(ISD::FPOW, MVT::f128, Expand); 267 setOperationAction(ISD::FREM, MVT::f128, Expand); 268 setOperationAction(ISD::FRINT, MVT::f128, Expand); 269 setOperationAction(ISD::FSIN, MVT::f128, Expand); 270 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 271 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 272 setOperationAction(ISD::FSUB, MVT::f128, Custom); 273 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 274 setOperationAction(ISD::SETCC, MVT::f128, Custom); 275 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 276 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 277 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 278 setOperationAction(ISD::SELECT, MVT::f128, Custom); 279 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 280 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 281 282 // Lowering for many of the conversions is actually specified by the non-f128 283 // type. The LowerXXX function will be trivial when f128 isn't involved. 284 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 285 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 286 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 287 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 288 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 289 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom); 290 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 291 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 292 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 293 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 294 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 295 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom); 296 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 297 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 298 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 299 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 300 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 301 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom); 302 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 303 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 304 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 305 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 306 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 307 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom); 308 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 309 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 310 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 311 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom); 312 313 // Variable arguments. 314 setOperationAction(ISD::VASTART, MVT::Other, Custom); 315 setOperationAction(ISD::VAARG, MVT::Other, Custom); 316 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 317 setOperationAction(ISD::VAEND, MVT::Other, Expand); 318 319 // Variable-sized objects. 320 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 321 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 322 323 if (Subtarget->isTargetWindows()) 324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 325 else 326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 327 328 // Constant pool entries 329 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 330 331 // BlockAddress 332 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 333 334 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 335 setOperationAction(ISD::ADDC, MVT::i32, Custom); 336 setOperationAction(ISD::ADDE, MVT::i32, Custom); 337 setOperationAction(ISD::SUBC, MVT::i32, Custom); 338 setOperationAction(ISD::SUBE, MVT::i32, Custom); 339 setOperationAction(ISD::ADDC, MVT::i64, Custom); 340 setOperationAction(ISD::ADDE, MVT::i64, Custom); 341 setOperationAction(ISD::SUBC, MVT::i64, Custom); 342 setOperationAction(ISD::SUBE, MVT::i64, Custom); 343 344 // AArch64 lacks both left-rotate and popcount instructions. 345 setOperationAction(ISD::ROTL, MVT::i32, Expand); 346 setOperationAction(ISD::ROTL, MVT::i64, Expand); 347 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 348 setOperationAction(ISD::ROTL, VT, Expand); 349 setOperationAction(ISD::ROTR, VT, Expand); 350 } 351 352 // AArch64 doesn't have {U|S}MUL_LOHI. 353 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 354 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 355 356 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 357 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 358 359 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 360 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 361 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 362 setOperationAction(ISD::SDIVREM, VT, Expand); 363 setOperationAction(ISD::UDIVREM, VT, Expand); 364 } 365 setOperationAction(ISD::SREM, MVT::i32, Expand); 366 setOperationAction(ISD::SREM, MVT::i64, Expand); 367 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 368 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 369 setOperationAction(ISD::UREM, MVT::i32, Expand); 370 setOperationAction(ISD::UREM, MVT::i64, Expand); 371 372 // Custom lower Add/Sub/Mul with overflow. 373 setOperationAction(ISD::SADDO, MVT::i32, Custom); 374 setOperationAction(ISD::SADDO, MVT::i64, Custom); 375 setOperationAction(ISD::UADDO, MVT::i32, Custom); 376 setOperationAction(ISD::UADDO, MVT::i64, Custom); 377 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 378 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 379 setOperationAction(ISD::USUBO, MVT::i32, Custom); 380 setOperationAction(ISD::USUBO, MVT::i64, Custom); 381 setOperationAction(ISD::SMULO, MVT::i32, Custom); 382 setOperationAction(ISD::SMULO, MVT::i64, Custom); 383 setOperationAction(ISD::UMULO, MVT::i32, Custom); 384 setOperationAction(ISD::UMULO, MVT::i64, Custom); 385 386 setOperationAction(ISD::FSIN, MVT::f32, Expand); 387 setOperationAction(ISD::FSIN, MVT::f64, Expand); 388 setOperationAction(ISD::FCOS, MVT::f32, Expand); 389 setOperationAction(ISD::FCOS, MVT::f64, Expand); 390 setOperationAction(ISD::FPOW, MVT::f32, Expand); 391 setOperationAction(ISD::FPOW, MVT::f64, Expand); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 393 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 394 if (Subtarget->hasFullFP16()) 395 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 396 else 397 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 398 399 setOperationAction(ISD::FREM, MVT::f16, Promote); 400 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 401 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 402 setOperationAction(ISD::FPOW, MVT::f16, Promote); 403 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 404 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 405 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 406 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 407 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 408 setOperationAction(ISD::FCOS, MVT::f16, Promote); 409 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 410 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 411 setOperationAction(ISD::FSIN, MVT::f16, Promote); 412 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 413 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 414 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 415 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 416 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 417 setOperationAction(ISD::FEXP, MVT::f16, Promote); 418 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 419 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 420 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 421 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 422 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 423 setOperationAction(ISD::FLOG, MVT::f16, Promote); 424 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 425 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 426 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 427 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 428 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 429 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 430 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 431 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 432 433 if (!Subtarget->hasFullFP16()) { 434 setOperationAction(ISD::SELECT, MVT::f16, Promote); 435 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 436 setOperationAction(ISD::SETCC, MVT::f16, Promote); 437 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 438 setOperationAction(ISD::FADD, MVT::f16, Promote); 439 setOperationAction(ISD::FSUB, MVT::f16, Promote); 440 setOperationAction(ISD::FMUL, MVT::f16, Promote); 441 setOperationAction(ISD::FDIV, MVT::f16, Promote); 442 setOperationAction(ISD::FMA, MVT::f16, Promote); 443 setOperationAction(ISD::FNEG, MVT::f16, Promote); 444 setOperationAction(ISD::FABS, MVT::f16, Promote); 445 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 446 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 447 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 448 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 449 setOperationAction(ISD::FRINT, MVT::f16, Promote); 450 setOperationAction(ISD::FROUND, MVT::f16, Promote); 451 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 452 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 453 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 454 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 455 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 456 457 // promote v4f16 to v4f32 when that is known to be safe. 458 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 459 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 460 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 461 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 462 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 463 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 464 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 465 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 466 467 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 468 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 469 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 470 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 471 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 472 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 473 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 474 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 475 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 476 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 477 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 478 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 479 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 480 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 481 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 482 483 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 484 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 485 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 486 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 487 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 488 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 489 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 490 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 491 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 492 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 493 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 494 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 495 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 496 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 497 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 498 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 499 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 500 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 501 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 502 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 503 } 504 505 // AArch64 has implementations of a lot of rounding-like FP operations. 506 for (MVT Ty : {MVT::f32, MVT::f64}) { 507 setOperationAction(ISD::FFLOOR, Ty, Legal); 508 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 509 setOperationAction(ISD::FCEIL, Ty, Legal); 510 setOperationAction(ISD::FRINT, Ty, Legal); 511 setOperationAction(ISD::FTRUNC, Ty, Legal); 512 setOperationAction(ISD::FROUND, Ty, Legal); 513 setOperationAction(ISD::FMINNUM, Ty, Legal); 514 setOperationAction(ISD::FMAXNUM, Ty, Legal); 515 setOperationAction(ISD::FMINIMUM, Ty, Legal); 516 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 517 setOperationAction(ISD::LROUND, Ty, Legal); 518 setOperationAction(ISD::LLROUND, Ty, Legal); 519 setOperationAction(ISD::LRINT, Ty, Legal); 520 setOperationAction(ISD::LLRINT, Ty, Legal); 521 } 522 523 if (Subtarget->hasFullFP16()) { 524 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 525 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 526 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 527 setOperationAction(ISD::FRINT, MVT::f16, Legal); 528 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 529 setOperationAction(ISD::FROUND, MVT::f16, Legal); 530 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 531 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 532 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 533 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 534 } 535 536 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 537 538 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 539 540 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 541 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 542 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 543 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 544 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 545 546 // 128-bit loads and stores can be done without expanding 547 setOperationAction(ISD::LOAD, MVT::i128, Custom); 548 setOperationAction(ISD::STORE, MVT::i128, Custom); 549 550 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the 551 // custom lowering, as there are no un-paired non-temporal stores and 552 // legalization will break up 256 bit inputs. 553 setOperationAction(ISD::STORE, MVT::v32i8, Custom); 554 setOperationAction(ISD::STORE, MVT::v16i16, Custom); 555 setOperationAction(ISD::STORE, MVT::v16f16, Custom); 556 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 557 setOperationAction(ISD::STORE, MVT::v8f32, Custom); 558 setOperationAction(ISD::STORE, MVT::v4f64, Custom); 559 setOperationAction(ISD::STORE, MVT::v4i64, Custom); 560 561 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 562 // This requires the Performance Monitors extension. 563 if (Subtarget->hasPerfMon()) 564 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 565 566 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 567 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 568 // Issue __sincos_stret if available. 569 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 570 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 571 } else { 572 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 573 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 574 } 575 576 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 577 // MSVCRT doesn't have powi; fall back to pow 578 setLibcallName(RTLIB::POWI_F32, nullptr); 579 setLibcallName(RTLIB::POWI_F64, nullptr); 580 } 581 582 // Make floating-point constants legal for the large code model, so they don't 583 // become loads from the constant pool. 584 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 585 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 586 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 587 } 588 589 // AArch64 does not have floating-point extending loads, i1 sign-extending 590 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 591 for (MVT VT : MVT::fp_valuetypes()) { 592 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 593 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 594 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 595 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 596 } 597 for (MVT VT : MVT::integer_valuetypes()) 598 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 599 600 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 601 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 602 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 603 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 604 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 605 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 606 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 607 608 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 609 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 610 611 // Indexed loads and stores are supported. 612 for (unsigned im = (unsigned)ISD::PRE_INC; 613 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 614 setIndexedLoadAction(im, MVT::i8, Legal); 615 setIndexedLoadAction(im, MVT::i16, Legal); 616 setIndexedLoadAction(im, MVT::i32, Legal); 617 setIndexedLoadAction(im, MVT::i64, Legal); 618 setIndexedLoadAction(im, MVT::f64, Legal); 619 setIndexedLoadAction(im, MVT::f32, Legal); 620 setIndexedLoadAction(im, MVT::f16, Legal); 621 setIndexedStoreAction(im, MVT::i8, Legal); 622 setIndexedStoreAction(im, MVT::i16, Legal); 623 setIndexedStoreAction(im, MVT::i32, Legal); 624 setIndexedStoreAction(im, MVT::i64, Legal); 625 setIndexedStoreAction(im, MVT::f64, Legal); 626 setIndexedStoreAction(im, MVT::f32, Legal); 627 setIndexedStoreAction(im, MVT::f16, Legal); 628 } 629 630 // Trap. 631 setOperationAction(ISD::TRAP, MVT::Other, Legal); 632 if (Subtarget->isTargetWindows()) 633 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 634 635 // We combine OR nodes for bitfield operations. 636 setTargetDAGCombine(ISD::OR); 637 // Try to create BICs for vector ANDs. 638 setTargetDAGCombine(ISD::AND); 639 640 // Vector add and sub nodes may conceal a high-half opportunity. 641 // Also, try to fold ADD into CSINC/CSINV.. 642 setTargetDAGCombine(ISD::ADD); 643 setTargetDAGCombine(ISD::SUB); 644 setTargetDAGCombine(ISD::SRL); 645 setTargetDAGCombine(ISD::XOR); 646 setTargetDAGCombine(ISD::SINT_TO_FP); 647 setTargetDAGCombine(ISD::UINT_TO_FP); 648 649 setTargetDAGCombine(ISD::FP_TO_SINT); 650 setTargetDAGCombine(ISD::FP_TO_UINT); 651 setTargetDAGCombine(ISD::FDIV); 652 653 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 654 655 setTargetDAGCombine(ISD::ANY_EXTEND); 656 setTargetDAGCombine(ISD::ZERO_EXTEND); 657 setTargetDAGCombine(ISD::SIGN_EXTEND); 658 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 659 setTargetDAGCombine(ISD::CONCAT_VECTORS); 660 setTargetDAGCombine(ISD::STORE); 661 if (Subtarget->supportsAddressTopByteIgnored()) 662 setTargetDAGCombine(ISD::LOAD); 663 664 setTargetDAGCombine(ISD::MUL); 665 666 setTargetDAGCombine(ISD::SELECT); 667 setTargetDAGCombine(ISD::VSELECT); 668 669 setTargetDAGCombine(ISD::INTRINSIC_VOID); 670 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 671 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 672 673 setTargetDAGCombine(ISD::GlobalAddress); 674 675 // In case of strict alignment, avoid an excessive number of byte wide stores. 676 MaxStoresPerMemsetOptSize = 8; 677 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 678 ? MaxStoresPerMemsetOptSize : 32; 679 680 MaxGluedStoresPerMemcpy = 4; 681 MaxStoresPerMemcpyOptSize = 4; 682 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 683 ? MaxStoresPerMemcpyOptSize : 16; 684 685 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 686 687 MaxLoadsPerMemcmpOptSize = 4; 688 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 689 ? MaxLoadsPerMemcmpOptSize : 8; 690 691 setStackPointerRegisterToSaveRestore(AArch64::SP); 692 693 setSchedulingPreference(Sched::Hybrid); 694 695 EnableExtLdPromotion = true; 696 697 // Set required alignment. 698 setMinFunctionAlignment(Align(4)); 699 // Set preferred alignments. 700 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 701 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 702 703 // Only change the limit for entries in a jump table if specified by 704 // the sub target, but not at the command line. 705 unsigned MaxJT = STI.getMaximumJumpTableSize(); 706 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 707 setMaximumJumpTableSize(MaxJT); 708 709 setHasExtractBitsInsn(true); 710 711 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 712 713 if (Subtarget->hasNEON()) { 714 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 715 // silliness like this: 716 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 717 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 718 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 719 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 720 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 721 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 722 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 723 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 724 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 725 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 726 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 727 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 728 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 729 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 730 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 731 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 732 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 733 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 734 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 735 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 736 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 737 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 738 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 739 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 740 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 741 742 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 743 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 744 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 745 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 746 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 747 748 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 749 750 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 751 // elements smaller than i32, so promote the input to i32 first. 752 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 753 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 754 // i8 vector elements also need promotion to i32 for v8i8 755 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 756 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 757 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 758 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 759 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 760 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 761 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 762 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 763 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 764 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 765 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 766 767 if (Subtarget->hasFullFP16()) { 768 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 769 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 770 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 771 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 772 } else { 773 // when AArch64 doesn't have fullfp16 support, promote the input 774 // to i32 first. 775 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 776 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 777 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 778 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 779 } 780 781 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 782 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 783 784 // AArch64 doesn't have MUL.2d: 785 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 786 // Custom handling for some quad-vector types to detect MULL. 787 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 788 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 789 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 790 791 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 792 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 793 // Vector reductions 794 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 795 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 796 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 797 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 798 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 799 800 // Saturates 801 setOperationAction(ISD::SADDSAT, VT, Legal); 802 setOperationAction(ISD::UADDSAT, VT, Legal); 803 setOperationAction(ISD::SSUBSAT, VT, Legal); 804 setOperationAction(ISD::USUBSAT, VT, Legal); 805 } 806 for (MVT VT : { MVT::v4f16, MVT::v2f32, 807 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 808 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 809 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 810 } 811 812 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 813 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 814 // Likewise, narrowing and extending vector loads/stores aren't handled 815 // directly. 816 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 817 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 818 819 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 820 setOperationAction(ISD::MULHS, VT, Legal); 821 setOperationAction(ISD::MULHU, VT, Legal); 822 } else { 823 setOperationAction(ISD::MULHS, VT, Expand); 824 setOperationAction(ISD::MULHU, VT, Expand); 825 } 826 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 827 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 828 829 setOperationAction(ISD::BSWAP, VT, Expand); 830 setOperationAction(ISD::CTTZ, VT, Expand); 831 832 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 833 setTruncStoreAction(VT, InnerVT, Expand); 834 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 835 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 836 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 837 } 838 } 839 840 // AArch64 has implementations of a lot of rounding-like FP operations. 841 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 842 setOperationAction(ISD::FFLOOR, Ty, Legal); 843 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 844 setOperationAction(ISD::FCEIL, Ty, Legal); 845 setOperationAction(ISD::FRINT, Ty, Legal); 846 setOperationAction(ISD::FTRUNC, Ty, Legal); 847 setOperationAction(ISD::FROUND, Ty, Legal); 848 } 849 850 if (Subtarget->hasFullFP16()) { 851 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 852 setOperationAction(ISD::FFLOOR, Ty, Legal); 853 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 854 setOperationAction(ISD::FCEIL, Ty, Legal); 855 setOperationAction(ISD::FRINT, Ty, Legal); 856 setOperationAction(ISD::FTRUNC, Ty, Legal); 857 setOperationAction(ISD::FROUND, Ty, Legal); 858 } 859 } 860 861 if (Subtarget->hasSVE()) 862 setOperationAction(ISD::VSCALE, MVT::i32, Custom); 863 864 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 865 } 866 867 if (Subtarget->hasSVE()) { 868 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a 869 // splat of 0 or undef) once vector selects supported in SVE codegen. See 870 // D68877 for more details. 871 for (MVT VT : MVT::integer_scalable_vector_valuetypes()) { 872 if (isTypeLegal(VT)) 873 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 874 } 875 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 876 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 877 } 878 879 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 880 } 881 882 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 883 assert(VT.isVector() && "VT should be a vector type"); 884 885 if (VT.isFloatingPoint()) { 886 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 887 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 888 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 889 } 890 891 // Mark vector float intrinsics as expand. 892 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 893 setOperationAction(ISD::FSIN, VT, Expand); 894 setOperationAction(ISD::FCOS, VT, Expand); 895 setOperationAction(ISD::FPOW, VT, Expand); 896 setOperationAction(ISD::FLOG, VT, Expand); 897 setOperationAction(ISD::FLOG2, VT, Expand); 898 setOperationAction(ISD::FLOG10, VT, Expand); 899 setOperationAction(ISD::FEXP, VT, Expand); 900 setOperationAction(ISD::FEXP2, VT, Expand); 901 902 // But we do support custom-lowering for FCOPYSIGN. 903 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 904 } 905 906 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 907 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 910 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 911 setOperationAction(ISD::SRA, VT, Custom); 912 setOperationAction(ISD::SRL, VT, Custom); 913 setOperationAction(ISD::SHL, VT, Custom); 914 setOperationAction(ISD::OR, VT, Custom); 915 setOperationAction(ISD::SETCC, VT, Custom); 916 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 917 918 setOperationAction(ISD::SELECT, VT, Expand); 919 setOperationAction(ISD::SELECT_CC, VT, Expand); 920 setOperationAction(ISD::VSELECT, VT, Expand); 921 for (MVT InnerVT : MVT::all_valuetypes()) 922 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 923 924 // CNT supports only B element sizes, then use UADDLP to widen. 925 if (VT != MVT::v8i8 && VT != MVT::v16i8) 926 setOperationAction(ISD::CTPOP, VT, Custom); 927 928 setOperationAction(ISD::UDIV, VT, Expand); 929 setOperationAction(ISD::SDIV, VT, Expand); 930 setOperationAction(ISD::UREM, VT, Expand); 931 setOperationAction(ISD::SREM, VT, Expand); 932 setOperationAction(ISD::FREM, VT, Expand); 933 934 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 935 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 936 937 if (!VT.isFloatingPoint()) 938 setOperationAction(ISD::ABS, VT, Legal); 939 940 // [SU][MIN|MAX] are available for all NEON types apart from i64. 941 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 942 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 943 setOperationAction(Opcode, VT, Legal); 944 945 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 946 if (VT.isFloatingPoint() && 947 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 948 for (unsigned Opcode : 949 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 950 setOperationAction(Opcode, VT, Legal); 951 952 if (Subtarget->isLittleEndian()) { 953 for (unsigned im = (unsigned)ISD::PRE_INC; 954 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 955 setIndexedLoadAction(im, VT, Legal); 956 setIndexedStoreAction(im, VT, Legal); 957 } 958 } 959 } 960 961 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 962 addRegisterClass(VT, &AArch64::FPR64RegClass); 963 addTypeForNEON(VT, MVT::v2i32); 964 } 965 966 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 967 addRegisterClass(VT, &AArch64::FPR128RegClass); 968 addTypeForNEON(VT, MVT::v4i32); 969 } 970 971 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 972 EVT VT) const { 973 if (!VT.isVector()) 974 return MVT::i32; 975 return VT.changeVectorElementTypeToInteger(); 976 } 977 978 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 979 const APInt &Demanded, 980 TargetLowering::TargetLoweringOpt &TLO, 981 unsigned NewOpc) { 982 uint64_t OldImm = Imm, NewImm, Enc; 983 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 984 985 // Return if the immediate is already all zeros, all ones, a bimm32 or a 986 // bimm64. 987 if (Imm == 0 || Imm == Mask || 988 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 989 return false; 990 991 unsigned EltSize = Size; 992 uint64_t DemandedBits = Demanded.getZExtValue(); 993 994 // Clear bits that are not demanded. 995 Imm &= DemandedBits; 996 997 while (true) { 998 // The goal here is to set the non-demanded bits in a way that minimizes 999 // the number of switching between 0 and 1. In order to achieve this goal, 1000 // we set the non-demanded bits to the value of the preceding demanded bits. 1001 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 1002 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 1003 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 1004 // The final result is 0b11000011. 1005 uint64_t NonDemandedBits = ~DemandedBits; 1006 uint64_t InvertedImm = ~Imm & DemandedBits; 1007 uint64_t RotatedImm = 1008 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 1009 NonDemandedBits; 1010 uint64_t Sum = RotatedImm + NonDemandedBits; 1011 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 1012 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 1013 NewImm = (Imm | Ones) & Mask; 1014 1015 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 1016 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 1017 // we halve the element size and continue the search. 1018 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 1019 break; 1020 1021 // We cannot shrink the element size any further if it is 2-bits. 1022 if (EltSize == 2) 1023 return false; 1024 1025 EltSize /= 2; 1026 Mask >>= EltSize; 1027 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 1028 1029 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 1030 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 1031 return false; 1032 1033 // Merge the upper and lower halves of Imm and DemandedBits. 1034 Imm |= Hi; 1035 DemandedBits |= DemandedBitsHi; 1036 } 1037 1038 ++NumOptimizedImms; 1039 1040 // Replicate the element across the register width. 1041 while (EltSize < Size) { 1042 NewImm |= NewImm << EltSize; 1043 EltSize *= 2; 1044 } 1045 1046 (void)OldImm; 1047 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 1048 "demanded bits should never be altered"); 1049 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 1050 1051 // Create the new constant immediate node. 1052 EVT VT = Op.getValueType(); 1053 SDLoc DL(Op); 1054 SDValue New; 1055 1056 // If the new constant immediate is all-zeros or all-ones, let the target 1057 // independent DAG combine optimize this node. 1058 if (NewImm == 0 || NewImm == OrigMask) { 1059 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 1060 TLO.DAG.getConstant(NewImm, DL, VT)); 1061 // Otherwise, create a machine node so that target independent DAG combine 1062 // doesn't undo this optimization. 1063 } else { 1064 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 1065 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 1066 New = SDValue( 1067 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1068 } 1069 1070 return TLO.CombineTo(Op, New); 1071 } 1072 1073 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1074 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 1075 // Delay this optimization to as late as possible. 1076 if (!TLO.LegalOps) 1077 return false; 1078 1079 if (!EnableOptimizeLogicalImm) 1080 return false; 1081 1082 EVT VT = Op.getValueType(); 1083 if (VT.isVector()) 1084 return false; 1085 1086 unsigned Size = VT.getSizeInBits(); 1087 assert((Size == 32 || Size == 64) && 1088 "i32 or i64 is expected after legalization."); 1089 1090 // Exit early if we demand all bits. 1091 if (Demanded.countPopulation() == Size) 1092 return false; 1093 1094 unsigned NewOpc; 1095 switch (Op.getOpcode()) { 1096 default: 1097 return false; 1098 case ISD::AND: 1099 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1100 break; 1101 case ISD::OR: 1102 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1103 break; 1104 case ISD::XOR: 1105 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1106 break; 1107 } 1108 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1109 if (!C) 1110 return false; 1111 uint64_t Imm = C->getZExtValue(); 1112 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 1113 } 1114 1115 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1116 /// Mask are known to be either zero or one and return them Known. 1117 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1118 const SDValue Op, KnownBits &Known, 1119 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1120 switch (Op.getOpcode()) { 1121 default: 1122 break; 1123 case AArch64ISD::CSEL: { 1124 KnownBits Known2; 1125 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1126 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1127 Known.Zero &= Known2.Zero; 1128 Known.One &= Known2.One; 1129 break; 1130 } 1131 case AArch64ISD::LOADgot: 1132 case AArch64ISD::ADDlow: { 1133 if (!Subtarget->isTargetILP32()) 1134 break; 1135 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1136 Known.Zero = APInt::getHighBitsSet(64, 32); 1137 break; 1138 } 1139 case ISD::INTRINSIC_W_CHAIN: { 1140 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1141 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1142 switch (IntID) { 1143 default: return; 1144 case Intrinsic::aarch64_ldaxr: 1145 case Intrinsic::aarch64_ldxr: { 1146 unsigned BitWidth = Known.getBitWidth(); 1147 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1148 unsigned MemBits = VT.getScalarSizeInBits(); 1149 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1150 return; 1151 } 1152 } 1153 break; 1154 } 1155 case ISD::INTRINSIC_WO_CHAIN: 1156 case ISD::INTRINSIC_VOID: { 1157 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1158 switch (IntNo) { 1159 default: 1160 break; 1161 case Intrinsic::aarch64_neon_umaxv: 1162 case Intrinsic::aarch64_neon_uminv: { 1163 // Figure out the datatype of the vector operand. The UMINV instruction 1164 // will zero extend the result, so we can mark as known zero all the 1165 // bits larger than the element datatype. 32-bit or larget doesn't need 1166 // this as those are legal types and will be handled by isel directly. 1167 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1168 unsigned BitWidth = Known.getBitWidth(); 1169 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1170 assert(BitWidth >= 8 && "Unexpected width!"); 1171 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1172 Known.Zero |= Mask; 1173 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1174 assert(BitWidth >= 16 && "Unexpected width!"); 1175 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1176 Known.Zero |= Mask; 1177 } 1178 break; 1179 } break; 1180 } 1181 } 1182 } 1183 } 1184 1185 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1186 EVT) const { 1187 return MVT::i64; 1188 } 1189 1190 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1191 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1192 bool *Fast) const { 1193 if (Subtarget->requiresStrictAlign()) 1194 return false; 1195 1196 if (Fast) { 1197 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1198 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1199 // See comments in performSTORECombine() for more details about 1200 // these conditions. 1201 1202 // Code that uses clang vector extensions can mark that it 1203 // wants unaligned accesses to be treated as fast by 1204 // underspecifying alignment to be 1 or 2. 1205 Align <= 2 || 1206 1207 // Disregard v2i64. Memcpy lowering produces those and splitting 1208 // them regresses performance on micro-benchmarks and olden/bh. 1209 VT == MVT::v2i64; 1210 } 1211 return true; 1212 } 1213 1214 // Same as above but handling LLTs instead. 1215 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1216 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1217 bool *Fast) const { 1218 if (Subtarget->requiresStrictAlign()) 1219 return false; 1220 1221 if (Fast) { 1222 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1223 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1224 Ty.getSizeInBytes() != 16 || 1225 // See comments in performSTORECombine() for more details about 1226 // these conditions. 1227 1228 // Code that uses clang vector extensions can mark that it 1229 // wants unaligned accesses to be treated as fast by 1230 // underspecifying alignment to be 1 or 2. 1231 Align <= 2 || 1232 1233 // Disregard v2i64. Memcpy lowering produces those and splitting 1234 // them regresses performance on micro-benchmarks and olden/bh. 1235 Ty == LLT::vector(2, 64); 1236 } 1237 return true; 1238 } 1239 1240 FastISel * 1241 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1242 const TargetLibraryInfo *libInfo) const { 1243 return AArch64::createFastISel(funcInfo, libInfo); 1244 } 1245 1246 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1247 switch ((AArch64ISD::NodeType)Opcode) { 1248 case AArch64ISD::FIRST_NUMBER: break; 1249 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1250 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1251 case AArch64ISD::ADR: return "AArch64ISD::ADR"; 1252 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1253 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1254 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1255 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1256 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1257 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1258 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1259 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1260 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1261 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1262 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1263 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1264 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1265 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1266 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1267 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1268 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1269 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1270 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1271 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1272 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1273 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1274 case AArch64ISD::STRICT_FCMP: return "AArch64ISD::STRICT_FCMP"; 1275 case AArch64ISD::STRICT_FCMPE: return "AArch64ISD::STRICT_FCMPE"; 1276 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1277 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1278 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1279 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1280 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1281 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1282 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1283 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1284 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1285 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1286 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1287 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1288 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1289 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1290 case AArch64ISD::BSP: return "AArch64ISD::BSP"; 1291 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1292 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1293 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1294 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1295 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1296 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1297 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1298 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1299 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1300 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1301 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1302 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1303 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1304 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1305 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1306 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1307 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1308 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1309 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1310 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1311 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1312 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1313 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1314 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1315 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1316 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1317 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1318 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1319 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1320 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1321 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1322 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1323 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1324 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1325 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1326 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1327 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1328 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1329 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1330 case AArch64ISD::SMAXV_PRED: return "AArch64ISD::SMAXV_PRED"; 1331 case AArch64ISD::UMAXV_PRED: return "AArch64ISD::UMAXV_PRED"; 1332 case AArch64ISD::SMINV_PRED: return "AArch64ISD::SMINV_PRED"; 1333 case AArch64ISD::UMINV_PRED: return "AArch64ISD::UMINV_PRED"; 1334 case AArch64ISD::ORV_PRED: return "AArch64ISD::ORV_PRED"; 1335 case AArch64ISD::EORV_PRED: return "AArch64ISD::EORV_PRED"; 1336 case AArch64ISD::ANDV_PRED: return "AArch64ISD::ANDV_PRED"; 1337 case AArch64ISD::CLASTA_N: return "AArch64ISD::CLASTA_N"; 1338 case AArch64ISD::CLASTB_N: return "AArch64ISD::CLASTB_N"; 1339 case AArch64ISD::LASTA: return "AArch64ISD::LASTA"; 1340 case AArch64ISD::LASTB: return "AArch64ISD::LASTB"; 1341 case AArch64ISD::REV: return "AArch64ISD::REV"; 1342 case AArch64ISD::TBL: return "AArch64ISD::TBL"; 1343 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1344 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1345 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1346 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1347 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1348 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1349 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1350 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1351 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1352 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1353 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1354 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1355 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1356 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1357 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1358 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1359 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1360 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1361 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1362 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1363 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1364 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1365 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1366 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1367 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1368 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1369 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1370 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1371 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1372 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1373 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1374 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1375 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1376 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1377 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1378 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1379 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1380 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1381 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1382 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1383 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1384 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1385 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1386 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1387 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1388 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1389 case AArch64ISD::STG: return "AArch64ISD::STG"; 1390 case AArch64ISD::STZG: return "AArch64ISD::STZG"; 1391 case AArch64ISD::ST2G: return "AArch64ISD::ST2G"; 1392 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G"; 1393 case AArch64ISD::SUNPKHI: return "AArch64ISD::SUNPKHI"; 1394 case AArch64ISD::SUNPKLO: return "AArch64ISD::SUNPKLO"; 1395 case AArch64ISD::UUNPKHI: return "AArch64ISD::UUNPKHI"; 1396 case AArch64ISD::UUNPKLO: return "AArch64ISD::UUNPKLO"; 1397 case AArch64ISD::INSR: return "AArch64ISD::INSR"; 1398 case AArch64ISD::PTEST: return "AArch64ISD::PTEST"; 1399 case AArch64ISD::PTRUE: return "AArch64ISD::PTRUE"; 1400 case AArch64ISD::LDNF1: return "AArch64ISD::LDNF1"; 1401 case AArch64ISD::LDNF1S: return "AArch64ISD::LDNF1S"; 1402 case AArch64ISD::LDFF1: return "AArch64ISD::LDFF1"; 1403 case AArch64ISD::LDFF1S: return "AArch64ISD::LDFF1S"; 1404 case AArch64ISD::GLD1: return "AArch64ISD::GLD1"; 1405 case AArch64ISD::GLD1_SCALED: return "AArch64ISD::GLD1_SCALED"; 1406 case AArch64ISD::GLD1_SXTW: return "AArch64ISD::GLD1_SXTW"; 1407 case AArch64ISD::GLD1_UXTW: return "AArch64ISD::GLD1_UXTW"; 1408 case AArch64ISD::GLD1_SXTW_SCALED: return "AArch64ISD::GLD1_SXTW_SCALED"; 1409 case AArch64ISD::GLD1_UXTW_SCALED: return "AArch64ISD::GLD1_UXTW_SCALED"; 1410 case AArch64ISD::GLD1_IMM: return "AArch64ISD::GLD1_IMM"; 1411 case AArch64ISD::GLD1S: return "AArch64ISD::GLD1S"; 1412 case AArch64ISD::GLD1S_SCALED: return "AArch64ISD::GLD1S_SCALED"; 1413 case AArch64ISD::GLD1S_SXTW: return "AArch64ISD::GLD1S_SXTW"; 1414 case AArch64ISD::GLD1S_UXTW: return "AArch64ISD::GLD1S_UXTW"; 1415 case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED"; 1416 case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED"; 1417 case AArch64ISD::GLD1S_IMM: return "AArch64ISD::GLD1S_IMM"; 1418 case AArch64ISD::SST1: return "AArch64ISD::SST1"; 1419 case AArch64ISD::SST1_SCALED: return "AArch64ISD::SST1_SCALED"; 1420 case AArch64ISD::SST1_SXTW: return "AArch64ISD::SST1_SXTW"; 1421 case AArch64ISD::SST1_UXTW: return "AArch64ISD::SST1_UXTW"; 1422 case AArch64ISD::SST1_SXTW_SCALED: return "AArch64ISD::SST1_SXTW_SCALED"; 1423 case AArch64ISD::SST1_UXTW_SCALED: return "AArch64ISD::SST1_UXTW_SCALED"; 1424 case AArch64ISD::SST1_IMM: return "AArch64ISD::SST1_IMM"; 1425 case AArch64ISD::LDP: return "AArch64ISD::LDP"; 1426 case AArch64ISD::STP: return "AArch64ISD::STP"; 1427 case AArch64ISD::STNP: return "AArch64ISD::STNP"; 1428 case AArch64ISD::DUP_PRED: return "AArch64ISD::DUP_PRED"; 1429 case AArch64ISD::INDEX_VECTOR: return "AArch64ISD::INDEX_VECTOR"; 1430 } 1431 return nullptr; 1432 } 1433 1434 MachineBasicBlock * 1435 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1436 MachineBasicBlock *MBB) const { 1437 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1438 // phi node: 1439 1440 // OrigBB: 1441 // [... previous instrs leading to comparison ...] 1442 // b.ne TrueBB 1443 // b EndBB 1444 // TrueBB: 1445 // ; Fallthrough 1446 // EndBB: 1447 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1448 1449 MachineFunction *MF = MBB->getParent(); 1450 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1451 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1452 DebugLoc DL = MI.getDebugLoc(); 1453 MachineFunction::iterator It = ++MBB->getIterator(); 1454 1455 Register DestReg = MI.getOperand(0).getReg(); 1456 Register IfTrueReg = MI.getOperand(1).getReg(); 1457 Register IfFalseReg = MI.getOperand(2).getReg(); 1458 unsigned CondCode = MI.getOperand(3).getImm(); 1459 bool NZCVKilled = MI.getOperand(4).isKill(); 1460 1461 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1462 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1463 MF->insert(It, TrueBB); 1464 MF->insert(It, EndBB); 1465 1466 // Transfer rest of current basic-block to EndBB 1467 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1468 MBB->end()); 1469 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1470 1471 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1472 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1473 MBB->addSuccessor(TrueBB); 1474 MBB->addSuccessor(EndBB); 1475 1476 // TrueBB falls through to the end. 1477 TrueBB->addSuccessor(EndBB); 1478 1479 if (!NZCVKilled) { 1480 TrueBB->addLiveIn(AArch64::NZCV); 1481 EndBB->addLiveIn(AArch64::NZCV); 1482 } 1483 1484 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1485 .addReg(IfTrueReg) 1486 .addMBB(TrueBB) 1487 .addReg(IfFalseReg) 1488 .addMBB(MBB); 1489 1490 MI.eraseFromParent(); 1491 return EndBB; 1492 } 1493 1494 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 1495 MachineInstr &MI, MachineBasicBlock *BB) const { 1496 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 1497 BB->getParent()->getFunction().getPersonalityFn())) && 1498 "SEH does not use catchret!"); 1499 return BB; 1500 } 1501 1502 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1503 MachineInstr &MI, MachineBasicBlock *BB) const { 1504 switch (MI.getOpcode()) { 1505 default: 1506 #ifndef NDEBUG 1507 MI.dump(); 1508 #endif 1509 llvm_unreachable("Unexpected instruction for custom inserter!"); 1510 1511 case AArch64::F128CSEL: 1512 return EmitF128CSEL(MI, BB); 1513 1514 case TargetOpcode::STACKMAP: 1515 case TargetOpcode::PATCHPOINT: 1516 return emitPatchPoint(MI, BB); 1517 1518 case AArch64::CATCHRET: 1519 return EmitLoweredCatchRet(MI, BB); 1520 } 1521 } 1522 1523 //===----------------------------------------------------------------------===// 1524 // AArch64 Lowering private implementation. 1525 //===----------------------------------------------------------------------===// 1526 1527 //===----------------------------------------------------------------------===// 1528 // Lowering Code 1529 //===----------------------------------------------------------------------===// 1530 1531 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1532 /// CC 1533 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1534 switch (CC) { 1535 default: 1536 llvm_unreachable("Unknown condition code!"); 1537 case ISD::SETNE: 1538 return AArch64CC::NE; 1539 case ISD::SETEQ: 1540 return AArch64CC::EQ; 1541 case ISD::SETGT: 1542 return AArch64CC::GT; 1543 case ISD::SETGE: 1544 return AArch64CC::GE; 1545 case ISD::SETLT: 1546 return AArch64CC::LT; 1547 case ISD::SETLE: 1548 return AArch64CC::LE; 1549 case ISD::SETUGT: 1550 return AArch64CC::HI; 1551 case ISD::SETUGE: 1552 return AArch64CC::HS; 1553 case ISD::SETULT: 1554 return AArch64CC::LO; 1555 case ISD::SETULE: 1556 return AArch64CC::LS; 1557 } 1558 } 1559 1560 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1561 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1562 AArch64CC::CondCode &CondCode, 1563 AArch64CC::CondCode &CondCode2) { 1564 CondCode2 = AArch64CC::AL; 1565 switch (CC) { 1566 default: 1567 llvm_unreachable("Unknown FP condition!"); 1568 case ISD::SETEQ: 1569 case ISD::SETOEQ: 1570 CondCode = AArch64CC::EQ; 1571 break; 1572 case ISD::SETGT: 1573 case ISD::SETOGT: 1574 CondCode = AArch64CC::GT; 1575 break; 1576 case ISD::SETGE: 1577 case ISD::SETOGE: 1578 CondCode = AArch64CC::GE; 1579 break; 1580 case ISD::SETOLT: 1581 CondCode = AArch64CC::MI; 1582 break; 1583 case ISD::SETOLE: 1584 CondCode = AArch64CC::LS; 1585 break; 1586 case ISD::SETONE: 1587 CondCode = AArch64CC::MI; 1588 CondCode2 = AArch64CC::GT; 1589 break; 1590 case ISD::SETO: 1591 CondCode = AArch64CC::VC; 1592 break; 1593 case ISD::SETUO: 1594 CondCode = AArch64CC::VS; 1595 break; 1596 case ISD::SETUEQ: 1597 CondCode = AArch64CC::EQ; 1598 CondCode2 = AArch64CC::VS; 1599 break; 1600 case ISD::SETUGT: 1601 CondCode = AArch64CC::HI; 1602 break; 1603 case ISD::SETUGE: 1604 CondCode = AArch64CC::PL; 1605 break; 1606 case ISD::SETLT: 1607 case ISD::SETULT: 1608 CondCode = AArch64CC::LT; 1609 break; 1610 case ISD::SETLE: 1611 case ISD::SETULE: 1612 CondCode = AArch64CC::LE; 1613 break; 1614 case ISD::SETNE: 1615 case ISD::SETUNE: 1616 CondCode = AArch64CC::NE; 1617 break; 1618 } 1619 } 1620 1621 /// Convert a DAG fp condition code to an AArch64 CC. 1622 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1623 /// should be AND'ed instead of OR'ed. 1624 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1625 AArch64CC::CondCode &CondCode, 1626 AArch64CC::CondCode &CondCode2) { 1627 CondCode2 = AArch64CC::AL; 1628 switch (CC) { 1629 default: 1630 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1631 assert(CondCode2 == AArch64CC::AL); 1632 break; 1633 case ISD::SETONE: 1634 // (a one b) 1635 // == ((a olt b) || (a ogt b)) 1636 // == ((a ord b) && (a une b)) 1637 CondCode = AArch64CC::VC; 1638 CondCode2 = AArch64CC::NE; 1639 break; 1640 case ISD::SETUEQ: 1641 // (a ueq b) 1642 // == ((a uno b) || (a oeq b)) 1643 // == ((a ule b) && (a uge b)) 1644 CondCode = AArch64CC::PL; 1645 CondCode2 = AArch64CC::LE; 1646 break; 1647 } 1648 } 1649 1650 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1651 /// CC usable with the vector instructions. Fewer operations are available 1652 /// without a real NZCV register, so we have to use less efficient combinations 1653 /// to get the same effect. 1654 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1655 AArch64CC::CondCode &CondCode, 1656 AArch64CC::CondCode &CondCode2, 1657 bool &Invert) { 1658 Invert = false; 1659 switch (CC) { 1660 default: 1661 // Mostly the scalar mappings work fine. 1662 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1663 break; 1664 case ISD::SETUO: 1665 Invert = true; 1666 LLVM_FALLTHROUGH; 1667 case ISD::SETO: 1668 CondCode = AArch64CC::MI; 1669 CondCode2 = AArch64CC::GE; 1670 break; 1671 case ISD::SETUEQ: 1672 case ISD::SETULT: 1673 case ISD::SETULE: 1674 case ISD::SETUGT: 1675 case ISD::SETUGE: 1676 // All of the compare-mask comparisons are ordered, but we can switch 1677 // between the two by a double inversion. E.g. ULE == !OGT. 1678 Invert = true; 1679 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32), 1680 CondCode, CondCode2); 1681 break; 1682 } 1683 } 1684 1685 static bool isLegalArithImmed(uint64_t C) { 1686 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1687 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1688 LLVM_DEBUG(dbgs() << "Is imm " << C 1689 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 1690 return IsLegal; 1691 } 1692 1693 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 1694 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 1695 // can be set differently by this operation. It comes down to whether 1696 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1697 // everything is fine. If not then the optimization is wrong. Thus general 1698 // comparisons are only valid if op2 != 0. 1699 // 1700 // So, finally, the only LLVM-native comparisons that don't mention C and V 1701 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1702 // the absence of information about op2. 1703 static bool isCMN(SDValue Op, ISD::CondCode CC) { 1704 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 1705 (CC == ISD::SETEQ || CC == ISD::SETNE); 1706 } 1707 1708 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl, 1709 SelectionDAG &DAG, SDValue Chain, 1710 bool IsSignaling) { 1711 EVT VT = LHS.getValueType(); 1712 assert(VT != MVT::f128); 1713 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented"); 1714 unsigned Opcode = 1715 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP; 1716 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS}); 1717 } 1718 1719 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1720 const SDLoc &dl, SelectionDAG &DAG) { 1721 EVT VT = LHS.getValueType(); 1722 const bool FullFP16 = 1723 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1724 1725 if (VT.isFloatingPoint()) { 1726 assert(VT != MVT::f128); 1727 if (VT == MVT::f16 && !FullFP16) { 1728 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1729 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1730 VT = MVT::f32; 1731 } 1732 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1733 } 1734 1735 // The CMP instruction is just an alias for SUBS, and representing it as 1736 // SUBS means that it's possible to get CSE with subtract operations. 1737 // A later phase can perform the optimization of setting the destination 1738 // register to WZR/XZR if it ends up being unused. 1739 unsigned Opcode = AArch64ISD::SUBS; 1740 1741 if (isCMN(RHS, CC)) { 1742 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 1743 Opcode = AArch64ISD::ADDS; 1744 RHS = RHS.getOperand(1); 1745 } else if (isCMN(LHS, CC)) { 1746 // As we are looking for EQ/NE compares, the operands can be commuted ; can 1747 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 1748 Opcode = AArch64ISD::ADDS; 1749 LHS = LHS.getOperand(1); 1750 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1751 !isUnsignedIntSetCC(CC)) { 1752 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1753 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1754 // of the signed comparisons. 1755 Opcode = AArch64ISD::ANDS; 1756 RHS = LHS.getOperand(1); 1757 LHS = LHS.getOperand(0); 1758 } 1759 1760 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1761 .getValue(1); 1762 } 1763 1764 /// \defgroup AArch64CCMP CMP;CCMP matching 1765 /// 1766 /// These functions deal with the formation of CMP;CCMP;... sequences. 1767 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1768 /// a comparison. They set the NZCV flags to a predefined value if their 1769 /// predicate is false. This allows to express arbitrary conjunctions, for 1770 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 1771 /// expressed as: 1772 /// cmp A 1773 /// ccmp B, inv(CB), CA 1774 /// check for CB flags 1775 /// 1776 /// This naturally lets us implement chains of AND operations with SETCC 1777 /// operands. And we can even implement some other situations by transforming 1778 /// them: 1779 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 1780 /// negating the flags used in a CCMP/FCCMP operations. 1781 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 1782 /// by negating the flags we test for afterwards. i.e. 1783 /// NEG (CMP CCMP CCCMP ...) can be implemented. 1784 /// - Note that we can only ever negate all previously processed results. 1785 /// What we can not implement by flipping the flags to test is a negation 1786 /// of two sub-trees (because the negation affects all sub-trees emitted so 1787 /// far, so the 2nd sub-tree we emit would also affect the first). 1788 /// With those tools we can implement some OR operations: 1789 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 1790 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 1791 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 1792 /// elimination rules from earlier to implement the whole thing as a 1793 /// CCMP/FCCMP chain. 1794 /// 1795 /// As complete example: 1796 /// or (or (setCA (cmp A)) (setCB (cmp B))) 1797 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1798 /// can be reassociated to: 1799 /// or (and (setCC (cmp C)) setCD (cmp D)) 1800 // (or (setCA (cmp A)) (setCB (cmp B))) 1801 /// can be transformed to: 1802 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 1803 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1804 /// which can be implemented as: 1805 /// cmp C 1806 /// ccmp D, inv(CD), CC 1807 /// ccmp A, CA, inv(CD) 1808 /// ccmp B, CB, inv(CA) 1809 /// check for CB flags 1810 /// 1811 /// A counterexample is "or (and A B) (and C D)" which translates to 1812 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 1813 /// can only implement 1 of the inner (not) operations, but not both! 1814 /// @{ 1815 1816 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1817 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1818 ISD::CondCode CC, SDValue CCOp, 1819 AArch64CC::CondCode Predicate, 1820 AArch64CC::CondCode OutCC, 1821 const SDLoc &DL, SelectionDAG &DAG) { 1822 unsigned Opcode = 0; 1823 const bool FullFP16 = 1824 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1825 1826 if (LHS.getValueType().isFloatingPoint()) { 1827 assert(LHS.getValueType() != MVT::f128); 1828 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 1829 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1830 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1831 } 1832 Opcode = AArch64ISD::FCCMP; 1833 } else if (RHS.getOpcode() == ISD::SUB) { 1834 SDValue SubOp0 = RHS.getOperand(0); 1835 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1836 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1837 Opcode = AArch64ISD::CCMN; 1838 RHS = RHS.getOperand(1); 1839 } 1840 } 1841 if (Opcode == 0) 1842 Opcode = AArch64ISD::CCMP; 1843 1844 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1845 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1846 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1847 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1848 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1849 } 1850 1851 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 1852 /// expressed as a conjunction. See \ref AArch64CCMP. 1853 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 1854 /// changing the conditions on the SETCC tests. 1855 /// (this means we can call emitConjunctionRec() with 1856 /// Negate==true on this sub-tree) 1857 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 1858 /// cannot do the negation naturally. We are required to 1859 /// emit the subtree first in this case. 1860 /// \param WillNegate Is true if are called when the result of this 1861 /// subexpression must be negated. This happens when the 1862 /// outer expression is an OR. We can use this fact to know 1863 /// that we have a double negation (or (or ...) ...) that 1864 /// can be implemented for free. 1865 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 1866 bool &MustBeFirst, bool WillNegate, 1867 unsigned Depth = 0) { 1868 if (!Val.hasOneUse()) 1869 return false; 1870 unsigned Opcode = Val->getOpcode(); 1871 if (Opcode == ISD::SETCC) { 1872 if (Val->getOperand(0).getValueType() == MVT::f128) 1873 return false; 1874 CanNegate = true; 1875 MustBeFirst = false; 1876 return true; 1877 } 1878 // Protect against exponential runtime and stack overflow. 1879 if (Depth > 6) 1880 return false; 1881 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1882 bool IsOR = Opcode == ISD::OR; 1883 SDValue O0 = Val->getOperand(0); 1884 SDValue O1 = Val->getOperand(1); 1885 bool CanNegateL; 1886 bool MustBeFirstL; 1887 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 1888 return false; 1889 bool CanNegateR; 1890 bool MustBeFirstR; 1891 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 1892 return false; 1893 1894 if (MustBeFirstL && MustBeFirstR) 1895 return false; 1896 1897 if (IsOR) { 1898 // For an OR expression we need to be able to naturally negate at least 1899 // one side or we cannot do the transformation at all. 1900 if (!CanNegateL && !CanNegateR) 1901 return false; 1902 // If we the result of the OR will be negated and we can naturally negate 1903 // the leafs, then this sub-tree as a whole negates naturally. 1904 CanNegate = WillNegate && CanNegateL && CanNegateR; 1905 // If we cannot naturally negate the whole sub-tree, then this must be 1906 // emitted first. 1907 MustBeFirst = !CanNegate; 1908 } else { 1909 assert(Opcode == ISD::AND && "Must be OR or AND"); 1910 // We cannot naturally negate an AND operation. 1911 CanNegate = false; 1912 MustBeFirst = MustBeFirstL || MustBeFirstR; 1913 } 1914 return true; 1915 } 1916 return false; 1917 } 1918 1919 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1920 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1921 /// Tries to transform the given i1 producing node @p Val to a series compare 1922 /// and conditional compare operations. @returns an NZCV flags producing node 1923 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1924 /// transformation was not possible. 1925 /// \p Negate is true if we want this sub-tree being negated just by changing 1926 /// SETCC conditions. 1927 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 1928 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1929 AArch64CC::CondCode Predicate) { 1930 // We're at a tree leaf, produce a conditional comparison operation. 1931 unsigned Opcode = Val->getOpcode(); 1932 if (Opcode == ISD::SETCC) { 1933 SDValue LHS = Val->getOperand(0); 1934 SDValue RHS = Val->getOperand(1); 1935 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1936 bool isInteger = LHS.getValueType().isInteger(); 1937 if (Negate) 1938 CC = getSetCCInverse(CC, LHS.getValueType()); 1939 SDLoc DL(Val); 1940 // Determine OutCC and handle FP special case. 1941 if (isInteger) { 1942 OutCC = changeIntCCToAArch64CC(CC); 1943 } else { 1944 assert(LHS.getValueType().isFloatingPoint()); 1945 AArch64CC::CondCode ExtraCC; 1946 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1947 // Some floating point conditions can't be tested with a single condition 1948 // code. Construct an additional comparison in this case. 1949 if (ExtraCC != AArch64CC::AL) { 1950 SDValue ExtraCmp; 1951 if (!CCOp.getNode()) 1952 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1953 else 1954 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1955 ExtraCC, DL, DAG); 1956 CCOp = ExtraCmp; 1957 Predicate = ExtraCC; 1958 } 1959 } 1960 1961 // Produce a normal comparison if we are first in the chain 1962 if (!CCOp) 1963 return emitComparison(LHS, RHS, CC, DL, DAG); 1964 // Otherwise produce a ccmp. 1965 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1966 DAG); 1967 } 1968 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 1969 1970 bool IsOR = Opcode == ISD::OR; 1971 1972 SDValue LHS = Val->getOperand(0); 1973 bool CanNegateL; 1974 bool MustBeFirstL; 1975 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 1976 assert(ValidL && "Valid conjunction/disjunction tree"); 1977 (void)ValidL; 1978 1979 SDValue RHS = Val->getOperand(1); 1980 bool CanNegateR; 1981 bool MustBeFirstR; 1982 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 1983 assert(ValidR && "Valid conjunction/disjunction tree"); 1984 (void)ValidR; 1985 1986 // Swap sub-tree that must come first to the right side. 1987 if (MustBeFirstL) { 1988 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 1989 std::swap(LHS, RHS); 1990 std::swap(CanNegateL, CanNegateR); 1991 std::swap(MustBeFirstL, MustBeFirstR); 1992 } 1993 1994 bool NegateR; 1995 bool NegateAfterR; 1996 bool NegateL; 1997 bool NegateAfterAll; 1998 if (Opcode == ISD::OR) { 1999 // Swap the sub-tree that we can negate naturally to the left. 2000 if (!CanNegateL) { 2001 assert(CanNegateR && "at least one side must be negatable"); 2002 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 2003 assert(!Negate); 2004 std::swap(LHS, RHS); 2005 NegateR = false; 2006 NegateAfterR = true; 2007 } else { 2008 // Negate the left sub-tree if possible, otherwise negate the result. 2009 NegateR = CanNegateR; 2010 NegateAfterR = !CanNegateR; 2011 } 2012 NegateL = true; 2013 NegateAfterAll = !Negate; 2014 } else { 2015 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 2016 assert(!Negate && "Valid conjunction/disjunction tree"); 2017 2018 NegateL = false; 2019 NegateR = false; 2020 NegateAfterR = false; 2021 NegateAfterAll = false; 2022 } 2023 2024 // Emit sub-trees. 2025 AArch64CC::CondCode RHSCC; 2026 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 2027 if (NegateAfterR) 2028 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 2029 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 2030 if (NegateAfterAll) 2031 OutCC = AArch64CC::getInvertedCondCode(OutCC); 2032 return CmpL; 2033 } 2034 2035 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 2036 /// In some cases this is even possible with OR operations in the expression. 2037 /// See \ref AArch64CCMP. 2038 /// \see emitConjunctionRec(). 2039 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 2040 AArch64CC::CondCode &OutCC) { 2041 bool DummyCanNegate; 2042 bool DummyMustBeFirst; 2043 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 2044 return SDValue(); 2045 2046 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 2047 } 2048 2049 /// @} 2050 2051 /// Returns how profitable it is to fold a comparison's operand's shift and/or 2052 /// extension operations. 2053 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 2054 auto isSupportedExtend = [&](SDValue V) { 2055 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 2056 return true; 2057 2058 if (V.getOpcode() == ISD::AND) 2059 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2060 uint64_t Mask = MaskCst->getZExtValue(); 2061 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 2062 } 2063 2064 return false; 2065 }; 2066 2067 if (!Op.hasOneUse()) 2068 return 0; 2069 2070 if (isSupportedExtend(Op)) 2071 return 1; 2072 2073 unsigned Opc = Op.getOpcode(); 2074 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 2075 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2076 uint64_t Shift = ShiftCst->getZExtValue(); 2077 if (isSupportedExtend(Op.getOperand(0))) 2078 return (Shift <= 4) ? 2 : 1; 2079 EVT VT = Op.getValueType(); 2080 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 2081 return 1; 2082 } 2083 2084 return 0; 2085 } 2086 2087 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2088 SDValue &AArch64cc, SelectionDAG &DAG, 2089 const SDLoc &dl) { 2090 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 2091 EVT VT = RHS.getValueType(); 2092 uint64_t C = RHSC->getZExtValue(); 2093 if (!isLegalArithImmed(C)) { 2094 // Constant does not fit, try adjusting it by one? 2095 switch (CC) { 2096 default: 2097 break; 2098 case ISD::SETLT: 2099 case ISD::SETGE: 2100 if ((VT == MVT::i32 && C != 0x80000000 && 2101 isLegalArithImmed((uint32_t)(C - 1))) || 2102 (VT == MVT::i64 && C != 0x80000000ULL && 2103 isLegalArithImmed(C - 1ULL))) { 2104 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 2105 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2106 RHS = DAG.getConstant(C, dl, VT); 2107 } 2108 break; 2109 case ISD::SETULT: 2110 case ISD::SETUGE: 2111 if ((VT == MVT::i32 && C != 0 && 2112 isLegalArithImmed((uint32_t)(C - 1))) || 2113 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 2114 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 2115 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2116 RHS = DAG.getConstant(C, dl, VT); 2117 } 2118 break; 2119 case ISD::SETLE: 2120 case ISD::SETGT: 2121 if ((VT == MVT::i32 && C != INT32_MAX && 2122 isLegalArithImmed((uint32_t)(C + 1))) || 2123 (VT == MVT::i64 && C != INT64_MAX && 2124 isLegalArithImmed(C + 1ULL))) { 2125 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2126 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2127 RHS = DAG.getConstant(C, dl, VT); 2128 } 2129 break; 2130 case ISD::SETULE: 2131 case ISD::SETUGT: 2132 if ((VT == MVT::i32 && C != UINT32_MAX && 2133 isLegalArithImmed((uint32_t)(C + 1))) || 2134 (VT == MVT::i64 && C != UINT64_MAX && 2135 isLegalArithImmed(C + 1ULL))) { 2136 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2137 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2138 RHS = DAG.getConstant(C, dl, VT); 2139 } 2140 break; 2141 } 2142 } 2143 } 2144 2145 // Comparisons are canonicalized so that the RHS operand is simpler than the 2146 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2147 // can fold some shift+extend operations on the RHS operand, so swap the 2148 // operands if that can be done. 2149 // 2150 // For example: 2151 // lsl w13, w11, #1 2152 // cmp w13, w12 2153 // can be turned into: 2154 // cmp w12, w11, lsl #1 2155 if (!isa<ConstantSDNode>(RHS) || 2156 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2157 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2158 2159 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2160 std::swap(LHS, RHS); 2161 CC = ISD::getSetCCSwappedOperands(CC); 2162 } 2163 } 2164 2165 SDValue Cmp; 2166 AArch64CC::CondCode AArch64CC; 2167 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2168 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2169 2170 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2171 // For the i8 operand, the largest immediate is 255, so this can be easily 2172 // encoded in the compare instruction. For the i16 operand, however, the 2173 // largest immediate cannot be encoded in the compare. 2174 // Therefore, use a sign extending load and cmn to avoid materializing the 2175 // -1 constant. For example, 2176 // movz w1, #65535 2177 // ldrh w0, [x0, #0] 2178 // cmp w0, w1 2179 // > 2180 // ldrsh w0, [x0, #0] 2181 // cmn w0, #1 2182 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2183 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2184 // ensure both the LHS and RHS are truly zero extended and to make sure the 2185 // transformation is profitable. 2186 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2187 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2188 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2189 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2190 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2191 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2192 SDValue SExt = 2193 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2194 DAG.getValueType(MVT::i16)); 2195 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2196 RHS.getValueType()), 2197 CC, dl, DAG); 2198 AArch64CC = changeIntCCToAArch64CC(CC); 2199 } 2200 } 2201 2202 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2203 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2204 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2205 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2206 } 2207 } 2208 } 2209 2210 if (!Cmp) { 2211 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2212 AArch64CC = changeIntCCToAArch64CC(CC); 2213 } 2214 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2215 return Cmp; 2216 } 2217 2218 static std::pair<SDValue, SDValue> 2219 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2220 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2221 "Unsupported value type"); 2222 SDValue Value, Overflow; 2223 SDLoc DL(Op); 2224 SDValue LHS = Op.getOperand(0); 2225 SDValue RHS = Op.getOperand(1); 2226 unsigned Opc = 0; 2227 switch (Op.getOpcode()) { 2228 default: 2229 llvm_unreachable("Unknown overflow instruction!"); 2230 case ISD::SADDO: 2231 Opc = AArch64ISD::ADDS; 2232 CC = AArch64CC::VS; 2233 break; 2234 case ISD::UADDO: 2235 Opc = AArch64ISD::ADDS; 2236 CC = AArch64CC::HS; 2237 break; 2238 case ISD::SSUBO: 2239 Opc = AArch64ISD::SUBS; 2240 CC = AArch64CC::VS; 2241 break; 2242 case ISD::USUBO: 2243 Opc = AArch64ISD::SUBS; 2244 CC = AArch64CC::LO; 2245 break; 2246 // Multiply needs a little bit extra work. 2247 case ISD::SMULO: 2248 case ISD::UMULO: { 2249 CC = AArch64CC::NE; 2250 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2251 if (Op.getValueType() == MVT::i32) { 2252 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2253 // For a 32 bit multiply with overflow check we want the instruction 2254 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2255 // need to generate the following pattern: 2256 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2257 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2258 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2259 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2260 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2261 DAG.getConstant(0, DL, MVT::i64)); 2262 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2263 // operation. We need to clear out the upper 32 bits, because we used a 2264 // widening multiply that wrote all 64 bits. In the end this should be a 2265 // noop. 2266 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2267 if (IsSigned) { 2268 // The signed overflow check requires more than just a simple check for 2269 // any bit set in the upper 32 bits of the result. These bits could be 2270 // just the sign bits of a negative number. To perform the overflow 2271 // check we have to arithmetic shift right the 32nd bit of the result by 2272 // 31 bits. Then we compare the result to the upper 32 bits. 2273 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2274 DAG.getConstant(32, DL, MVT::i64)); 2275 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2276 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2277 DAG.getConstant(31, DL, MVT::i64)); 2278 // It is important that LowerBits is last, otherwise the arithmetic 2279 // shift will not be folded into the compare (SUBS). 2280 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2281 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2282 .getValue(1); 2283 } else { 2284 // The overflow check for unsigned multiply is easy. We only need to 2285 // check if any of the upper 32 bits are set. This can be done with a 2286 // CMP (shifted register). For that we need to generate the following 2287 // pattern: 2288 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2289 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2290 DAG.getConstant(32, DL, MVT::i64)); 2291 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2292 Overflow = 2293 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2294 DAG.getConstant(0, DL, MVT::i64), 2295 UpperBits).getValue(1); 2296 } 2297 break; 2298 } 2299 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2300 // For the 64 bit multiply 2301 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2302 if (IsSigned) { 2303 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2304 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2305 DAG.getConstant(63, DL, MVT::i64)); 2306 // It is important that LowerBits is last, otherwise the arithmetic 2307 // shift will not be folded into the compare (SUBS). 2308 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2309 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2310 .getValue(1); 2311 } else { 2312 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2313 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2314 Overflow = 2315 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2316 DAG.getConstant(0, DL, MVT::i64), 2317 UpperBits).getValue(1); 2318 } 2319 break; 2320 } 2321 } // switch (...) 2322 2323 if (Opc) { 2324 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2325 2326 // Emit the AArch64 operation with overflow check. 2327 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2328 Overflow = Value.getValue(1); 2329 } 2330 return std::make_pair(Value, Overflow); 2331 } 2332 2333 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 2334 RTLIB::Libcall Call) const { 2335 bool IsStrict = Op->isStrictFPOpcode(); 2336 unsigned Offset = IsStrict ? 1 : 0; 2337 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 2338 SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end()); 2339 MakeLibCallOptions CallOptions; 2340 SDValue Result; 2341 SDLoc dl(Op); 2342 std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops, 2343 CallOptions, dl, Chain); 2344 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result; 2345 } 2346 2347 // Returns true if the given Op is the overflow flag result of an overflow 2348 // intrinsic operation. 2349 static bool isOverflowIntrOpRes(SDValue Op) { 2350 unsigned Opc = Op.getOpcode(); 2351 return (Op.getResNo() == 1 && 2352 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 2353 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)); 2354 } 2355 2356 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 2357 SDValue Sel = Op.getOperand(0); 2358 SDValue Other = Op.getOperand(1); 2359 SDLoc dl(Sel); 2360 2361 // If the operand is an overflow checking operation, invert the condition 2362 // code and kill the Not operation. I.e., transform: 2363 // (xor (overflow_op_bool, 1)) 2364 // --> 2365 // (csel 1, 0, invert(cc), overflow_op_bool) 2366 // ... which later gets transformed to just a cset instruction with an 2367 // inverted condition code, rather than a cset + eor sequence. 2368 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) { 2369 // Only lower legal XALUO ops. 2370 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2371 return SDValue(); 2372 2373 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2374 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2375 AArch64CC::CondCode CC; 2376 SDValue Value, Overflow; 2377 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2378 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2379 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2380 CCVal, Overflow); 2381 } 2382 // If neither operand is a SELECT_CC, give up. 2383 if (Sel.getOpcode() != ISD::SELECT_CC) 2384 std::swap(Sel, Other); 2385 if (Sel.getOpcode() != ISD::SELECT_CC) 2386 return Op; 2387 2388 // The folding we want to perform is: 2389 // (xor x, (select_cc a, b, cc, 0, -1) ) 2390 // --> 2391 // (csel x, (xor x, -1), cc ...) 2392 // 2393 // The latter will get matched to a CSINV instruction. 2394 2395 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2396 SDValue LHS = Sel.getOperand(0); 2397 SDValue RHS = Sel.getOperand(1); 2398 SDValue TVal = Sel.getOperand(2); 2399 SDValue FVal = Sel.getOperand(3); 2400 2401 // FIXME: This could be generalized to non-integer comparisons. 2402 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2403 return Op; 2404 2405 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2406 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2407 2408 // The values aren't constants, this isn't the pattern we're looking for. 2409 if (!CFVal || !CTVal) 2410 return Op; 2411 2412 // We can commute the SELECT_CC by inverting the condition. This 2413 // might be needed to make this fit into a CSINV pattern. 2414 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2415 std::swap(TVal, FVal); 2416 std::swap(CTVal, CFVal); 2417 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 2418 } 2419 2420 // If the constants line up, perform the transform! 2421 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2422 SDValue CCVal; 2423 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2424 2425 FVal = Other; 2426 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2427 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2428 2429 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2430 CCVal, Cmp); 2431 } 2432 2433 return Op; 2434 } 2435 2436 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2437 EVT VT = Op.getValueType(); 2438 2439 // Let legalize expand this if it isn't a legal type yet. 2440 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2441 return SDValue(); 2442 2443 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2444 2445 unsigned Opc; 2446 bool ExtraOp = false; 2447 switch (Op.getOpcode()) { 2448 default: 2449 llvm_unreachable("Invalid code"); 2450 case ISD::ADDC: 2451 Opc = AArch64ISD::ADDS; 2452 break; 2453 case ISD::SUBC: 2454 Opc = AArch64ISD::SUBS; 2455 break; 2456 case ISD::ADDE: 2457 Opc = AArch64ISD::ADCS; 2458 ExtraOp = true; 2459 break; 2460 case ISD::SUBE: 2461 Opc = AArch64ISD::SBCS; 2462 ExtraOp = true; 2463 break; 2464 } 2465 2466 if (!ExtraOp) 2467 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2468 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2469 Op.getOperand(2)); 2470 } 2471 2472 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2473 // Let legalize expand this if it isn't a legal type yet. 2474 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2475 return SDValue(); 2476 2477 SDLoc dl(Op); 2478 AArch64CC::CondCode CC; 2479 // The actual operation that sets the overflow or carry flag. 2480 SDValue Value, Overflow; 2481 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2482 2483 // We use 0 and 1 as false and true values. 2484 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2485 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2486 2487 // We use an inverted condition, because the conditional select is inverted 2488 // too. This will allow it to be selected to a single instruction: 2489 // CSINC Wd, WZR, WZR, invert(cond). 2490 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2491 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2492 CCVal, Overflow); 2493 2494 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2495 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2496 } 2497 2498 // Prefetch operands are: 2499 // 1: Address to prefetch 2500 // 2: bool isWrite 2501 // 3: int locality (0 = no locality ... 3 = extreme locality) 2502 // 4: bool isDataCache 2503 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2504 SDLoc DL(Op); 2505 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2506 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2507 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2508 2509 bool IsStream = !Locality; 2510 // When the locality number is set 2511 if (Locality) { 2512 // The front-end should have filtered out the out-of-range values 2513 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2514 // The locality degree is the opposite of the cache speed. 2515 // Put the number the other way around. 2516 // The encoding starts at 0 for level 1 2517 Locality = 3 - Locality; 2518 } 2519 2520 // built the mask value encoding the expected behavior. 2521 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2522 (!IsData << 3) | // IsDataCache bit 2523 (Locality << 1) | // Cache level bits 2524 (unsigned)IsStream; // Stream bit 2525 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2526 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2527 } 2528 2529 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2530 SelectionDAG &DAG) const { 2531 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2532 2533 RTLIB::Libcall LC; 2534 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2535 2536 return LowerF128Call(Op, DAG, LC); 2537 } 2538 2539 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2540 SelectionDAG &DAG) const { 2541 bool IsStrict = Op->isStrictFPOpcode(); 2542 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2543 if (SrcVal.getValueType() != MVT::f128) { 2544 // It's legal except when f128 is involved 2545 return Op; 2546 } 2547 2548 RTLIB::Libcall LC; 2549 LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType()); 2550 2551 // FP_ROUND node has a second operand indicating whether it is known to be 2552 // precise. That doesn't take part in the LibCall so we can't directly use 2553 // LowerF128Call. 2554 MakeLibCallOptions CallOptions; 2555 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 2556 SDValue Result; 2557 SDLoc dl(Op); 2558 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 2559 CallOptions, dl, Chain); 2560 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result; 2561 } 2562 2563 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 2564 SelectionDAG &DAG) const { 2565 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2566 // Any additional optimization in this function should be recorded 2567 // in the cost tables. 2568 EVT InVT = Op.getOperand(0).getValueType(); 2569 EVT VT = Op.getValueType(); 2570 unsigned NumElts = InVT.getVectorNumElements(); 2571 2572 // f16 conversions are promoted to f32 when full fp16 is not supported. 2573 if (InVT.getVectorElementType() == MVT::f16 && 2574 !Subtarget->hasFullFP16()) { 2575 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2576 SDLoc dl(Op); 2577 return DAG.getNode( 2578 Op.getOpcode(), dl, Op.getValueType(), 2579 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2580 } 2581 2582 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2583 SDLoc dl(Op); 2584 SDValue Cv = 2585 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2586 Op.getOperand(0)); 2587 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2588 } 2589 2590 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2591 SDLoc dl(Op); 2592 MVT ExtVT = 2593 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2594 VT.getVectorNumElements()); 2595 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2596 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2597 } 2598 2599 // Type changing conversions are illegal. 2600 return Op; 2601 } 2602 2603 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2604 SelectionDAG &DAG) const { 2605 bool IsStrict = Op->isStrictFPOpcode(); 2606 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2607 2608 if (SrcVal.getValueType().isVector()) 2609 return LowerVectorFP_TO_INT(Op, DAG); 2610 2611 // f16 conversions are promoted to f32 when full fp16 is not supported. 2612 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 2613 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 2614 SDLoc dl(Op); 2615 return DAG.getNode( 2616 Op.getOpcode(), dl, Op.getValueType(), 2617 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal)); 2618 } 2619 2620 if (SrcVal.getValueType() != MVT::f128) { 2621 // It's legal except when f128 is involved 2622 return Op; 2623 } 2624 2625 RTLIB::Libcall LC; 2626 if (Op.getOpcode() == ISD::FP_TO_SINT || 2627 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 2628 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType()); 2629 else 2630 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType()); 2631 2632 return LowerF128Call(Op, DAG, LC); 2633 } 2634 2635 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2636 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2637 // Any additional optimization in this function should be recorded 2638 // in the cost tables. 2639 EVT VT = Op.getValueType(); 2640 SDLoc dl(Op); 2641 SDValue In = Op.getOperand(0); 2642 EVT InVT = In.getValueType(); 2643 2644 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2645 MVT CastVT = 2646 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2647 InVT.getVectorNumElements()); 2648 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2649 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2650 } 2651 2652 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2653 unsigned CastOpc = 2654 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2655 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2656 In = DAG.getNode(CastOpc, dl, CastVT, In); 2657 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2658 } 2659 2660 return Op; 2661 } 2662 2663 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2664 SelectionDAG &DAG) const { 2665 if (Op.getValueType().isVector()) 2666 return LowerVectorINT_TO_FP(Op, DAG); 2667 2668 bool IsStrict = Op->isStrictFPOpcode(); 2669 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2670 2671 // f16 conversions are promoted to f32 when full fp16 is not supported. 2672 if (Op.getValueType() == MVT::f16 && 2673 !Subtarget->hasFullFP16()) { 2674 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 2675 SDLoc dl(Op); 2676 return DAG.getNode( 2677 ISD::FP_ROUND, dl, MVT::f16, 2678 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal), 2679 DAG.getIntPtrConstant(0, dl)); 2680 } 2681 2682 // i128 conversions are libcalls. 2683 if (SrcVal.getValueType() == MVT::i128) 2684 return SDValue(); 2685 2686 // Other conversions are legal, unless it's to the completely software-based 2687 // fp128. 2688 if (Op.getValueType() != MVT::f128) 2689 return Op; 2690 2691 RTLIB::Libcall LC; 2692 if (Op.getOpcode() == ISD::SINT_TO_FP || 2693 Op.getOpcode() == ISD::STRICT_SINT_TO_FP) 2694 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType()); 2695 else 2696 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType()); 2697 2698 return LowerF128Call(Op, DAG, LC); 2699 } 2700 2701 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2702 SelectionDAG &DAG) const { 2703 // For iOS, we want to call an alternative entry point: __sincos_stret, 2704 // which returns the values in two S / D registers. 2705 SDLoc dl(Op); 2706 SDValue Arg = Op.getOperand(0); 2707 EVT ArgVT = Arg.getValueType(); 2708 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2709 2710 ArgListTy Args; 2711 ArgListEntry Entry; 2712 2713 Entry.Node = Arg; 2714 Entry.Ty = ArgTy; 2715 Entry.IsSExt = false; 2716 Entry.IsZExt = false; 2717 Args.push_back(Entry); 2718 2719 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 2720 : RTLIB::SINCOS_STRET_F32; 2721 const char *LibcallName = getLibcallName(LC); 2722 SDValue Callee = 2723 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2724 2725 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2726 TargetLowering::CallLoweringInfo CLI(DAG); 2727 CLI.setDebugLoc(dl) 2728 .setChain(DAG.getEntryNode()) 2729 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2730 2731 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2732 return CallResult.first; 2733 } 2734 2735 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2736 if (Op.getValueType() != MVT::f16) 2737 return SDValue(); 2738 2739 assert(Op.getOperand(0).getValueType() == MVT::i16); 2740 SDLoc DL(Op); 2741 2742 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2743 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2744 return SDValue( 2745 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2746 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2747 0); 2748 } 2749 2750 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2751 if (OrigVT.getSizeInBits() >= 64) 2752 return OrigVT; 2753 2754 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2755 2756 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2757 switch (OrigSimpleTy) { 2758 default: llvm_unreachable("Unexpected Vector Type"); 2759 case MVT::v2i8: 2760 case MVT::v2i16: 2761 return MVT::v2i32; 2762 case MVT::v4i8: 2763 return MVT::v4i16; 2764 } 2765 } 2766 2767 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2768 const EVT &OrigTy, 2769 const EVT &ExtTy, 2770 unsigned ExtOpcode) { 2771 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2772 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2773 // 64-bits we need to insert a new extension so that it will be 64-bits. 2774 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2775 if (OrigTy.getSizeInBits() >= 64) 2776 return N; 2777 2778 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2779 EVT NewVT = getExtensionTo64Bits(OrigTy); 2780 2781 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2782 } 2783 2784 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2785 bool isSigned) { 2786 EVT VT = N->getValueType(0); 2787 2788 if (N->getOpcode() != ISD::BUILD_VECTOR) 2789 return false; 2790 2791 for (const SDValue &Elt : N->op_values()) { 2792 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2793 unsigned EltSize = VT.getScalarSizeInBits(); 2794 unsigned HalfSize = EltSize / 2; 2795 if (isSigned) { 2796 if (!isIntN(HalfSize, C->getSExtValue())) 2797 return false; 2798 } else { 2799 if (!isUIntN(HalfSize, C->getZExtValue())) 2800 return false; 2801 } 2802 continue; 2803 } 2804 return false; 2805 } 2806 2807 return true; 2808 } 2809 2810 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2811 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2812 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2813 N->getOperand(0)->getValueType(0), 2814 N->getValueType(0), 2815 N->getOpcode()); 2816 2817 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2818 EVT VT = N->getValueType(0); 2819 SDLoc dl(N); 2820 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2821 unsigned NumElts = VT.getVectorNumElements(); 2822 MVT TruncVT = MVT::getIntegerVT(EltSize); 2823 SmallVector<SDValue, 8> Ops; 2824 for (unsigned i = 0; i != NumElts; ++i) { 2825 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2826 const APInt &CInt = C->getAPIntValue(); 2827 // Element types smaller than 32 bits are not legal, so use i32 elements. 2828 // The values are implicitly truncated so sext vs. zext doesn't matter. 2829 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2830 } 2831 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2832 } 2833 2834 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2835 return N->getOpcode() == ISD::SIGN_EXTEND || 2836 isExtendedBUILD_VECTOR(N, DAG, true); 2837 } 2838 2839 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2840 return N->getOpcode() == ISD::ZERO_EXTEND || 2841 isExtendedBUILD_VECTOR(N, DAG, false); 2842 } 2843 2844 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2845 unsigned Opcode = N->getOpcode(); 2846 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2847 SDNode *N0 = N->getOperand(0).getNode(); 2848 SDNode *N1 = N->getOperand(1).getNode(); 2849 return N0->hasOneUse() && N1->hasOneUse() && 2850 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2851 } 2852 return false; 2853 } 2854 2855 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2856 unsigned Opcode = N->getOpcode(); 2857 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2858 SDNode *N0 = N->getOperand(0).getNode(); 2859 SDNode *N1 = N->getOperand(1).getNode(); 2860 return N0->hasOneUse() && N1->hasOneUse() && 2861 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2862 } 2863 return false; 2864 } 2865 2866 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 2867 SelectionDAG &DAG) const { 2868 // The rounding mode is in bits 23:22 of the FPSCR. 2869 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 2870 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 2871 // so that the shift + and get folded into a bitfield extract. 2872 SDLoc dl(Op); 2873 2874 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64, 2875 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, 2876 MVT::i64)); 2877 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 2878 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 2879 DAG.getConstant(1U << 22, dl, MVT::i32)); 2880 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 2881 DAG.getConstant(22, dl, MVT::i32)); 2882 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 2883 DAG.getConstant(3, dl, MVT::i32)); 2884 } 2885 2886 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2887 // Multiplications are only custom-lowered for 128-bit vectors so that 2888 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2889 EVT VT = Op.getValueType(); 2890 assert(VT.is128BitVector() && VT.isInteger() && 2891 "unexpected type for custom-lowering ISD::MUL"); 2892 SDNode *N0 = Op.getOperand(0).getNode(); 2893 SDNode *N1 = Op.getOperand(1).getNode(); 2894 unsigned NewOpc = 0; 2895 bool isMLA = false; 2896 bool isN0SExt = isSignExtended(N0, DAG); 2897 bool isN1SExt = isSignExtended(N1, DAG); 2898 if (isN0SExt && isN1SExt) 2899 NewOpc = AArch64ISD::SMULL; 2900 else { 2901 bool isN0ZExt = isZeroExtended(N0, DAG); 2902 bool isN1ZExt = isZeroExtended(N1, DAG); 2903 if (isN0ZExt && isN1ZExt) 2904 NewOpc = AArch64ISD::UMULL; 2905 else if (isN1SExt || isN1ZExt) { 2906 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2907 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2908 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2909 NewOpc = AArch64ISD::SMULL; 2910 isMLA = true; 2911 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2912 NewOpc = AArch64ISD::UMULL; 2913 isMLA = true; 2914 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2915 std::swap(N0, N1); 2916 NewOpc = AArch64ISD::UMULL; 2917 isMLA = true; 2918 } 2919 } 2920 2921 if (!NewOpc) { 2922 if (VT == MVT::v2i64) 2923 // Fall through to expand this. It is not legal. 2924 return SDValue(); 2925 else 2926 // Other vector multiplications are legal. 2927 return Op; 2928 } 2929 } 2930 2931 // Legalize to a S/UMULL instruction 2932 SDLoc DL(Op); 2933 SDValue Op0; 2934 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2935 if (!isMLA) { 2936 Op0 = skipExtensionForVectorMULL(N0, DAG); 2937 assert(Op0.getValueType().is64BitVector() && 2938 Op1.getValueType().is64BitVector() && 2939 "unexpected types for extended operands to VMULL"); 2940 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2941 } 2942 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2943 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2944 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2945 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2946 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2947 EVT Op1VT = Op1.getValueType(); 2948 return DAG.getNode(N0->getOpcode(), DL, VT, 2949 DAG.getNode(NewOpc, DL, VT, 2950 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2951 DAG.getNode(NewOpc, DL, VT, 2952 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2953 } 2954 2955 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2956 SelectionDAG &DAG) const { 2957 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2958 SDLoc dl(Op); 2959 switch (IntNo) { 2960 default: return SDValue(); // Don't custom lower most intrinsics. 2961 case Intrinsic::thread_pointer: { 2962 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2963 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2964 } 2965 case Intrinsic::aarch64_neon_abs: { 2966 EVT Ty = Op.getValueType(); 2967 if (Ty == MVT::i64) { 2968 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 2969 Op.getOperand(1)); 2970 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 2971 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 2972 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 2973 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 2974 } else { 2975 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 2976 } 2977 } 2978 case Intrinsic::aarch64_neon_smax: 2979 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2980 Op.getOperand(1), Op.getOperand(2)); 2981 case Intrinsic::aarch64_neon_umax: 2982 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2983 Op.getOperand(1), Op.getOperand(2)); 2984 case Intrinsic::aarch64_neon_smin: 2985 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2986 Op.getOperand(1), Op.getOperand(2)); 2987 case Intrinsic::aarch64_neon_umin: 2988 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2989 Op.getOperand(1), Op.getOperand(2)); 2990 2991 case Intrinsic::aarch64_sve_sunpkhi: 2992 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 2993 Op.getOperand(1)); 2994 case Intrinsic::aarch64_sve_sunpklo: 2995 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 2996 Op.getOperand(1)); 2997 case Intrinsic::aarch64_sve_uunpkhi: 2998 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 2999 Op.getOperand(1)); 3000 case Intrinsic::aarch64_sve_uunpklo: 3001 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 3002 Op.getOperand(1)); 3003 case Intrinsic::aarch64_sve_clasta_n: 3004 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(), 3005 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3006 case Intrinsic::aarch64_sve_clastb_n: 3007 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(), 3008 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3009 case Intrinsic::aarch64_sve_lasta: 3010 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(), 3011 Op.getOperand(1), Op.getOperand(2)); 3012 case Intrinsic::aarch64_sve_lastb: 3013 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(), 3014 Op.getOperand(1), Op.getOperand(2)); 3015 case Intrinsic::aarch64_sve_rev: 3016 return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(), 3017 Op.getOperand(1)); 3018 case Intrinsic::aarch64_sve_tbl: 3019 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(), 3020 Op.getOperand(1), Op.getOperand(2)); 3021 case Intrinsic::aarch64_sve_trn1: 3022 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(), 3023 Op.getOperand(1), Op.getOperand(2)); 3024 case Intrinsic::aarch64_sve_trn2: 3025 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(), 3026 Op.getOperand(1), Op.getOperand(2)); 3027 case Intrinsic::aarch64_sve_uzp1: 3028 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(), 3029 Op.getOperand(1), Op.getOperand(2)); 3030 case Intrinsic::aarch64_sve_uzp2: 3031 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(), 3032 Op.getOperand(1), Op.getOperand(2)); 3033 case Intrinsic::aarch64_sve_zip1: 3034 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(), 3035 Op.getOperand(1), Op.getOperand(2)); 3036 case Intrinsic::aarch64_sve_zip2: 3037 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(), 3038 Op.getOperand(1), Op.getOperand(2)); 3039 case Intrinsic::aarch64_sve_ptrue: 3040 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(), 3041 Op.getOperand(1)); 3042 3043 case Intrinsic::aarch64_sve_insr: { 3044 SDValue Scalar = Op.getOperand(2); 3045 EVT ScalarTy = Scalar.getValueType(); 3046 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 3047 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 3048 3049 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(), 3050 Op.getOperand(1), Scalar); 3051 } 3052 3053 case Intrinsic::localaddress: { 3054 const auto &MF = DAG.getMachineFunction(); 3055 const auto *RegInfo = Subtarget->getRegisterInfo(); 3056 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 3057 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 3058 Op.getSimpleValueType()); 3059 } 3060 3061 case Intrinsic::eh_recoverfp: { 3062 // FIXME: This needs to be implemented to correctly handle highly aligned 3063 // stack objects. For now we simply return the incoming FP. Refer D53541 3064 // for more details. 3065 SDValue FnOp = Op.getOperand(1); 3066 SDValue IncomingFPOp = Op.getOperand(2); 3067 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 3068 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 3069 if (!Fn) 3070 report_fatal_error( 3071 "llvm.eh.recoverfp must take a function as the first argument"); 3072 return IncomingFPOp; 3073 } 3074 } 3075 } 3076 3077 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 3078 return ExtVal.getValueType().isScalableVector(); 3079 } 3080 3081 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 3082 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 3083 EVT VT, EVT MemVT, 3084 SelectionDAG &DAG) { 3085 assert(VT.isVector() && "VT should be a vector type"); 3086 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 3087 3088 SDValue Value = ST->getValue(); 3089 3090 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 3091 // the word lane which represent the v4i8 subvector. It optimizes the store 3092 // to: 3093 // 3094 // xtn v0.8b, v0.8h 3095 // str s0, [x0] 3096 3097 SDValue Undef = DAG.getUNDEF(MVT::i16); 3098 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 3099 {Undef, Undef, Undef, Undef}); 3100 3101 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 3102 Value, UndefVec); 3103 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 3104 3105 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 3106 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 3107 Trunc, DAG.getConstant(0, DL, MVT::i64)); 3108 3109 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 3110 ST->getBasePtr(), ST->getMemOperand()); 3111 } 3112 3113 // Custom lowering for any store, vector or scalar and/or default or with 3114 // a truncate operations. Currently only custom lower truncate operation 3115 // from vector v4i16 to v4i8 or volatile stores of i128. 3116 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 3117 SelectionDAG &DAG) const { 3118 SDLoc Dl(Op); 3119 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 3120 assert (StoreNode && "Can only custom lower store nodes"); 3121 3122 SDValue Value = StoreNode->getValue(); 3123 3124 EVT VT = Value.getValueType(); 3125 EVT MemVT = StoreNode->getMemoryVT(); 3126 3127 if (VT.isVector()) { 3128 unsigned AS = StoreNode->getAddressSpace(); 3129 unsigned Align = StoreNode->getAlignment(); 3130 if (Align < MemVT.getStoreSize() && 3131 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, 3132 StoreNode->getMemOperand()->getFlags(), 3133 nullptr)) { 3134 return scalarizeVectorStore(StoreNode, DAG); 3135 } 3136 3137 if (StoreNode->isTruncatingStore()) { 3138 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 3139 } 3140 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of 3141 // the custom lowering, as there are no un-paired non-temporal stores and 3142 // legalization will break up 256 bit inputs. 3143 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u && 3144 MemVT.getVectorElementCount().Min % 2u == 0 && 3145 ((MemVT.getScalarSizeInBits() == 8u || 3146 MemVT.getScalarSizeInBits() == 16u || 3147 MemVT.getScalarSizeInBits() == 32u || 3148 MemVT.getScalarSizeInBits() == 64u))) { 3149 SDValue Lo = 3150 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 3151 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 3152 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64)); 3153 SDValue Hi = DAG.getNode( 3154 ISD::EXTRACT_SUBVECTOR, Dl, 3155 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 3156 StoreNode->getValue(), 3157 DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64)); 3158 SDValue Result = DAG.getMemIntrinsicNode( 3159 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other), 3160 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 3161 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 3162 return Result; 3163 } 3164 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) { 3165 assert(StoreNode->getValue()->getValueType(0) == MVT::i128); 3166 SDValue Lo = 3167 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 3168 DAG.getConstant(0, Dl, MVT::i64)); 3169 SDValue Hi = 3170 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 3171 DAG.getConstant(1, Dl, MVT::i64)); 3172 SDValue Result = DAG.getMemIntrinsicNode( 3173 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other), 3174 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 3175 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 3176 return Result; 3177 } 3178 3179 return SDValue(); 3180 } 3181 3182 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 3183 SelectionDAG &DAG) const { 3184 LLVM_DEBUG(dbgs() << "Custom lowering: "); 3185 LLVM_DEBUG(Op.dump()); 3186 3187 switch (Op.getOpcode()) { 3188 default: 3189 llvm_unreachable("unimplemented operand"); 3190 return SDValue(); 3191 case ISD::BITCAST: 3192 return LowerBITCAST(Op, DAG); 3193 case ISD::GlobalAddress: 3194 return LowerGlobalAddress(Op, DAG); 3195 case ISD::GlobalTLSAddress: 3196 return LowerGlobalTLSAddress(Op, DAG); 3197 case ISD::SETCC: 3198 case ISD::STRICT_FSETCC: 3199 case ISD::STRICT_FSETCCS: 3200 return LowerSETCC(Op, DAG); 3201 case ISD::BR_CC: 3202 return LowerBR_CC(Op, DAG); 3203 case ISD::SELECT: 3204 return LowerSELECT(Op, DAG); 3205 case ISD::SELECT_CC: 3206 return LowerSELECT_CC(Op, DAG); 3207 case ISD::JumpTable: 3208 return LowerJumpTable(Op, DAG); 3209 case ISD::BR_JT: 3210 return LowerBR_JT(Op, DAG); 3211 case ISD::ConstantPool: 3212 return LowerConstantPool(Op, DAG); 3213 case ISD::BlockAddress: 3214 return LowerBlockAddress(Op, DAG); 3215 case ISD::VASTART: 3216 return LowerVASTART(Op, DAG); 3217 case ISD::VACOPY: 3218 return LowerVACOPY(Op, DAG); 3219 case ISD::VAARG: 3220 return LowerVAARG(Op, DAG); 3221 case ISD::ADDC: 3222 case ISD::ADDE: 3223 case ISD::SUBC: 3224 case ISD::SUBE: 3225 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 3226 case ISD::SADDO: 3227 case ISD::UADDO: 3228 case ISD::SSUBO: 3229 case ISD::USUBO: 3230 case ISD::SMULO: 3231 case ISD::UMULO: 3232 return LowerXALUO(Op, DAG); 3233 case ISD::FADD: 3234 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 3235 case ISD::FSUB: 3236 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 3237 case ISD::FMUL: 3238 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 3239 case ISD::FDIV: 3240 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 3241 case ISD::FP_ROUND: 3242 case ISD::STRICT_FP_ROUND: 3243 return LowerFP_ROUND(Op, DAG); 3244 case ISD::FP_EXTEND: 3245 return LowerFP_EXTEND(Op, DAG); 3246 case ISD::FRAMEADDR: 3247 return LowerFRAMEADDR(Op, DAG); 3248 case ISD::SPONENTRY: 3249 return LowerSPONENTRY(Op, DAG); 3250 case ISD::RETURNADDR: 3251 return LowerRETURNADDR(Op, DAG); 3252 case ISD::ADDROFRETURNADDR: 3253 return LowerADDROFRETURNADDR(Op, DAG); 3254 case ISD::INSERT_VECTOR_ELT: 3255 return LowerINSERT_VECTOR_ELT(Op, DAG); 3256 case ISD::EXTRACT_VECTOR_ELT: 3257 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 3258 case ISD::BUILD_VECTOR: 3259 return LowerBUILD_VECTOR(Op, DAG); 3260 case ISD::VECTOR_SHUFFLE: 3261 return LowerVECTOR_SHUFFLE(Op, DAG); 3262 case ISD::SPLAT_VECTOR: 3263 return LowerSPLAT_VECTOR(Op, DAG); 3264 case ISD::EXTRACT_SUBVECTOR: 3265 return LowerEXTRACT_SUBVECTOR(Op, DAG); 3266 case ISD::SRA: 3267 case ISD::SRL: 3268 case ISD::SHL: 3269 return LowerVectorSRA_SRL_SHL(Op, DAG); 3270 case ISD::SHL_PARTS: 3271 return LowerShiftLeftParts(Op, DAG); 3272 case ISD::SRL_PARTS: 3273 case ISD::SRA_PARTS: 3274 return LowerShiftRightParts(Op, DAG); 3275 case ISD::CTPOP: 3276 return LowerCTPOP(Op, DAG); 3277 case ISD::FCOPYSIGN: 3278 return LowerFCOPYSIGN(Op, DAG); 3279 case ISD::OR: 3280 return LowerVectorOR(Op, DAG); 3281 case ISD::XOR: 3282 return LowerXOR(Op, DAG); 3283 case ISD::PREFETCH: 3284 return LowerPREFETCH(Op, DAG); 3285 case ISD::SINT_TO_FP: 3286 case ISD::UINT_TO_FP: 3287 case ISD::STRICT_SINT_TO_FP: 3288 case ISD::STRICT_UINT_TO_FP: 3289 return LowerINT_TO_FP(Op, DAG); 3290 case ISD::FP_TO_SINT: 3291 case ISD::FP_TO_UINT: 3292 case ISD::STRICT_FP_TO_SINT: 3293 case ISD::STRICT_FP_TO_UINT: 3294 return LowerFP_TO_INT(Op, DAG); 3295 case ISD::FSINCOS: 3296 return LowerFSINCOS(Op, DAG); 3297 case ISD::FLT_ROUNDS_: 3298 return LowerFLT_ROUNDS_(Op, DAG); 3299 case ISD::MUL: 3300 return LowerMUL(Op, DAG); 3301 case ISD::INTRINSIC_WO_CHAIN: 3302 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3303 case ISD::STORE: 3304 return LowerSTORE(Op, DAG); 3305 case ISD::VECREDUCE_ADD: 3306 case ISD::VECREDUCE_SMAX: 3307 case ISD::VECREDUCE_SMIN: 3308 case ISD::VECREDUCE_UMAX: 3309 case ISD::VECREDUCE_UMIN: 3310 case ISD::VECREDUCE_FMAX: 3311 case ISD::VECREDUCE_FMIN: 3312 return LowerVECREDUCE(Op, DAG); 3313 case ISD::ATOMIC_LOAD_SUB: 3314 return LowerATOMIC_LOAD_SUB(Op, DAG); 3315 case ISD::ATOMIC_LOAD_AND: 3316 return LowerATOMIC_LOAD_AND(Op, DAG); 3317 case ISD::DYNAMIC_STACKALLOC: 3318 return LowerDYNAMIC_STACKALLOC(Op, DAG); 3319 case ISD::VSCALE: 3320 return LowerVSCALE(Op, DAG); 3321 } 3322 } 3323 3324 //===----------------------------------------------------------------------===// 3325 // Calling Convention Implementation 3326 //===----------------------------------------------------------------------===// 3327 3328 /// Selects the correct CCAssignFn for a given CallingConvention value. 3329 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 3330 bool IsVarArg) const { 3331 switch (CC) { 3332 default: 3333 report_fatal_error("Unsupported calling convention."); 3334 case CallingConv::WebKit_JS: 3335 return CC_AArch64_WebKit_JS; 3336 case CallingConv::GHC: 3337 return CC_AArch64_GHC; 3338 case CallingConv::C: 3339 case CallingConv::Fast: 3340 case CallingConv::PreserveMost: 3341 case CallingConv::CXX_FAST_TLS: 3342 case CallingConv::Swift: 3343 if (Subtarget->isTargetWindows() && IsVarArg) 3344 return CC_AArch64_Win64_VarArg; 3345 if (!Subtarget->isTargetDarwin()) 3346 return CC_AArch64_AAPCS; 3347 if (!IsVarArg) 3348 return CC_AArch64_DarwinPCS; 3349 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 3350 : CC_AArch64_DarwinPCS_VarArg; 3351 case CallingConv::Win64: 3352 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 3353 case CallingConv::CFGuard_Check: 3354 return CC_AArch64_Win64_CFGuard_Check; 3355 case CallingConv::AArch64_VectorCall: 3356 case CallingConv::AArch64_SVE_VectorCall: 3357 return CC_AArch64_AAPCS; 3358 } 3359 } 3360 3361 CCAssignFn * 3362 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 3363 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 3364 : RetCC_AArch64_AAPCS; 3365 } 3366 3367 SDValue AArch64TargetLowering::LowerFormalArguments( 3368 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3369 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3370 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3371 MachineFunction &MF = DAG.getMachineFunction(); 3372 MachineFrameInfo &MFI = MF.getFrameInfo(); 3373 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3374 3375 // Assign locations to all of the incoming arguments. 3376 SmallVector<CCValAssign, 16> ArgLocs; 3377 DenseMap<unsigned, SDValue> CopiedRegs; 3378 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3379 *DAG.getContext()); 3380 3381 // At this point, Ins[].VT may already be promoted to i32. To correctly 3382 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3383 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3384 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 3385 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 3386 // LocVT. 3387 unsigned NumArgs = Ins.size(); 3388 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3389 unsigned CurArgIdx = 0; 3390 for (unsigned i = 0; i != NumArgs; ++i) { 3391 MVT ValVT = Ins[i].VT; 3392 if (Ins[i].isOrigArg()) { 3393 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 3394 CurArgIdx = Ins[i].getOrigArgIndex(); 3395 3396 // Get type of the original argument. 3397 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 3398 /*AllowUnknown*/ true); 3399 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 3400 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3401 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3402 ValVT = MVT::i8; 3403 else if (ActualMVT == MVT::i16) 3404 ValVT = MVT::i16; 3405 } 3406 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3407 bool Res = 3408 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 3409 assert(!Res && "Call operand has unhandled type"); 3410 (void)Res; 3411 } 3412 assert(ArgLocs.size() == Ins.size()); 3413 SmallVector<SDValue, 16> ArgValues; 3414 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3415 CCValAssign &VA = ArgLocs[i]; 3416 3417 if (Ins[i].Flags.isByVal()) { 3418 // Byval is used for HFAs in the PCS, but the system should work in a 3419 // non-compliant manner for larger structs. 3420 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3421 int Size = Ins[i].Flags.getByValSize(); 3422 unsigned NumRegs = (Size + 7) / 8; 3423 3424 // FIXME: This works on big-endian for composite byvals, which are the common 3425 // case. It should also work for fundamental types too. 3426 unsigned FrameIdx = 3427 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 3428 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 3429 InVals.push_back(FrameIdxN); 3430 3431 continue; 3432 } 3433 3434 SDValue ArgValue; 3435 if (VA.isRegLoc()) { 3436 // Arguments stored in registers. 3437 EVT RegVT = VA.getLocVT(); 3438 const TargetRegisterClass *RC; 3439 3440 if (RegVT == MVT::i32) 3441 RC = &AArch64::GPR32RegClass; 3442 else if (RegVT == MVT::i64) 3443 RC = &AArch64::GPR64RegClass; 3444 else if (RegVT == MVT::f16) 3445 RC = &AArch64::FPR16RegClass; 3446 else if (RegVT == MVT::f32) 3447 RC = &AArch64::FPR32RegClass; 3448 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 3449 RC = &AArch64::FPR64RegClass; 3450 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 3451 RC = &AArch64::FPR128RegClass; 3452 else if (RegVT.isScalableVector() && 3453 RegVT.getVectorElementType() == MVT::i1) 3454 RC = &AArch64::PPRRegClass; 3455 else if (RegVT.isScalableVector()) 3456 RC = &AArch64::ZPRRegClass; 3457 else 3458 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3459 3460 // Transform the arguments in physical registers into virtual ones. 3461 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3462 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3463 3464 // If this is an 8, 16 or 32-bit value, it is really passed promoted 3465 // to 64 bits. Insert an assert[sz]ext to capture this, then 3466 // truncate to the right size. 3467 switch (VA.getLocInfo()) { 3468 default: 3469 llvm_unreachable("Unknown loc info!"); 3470 case CCValAssign::Full: 3471 break; 3472 case CCValAssign::Indirect: 3473 assert(VA.getValVT().isScalableVector() && 3474 "Only scalable vectors can be passed indirectly"); 3475 break; 3476 case CCValAssign::BCvt: 3477 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 3478 break; 3479 case CCValAssign::AExt: 3480 case CCValAssign::SExt: 3481 case CCValAssign::ZExt: 3482 break; 3483 case CCValAssign::AExtUpper: 3484 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 3485 DAG.getConstant(32, DL, RegVT)); 3486 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 3487 break; 3488 } 3489 } else { // VA.isRegLoc() 3490 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 3491 unsigned ArgOffset = VA.getLocMemOffset(); 3492 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect 3493 ? VA.getLocVT().getSizeInBits() 3494 : VA.getValVT().getSizeInBits()) / 8; 3495 3496 uint32_t BEAlign = 0; 3497 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 3498 !Ins[i].Flags.isInConsecutiveRegs()) 3499 BEAlign = 8 - ArgSize; 3500 3501 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 3502 3503 // Create load nodes to retrieve arguments from the stack. 3504 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3505 3506 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 3507 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3508 MVT MemVT = VA.getValVT(); 3509 3510 switch (VA.getLocInfo()) { 3511 default: 3512 break; 3513 case CCValAssign::Trunc: 3514 case CCValAssign::BCvt: 3515 MemVT = VA.getLocVT(); 3516 break; 3517 case CCValAssign::Indirect: 3518 assert(VA.getValVT().isScalableVector() && 3519 "Only scalable vectors can be passed indirectly"); 3520 MemVT = VA.getLocVT(); 3521 break; 3522 case CCValAssign::SExt: 3523 ExtType = ISD::SEXTLOAD; 3524 break; 3525 case CCValAssign::ZExt: 3526 ExtType = ISD::ZEXTLOAD; 3527 break; 3528 case CCValAssign::AExt: 3529 ExtType = ISD::EXTLOAD; 3530 break; 3531 } 3532 3533 ArgValue = DAG.getExtLoad( 3534 ExtType, DL, VA.getLocVT(), Chain, FIN, 3535 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3536 MemVT); 3537 3538 } 3539 3540 if (VA.getLocInfo() == CCValAssign::Indirect) { 3541 assert(VA.getValVT().isScalableVector() && 3542 "Only scalable vectors can be passed indirectly"); 3543 // If value is passed via pointer - do a load. 3544 ArgValue = 3545 DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo()); 3546 } 3547 3548 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 3549 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 3550 ArgValue, DAG.getValueType(MVT::i32)); 3551 InVals.push_back(ArgValue); 3552 } 3553 3554 // varargs 3555 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3556 if (isVarArg) { 3557 if (!Subtarget->isTargetDarwin() || IsWin64) { 3558 // The AAPCS variadic function ABI is identical to the non-variadic 3559 // one. As a result there may be more arguments in registers and we should 3560 // save them for future reference. 3561 // Win64 variadic functions also pass arguments in registers, but all float 3562 // arguments are passed in integer registers. 3563 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 3564 } 3565 3566 // This will point to the next argument passed via stack. 3567 unsigned StackOffset = CCInfo.getNextStackOffset(); 3568 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 3569 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 3570 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 3571 3572 if (MFI.hasMustTailInVarArgFunc()) { 3573 SmallVector<MVT, 2> RegParmTypes; 3574 RegParmTypes.push_back(MVT::i64); 3575 RegParmTypes.push_back(MVT::f128); 3576 // Compute the set of forwarded registers. The rest are scratch. 3577 SmallVectorImpl<ForwardedRegister> &Forwards = 3578 FuncInfo->getForwardedMustTailRegParms(); 3579 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 3580 CC_AArch64_AAPCS); 3581 3582 // Conservatively forward X8, since it might be used for aggregate return. 3583 if (!CCInfo.isAllocated(AArch64::X8)) { 3584 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 3585 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 3586 } 3587 } 3588 } 3589 3590 // On Windows, InReg pointers must be returned, so record the pointer in a 3591 // virtual register at the start of the function so it can be returned in the 3592 // epilogue. 3593 if (IsWin64) { 3594 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 3595 if (Ins[I].Flags.isInReg()) { 3596 assert(!FuncInfo->getSRetReturnReg()); 3597 3598 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 3599 Register Reg = 3600 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 3601 FuncInfo->setSRetReturnReg(Reg); 3602 3603 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 3604 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3605 break; 3606 } 3607 } 3608 } 3609 3610 unsigned StackArgSize = CCInfo.getNextStackOffset(); 3611 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3612 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 3613 // This is a non-standard ABI so by fiat I say we're allowed to make full 3614 // use of the stack area to be popped, which must be aligned to 16 bytes in 3615 // any case: 3616 StackArgSize = alignTo(StackArgSize, 16); 3617 3618 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 3619 // a multiple of 16. 3620 FuncInfo->setArgumentStackToRestore(StackArgSize); 3621 3622 // This realignment carries over to the available bytes below. Our own 3623 // callers will guarantee the space is free by giving an aligned value to 3624 // CALLSEQ_START. 3625 } 3626 // Even if we're not expected to free up the space, it's useful to know how 3627 // much is there while considering tail calls (because we can reuse it). 3628 FuncInfo->setBytesInStackArgArea(StackArgSize); 3629 3630 if (Subtarget->hasCustomCallingConv()) 3631 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 3632 3633 return Chain; 3634 } 3635 3636 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 3637 SelectionDAG &DAG, 3638 const SDLoc &DL, 3639 SDValue &Chain) const { 3640 MachineFunction &MF = DAG.getMachineFunction(); 3641 MachineFrameInfo &MFI = MF.getFrameInfo(); 3642 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3643 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3644 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3645 3646 SmallVector<SDValue, 8> MemOps; 3647 3648 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 3649 AArch64::X3, AArch64::X4, AArch64::X5, 3650 AArch64::X6, AArch64::X7 }; 3651 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 3652 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 3653 3654 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 3655 int GPRIdx = 0; 3656 if (GPRSaveSize != 0) { 3657 if (IsWin64) { 3658 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 3659 if (GPRSaveSize & 15) 3660 // The extra size here, if triggered, will always be 8. 3661 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 3662 } else 3663 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 3664 3665 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 3666 3667 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 3668 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 3669 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 3670 SDValue Store = DAG.getStore( 3671 Val.getValue(1), DL, Val, FIN, 3672 IsWin64 3673 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 3674 GPRIdx, 3675 (i - FirstVariadicGPR) * 8) 3676 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 3677 MemOps.push_back(Store); 3678 FIN = 3679 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 3680 } 3681 } 3682 FuncInfo->setVarArgsGPRIndex(GPRIdx); 3683 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 3684 3685 if (Subtarget->hasFPARMv8() && !IsWin64) { 3686 static const MCPhysReg FPRArgRegs[] = { 3687 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 3688 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 3689 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 3690 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 3691 3692 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 3693 int FPRIdx = 0; 3694 if (FPRSaveSize != 0) { 3695 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 3696 3697 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 3698 3699 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 3700 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 3701 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 3702 3703 SDValue Store = DAG.getStore( 3704 Val.getValue(1), DL, Val, FIN, 3705 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 3706 MemOps.push_back(Store); 3707 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 3708 DAG.getConstant(16, DL, PtrVT)); 3709 } 3710 } 3711 FuncInfo->setVarArgsFPRIndex(FPRIdx); 3712 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 3713 } 3714 3715 if (!MemOps.empty()) { 3716 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3717 } 3718 } 3719 3720 /// LowerCallResult - Lower the result values of a call into the 3721 /// appropriate copies out of appropriate physical registers. 3722 SDValue AArch64TargetLowering::LowerCallResult( 3723 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 3724 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3725 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 3726 SDValue ThisVal) const { 3727 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3728 ? RetCC_AArch64_WebKit_JS 3729 : RetCC_AArch64_AAPCS; 3730 // Assign locations to each value returned by this call. 3731 SmallVector<CCValAssign, 16> RVLocs; 3732 DenseMap<unsigned, SDValue> CopiedRegs; 3733 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3734 *DAG.getContext()); 3735 CCInfo.AnalyzeCallResult(Ins, RetCC); 3736 3737 // Copy all of the result registers out of their specified physreg. 3738 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3739 CCValAssign VA = RVLocs[i]; 3740 3741 // Pass 'this' value directly from the argument to return value, to avoid 3742 // reg unit interference 3743 if (i == 0 && isThisReturn) { 3744 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3745 "unexpected return calling convention register assignment"); 3746 InVals.push_back(ThisVal); 3747 continue; 3748 } 3749 3750 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 3751 // allows one use of a physreg per block. 3752 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 3753 if (!Val) { 3754 Val = 3755 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3756 Chain = Val.getValue(1); 3757 InFlag = Val.getValue(2); 3758 CopiedRegs[VA.getLocReg()] = Val; 3759 } 3760 3761 switch (VA.getLocInfo()) { 3762 default: 3763 llvm_unreachable("Unknown loc info!"); 3764 case CCValAssign::Full: 3765 break; 3766 case CCValAssign::BCvt: 3767 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3768 break; 3769 case CCValAssign::AExtUpper: 3770 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 3771 DAG.getConstant(32, DL, VA.getLocVT())); 3772 LLVM_FALLTHROUGH; 3773 case CCValAssign::AExt: 3774 LLVM_FALLTHROUGH; 3775 case CCValAssign::ZExt: 3776 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 3777 break; 3778 } 3779 3780 InVals.push_back(Val); 3781 } 3782 3783 return Chain; 3784 } 3785 3786 /// Return true if the calling convention is one that we can guarantee TCO for. 3787 static bool canGuaranteeTCO(CallingConv::ID CC) { 3788 return CC == CallingConv::Fast; 3789 } 3790 3791 /// Return true if we might ever do TCO for calls with this calling convention. 3792 static bool mayTailCallThisCC(CallingConv::ID CC) { 3793 switch (CC) { 3794 case CallingConv::C: 3795 case CallingConv::PreserveMost: 3796 case CallingConv::Swift: 3797 return true; 3798 default: 3799 return canGuaranteeTCO(CC); 3800 } 3801 } 3802 3803 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3804 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3805 const SmallVectorImpl<ISD::OutputArg> &Outs, 3806 const SmallVectorImpl<SDValue> &OutVals, 3807 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3808 if (!mayTailCallThisCC(CalleeCC)) 3809 return false; 3810 3811 MachineFunction &MF = DAG.getMachineFunction(); 3812 const Function &CallerF = MF.getFunction(); 3813 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3814 bool CCMatch = CallerCC == CalleeCC; 3815 3816 // Byval parameters hand the function a pointer directly into the stack area 3817 // we want to reuse during a tail call. Working around this *is* possible (see 3818 // X86) but less efficient and uglier in LowerCall. 3819 for (Function::const_arg_iterator i = CallerF.arg_begin(), 3820 e = CallerF.arg_end(); 3821 i != e; ++i) { 3822 if (i->hasByValAttr()) 3823 return false; 3824 3825 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 3826 // In this case, it is necessary to save/restore X0 in the callee. Tail 3827 // call opt interferes with this. So we disable tail call opt when the 3828 // caller has an argument with "inreg" attribute. 3829 3830 // FIXME: Check whether the callee also has an "inreg" argument. 3831 if (i->hasInRegAttr()) 3832 return false; 3833 } 3834 3835 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3836 return canGuaranteeTCO(CalleeCC) && CCMatch; 3837 3838 // Externally-defined functions with weak linkage should not be 3839 // tail-called on AArch64 when the OS does not support dynamic 3840 // pre-emption of symbols, as the AAELF spec requires normal calls 3841 // to undefined weak functions to be replaced with a NOP or jump to the 3842 // next instruction. The behaviour of branch instructions in this 3843 // situation (as used for tail calls) is implementation-defined, so we 3844 // cannot rely on the linker replacing the tail call with a return. 3845 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3846 const GlobalValue *GV = G->getGlobal(); 3847 const Triple &TT = getTargetMachine().getTargetTriple(); 3848 if (GV->hasExternalWeakLinkage() && 3849 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3850 return false; 3851 } 3852 3853 // Now we search for cases where we can use a tail call without changing the 3854 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3855 // concept. 3856 3857 // I want anyone implementing a new calling convention to think long and hard 3858 // about this assert. 3859 assert((!isVarArg || CalleeCC == CallingConv::C) && 3860 "Unexpected variadic calling convention"); 3861 3862 LLVMContext &C = *DAG.getContext(); 3863 if (isVarArg && !Outs.empty()) { 3864 // At least two cases here: if caller is fastcc then we can't have any 3865 // memory arguments (we'd be expected to clean up the stack afterwards). If 3866 // caller is C then we could potentially use its argument area. 3867 3868 // FIXME: for now we take the most conservative of these in both cases: 3869 // disallow all variadic memory operands. 3870 SmallVector<CCValAssign, 16> ArgLocs; 3871 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3872 3873 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3874 for (const CCValAssign &ArgLoc : ArgLocs) 3875 if (!ArgLoc.isRegLoc()) 3876 return false; 3877 } 3878 3879 // Check that the call results are passed in the same way. 3880 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3881 CCAssignFnForCall(CalleeCC, isVarArg), 3882 CCAssignFnForCall(CallerCC, isVarArg))) 3883 return false; 3884 // The callee has to preserve all registers the caller needs to preserve. 3885 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3886 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3887 if (!CCMatch) { 3888 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3889 if (Subtarget->hasCustomCallingConv()) { 3890 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 3891 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 3892 } 3893 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3894 return false; 3895 } 3896 3897 // Nothing more to check if the callee is taking no arguments 3898 if (Outs.empty()) 3899 return true; 3900 3901 SmallVector<CCValAssign, 16> ArgLocs; 3902 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3903 3904 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3905 3906 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3907 3908 // If any of the arguments is passed indirectly, it must be SVE, so the 3909 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to 3910 // allocate space on the stack. That is why we determine this explicitly here 3911 // the call cannot be a tailcall. 3912 if (llvm::any_of(ArgLocs, [](CCValAssign &A) { 3913 assert((A.getLocInfo() != CCValAssign::Indirect || 3914 A.getValVT().isScalableVector()) && 3915 "Expected value to be scalable"); 3916 return A.getLocInfo() == CCValAssign::Indirect; 3917 })) 3918 return false; 3919 3920 // If the stack arguments for this call do not fit into our own save area then 3921 // the call cannot be made tail. 3922 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3923 return false; 3924 3925 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3926 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3927 return false; 3928 3929 return true; 3930 } 3931 3932 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3933 SelectionDAG &DAG, 3934 MachineFrameInfo &MFI, 3935 int ClobberedFI) const { 3936 SmallVector<SDValue, 8> ArgChains; 3937 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3938 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3939 3940 // Include the original chain at the beginning of the list. When this is 3941 // used by target LowerCall hooks, this helps legalize find the 3942 // CALLSEQ_BEGIN node. 3943 ArgChains.push_back(Chain); 3944 3945 // Add a chain value for each stack argument corresponding 3946 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 3947 UE = DAG.getEntryNode().getNode()->use_end(); 3948 U != UE; ++U) 3949 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3950 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3951 if (FI->getIndex() < 0) { 3952 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 3953 int64_t InLastByte = InFirstByte; 3954 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 3955 3956 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 3957 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 3958 ArgChains.push_back(SDValue(L, 1)); 3959 } 3960 3961 // Build a tokenfactor for all the chains. 3962 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3963 } 3964 3965 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 3966 bool TailCallOpt) const { 3967 return CallCC == CallingConv::Fast && TailCallOpt; 3968 } 3969 3970 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 3971 /// and add input and output parameter nodes. 3972 SDValue 3973 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 3974 SmallVectorImpl<SDValue> &InVals) const { 3975 SelectionDAG &DAG = CLI.DAG; 3976 SDLoc &DL = CLI.DL; 3977 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3978 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3979 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3980 SDValue Chain = CLI.Chain; 3981 SDValue Callee = CLI.Callee; 3982 bool &IsTailCall = CLI.IsTailCall; 3983 CallingConv::ID CallConv = CLI.CallConv; 3984 bool IsVarArg = CLI.IsVarArg; 3985 3986 MachineFunction &MF = DAG.getMachineFunction(); 3987 MachineFunction::CallSiteInfo CSInfo; 3988 bool IsThisReturn = false; 3989 3990 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3991 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3992 bool IsSibCall = false; 3993 3994 if (IsTailCall) { 3995 // Check if it's really possible to do a tail call. 3996 IsTailCall = isEligibleForTailCallOptimization( 3997 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3998 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 3999 report_fatal_error("failed to perform tail call elimination on a call " 4000 "site marked musttail"); 4001 4002 // A sibling call is one where we're under the usual C ABI and not planning 4003 // to change that but can still do a tail call: 4004 if (!TailCallOpt && IsTailCall) 4005 IsSibCall = true; 4006 4007 if (IsTailCall) 4008 ++NumTailCalls; 4009 } 4010 4011 // Analyze operands of the call, assigning locations to each operand. 4012 SmallVector<CCValAssign, 16> ArgLocs; 4013 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 4014 *DAG.getContext()); 4015 4016 if (IsVarArg) { 4017 // Handle fixed and variable vector arguments differently. 4018 // Variable vector arguments always go into memory. 4019 unsigned NumArgs = Outs.size(); 4020 4021 for (unsigned i = 0; i != NumArgs; ++i) { 4022 MVT ArgVT = Outs[i].VT; 4023 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4024 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 4025 /*IsVarArg=*/ !Outs[i].IsFixed); 4026 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 4027 assert(!Res && "Call operand has unhandled type"); 4028 (void)Res; 4029 } 4030 } else { 4031 // At this point, Outs[].VT may already be promoted to i32. To correctly 4032 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 4033 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 4034 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 4035 // we use a special version of AnalyzeCallOperands to pass in ValVT and 4036 // LocVT. 4037 unsigned NumArgs = Outs.size(); 4038 for (unsigned i = 0; i != NumArgs; ++i) { 4039 MVT ValVT = Outs[i].VT; 4040 // Get type of the original argument. 4041 EVT ActualVT = getValueType(DAG.getDataLayout(), 4042 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 4043 /*AllowUnknown*/ true); 4044 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 4045 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4046 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 4047 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 4048 ValVT = MVT::i8; 4049 else if (ActualMVT == MVT::i16) 4050 ValVT = MVT::i16; 4051 4052 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 4053 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 4054 assert(!Res && "Call operand has unhandled type"); 4055 (void)Res; 4056 } 4057 } 4058 4059 // Get a count of how many bytes are to be pushed on the stack. 4060 unsigned NumBytes = CCInfo.getNextStackOffset(); 4061 4062 if (IsSibCall) { 4063 // Since we're not changing the ABI to make this a tail call, the memory 4064 // operands are already available in the caller's incoming argument space. 4065 NumBytes = 0; 4066 } 4067 4068 // FPDiff is the byte offset of the call's argument area from the callee's. 4069 // Stores to callee stack arguments will be placed in FixedStackSlots offset 4070 // by this amount for a tail call. In a sibling call it must be 0 because the 4071 // caller will deallocate the entire stack and the callee still expects its 4072 // arguments to begin at SP+0. Completely unused for non-tail calls. 4073 int FPDiff = 0; 4074 4075 if (IsTailCall && !IsSibCall) { 4076 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 4077 4078 // Since callee will pop argument stack as a tail call, we must keep the 4079 // popped size 16-byte aligned. 4080 NumBytes = alignTo(NumBytes, 16); 4081 4082 // FPDiff will be negative if this tail call requires more space than we 4083 // would automatically have in our incoming argument space. Positive if we 4084 // can actually shrink the stack. 4085 FPDiff = NumReusableBytes - NumBytes; 4086 4087 // The stack pointer must be 16-byte aligned at all times it's used for a 4088 // memory operation, which in practice means at *all* times and in 4089 // particular across call boundaries. Therefore our own arguments started at 4090 // a 16-byte aligned SP and the delta applied for the tail call should 4091 // satisfy the same constraint. 4092 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 4093 } 4094 4095 // Adjust the stack pointer for the new arguments... 4096 // These operations are automatically eliminated by the prolog/epilog pass 4097 if (!IsSibCall) 4098 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 4099 4100 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 4101 getPointerTy(DAG.getDataLayout())); 4102 4103 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4104 SmallSet<unsigned, 8> RegsUsed; 4105 SmallVector<SDValue, 8> MemOpChains; 4106 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4107 4108 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) { 4109 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 4110 for (const auto &F : Forwards) { 4111 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 4112 RegsToPass.emplace_back(F.PReg, Val); 4113 } 4114 } 4115 4116 // Walk the register/memloc assignments, inserting copies/loads. 4117 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4118 CCValAssign &VA = ArgLocs[i]; 4119 SDValue Arg = OutVals[i]; 4120 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4121 4122 // Promote the value if needed. 4123 switch (VA.getLocInfo()) { 4124 default: 4125 llvm_unreachable("Unknown loc info!"); 4126 case CCValAssign::Full: 4127 break; 4128 case CCValAssign::SExt: 4129 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 4130 break; 4131 case CCValAssign::ZExt: 4132 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4133 break; 4134 case CCValAssign::AExt: 4135 if (Outs[i].ArgVT == MVT::i1) { 4136 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 4137 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4138 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 4139 } 4140 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 4141 break; 4142 case CCValAssign::AExtUpper: 4143 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4144 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 4145 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4146 DAG.getConstant(32, DL, VA.getLocVT())); 4147 break; 4148 case CCValAssign::BCvt: 4149 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 4150 break; 4151 case CCValAssign::Trunc: 4152 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4153 break; 4154 case CCValAssign::FPExt: 4155 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 4156 break; 4157 case CCValAssign::Indirect: 4158 assert(VA.getValVT().isScalableVector() && 4159 "Only scalable vectors can be passed indirectly"); 4160 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4161 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext()); 4162 unsigned Align = DAG.getDataLayout().getPrefTypeAlignment(Ty); 4163 int FI = MFI.CreateStackObject( 4164 VA.getValVT().getStoreSize().getKnownMinSize(), Align, false); 4165 MFI.setStackID(FI, TargetStackID::SVEVector); 4166 4167 SDValue SpillSlot = DAG.getFrameIndex( 4168 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout())); 4169 Chain = DAG.getStore( 4170 Chain, DL, Arg, SpillSlot, 4171 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4172 Arg = SpillSlot; 4173 break; 4174 } 4175 4176 if (VA.isRegLoc()) { 4177 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 4178 Outs[0].VT == MVT::i64) { 4179 assert(VA.getLocVT() == MVT::i64 && 4180 "unexpected calling convention register assignment"); 4181 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 4182 "unexpected use of 'returned'"); 4183 IsThisReturn = true; 4184 } 4185 if (RegsUsed.count(VA.getLocReg())) { 4186 // If this register has already been used then we're trying to pack 4187 // parts of an [N x i32] into an X-register. The extension type will 4188 // take care of putting the two halves in the right place but we have to 4189 // combine them. 4190 SDValue &Bits = 4191 std::find_if(RegsToPass.begin(), RegsToPass.end(), 4192 [=](const std::pair<unsigned, SDValue> &Elt) { 4193 return Elt.first == VA.getLocReg(); 4194 }) 4195 ->second; 4196 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4197 // Call site info is used for function's parameter entry value 4198 // tracking. For now we track only simple cases when parameter 4199 // is transferred through whole register. 4200 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(), 4201 [&VA](MachineFunction::ArgRegPair ArgReg) { 4202 return ArgReg.Reg == VA.getLocReg(); 4203 }), 4204 CSInfo.end()); 4205 } else { 4206 RegsToPass.emplace_back(VA.getLocReg(), Arg); 4207 RegsUsed.insert(VA.getLocReg()); 4208 const TargetOptions &Options = DAG.getTarget().Options; 4209 if (Options.EnableDebugEntryValues) 4210 CSInfo.emplace_back(VA.getLocReg(), i); 4211 } 4212 } else { 4213 assert(VA.isMemLoc()); 4214 4215 SDValue DstAddr; 4216 MachinePointerInfo DstInfo; 4217 4218 // FIXME: This works on big-endian for composite byvals, which are the 4219 // common case. It should also work for fundamental types too. 4220 uint32_t BEAlign = 0; 4221 unsigned OpSize; 4222 if (VA.getLocInfo() == CCValAssign::Indirect) 4223 OpSize = VA.getLocVT().getSizeInBits(); 4224 else 4225 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 4226 : VA.getValVT().getSizeInBits(); 4227 OpSize = (OpSize + 7) / 8; 4228 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 4229 !Flags.isInConsecutiveRegs()) { 4230 if (OpSize < 8) 4231 BEAlign = 8 - OpSize; 4232 } 4233 unsigned LocMemOffset = VA.getLocMemOffset(); 4234 int32_t Offset = LocMemOffset + BEAlign; 4235 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 4236 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 4237 4238 if (IsTailCall) { 4239 Offset = Offset + FPDiff; 4240 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4241 4242 DstAddr = DAG.getFrameIndex(FI, PtrVT); 4243 DstInfo = 4244 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 4245 4246 // Make sure any stack arguments overlapping with where we're storing 4247 // are loaded before this eventual operation. Otherwise they'll be 4248 // clobbered. 4249 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 4250 } else { 4251 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 4252 4253 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 4254 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 4255 LocMemOffset); 4256 } 4257 4258 if (Outs[i].Flags.isByVal()) { 4259 SDValue SizeNode = 4260 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 4261 SDValue Cpy = DAG.getMemcpy( 4262 Chain, DL, DstAddr, Arg, SizeNode, 4263 Outs[i].Flags.getNonZeroByValAlign(), 4264 /*isVol = */ false, /*AlwaysInline = */ false, 4265 /*isTailCall = */ false, DstInfo, MachinePointerInfo()); 4266 4267 MemOpChains.push_back(Cpy); 4268 } else { 4269 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 4270 // promoted to a legal register type i32, we should truncate Arg back to 4271 // i1/i8/i16. 4272 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 4273 VA.getValVT() == MVT::i16) 4274 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 4275 4276 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 4277 MemOpChains.push_back(Store); 4278 } 4279 } 4280 } 4281 4282 if (!MemOpChains.empty()) 4283 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 4284 4285 // Build a sequence of copy-to-reg nodes chained together with token chain 4286 // and flag operands which copy the outgoing args into the appropriate regs. 4287 SDValue InFlag; 4288 for (auto &RegToPass : RegsToPass) { 4289 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 4290 RegToPass.second, InFlag); 4291 InFlag = Chain.getValue(1); 4292 } 4293 4294 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 4295 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 4296 // node so that legalize doesn't hack it. 4297 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4298 auto GV = G->getGlobal(); 4299 unsigned OpFlags = 4300 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()); 4301 if (OpFlags & AArch64II::MO_GOT) { 4302 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 4303 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4304 } else { 4305 const GlobalValue *GV = G->getGlobal(); 4306 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 4307 } 4308 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4309 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4310 Subtarget->isTargetMachO()) { 4311 const char *Sym = S->getSymbol(); 4312 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 4313 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4314 } else { 4315 const char *Sym = S->getSymbol(); 4316 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 4317 } 4318 } 4319 4320 // We don't usually want to end the call-sequence here because we would tidy 4321 // the frame up *after* the call, however in the ABI-changing tail-call case 4322 // we've carefully laid out the parameters so that when sp is reset they'll be 4323 // in the correct location. 4324 if (IsTailCall && !IsSibCall) { 4325 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4326 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 4327 InFlag = Chain.getValue(1); 4328 } 4329 4330 std::vector<SDValue> Ops; 4331 Ops.push_back(Chain); 4332 Ops.push_back(Callee); 4333 4334 if (IsTailCall) { 4335 // Each tail call may have to adjust the stack by a different amount, so 4336 // this information must travel along with the operation for eventual 4337 // consumption by emitEpilogue. 4338 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 4339 } 4340 4341 // Add argument registers to the end of the list so that they are known live 4342 // into the call. 4343 for (auto &RegToPass : RegsToPass) 4344 Ops.push_back(DAG.getRegister(RegToPass.first, 4345 RegToPass.second.getValueType())); 4346 4347 // Check callee args/returns for SVE registers and set calling convention 4348 // accordingly. 4349 if (CallConv == CallingConv::C) { 4350 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 4351 return Out.VT.isScalableVector(); 4352 }); 4353 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 4354 return In.VT.isScalableVector(); 4355 }); 4356 4357 if (CalleeInSVE || CalleeOutSVE) 4358 CallConv = CallingConv::AArch64_SVE_VectorCall; 4359 } 4360 4361 // Add a register mask operand representing the call-preserved registers. 4362 const uint32_t *Mask; 4363 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4364 if (IsThisReturn) { 4365 // For 'this' returns, use the X0-preserving mask if applicable 4366 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 4367 if (!Mask) { 4368 IsThisReturn = false; 4369 Mask = TRI->getCallPreservedMask(MF, CallConv); 4370 } 4371 } else 4372 Mask = TRI->getCallPreservedMask(MF, CallConv); 4373 4374 if (Subtarget->hasCustomCallingConv()) 4375 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 4376 4377 if (TRI->isAnyArgRegReserved(MF)) 4378 TRI->emitReservedArgRegCallError(MF); 4379 4380 assert(Mask && "Missing call preserved mask for calling convention"); 4381 Ops.push_back(DAG.getRegisterMask(Mask)); 4382 4383 if (InFlag.getNode()) 4384 Ops.push_back(InFlag); 4385 4386 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4387 4388 // If we're doing a tall call, use a TC_RETURN here rather than an 4389 // actual call instruction. 4390 if (IsTailCall) { 4391 MF.getFrameInfo().setHasTailCall(); 4392 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 4393 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 4394 return Ret; 4395 } 4396 4397 // Returns a chain and a flag for retval copy to use. 4398 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 4399 InFlag = Chain.getValue(1); 4400 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 4401 4402 uint64_t CalleePopBytes = 4403 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 4404 4405 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4406 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 4407 InFlag, DL); 4408 if (!Ins.empty()) 4409 InFlag = Chain.getValue(1); 4410 4411 // Handle result values, copying them out of physregs into vregs that we 4412 // return. 4413 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 4414 InVals, IsThisReturn, 4415 IsThisReturn ? OutVals[0] : SDValue()); 4416 } 4417 4418 bool AArch64TargetLowering::CanLowerReturn( 4419 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 4420 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 4421 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4422 ? RetCC_AArch64_WebKit_JS 4423 : RetCC_AArch64_AAPCS; 4424 SmallVector<CCValAssign, 16> RVLocs; 4425 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 4426 return CCInfo.CheckReturn(Outs, RetCC); 4427 } 4428 4429 SDValue 4430 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 4431 bool isVarArg, 4432 const SmallVectorImpl<ISD::OutputArg> &Outs, 4433 const SmallVectorImpl<SDValue> &OutVals, 4434 const SDLoc &DL, SelectionDAG &DAG) const { 4435 auto &MF = DAG.getMachineFunction(); 4436 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4437 4438 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4439 ? RetCC_AArch64_WebKit_JS 4440 : RetCC_AArch64_AAPCS; 4441 SmallVector<CCValAssign, 16> RVLocs; 4442 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4443 *DAG.getContext()); 4444 CCInfo.AnalyzeReturn(Outs, RetCC); 4445 4446 // Copy the result values into the output registers. 4447 SDValue Flag; 4448 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 4449 SmallSet<unsigned, 4> RegsUsed; 4450 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 4451 ++i, ++realRVLocIdx) { 4452 CCValAssign &VA = RVLocs[i]; 4453 assert(VA.isRegLoc() && "Can only return in registers!"); 4454 SDValue Arg = OutVals[realRVLocIdx]; 4455 4456 switch (VA.getLocInfo()) { 4457 default: 4458 llvm_unreachable("Unknown loc info!"); 4459 case CCValAssign::Full: 4460 if (Outs[i].ArgVT == MVT::i1) { 4461 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 4462 // value. This is strictly redundant on Darwin (which uses "zeroext 4463 // i1"), but will be optimised out before ISel. 4464 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4465 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4466 } 4467 break; 4468 case CCValAssign::BCvt: 4469 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 4470 break; 4471 case CCValAssign::AExt: 4472 case CCValAssign::ZExt: 4473 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4474 break; 4475 case CCValAssign::AExtUpper: 4476 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4477 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4478 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4479 DAG.getConstant(32, DL, VA.getLocVT())); 4480 break; 4481 } 4482 4483 if (RegsUsed.count(VA.getLocReg())) { 4484 SDValue &Bits = 4485 std::find_if(RetVals.begin(), RetVals.end(), 4486 [=](const std::pair<unsigned, SDValue> &Elt) { 4487 return Elt.first == VA.getLocReg(); 4488 }) 4489 ->second; 4490 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4491 } else { 4492 RetVals.emplace_back(VA.getLocReg(), Arg); 4493 RegsUsed.insert(VA.getLocReg()); 4494 } 4495 } 4496 4497 SmallVector<SDValue, 4> RetOps(1, Chain); 4498 for (auto &RetVal : RetVals) { 4499 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 4500 Flag = Chain.getValue(1); 4501 RetOps.push_back( 4502 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 4503 } 4504 4505 // Windows AArch64 ABIs require that for returning structs by value we copy 4506 // the sret argument into X0 for the return. 4507 // We saved the argument into a virtual register in the entry block, 4508 // so now we copy the value out and into X0. 4509 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 4510 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 4511 getPointerTy(MF.getDataLayout())); 4512 4513 unsigned RetValReg = AArch64::X0; 4514 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 4515 Flag = Chain.getValue(1); 4516 4517 RetOps.push_back( 4518 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 4519 } 4520 4521 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4522 const MCPhysReg *I = 4523 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 4524 if (I) { 4525 for (; *I; ++I) { 4526 if (AArch64::GPR64RegClass.contains(*I)) 4527 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 4528 else if (AArch64::FPR64RegClass.contains(*I)) 4529 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 4530 else 4531 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 4532 } 4533 } 4534 4535 RetOps[0] = Chain; // Update chain. 4536 4537 // Add the flag if we have it. 4538 if (Flag.getNode()) 4539 RetOps.push_back(Flag); 4540 4541 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 4542 } 4543 4544 //===----------------------------------------------------------------------===// 4545 // Other Lowering Code 4546 //===----------------------------------------------------------------------===// 4547 4548 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 4549 SelectionDAG &DAG, 4550 unsigned Flag) const { 4551 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 4552 N->getOffset(), Flag); 4553 } 4554 4555 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 4556 SelectionDAG &DAG, 4557 unsigned Flag) const { 4558 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 4559 } 4560 4561 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 4562 SelectionDAG &DAG, 4563 unsigned Flag) const { 4564 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 4565 N->getOffset(), Flag); 4566 } 4567 4568 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 4569 SelectionDAG &DAG, 4570 unsigned Flag) const { 4571 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 4572 } 4573 4574 // (loadGOT sym) 4575 template <class NodeTy> 4576 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 4577 unsigned Flags) const { 4578 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 4579 SDLoc DL(N); 4580 EVT Ty = getPointerTy(DAG.getDataLayout()); 4581 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 4582 // FIXME: Once remat is capable of dealing with instructions with register 4583 // operands, expand this into two nodes instead of using a wrapper node. 4584 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 4585 } 4586 4587 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 4588 template <class NodeTy> 4589 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 4590 unsigned Flags) const { 4591 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 4592 SDLoc DL(N); 4593 EVT Ty = getPointerTy(DAG.getDataLayout()); 4594 const unsigned char MO_NC = AArch64II::MO_NC; 4595 return DAG.getNode( 4596 AArch64ISD::WrapperLarge, DL, Ty, 4597 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 4598 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 4599 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 4600 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 4601 } 4602 4603 // (addlow (adrp %hi(sym)) %lo(sym)) 4604 template <class NodeTy> 4605 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 4606 unsigned Flags) const { 4607 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 4608 SDLoc DL(N); 4609 EVT Ty = getPointerTy(DAG.getDataLayout()); 4610 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 4611 SDValue Lo = getTargetNode(N, Ty, DAG, 4612 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 4613 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 4614 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 4615 } 4616 4617 // (adr sym) 4618 template <class NodeTy> 4619 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 4620 unsigned Flags) const { 4621 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 4622 SDLoc DL(N); 4623 EVT Ty = getPointerTy(DAG.getDataLayout()); 4624 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 4625 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 4626 } 4627 4628 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 4629 SelectionDAG &DAG) const { 4630 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 4631 const GlobalValue *GV = GN->getGlobal(); 4632 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 4633 4634 if (OpFlags != AArch64II::MO_NO_FLAG) 4635 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 4636 "unexpected offset in global node"); 4637 4638 // This also catches the large code model case for Darwin, and tiny code 4639 // model with got relocations. 4640 if ((OpFlags & AArch64II::MO_GOT) != 0) { 4641 return getGOT(GN, DAG, OpFlags); 4642 } 4643 4644 SDValue Result; 4645 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4646 Result = getAddrLarge(GN, DAG, OpFlags); 4647 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 4648 Result = getAddrTiny(GN, DAG, OpFlags); 4649 } else { 4650 Result = getAddr(GN, DAG, OpFlags); 4651 } 4652 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4653 SDLoc DL(GN); 4654 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 4655 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 4656 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 4657 return Result; 4658 } 4659 4660 /// Convert a TLS address reference into the correct sequence of loads 4661 /// and calls to compute the variable's address (for Darwin, currently) and 4662 /// return an SDValue containing the final node. 4663 4664 /// Darwin only has one TLS scheme which must be capable of dealing with the 4665 /// fully general situation, in the worst case. This means: 4666 /// + "extern __thread" declaration. 4667 /// + Defined in a possibly unknown dynamic library. 4668 /// 4669 /// The general system is that each __thread variable has a [3 x i64] descriptor 4670 /// which contains information used by the runtime to calculate the address. The 4671 /// only part of this the compiler needs to know about is the first xword, which 4672 /// contains a function pointer that must be called with the address of the 4673 /// entire descriptor in "x0". 4674 /// 4675 /// Since this descriptor may be in a different unit, in general even the 4676 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 4677 /// is: 4678 /// adrp x0, _var@TLVPPAGE 4679 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 4680 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 4681 /// ; the function pointer 4682 /// blr x1 ; Uses descriptor address in x0 4683 /// ; Address of _var is now in x0. 4684 /// 4685 /// If the address of _var's descriptor *is* known to the linker, then it can 4686 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 4687 /// a slight efficiency gain. 4688 SDValue 4689 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 4690 SelectionDAG &DAG) const { 4691 assert(Subtarget->isTargetDarwin() && 4692 "This function expects a Darwin target"); 4693 4694 SDLoc DL(Op); 4695 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 4696 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 4697 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 4698 4699 SDValue TLVPAddr = 4700 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4701 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 4702 4703 // The first entry in the descriptor is a function pointer that we must call 4704 // to obtain the address of the variable. 4705 SDValue Chain = DAG.getEntryNode(); 4706 SDValue FuncTLVGet = DAG.getLoad( 4707 PtrMemVT, DL, Chain, DescAddr, 4708 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 4709 /* Alignment = */ PtrMemVT.getSizeInBits() / 8, 4710 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 4711 Chain = FuncTLVGet.getValue(1); 4712 4713 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 4714 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 4715 4716 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4717 MFI.setAdjustsStack(true); 4718 4719 // TLS calls preserve all registers except those that absolutely must be 4720 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 4721 // silly). 4722 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4723 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 4724 if (Subtarget->hasCustomCallingConv()) 4725 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 4726 4727 // Finally, we can make the call. This is just a degenerate version of a 4728 // normal AArch64 call node: x0 takes the address of the descriptor, and 4729 // returns the address of the variable in this thread. 4730 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 4731 Chain = 4732 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 4733 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 4734 DAG.getRegisterMask(Mask), Chain.getValue(1)); 4735 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 4736 } 4737 4738 /// Convert a thread-local variable reference into a sequence of instructions to 4739 /// compute the variable's address for the local exec TLS model of ELF targets. 4740 /// The sequence depends on the maximum TLS area size. 4741 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV, 4742 SDValue ThreadBase, 4743 const SDLoc &DL, 4744 SelectionDAG &DAG) const { 4745 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4746 SDValue TPOff, Addr; 4747 4748 switch (DAG.getTarget().Options.TLSSize) { 4749 default: 4750 llvm_unreachable("Unexpected TLS size"); 4751 4752 case 12: { 4753 // mrs x0, TPIDR_EL0 4754 // add x0, x0, :tprel_lo12:a 4755 SDValue Var = DAG.getTargetGlobalAddress( 4756 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF); 4757 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4758 Var, 4759 DAG.getTargetConstant(0, DL, MVT::i32)), 4760 0); 4761 } 4762 4763 case 24: { 4764 // mrs x0, TPIDR_EL0 4765 // add x0, x0, :tprel_hi12:a 4766 // add x0, x0, :tprel_lo12_nc:a 4767 SDValue HiVar = DAG.getTargetGlobalAddress( 4768 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4769 SDValue LoVar = DAG.getTargetGlobalAddress( 4770 GV, DL, PtrVT, 0, 4771 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4772 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4773 HiVar, 4774 DAG.getTargetConstant(0, DL, MVT::i32)), 4775 0); 4776 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr, 4777 LoVar, 4778 DAG.getTargetConstant(0, DL, MVT::i32)), 4779 0); 4780 } 4781 4782 case 32: { 4783 // mrs x1, TPIDR_EL0 4784 // movz x0, #:tprel_g1:a 4785 // movk x0, #:tprel_g0_nc:a 4786 // add x0, x1, x0 4787 SDValue HiVar = DAG.getTargetGlobalAddress( 4788 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1); 4789 SDValue LoVar = DAG.getTargetGlobalAddress( 4790 GV, DL, PtrVT, 0, 4791 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 4792 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 4793 DAG.getTargetConstant(16, DL, MVT::i32)), 4794 0); 4795 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 4796 DAG.getTargetConstant(0, DL, MVT::i32)), 4797 0); 4798 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4799 } 4800 4801 case 48: { 4802 // mrs x1, TPIDR_EL0 4803 // movz x0, #:tprel_g2:a 4804 // movk x0, #:tprel_g1_nc:a 4805 // movk x0, #:tprel_g0_nc:a 4806 // add x0, x1, x0 4807 SDValue HiVar = DAG.getTargetGlobalAddress( 4808 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2); 4809 SDValue MiVar = DAG.getTargetGlobalAddress( 4810 GV, DL, PtrVT, 0, 4811 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC); 4812 SDValue LoVar = DAG.getTargetGlobalAddress( 4813 GV, DL, PtrVT, 0, 4814 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 4815 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 4816 DAG.getTargetConstant(32, DL, MVT::i32)), 4817 0); 4818 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar, 4819 DAG.getTargetConstant(16, DL, MVT::i32)), 4820 0); 4821 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 4822 DAG.getTargetConstant(0, DL, MVT::i32)), 4823 0); 4824 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4825 } 4826 } 4827 } 4828 4829 /// When accessing thread-local variables under either the general-dynamic or 4830 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 4831 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 4832 /// is a function pointer to carry out the resolution. 4833 /// 4834 /// The sequence is: 4835 /// adrp x0, :tlsdesc:var 4836 /// ldr x1, [x0, #:tlsdesc_lo12:var] 4837 /// add x0, x0, #:tlsdesc_lo12:var 4838 /// .tlsdesccall var 4839 /// blr x1 4840 /// (TPIDR_EL0 offset now in x0) 4841 /// 4842 /// The above sequence must be produced unscheduled, to enable the linker to 4843 /// optimize/relax this sequence. 4844 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 4845 /// above sequence, and expanded really late in the compilation flow, to ensure 4846 /// the sequence is produced as per above. 4847 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 4848 const SDLoc &DL, 4849 SelectionDAG &DAG) const { 4850 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4851 4852 SDValue Chain = DAG.getEntryNode(); 4853 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4854 4855 Chain = 4856 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 4857 SDValue Glue = Chain.getValue(1); 4858 4859 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 4860 } 4861 4862 SDValue 4863 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 4864 SelectionDAG &DAG) const { 4865 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 4866 4867 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4868 4869 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 4870 4871 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 4872 if (Model == TLSModel::LocalDynamic) 4873 Model = TLSModel::GeneralDynamic; 4874 } 4875 4876 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4877 Model != TLSModel::LocalExec) 4878 report_fatal_error("ELF TLS only supported in small memory model or " 4879 "in local exec TLS model"); 4880 // Different choices can be made for the maximum size of the TLS area for a 4881 // module. For the small address model, the default TLS size is 16MiB and the 4882 // maximum TLS size is 4GiB. 4883 // FIXME: add tiny and large code model support for TLS access models other 4884 // than local exec. We currently generate the same code as small for tiny, 4885 // which may be larger than needed. 4886 4887 SDValue TPOff; 4888 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4889 SDLoc DL(Op); 4890 const GlobalValue *GV = GA->getGlobal(); 4891 4892 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 4893 4894 if (Model == TLSModel::LocalExec) { 4895 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG); 4896 } else if (Model == TLSModel::InitialExec) { 4897 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4898 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 4899 } else if (Model == TLSModel::LocalDynamic) { 4900 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 4901 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 4902 // the beginning of the module's TLS region, followed by a DTPREL offset 4903 // calculation. 4904 4905 // These accesses will need deduplicating if there's more than one. 4906 AArch64FunctionInfo *MFI = 4907 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4908 MFI->incNumLocalDynamicTLSAccesses(); 4909 4910 // The call needs a relocation too for linker relaxation. It doesn't make 4911 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4912 // the address. 4913 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 4914 AArch64II::MO_TLS); 4915 4916 // Now we can calculate the offset from TPIDR_EL0 to this module's 4917 // thread-local area. 4918 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4919 4920 // Now use :dtprel_whatever: operations to calculate this variable's offset 4921 // in its thread-storage area. 4922 SDValue HiVar = DAG.getTargetGlobalAddress( 4923 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4924 SDValue LoVar = DAG.getTargetGlobalAddress( 4925 GV, DL, MVT::i64, 0, 4926 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4927 4928 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 4929 DAG.getTargetConstant(0, DL, MVT::i32)), 4930 0); 4931 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 4932 DAG.getTargetConstant(0, DL, MVT::i32)), 4933 0); 4934 } else if (Model == TLSModel::GeneralDynamic) { 4935 // The call needs a relocation too for linker relaxation. It doesn't make 4936 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4937 // the address. 4938 SDValue SymAddr = 4939 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4940 4941 // Finally we can make a call to calculate the offset from tpidr_el0. 4942 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4943 } else 4944 llvm_unreachable("Unsupported ELF TLS access model"); 4945 4946 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4947 } 4948 4949 SDValue 4950 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 4951 SelectionDAG &DAG) const { 4952 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 4953 4954 SDValue Chain = DAG.getEntryNode(); 4955 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4956 SDLoc DL(Op); 4957 4958 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 4959 4960 // Load the ThreadLocalStoragePointer from the TEB 4961 // A pointer to the TLS array is located at offset 0x58 from the TEB. 4962 SDValue TLSArray = 4963 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 4964 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 4965 Chain = TLSArray.getValue(1); 4966 4967 // Load the TLS index from the C runtime; 4968 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 4969 // This also does the same as LOADgot, but using a generic i32 load, 4970 // while LOADgot only loads i64. 4971 SDValue TLSIndexHi = 4972 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 4973 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 4974 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4975 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 4976 SDValue TLSIndex = 4977 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 4978 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 4979 Chain = TLSIndex.getValue(1); 4980 4981 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 4982 // offset into the TLSArray. 4983 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 4984 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 4985 DAG.getConstant(3, DL, PtrVT)); 4986 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 4987 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 4988 MachinePointerInfo()); 4989 Chain = TLS.getValue(1); 4990 4991 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4992 const GlobalValue *GV = GA->getGlobal(); 4993 SDValue TGAHi = DAG.getTargetGlobalAddress( 4994 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4995 SDValue TGALo = DAG.getTargetGlobalAddress( 4996 GV, DL, PtrVT, 0, 4997 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4998 4999 // Add the offset from the start of the .tls section (section base). 5000 SDValue Addr = 5001 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 5002 DAG.getTargetConstant(0, DL, MVT::i32)), 5003 0); 5004 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 5005 return Addr; 5006 } 5007 5008 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 5009 SelectionDAG &DAG) const { 5010 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 5011 if (DAG.getTarget().useEmulatedTLS()) 5012 return LowerToTLSEmulatedModel(GA, DAG); 5013 5014 if (Subtarget->isTargetDarwin()) 5015 return LowerDarwinGlobalTLSAddress(Op, DAG); 5016 if (Subtarget->isTargetELF()) 5017 return LowerELFGlobalTLSAddress(Op, DAG); 5018 if (Subtarget->isTargetWindows()) 5019 return LowerWindowsGlobalTLSAddress(Op, DAG); 5020 5021 llvm_unreachable("Unexpected platform trying to use TLS"); 5022 } 5023 5024 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5025 SDValue Chain = Op.getOperand(0); 5026 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5027 SDValue LHS = Op.getOperand(2); 5028 SDValue RHS = Op.getOperand(3); 5029 SDValue Dest = Op.getOperand(4); 5030 SDLoc dl(Op); 5031 5032 MachineFunction &MF = DAG.getMachineFunction(); 5033 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 5034 // will not be produced, as they are conditional branch instructions that do 5035 // not set flags. 5036 bool ProduceNonFlagSettingCondBr = 5037 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 5038 5039 // Handle f128 first, since lowering it will result in comparing the return 5040 // value of a libcall against zero, which is just what the rest of LowerBR_CC 5041 // is expecting to deal with. 5042 if (LHS.getValueType() == MVT::f128) { 5043 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5044 5045 // If softenSetCCOperands returned a scalar, we need to compare the result 5046 // against zero to select between true and false values. 5047 if (!RHS.getNode()) { 5048 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5049 CC = ISD::SETNE; 5050 } 5051 } 5052 5053 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5054 // instruction. 5055 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 5056 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5057 // Only lower legal XALUO ops. 5058 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5059 return SDValue(); 5060 5061 // The actual operation with overflow check. 5062 AArch64CC::CondCode OFCC; 5063 SDValue Value, Overflow; 5064 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 5065 5066 if (CC == ISD::SETNE) 5067 OFCC = getInvertedCondCode(OFCC); 5068 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 5069 5070 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 5071 Overflow); 5072 } 5073 5074 if (LHS.getValueType().isInteger()) { 5075 assert((LHS.getValueType() == RHS.getValueType()) && 5076 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5077 5078 // If the RHS of the comparison is zero, we can potentially fold this 5079 // to a specialized branch. 5080 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 5081 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 5082 if (CC == ISD::SETEQ) { 5083 // See if we can use a TBZ to fold in an AND as well. 5084 // TBZ has a smaller branch displacement than CBZ. If the offset is 5085 // out of bounds, a late MI-layer pass rewrites branches. 5086 // 403.gcc is an example that hits this case. 5087 if (LHS.getOpcode() == ISD::AND && 5088 isa<ConstantSDNode>(LHS.getOperand(1)) && 5089 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 5090 SDValue Test = LHS.getOperand(0); 5091 uint64_t Mask = LHS.getConstantOperandVal(1); 5092 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 5093 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 5094 Dest); 5095 } 5096 5097 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 5098 } else if (CC == ISD::SETNE) { 5099 // See if we can use a TBZ to fold in an AND as well. 5100 // TBZ has a smaller branch displacement than CBZ. If the offset is 5101 // out of bounds, a late MI-layer pass rewrites branches. 5102 // 403.gcc is an example that hits this case. 5103 if (LHS.getOpcode() == ISD::AND && 5104 isa<ConstantSDNode>(LHS.getOperand(1)) && 5105 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 5106 SDValue Test = LHS.getOperand(0); 5107 uint64_t Mask = LHS.getConstantOperandVal(1); 5108 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 5109 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 5110 Dest); 5111 } 5112 5113 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 5114 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 5115 // Don't combine AND since emitComparison converts the AND to an ANDS 5116 // (a.k.a. TST) and the test in the test bit and branch instruction 5117 // becomes redundant. This would also increase register pressure. 5118 uint64_t Mask = LHS.getValueSizeInBits() - 1; 5119 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 5120 DAG.getConstant(Mask, dl, MVT::i64), Dest); 5121 } 5122 } 5123 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 5124 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 5125 // Don't combine AND since emitComparison converts the AND to an ANDS 5126 // (a.k.a. TST) and the test in the test bit and branch instruction 5127 // becomes redundant. This would also increase register pressure. 5128 uint64_t Mask = LHS.getValueSizeInBits() - 1; 5129 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 5130 DAG.getConstant(Mask, dl, MVT::i64), Dest); 5131 } 5132 5133 SDValue CCVal; 5134 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5135 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 5136 Cmp); 5137 } 5138 5139 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5140 LHS.getValueType() == MVT::f64); 5141 5142 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5143 // clean. Some of them require two branches to implement. 5144 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5145 AArch64CC::CondCode CC1, CC2; 5146 changeFPCCToAArch64CC(CC, CC1, CC2); 5147 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5148 SDValue BR1 = 5149 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 5150 if (CC2 != AArch64CC::AL) { 5151 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5152 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 5153 Cmp); 5154 } 5155 5156 return BR1; 5157 } 5158 5159 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 5160 SelectionDAG &DAG) const { 5161 EVT VT = Op.getValueType(); 5162 SDLoc DL(Op); 5163 5164 SDValue In1 = Op.getOperand(0); 5165 SDValue In2 = Op.getOperand(1); 5166 EVT SrcVT = In2.getValueType(); 5167 5168 if (SrcVT.bitsLT(VT)) 5169 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 5170 else if (SrcVT.bitsGT(VT)) 5171 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 5172 5173 EVT VecVT; 5174 uint64_t EltMask; 5175 SDValue VecVal1, VecVal2; 5176 5177 auto setVecVal = [&] (int Idx) { 5178 if (!VT.isVector()) { 5179 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 5180 DAG.getUNDEF(VecVT), In1); 5181 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 5182 DAG.getUNDEF(VecVT), In2); 5183 } else { 5184 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 5185 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 5186 } 5187 }; 5188 5189 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 5190 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 5191 EltMask = 0x80000000ULL; 5192 setVecVal(AArch64::ssub); 5193 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 5194 VecVT = MVT::v2i64; 5195 5196 // We want to materialize a mask with the high bit set, but the AdvSIMD 5197 // immediate moves cannot materialize that in a single instruction for 5198 // 64-bit elements. Instead, materialize zero and then negate it. 5199 EltMask = 0; 5200 5201 setVecVal(AArch64::dsub); 5202 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 5203 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 5204 EltMask = 0x8000ULL; 5205 setVecVal(AArch64::hsub); 5206 } else { 5207 llvm_unreachable("Invalid type for copysign!"); 5208 } 5209 5210 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 5211 5212 // If we couldn't materialize the mask above, then the mask vector will be 5213 // the zero vector, and we need to negate it here. 5214 if (VT == MVT::f64 || VT == MVT::v2f64) { 5215 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 5216 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 5217 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 5218 } 5219 5220 SDValue Sel = 5221 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 5222 5223 if (VT == MVT::f16) 5224 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 5225 if (VT == MVT::f32) 5226 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 5227 else if (VT == MVT::f64) 5228 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 5229 else 5230 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 5231 } 5232 5233 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 5234 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 5235 Attribute::NoImplicitFloat)) 5236 return SDValue(); 5237 5238 if (!Subtarget->hasNEON()) 5239 return SDValue(); 5240 5241 // While there is no integer popcount instruction, it can 5242 // be more efficiently lowered to the following sequence that uses 5243 // AdvSIMD registers/instructions as long as the copies to/from 5244 // the AdvSIMD registers are cheap. 5245 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 5246 // CNT V0.8B, V0.8B // 8xbyte pop-counts 5247 // ADDV B0, V0.8B // sum 8xbyte pop-counts 5248 // UMOV X0, V0.B[0] // copy byte result back to integer reg 5249 SDValue Val = Op.getOperand(0); 5250 SDLoc DL(Op); 5251 EVT VT = Op.getValueType(); 5252 5253 if (VT == MVT::i32 || VT == MVT::i64) { 5254 if (VT == MVT::i32) 5255 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 5256 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 5257 5258 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 5259 SDValue UaddLV = DAG.getNode( 5260 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 5261 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 5262 5263 if (VT == MVT::i64) 5264 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 5265 return UaddLV; 5266 } 5267 5268 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5269 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5270 "Unexpected type for custom ctpop lowering"); 5271 5272 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5273 Val = DAG.getBitcast(VT8Bit, Val); 5274 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 5275 5276 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5277 unsigned EltSize = 8; 5278 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5279 while (EltSize != VT.getScalarSizeInBits()) { 5280 EltSize *= 2; 5281 NumElts /= 2; 5282 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5283 Val = DAG.getNode( 5284 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 5285 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 5286 } 5287 5288 return Val; 5289 } 5290 5291 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 5292 5293 if (Op.getValueType().isVector()) 5294 return LowerVSETCC(Op, DAG); 5295 5296 bool IsStrict = Op->isStrictFPOpcode(); 5297 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 5298 unsigned OpNo = IsStrict ? 1 : 0; 5299 SDValue Chain; 5300 if (IsStrict) 5301 Chain = Op.getOperand(0); 5302 SDValue LHS = Op.getOperand(OpNo + 0); 5303 SDValue RHS = Op.getOperand(OpNo + 1); 5304 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get(); 5305 SDLoc dl(Op); 5306 5307 // We chose ZeroOrOneBooleanContents, so use zero and one. 5308 EVT VT = Op.getValueType(); 5309 SDValue TVal = DAG.getConstant(1, dl, VT); 5310 SDValue FVal = DAG.getConstant(0, dl, VT); 5311 5312 // Handle f128 first, since one possible outcome is a normal integer 5313 // comparison which gets picked up by the next if statement. 5314 if (LHS.getValueType() == MVT::f128) { 5315 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain, 5316 IsSignaling); 5317 5318 // If softenSetCCOperands returned a scalar, use it. 5319 if (!RHS.getNode()) { 5320 assert(LHS.getValueType() == Op.getValueType() && 5321 "Unexpected setcc expansion!"); 5322 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS; 5323 } 5324 } 5325 5326 if (LHS.getValueType().isInteger()) { 5327 SDValue CCVal; 5328 SDValue Cmp = getAArch64Cmp( 5329 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl); 5330 5331 // Note that we inverted the condition above, so we reverse the order of 5332 // the true and false operands here. This will allow the setcc to be 5333 // matched to a single CSINC instruction. 5334 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 5335 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res; 5336 } 5337 5338 // Now we know we're dealing with FP values. 5339 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5340 LHS.getValueType() == MVT::f64); 5341 5342 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 5343 // and do the comparison. 5344 SDValue Cmp; 5345 if (IsStrict) 5346 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling); 5347 else 5348 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5349 5350 AArch64CC::CondCode CC1, CC2; 5351 changeFPCCToAArch64CC(CC, CC1, CC2); 5352 SDValue Res; 5353 if (CC2 == AArch64CC::AL) { 5354 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1, 5355 CC2); 5356 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5357 5358 // Note that we inverted the condition above, so we reverse the order of 5359 // the true and false operands here. This will allow the setcc to be 5360 // matched to a single CSINC instruction. 5361 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 5362 } else { 5363 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 5364 // totally clean. Some of them require two CSELs to implement. As is in 5365 // this case, we emit the first CSEL and then emit a second using the output 5366 // of the first as the RHS. We're effectively OR'ing the two CC's together. 5367 5368 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 5369 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5370 SDValue CS1 = 5371 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5372 5373 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5374 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5375 } 5376 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res; 5377 } 5378 5379 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 5380 SDValue RHS, SDValue TVal, 5381 SDValue FVal, const SDLoc &dl, 5382 SelectionDAG &DAG) const { 5383 // Handle f128 first, because it will result in a comparison of some RTLIB 5384 // call result against zero. 5385 if (LHS.getValueType() == MVT::f128) { 5386 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5387 5388 // If softenSetCCOperands returned a scalar, we need to compare the result 5389 // against zero to select between true and false values. 5390 if (!RHS.getNode()) { 5391 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5392 CC = ISD::SETNE; 5393 } 5394 } 5395 5396 // Also handle f16, for which we need to do a f32 comparison. 5397 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 5398 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 5399 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 5400 } 5401 5402 // Next, handle integers. 5403 if (LHS.getValueType().isInteger()) { 5404 assert((LHS.getValueType() == RHS.getValueType()) && 5405 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5406 5407 unsigned Opcode = AArch64ISD::CSEL; 5408 5409 // If both the TVal and the FVal are constants, see if we can swap them in 5410 // order to for a CSINV or CSINC out of them. 5411 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 5412 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 5413 5414 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 5415 std::swap(TVal, FVal); 5416 std::swap(CTVal, CFVal); 5417 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5418 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 5419 std::swap(TVal, FVal); 5420 std::swap(CTVal, CFVal); 5421 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5422 } else if (TVal.getOpcode() == ISD::XOR) { 5423 // If TVal is a NOT we want to swap TVal and FVal so that we can match 5424 // with a CSINV rather than a CSEL. 5425 if (isAllOnesConstant(TVal.getOperand(1))) { 5426 std::swap(TVal, FVal); 5427 std::swap(CTVal, CFVal); 5428 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5429 } 5430 } else if (TVal.getOpcode() == ISD::SUB) { 5431 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 5432 // that we can match with a CSNEG rather than a CSEL. 5433 if (isNullConstant(TVal.getOperand(0))) { 5434 std::swap(TVal, FVal); 5435 std::swap(CTVal, CFVal); 5436 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5437 } 5438 } else if (CTVal && CFVal) { 5439 const int64_t TrueVal = CTVal->getSExtValue(); 5440 const int64_t FalseVal = CFVal->getSExtValue(); 5441 bool Swap = false; 5442 5443 // If both TVal and FVal are constants, see if FVal is the 5444 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 5445 // instead of a CSEL in that case. 5446 if (TrueVal == ~FalseVal) { 5447 Opcode = AArch64ISD::CSINV; 5448 } else if (TrueVal == -FalseVal) { 5449 Opcode = AArch64ISD::CSNEG; 5450 } else if (TVal.getValueType() == MVT::i32) { 5451 // If our operands are only 32-bit wide, make sure we use 32-bit 5452 // arithmetic for the check whether we can use CSINC. This ensures that 5453 // the addition in the check will wrap around properly in case there is 5454 // an overflow (which would not be the case if we do the check with 5455 // 64-bit arithmetic). 5456 const uint32_t TrueVal32 = CTVal->getZExtValue(); 5457 const uint32_t FalseVal32 = CFVal->getZExtValue(); 5458 5459 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 5460 Opcode = AArch64ISD::CSINC; 5461 5462 if (TrueVal32 > FalseVal32) { 5463 Swap = true; 5464 } 5465 } 5466 // 64-bit check whether we can use CSINC. 5467 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 5468 Opcode = AArch64ISD::CSINC; 5469 5470 if (TrueVal > FalseVal) { 5471 Swap = true; 5472 } 5473 } 5474 5475 // Swap TVal and FVal if necessary. 5476 if (Swap) { 5477 std::swap(TVal, FVal); 5478 std::swap(CTVal, CFVal); 5479 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5480 } 5481 5482 if (Opcode != AArch64ISD::CSEL) { 5483 // Drop FVal since we can get its value by simply inverting/negating 5484 // TVal. 5485 FVal = TVal; 5486 } 5487 } 5488 5489 // Avoid materializing a constant when possible by reusing a known value in 5490 // a register. However, don't perform this optimization if the known value 5491 // is one, zero or negative one in the case of a CSEL. We can always 5492 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 5493 // FVal, respectively. 5494 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 5495 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 5496 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 5497 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5498 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 5499 // "a != C ? x : a" to avoid materializing C. 5500 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 5501 TVal = LHS; 5502 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 5503 FVal = LHS; 5504 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 5505 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 5506 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 5507 // avoid materializing C. 5508 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5509 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 5510 Opcode = AArch64ISD::CSINV; 5511 TVal = LHS; 5512 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 5513 } 5514 } 5515 5516 SDValue CCVal; 5517 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5518 EVT VT = TVal.getValueType(); 5519 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 5520 } 5521 5522 // Now we know we're dealing with FP values. 5523 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5524 LHS.getValueType() == MVT::f64); 5525 assert(LHS.getValueType() == RHS.getValueType()); 5526 EVT VT = TVal.getValueType(); 5527 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5528 5529 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5530 // clean. Some of them require two CSELs to implement. 5531 AArch64CC::CondCode CC1, CC2; 5532 changeFPCCToAArch64CC(CC, CC1, CC2); 5533 5534 if (DAG.getTarget().Options.UnsafeFPMath) { 5535 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 5536 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 5537 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 5538 if (RHSVal && RHSVal->isZero()) { 5539 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 5540 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 5541 5542 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 5543 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 5544 TVal = LHS; 5545 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 5546 CFVal && CFVal->isZero() && 5547 FVal.getValueType() == LHS.getValueType()) 5548 FVal = LHS; 5549 } 5550 } 5551 5552 // Emit first, and possibly only, CSEL. 5553 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5554 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5555 5556 // If we need a second CSEL, emit it, using the output of the first as the 5557 // RHS. We're effectively OR'ing the two CC's together. 5558 if (CC2 != AArch64CC::AL) { 5559 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5560 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5561 } 5562 5563 // Otherwise, return the output of the first CSEL. 5564 return CS1; 5565 } 5566 5567 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 5568 SelectionDAG &DAG) const { 5569 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5570 SDValue LHS = Op.getOperand(0); 5571 SDValue RHS = Op.getOperand(1); 5572 SDValue TVal = Op.getOperand(2); 5573 SDValue FVal = Op.getOperand(3); 5574 SDLoc DL(Op); 5575 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5576 } 5577 5578 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 5579 SelectionDAG &DAG) const { 5580 SDValue CCVal = Op->getOperand(0); 5581 SDValue TVal = Op->getOperand(1); 5582 SDValue FVal = Op->getOperand(2); 5583 SDLoc DL(Op); 5584 5585 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 5586 // instruction. 5587 if (isOverflowIntrOpRes(CCVal)) { 5588 // Only lower legal XALUO ops. 5589 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 5590 return SDValue(); 5591 5592 AArch64CC::CondCode OFCC; 5593 SDValue Value, Overflow; 5594 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 5595 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 5596 5597 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 5598 CCVal, Overflow); 5599 } 5600 5601 // Lower it the same way as we would lower a SELECT_CC node. 5602 ISD::CondCode CC; 5603 SDValue LHS, RHS; 5604 if (CCVal.getOpcode() == ISD::SETCC) { 5605 LHS = CCVal.getOperand(0); 5606 RHS = CCVal.getOperand(1); 5607 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 5608 } else { 5609 LHS = CCVal; 5610 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 5611 CC = ISD::SETNE; 5612 } 5613 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5614 } 5615 5616 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 5617 SelectionDAG &DAG) const { 5618 // Jump table entries as PC relative offsets. No additional tweaking 5619 // is necessary here. Just get the address of the jump table. 5620 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 5621 5622 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5623 !Subtarget->isTargetMachO()) { 5624 return getAddrLarge(JT, DAG); 5625 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5626 return getAddrTiny(JT, DAG); 5627 } 5628 return getAddr(JT, DAG); 5629 } 5630 5631 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 5632 SelectionDAG &DAG) const { 5633 // Jump table entries as PC relative offsets. No additional tweaking 5634 // is necessary here. Just get the address of the jump table. 5635 SDLoc DL(Op); 5636 SDValue JT = Op.getOperand(1); 5637 SDValue Entry = Op.getOperand(2); 5638 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 5639 5640 SDNode *Dest = 5641 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 5642 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 5643 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 5644 SDValue(Dest, 0)); 5645 } 5646 5647 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 5648 SelectionDAG &DAG) const { 5649 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 5650 5651 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5652 // Use the GOT for the large code model on iOS. 5653 if (Subtarget->isTargetMachO()) { 5654 return getGOT(CP, DAG); 5655 } 5656 return getAddrLarge(CP, DAG); 5657 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5658 return getAddrTiny(CP, DAG); 5659 } else { 5660 return getAddr(CP, DAG); 5661 } 5662 } 5663 5664 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 5665 SelectionDAG &DAG) const { 5666 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 5667 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5668 !Subtarget->isTargetMachO()) { 5669 return getAddrLarge(BA, DAG); 5670 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5671 return getAddrTiny(BA, DAG); 5672 } 5673 return getAddr(BA, DAG); 5674 } 5675 5676 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 5677 SelectionDAG &DAG) const { 5678 AArch64FunctionInfo *FuncInfo = 5679 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5680 5681 SDLoc DL(Op); 5682 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 5683 getPointerTy(DAG.getDataLayout())); 5684 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 5685 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5686 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5687 MachinePointerInfo(SV)); 5688 } 5689 5690 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 5691 SelectionDAG &DAG) const { 5692 AArch64FunctionInfo *FuncInfo = 5693 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5694 5695 SDLoc DL(Op); 5696 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 5697 ? FuncInfo->getVarArgsGPRIndex() 5698 : FuncInfo->getVarArgsStackIndex(), 5699 getPointerTy(DAG.getDataLayout())); 5700 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5701 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5702 MachinePointerInfo(SV)); 5703 } 5704 5705 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 5706 SelectionDAG &DAG) const { 5707 // The layout of the va_list struct is specified in the AArch64 Procedure Call 5708 // Standard, section B.3. 5709 MachineFunction &MF = DAG.getMachineFunction(); 5710 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5711 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5712 SDLoc DL(Op); 5713 5714 SDValue Chain = Op.getOperand(0); 5715 SDValue VAList = Op.getOperand(1); 5716 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5717 SmallVector<SDValue, 4> MemOps; 5718 5719 // void *__stack at offset 0 5720 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 5721 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 5722 MachinePointerInfo(SV), /* Alignment = */ 8)); 5723 5724 // void *__gr_top at offset 8 5725 int GPRSize = FuncInfo->getVarArgsGPRSize(); 5726 if (GPRSize > 0) { 5727 SDValue GRTop, GRTopAddr; 5728 5729 GRTopAddr = 5730 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 5731 5732 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 5733 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 5734 DAG.getConstant(GPRSize, DL, PtrVT)); 5735 5736 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 5737 MachinePointerInfo(SV, 8), 5738 /* Alignment = */ 8)); 5739 } 5740 5741 // void *__vr_top at offset 16 5742 int FPRSize = FuncInfo->getVarArgsFPRSize(); 5743 if (FPRSize > 0) { 5744 SDValue VRTop, VRTopAddr; 5745 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5746 DAG.getConstant(16, DL, PtrVT)); 5747 5748 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 5749 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 5750 DAG.getConstant(FPRSize, DL, PtrVT)); 5751 5752 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 5753 MachinePointerInfo(SV, 16), 5754 /* Alignment = */ 8)); 5755 } 5756 5757 // int __gr_offs at offset 24 5758 SDValue GROffsAddr = 5759 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 5760 MemOps.push_back(DAG.getStore( 5761 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 5762 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 5763 5764 // int __vr_offs at offset 28 5765 SDValue VROffsAddr = 5766 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 5767 MemOps.push_back(DAG.getStore( 5768 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 5769 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 5770 5771 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5772 } 5773 5774 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 5775 SelectionDAG &DAG) const { 5776 MachineFunction &MF = DAG.getMachineFunction(); 5777 5778 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 5779 return LowerWin64_VASTART(Op, DAG); 5780 else if (Subtarget->isTargetDarwin()) 5781 return LowerDarwin_VASTART(Op, DAG); 5782 else 5783 return LowerAAPCS_VASTART(Op, DAG); 5784 } 5785 5786 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 5787 SelectionDAG &DAG) const { 5788 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 5789 // pointer. 5790 SDLoc DL(Op); 5791 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 5792 unsigned VaListSize = (Subtarget->isTargetDarwin() || 5793 Subtarget->isTargetWindows()) ? PtrSize : 32; 5794 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 5795 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 5796 5797 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 5798 DAG.getConstant(VaListSize, DL, MVT::i32), 5799 Align(PtrSize), false, false, false, 5800 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); 5801 } 5802 5803 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 5804 assert(Subtarget->isTargetDarwin() && 5805 "automatic va_arg instruction only works on Darwin"); 5806 5807 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5808 EVT VT = Op.getValueType(); 5809 SDLoc DL(Op); 5810 SDValue Chain = Op.getOperand(0); 5811 SDValue Addr = Op.getOperand(1); 5812 unsigned Align = Op.getConstantOperandVal(3); 5813 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 5814 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5815 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 5816 SDValue VAList = 5817 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 5818 Chain = VAList.getValue(1); 5819 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 5820 5821 if (Align > MinSlotSize) { 5822 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 5823 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5824 DAG.getConstant(Align - 1, DL, PtrVT)); 5825 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 5826 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 5827 } 5828 5829 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 5830 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 5831 5832 // Scalar integer and FP values smaller than 64 bits are implicitly extended 5833 // up to 64 bits. At the very least, we have to increase the striding of the 5834 // vaargs list to match this, and for FP values we need to introduce 5835 // FP_ROUND nodes as well. 5836 if (VT.isInteger() && !VT.isVector()) 5837 ArgSize = std::max(ArgSize, MinSlotSize); 5838 bool NeedFPTrunc = false; 5839 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 5840 ArgSize = 8; 5841 NeedFPTrunc = true; 5842 } 5843 5844 // Increment the pointer, VAList, to the next vaarg 5845 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5846 DAG.getConstant(ArgSize, DL, PtrVT)); 5847 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 5848 5849 // Store the incremented VAList to the legalized pointer 5850 SDValue APStore = 5851 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 5852 5853 // Load the actual argument out of the pointer VAList 5854 if (NeedFPTrunc) { 5855 // Load the value as an f64. 5856 SDValue WideFP = 5857 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 5858 // Round the value down to an f32. 5859 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 5860 DAG.getIntPtrConstant(1, DL)); 5861 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 5862 // Merge the rounded value with the chain output of the load. 5863 return DAG.getMergeValues(Ops, DL); 5864 } 5865 5866 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 5867 } 5868 5869 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 5870 SelectionDAG &DAG) const { 5871 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5872 MFI.setFrameAddressIsTaken(true); 5873 5874 EVT VT = Op.getValueType(); 5875 SDLoc DL(Op); 5876 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5877 SDValue FrameAddr = 5878 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 5879 while (Depth--) 5880 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 5881 MachinePointerInfo()); 5882 5883 if (Subtarget->isTargetILP32()) 5884 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 5885 DAG.getValueType(VT)); 5886 5887 return FrameAddr; 5888 } 5889 5890 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 5891 SelectionDAG &DAG) const { 5892 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5893 5894 EVT VT = getPointerTy(DAG.getDataLayout()); 5895 SDLoc DL(Op); 5896 int FI = MFI.CreateFixedObject(4, 0, false); 5897 return DAG.getFrameIndex(FI, VT); 5898 } 5899 5900 #define GET_REGISTER_MATCHER 5901 #include "AArch64GenAsmMatcher.inc" 5902 5903 // FIXME? Maybe this could be a TableGen attribute on some registers and 5904 // this table could be generated automatically from RegInfo. 5905 Register AArch64TargetLowering:: 5906 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const { 5907 Register Reg = MatchRegisterName(RegName); 5908 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 5909 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 5910 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 5911 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 5912 Reg = 0; 5913 } 5914 if (Reg) 5915 return Reg; 5916 report_fatal_error(Twine("Invalid register name \"" 5917 + StringRef(RegName) + "\".")); 5918 } 5919 5920 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 5921 SelectionDAG &DAG) const { 5922 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 5923 5924 EVT VT = Op.getValueType(); 5925 SDLoc DL(Op); 5926 5927 SDValue FrameAddr = 5928 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 5929 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5930 5931 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 5932 } 5933 5934 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 5935 SelectionDAG &DAG) const { 5936 MachineFunction &MF = DAG.getMachineFunction(); 5937 MachineFrameInfo &MFI = MF.getFrameInfo(); 5938 MFI.setReturnAddressIsTaken(true); 5939 5940 EVT VT = Op.getValueType(); 5941 SDLoc DL(Op); 5942 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5943 if (Depth) { 5944 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5945 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5946 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 5947 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 5948 MachinePointerInfo()); 5949 } 5950 5951 // Return LR, which contains the return address. Mark it an implicit live-in. 5952 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 5953 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5954 } 5955 5956 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5957 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 5958 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 5959 SelectionDAG &DAG) const { 5960 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5961 EVT VT = Op.getValueType(); 5962 unsigned VTBits = VT.getSizeInBits(); 5963 SDLoc dl(Op); 5964 SDValue ShOpLo = Op.getOperand(0); 5965 SDValue ShOpHi = Op.getOperand(1); 5966 SDValue ShAmt = Op.getOperand(2); 5967 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5968 5969 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5970 5971 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 5972 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 5973 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5974 5975 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 5976 // is "undef". We wanted 0, so CSEL it directly. 5977 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 5978 ISD::SETEQ, dl, DAG); 5979 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 5980 HiBitsForLo = 5981 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 5982 HiBitsForLo, CCVal, Cmp); 5983 5984 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 5985 DAG.getConstant(VTBits, dl, MVT::i64)); 5986 5987 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5988 SDValue LoForNormalShift = 5989 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 5990 5991 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 5992 dl, DAG); 5993 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 5994 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5995 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 5996 LoForNormalShift, CCVal, Cmp); 5997 5998 // AArch64 shifts larger than the register width are wrapped rather than 5999 // clamped, so we can't just emit "hi >> x". 6000 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6001 SDValue HiForBigShift = 6002 Opc == ISD::SRA 6003 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6004 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 6005 : DAG.getConstant(0, dl, VT); 6006 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 6007 HiForNormalShift, CCVal, Cmp); 6008 6009 SDValue Ops[2] = { Lo, Hi }; 6010 return DAG.getMergeValues(Ops, dl); 6011 } 6012 6013 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6014 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 6015 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 6016 SelectionDAG &DAG) const { 6017 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6018 EVT VT = Op.getValueType(); 6019 unsigned VTBits = VT.getSizeInBits(); 6020 SDLoc dl(Op); 6021 SDValue ShOpLo = Op.getOperand(0); 6022 SDValue ShOpHi = Op.getOperand(1); 6023 SDValue ShAmt = Op.getOperand(2); 6024 6025 assert(Op.getOpcode() == ISD::SHL_PARTS); 6026 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 6027 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 6028 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6029 6030 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 6031 // is "undef". We wanted 0, so CSEL it directly. 6032 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 6033 ISD::SETEQ, dl, DAG); 6034 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 6035 LoBitsForHi = 6036 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 6037 LoBitsForHi, CCVal, Cmp); 6038 6039 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 6040 DAG.getConstant(VTBits, dl, MVT::i64)); 6041 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6042 SDValue HiForNormalShift = 6043 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 6044 6045 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6046 6047 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 6048 dl, DAG); 6049 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 6050 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 6051 HiForNormalShift, CCVal, Cmp); 6052 6053 // AArch64 shifts of larger than register sizes are wrapped rather than 6054 // clamped, so we can't just emit "lo << a" if a is too big. 6055 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 6056 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6057 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 6058 LoForNormalShift, CCVal, Cmp); 6059 6060 SDValue Ops[2] = { Lo, Hi }; 6061 return DAG.getMergeValues(Ops, dl); 6062 } 6063 6064 bool AArch64TargetLowering::isOffsetFoldingLegal( 6065 const GlobalAddressSDNode *GA) const { 6066 // Offsets are folded in the DAG combine rather than here so that we can 6067 // intelligently choose an offset based on the uses. 6068 return false; 6069 } 6070 6071 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 6072 bool OptForSize) const { 6073 bool IsLegal = false; 6074 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 6075 // 16-bit case when target has full fp16 support. 6076 // FIXME: We should be able to handle f128 as well with a clever lowering. 6077 const APInt ImmInt = Imm.bitcastToAPInt(); 6078 if (VT == MVT::f64) 6079 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 6080 else if (VT == MVT::f32) 6081 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 6082 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 6083 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 6084 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 6085 // generate that fmov. 6086 6087 // If we can not materialize in immediate field for fmov, check if the 6088 // value can be encoded as the immediate operand of a logical instruction. 6089 // The immediate value will be created with either MOVZ, MOVN, or ORR. 6090 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 6091 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 6092 // however the mov+fmov sequence is always better because of the reduced 6093 // cache pressure. The timings are still the same if you consider 6094 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 6095 // movw+movk is fused). So we limit up to 2 instrdduction at most. 6096 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 6097 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 6098 Insn); 6099 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 6100 IsLegal = Insn.size() <= Limit; 6101 } 6102 6103 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 6104 << " imm value: "; Imm.dump();); 6105 return IsLegal; 6106 } 6107 6108 //===----------------------------------------------------------------------===// 6109 // AArch64 Optimization Hooks 6110 //===----------------------------------------------------------------------===// 6111 6112 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 6113 SDValue Operand, SelectionDAG &DAG, 6114 int &ExtraSteps) { 6115 EVT VT = Operand.getValueType(); 6116 if (ST->hasNEON() && 6117 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 6118 VT == MVT::f32 || VT == MVT::v1f32 || 6119 VT == MVT::v2f32 || VT == MVT::v4f32)) { 6120 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 6121 // For the reciprocal estimates, convergence is quadratic, so the number 6122 // of digits is doubled after each iteration. In ARMv8, the accuracy of 6123 // the initial estimate is 2^-8. Thus the number of extra steps to refine 6124 // the result for float (23 mantissa bits) is 2 and for double (52 6125 // mantissa bits) is 3. 6126 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 6127 6128 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 6129 } 6130 6131 return SDValue(); 6132 } 6133 6134 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 6135 SelectionDAG &DAG, int Enabled, 6136 int &ExtraSteps, 6137 bool &UseOneConst, 6138 bool Reciprocal) const { 6139 if (Enabled == ReciprocalEstimate::Enabled || 6140 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 6141 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 6142 DAG, ExtraSteps)) { 6143 SDLoc DL(Operand); 6144 EVT VT = Operand.getValueType(); 6145 6146 SDNodeFlags Flags; 6147 Flags.setAllowReassociation(true); 6148 6149 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 6150 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 6151 for (int i = ExtraSteps; i > 0; --i) { 6152 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 6153 Flags); 6154 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 6155 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 6156 } 6157 if (!Reciprocal) { 6158 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 6159 VT); 6160 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6161 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 6162 6163 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 6164 // Correct the result if the operand is 0.0. 6165 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 6166 VT, Eq, Operand, Estimate); 6167 } 6168 6169 ExtraSteps = 0; 6170 return Estimate; 6171 } 6172 6173 return SDValue(); 6174 } 6175 6176 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 6177 SelectionDAG &DAG, int Enabled, 6178 int &ExtraSteps) const { 6179 if (Enabled == ReciprocalEstimate::Enabled) 6180 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 6181 DAG, ExtraSteps)) { 6182 SDLoc DL(Operand); 6183 EVT VT = Operand.getValueType(); 6184 6185 SDNodeFlags Flags; 6186 Flags.setAllowReassociation(true); 6187 6188 // Newton reciprocal iteration: E * (2 - X * E) 6189 // AArch64 reciprocal iteration instruction: (2 - M * N) 6190 for (int i = ExtraSteps; i > 0; --i) { 6191 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 6192 Estimate, Flags); 6193 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 6194 } 6195 6196 ExtraSteps = 0; 6197 return Estimate; 6198 } 6199 6200 return SDValue(); 6201 } 6202 6203 //===----------------------------------------------------------------------===// 6204 // AArch64 Inline Assembly Support 6205 //===----------------------------------------------------------------------===// 6206 6207 // Table of Constraints 6208 // TODO: This is the current set of constraints supported by ARM for the 6209 // compiler, not all of them may make sense. 6210 // 6211 // r - A general register 6212 // w - An FP/SIMD register of some size in the range v0-v31 6213 // x - An FP/SIMD register of some size in the range v0-v15 6214 // I - Constant that can be used with an ADD instruction 6215 // J - Constant that can be used with a SUB instruction 6216 // K - Constant that can be used with a 32-bit logical instruction 6217 // L - Constant that can be used with a 64-bit logical instruction 6218 // M - Constant that can be used as a 32-bit MOV immediate 6219 // N - Constant that can be used as a 64-bit MOV immediate 6220 // Q - A memory reference with base register and no offset 6221 // S - A symbolic address 6222 // Y - Floating point constant zero 6223 // Z - Integer constant zero 6224 // 6225 // Note that general register operands will be output using their 64-bit x 6226 // register name, whatever the size of the variable, unless the asm operand 6227 // is prefixed by the %w modifier. Floating-point and SIMD register operands 6228 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 6229 // %q modifier. 6230 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 6231 // At this point, we have to lower this constraint to something else, so we 6232 // lower it to an "r" or "w". However, by doing this we will force the result 6233 // to be in register, while the X constraint is much more permissive. 6234 // 6235 // Although we are correct (we are free to emit anything, without 6236 // constraints), we might break use cases that would expect us to be more 6237 // efficient and emit something else. 6238 if (!Subtarget->hasFPARMv8()) 6239 return "r"; 6240 6241 if (ConstraintVT.isFloatingPoint()) 6242 return "w"; 6243 6244 if (ConstraintVT.isVector() && 6245 (ConstraintVT.getSizeInBits() == 64 || 6246 ConstraintVT.getSizeInBits() == 128)) 6247 return "w"; 6248 6249 return "r"; 6250 } 6251 6252 enum PredicateConstraint { 6253 Upl, 6254 Upa, 6255 Invalid 6256 }; 6257 6258 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 6259 PredicateConstraint P = PredicateConstraint::Invalid; 6260 if (Constraint == "Upa") 6261 P = PredicateConstraint::Upa; 6262 if (Constraint == "Upl") 6263 P = PredicateConstraint::Upl; 6264 return P; 6265 } 6266 6267 /// getConstraintType - Given a constraint letter, return the type of 6268 /// constraint it is for this target. 6269 AArch64TargetLowering::ConstraintType 6270 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 6271 if (Constraint.size() == 1) { 6272 switch (Constraint[0]) { 6273 default: 6274 break; 6275 case 'x': 6276 case 'w': 6277 case 'y': 6278 return C_RegisterClass; 6279 // An address with a single base register. Due to the way we 6280 // currently handle addresses it is the same as 'r'. 6281 case 'Q': 6282 return C_Memory; 6283 case 'I': 6284 case 'J': 6285 case 'K': 6286 case 'L': 6287 case 'M': 6288 case 'N': 6289 case 'Y': 6290 case 'Z': 6291 return C_Immediate; 6292 case 'z': 6293 case 'S': // A symbolic address 6294 return C_Other; 6295 } 6296 } else if (parsePredicateConstraint(Constraint) != 6297 PredicateConstraint::Invalid) 6298 return C_RegisterClass; 6299 return TargetLowering::getConstraintType(Constraint); 6300 } 6301 6302 /// Examine constraint type and operand type and determine a weight value. 6303 /// This object must already have been set up with the operand type 6304 /// and the current alternative constraint selected. 6305 TargetLowering::ConstraintWeight 6306 AArch64TargetLowering::getSingleConstraintMatchWeight( 6307 AsmOperandInfo &info, const char *constraint) const { 6308 ConstraintWeight weight = CW_Invalid; 6309 Value *CallOperandVal = info.CallOperandVal; 6310 // If we don't have a value, we can't do a match, 6311 // but allow it at the lowest weight. 6312 if (!CallOperandVal) 6313 return CW_Default; 6314 Type *type = CallOperandVal->getType(); 6315 // Look at the constraint type. 6316 switch (*constraint) { 6317 default: 6318 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 6319 break; 6320 case 'x': 6321 case 'w': 6322 case 'y': 6323 if (type->isFloatingPointTy() || type->isVectorTy()) 6324 weight = CW_Register; 6325 break; 6326 case 'z': 6327 weight = CW_Constant; 6328 break; 6329 case 'U': 6330 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 6331 weight = CW_Register; 6332 break; 6333 } 6334 return weight; 6335 } 6336 6337 std::pair<unsigned, const TargetRegisterClass *> 6338 AArch64TargetLowering::getRegForInlineAsmConstraint( 6339 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 6340 if (Constraint.size() == 1) { 6341 switch (Constraint[0]) { 6342 case 'r': 6343 if (VT.getSizeInBits() == 64) 6344 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 6345 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 6346 case 'w': 6347 if (!Subtarget->hasFPARMv8()) 6348 break; 6349 if (VT.isScalableVector()) 6350 return std::make_pair(0U, &AArch64::ZPRRegClass); 6351 if (VT.getSizeInBits() == 16) 6352 return std::make_pair(0U, &AArch64::FPR16RegClass); 6353 if (VT.getSizeInBits() == 32) 6354 return std::make_pair(0U, &AArch64::FPR32RegClass); 6355 if (VT.getSizeInBits() == 64) 6356 return std::make_pair(0U, &AArch64::FPR64RegClass); 6357 if (VT.getSizeInBits() == 128) 6358 return std::make_pair(0U, &AArch64::FPR128RegClass); 6359 break; 6360 // The instructions that this constraint is designed for can 6361 // only take 128-bit registers so just use that regclass. 6362 case 'x': 6363 if (!Subtarget->hasFPARMv8()) 6364 break; 6365 if (VT.isScalableVector()) 6366 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 6367 if (VT.getSizeInBits() == 128) 6368 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 6369 break; 6370 case 'y': 6371 if (!Subtarget->hasFPARMv8()) 6372 break; 6373 if (VT.isScalableVector()) 6374 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 6375 break; 6376 } 6377 } else { 6378 PredicateConstraint PC = parsePredicateConstraint(Constraint); 6379 if (PC != PredicateConstraint::Invalid) { 6380 assert(VT.isScalableVector()); 6381 bool restricted = (PC == PredicateConstraint::Upl); 6382 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 6383 : std::make_pair(0U, &AArch64::PPRRegClass); 6384 } 6385 } 6386 if (StringRef("{cc}").equals_lower(Constraint)) 6387 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 6388 6389 // Use the default implementation in TargetLowering to convert the register 6390 // constraint into a member of a register class. 6391 std::pair<unsigned, const TargetRegisterClass *> Res; 6392 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6393 6394 // Not found as a standard register? 6395 if (!Res.second) { 6396 unsigned Size = Constraint.size(); 6397 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 6398 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 6399 int RegNo; 6400 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 6401 if (!Failed && RegNo >= 0 && RegNo <= 31) { 6402 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 6403 // By default we'll emit v0-v31 for this unless there's a modifier where 6404 // we'll emit the correct register as well. 6405 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 6406 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 6407 Res.second = &AArch64::FPR64RegClass; 6408 } else { 6409 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 6410 Res.second = &AArch64::FPR128RegClass; 6411 } 6412 } 6413 } 6414 } 6415 6416 if (Res.second && !Subtarget->hasFPARMv8() && 6417 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 6418 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 6419 return std::make_pair(0U, nullptr); 6420 6421 return Res; 6422 } 6423 6424 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 6425 /// vector. If it is invalid, don't add anything to Ops. 6426 void AArch64TargetLowering::LowerAsmOperandForConstraint( 6427 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 6428 SelectionDAG &DAG) const { 6429 SDValue Result; 6430 6431 // Currently only support length 1 constraints. 6432 if (Constraint.length() != 1) 6433 return; 6434 6435 char ConstraintLetter = Constraint[0]; 6436 switch (ConstraintLetter) { 6437 default: 6438 break; 6439 6440 // This set of constraints deal with valid constants for various instructions. 6441 // Validate and return a target constant for them if we can. 6442 case 'z': { 6443 // 'z' maps to xzr or wzr so it needs an input of 0. 6444 if (!isNullConstant(Op)) 6445 return; 6446 6447 if (Op.getValueType() == MVT::i64) 6448 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 6449 else 6450 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 6451 break; 6452 } 6453 case 'S': { 6454 // An absolute symbolic address or label reference. 6455 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 6456 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 6457 GA->getValueType(0)); 6458 } else if (const BlockAddressSDNode *BA = 6459 dyn_cast<BlockAddressSDNode>(Op)) { 6460 Result = 6461 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 6462 } else if (const ExternalSymbolSDNode *ES = 6463 dyn_cast<ExternalSymbolSDNode>(Op)) { 6464 Result = 6465 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 6466 } else 6467 return; 6468 break; 6469 } 6470 6471 case 'I': 6472 case 'J': 6473 case 'K': 6474 case 'L': 6475 case 'M': 6476 case 'N': 6477 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 6478 if (!C) 6479 return; 6480 6481 // Grab the value and do some validation. 6482 uint64_t CVal = C->getZExtValue(); 6483 switch (ConstraintLetter) { 6484 // The I constraint applies only to simple ADD or SUB immediate operands: 6485 // i.e. 0 to 4095 with optional shift by 12 6486 // The J constraint applies only to ADD or SUB immediates that would be 6487 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 6488 // instruction [or vice versa], in other words -1 to -4095 with optional 6489 // left shift by 12. 6490 case 'I': 6491 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 6492 break; 6493 return; 6494 case 'J': { 6495 uint64_t NVal = -C->getSExtValue(); 6496 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 6497 CVal = C->getSExtValue(); 6498 break; 6499 } 6500 return; 6501 } 6502 // The K and L constraints apply *only* to logical immediates, including 6503 // what used to be the MOVI alias for ORR (though the MOVI alias has now 6504 // been removed and MOV should be used). So these constraints have to 6505 // distinguish between bit patterns that are valid 32-bit or 64-bit 6506 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 6507 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 6508 // versa. 6509 case 'K': 6510 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6511 break; 6512 return; 6513 case 'L': 6514 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6515 break; 6516 return; 6517 // The M and N constraints are a superset of K and L respectively, for use 6518 // with the MOV (immediate) alias. As well as the logical immediates they 6519 // also match 32 or 64-bit immediates that can be loaded either using a 6520 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 6521 // (M) or 64-bit 0x1234000000000000 (N) etc. 6522 // As a note some of this code is liberally stolen from the asm parser. 6523 case 'M': { 6524 if (!isUInt<32>(CVal)) 6525 return; 6526 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6527 break; 6528 if ((CVal & 0xFFFF) == CVal) 6529 break; 6530 if ((CVal & 0xFFFF0000ULL) == CVal) 6531 break; 6532 uint64_t NCVal = ~(uint32_t)CVal; 6533 if ((NCVal & 0xFFFFULL) == NCVal) 6534 break; 6535 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6536 break; 6537 return; 6538 } 6539 case 'N': { 6540 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6541 break; 6542 if ((CVal & 0xFFFFULL) == CVal) 6543 break; 6544 if ((CVal & 0xFFFF0000ULL) == CVal) 6545 break; 6546 if ((CVal & 0xFFFF00000000ULL) == CVal) 6547 break; 6548 if ((CVal & 0xFFFF000000000000ULL) == CVal) 6549 break; 6550 uint64_t NCVal = ~CVal; 6551 if ((NCVal & 0xFFFFULL) == NCVal) 6552 break; 6553 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6554 break; 6555 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 6556 break; 6557 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 6558 break; 6559 return; 6560 } 6561 default: 6562 return; 6563 } 6564 6565 // All assembler immediates are 64-bit integers. 6566 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 6567 break; 6568 } 6569 6570 if (Result.getNode()) { 6571 Ops.push_back(Result); 6572 return; 6573 } 6574 6575 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 6576 } 6577 6578 //===----------------------------------------------------------------------===// 6579 // AArch64 Advanced SIMD Support 6580 //===----------------------------------------------------------------------===// 6581 6582 /// WidenVector - Given a value in the V64 register class, produce the 6583 /// equivalent value in the V128 register class. 6584 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 6585 EVT VT = V64Reg.getValueType(); 6586 unsigned NarrowSize = VT.getVectorNumElements(); 6587 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6588 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 6589 SDLoc DL(V64Reg); 6590 6591 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 6592 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 6593 } 6594 6595 /// getExtFactor - Determine the adjustment factor for the position when 6596 /// generating an "extract from vector registers" instruction. 6597 static unsigned getExtFactor(SDValue &V) { 6598 EVT EltType = V.getValueType().getVectorElementType(); 6599 return EltType.getSizeInBits() / 8; 6600 } 6601 6602 /// NarrowVector - Given a value in the V128 register class, produce the 6603 /// equivalent value in the V64 register class. 6604 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 6605 EVT VT = V128Reg.getValueType(); 6606 unsigned WideSize = VT.getVectorNumElements(); 6607 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6608 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 6609 SDLoc DL(V128Reg); 6610 6611 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 6612 } 6613 6614 // Gather data to see if the operation can be modelled as a 6615 // shuffle in combination with VEXTs. 6616 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 6617 SelectionDAG &DAG) const { 6618 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6619 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 6620 SDLoc dl(Op); 6621 EVT VT = Op.getValueType(); 6622 unsigned NumElts = VT.getVectorNumElements(); 6623 6624 struct ShuffleSourceInfo { 6625 SDValue Vec; 6626 unsigned MinElt; 6627 unsigned MaxElt; 6628 6629 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6630 // be compatible with the shuffle we intend to construct. As a result 6631 // ShuffleVec will be some sliding window into the original Vec. 6632 SDValue ShuffleVec; 6633 6634 // Code should guarantee that element i in Vec starts at element "WindowBase 6635 // + i * WindowScale in ShuffleVec". 6636 int WindowBase; 6637 int WindowScale; 6638 6639 ShuffleSourceInfo(SDValue Vec) 6640 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 6641 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 6642 6643 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6644 }; 6645 6646 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6647 // node. 6648 SmallVector<ShuffleSourceInfo, 2> Sources; 6649 for (unsigned i = 0; i < NumElts; ++i) { 6650 SDValue V = Op.getOperand(i); 6651 if (V.isUndef()) 6652 continue; 6653 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6654 !isa<ConstantSDNode>(V.getOperand(1))) { 6655 LLVM_DEBUG( 6656 dbgs() << "Reshuffle failed: " 6657 "a shuffle can only come from building a vector from " 6658 "various elements of other vectors, provided their " 6659 "indices are constant\n"); 6660 return SDValue(); 6661 } 6662 6663 // Add this element source to the list if it's not already there. 6664 SDValue SourceVec = V.getOperand(0); 6665 auto Source = find(Sources, SourceVec); 6666 if (Source == Sources.end()) 6667 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6668 6669 // Update the minimum and maximum lane number seen. 6670 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6671 Source->MinElt = std::min(Source->MinElt, EltNo); 6672 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6673 } 6674 6675 if (Sources.size() > 2) { 6676 LLVM_DEBUG( 6677 dbgs() << "Reshuffle failed: currently only do something sane when at " 6678 "most two source vectors are involved\n"); 6679 return SDValue(); 6680 } 6681 6682 // Find out the smallest element size among result and two sources, and use 6683 // it as element size to build the shuffle_vector. 6684 EVT SmallestEltTy = VT.getVectorElementType(); 6685 for (auto &Source : Sources) { 6686 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6687 if (SrcEltTy.bitsLT(SmallestEltTy)) { 6688 SmallestEltTy = SrcEltTy; 6689 } 6690 } 6691 unsigned ResMultiplier = 6692 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6693 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6694 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6695 6696 // If the source vector is too wide or too narrow, we may nevertheless be able 6697 // to construct a compatible shuffle either by concatenating it with UNDEF or 6698 // extracting a suitable range of elements. 6699 for (auto &Src : Sources) { 6700 EVT SrcVT = Src.ShuffleVec.getValueType(); 6701 6702 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6703 continue; 6704 6705 // This stage of the search produces a source with the same element type as 6706 // the original, but with a total width matching the BUILD_VECTOR output. 6707 EVT EltVT = SrcVT.getVectorElementType(); 6708 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6709 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6710 6711 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6712 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 6713 // We can pad out the smaller vector for free, so if it's part of a 6714 // shuffle... 6715 Src.ShuffleVec = 6716 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6717 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6718 continue; 6719 } 6720 6721 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 6722 6723 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6724 LLVM_DEBUG( 6725 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 6726 return SDValue(); 6727 } 6728 6729 if (Src.MinElt >= NumSrcElts) { 6730 // The extraction can just take the second half 6731 Src.ShuffleVec = 6732 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6733 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6734 Src.WindowBase = -NumSrcElts; 6735 } else if (Src.MaxElt < NumSrcElts) { 6736 // The extraction can just take the first half 6737 Src.ShuffleVec = 6738 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6739 DAG.getConstant(0, dl, MVT::i64)); 6740 } else { 6741 // An actual VEXT is needed 6742 SDValue VEXTSrc1 = 6743 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6744 DAG.getConstant(0, dl, MVT::i64)); 6745 SDValue VEXTSrc2 = 6746 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6747 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6748 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 6749 6750 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 6751 VEXTSrc2, 6752 DAG.getConstant(Imm, dl, MVT::i32)); 6753 Src.WindowBase = -Src.MinElt; 6754 } 6755 } 6756 6757 // Another possible incompatibility occurs from the vector element types. We 6758 // can fix this by bitcasting the source vectors to the same type we intend 6759 // for the shuffle. 6760 for (auto &Src : Sources) { 6761 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6762 if (SrcEltTy == SmallestEltTy) 6763 continue; 6764 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6765 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6766 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6767 Src.WindowBase *= Src.WindowScale; 6768 } 6769 6770 // Final sanity check before we try to actually produce a shuffle. 6771 LLVM_DEBUG(for (auto Src 6772 : Sources) 6773 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6774 6775 // The stars all align, our next step is to produce the mask for the shuffle. 6776 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6777 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6778 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6779 SDValue Entry = Op.getOperand(i); 6780 if (Entry.isUndef()) 6781 continue; 6782 6783 auto Src = find(Sources, Entry.getOperand(0)); 6784 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6785 6786 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6787 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6788 // segment. 6789 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6790 int BitsDefined = 6791 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 6792 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6793 6794 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6795 // starting at the appropriate offset. 6796 int *LaneMask = &Mask[i * ResMultiplier]; 6797 6798 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6799 ExtractBase += NumElts * (Src - Sources.begin()); 6800 for (int j = 0; j < LanesDefined; ++j) 6801 LaneMask[j] = ExtractBase + j; 6802 } 6803 6804 // Final check before we try to produce nonsense... 6805 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 6806 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 6807 return SDValue(); 6808 } 6809 6810 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6811 for (unsigned i = 0; i < Sources.size(); ++i) 6812 ShuffleOps[i] = Sources[i].ShuffleVec; 6813 6814 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6815 ShuffleOps[1], Mask); 6816 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6817 6818 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 6819 dbgs() << "Reshuffle, creating node: "; V.dump();); 6820 6821 return V; 6822 } 6823 6824 // check if an EXT instruction can handle the shuffle mask when the 6825 // vector sources of the shuffle are the same. 6826 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6827 unsigned NumElts = VT.getVectorNumElements(); 6828 6829 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6830 if (M[0] < 0) 6831 return false; 6832 6833 Imm = M[0]; 6834 6835 // If this is a VEXT shuffle, the immediate value is the index of the first 6836 // element. The other shuffle indices must be the successive elements after 6837 // the first one. 6838 unsigned ExpectedElt = Imm; 6839 for (unsigned i = 1; i < NumElts; ++i) { 6840 // Increment the expected index. If it wraps around, just follow it 6841 // back to index zero and keep going. 6842 ++ExpectedElt; 6843 if (ExpectedElt == NumElts) 6844 ExpectedElt = 0; 6845 6846 if (M[i] < 0) 6847 continue; // ignore UNDEF indices 6848 if (ExpectedElt != static_cast<unsigned>(M[i])) 6849 return false; 6850 } 6851 6852 return true; 6853 } 6854 6855 // check if an EXT instruction can handle the shuffle mask when the 6856 // vector sources of the shuffle are different. 6857 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 6858 unsigned &Imm) { 6859 // Look for the first non-undef element. 6860 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 6861 6862 // Benefit form APInt to handle overflow when calculating expected element. 6863 unsigned NumElts = VT.getVectorNumElements(); 6864 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 6865 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 6866 // The following shuffle indices must be the successive elements after the 6867 // first real element. 6868 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 6869 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 6870 if (FirstWrongElt != M.end()) 6871 return false; 6872 6873 // The index of an EXT is the first element if it is not UNDEF. 6874 // Watch out for the beginning UNDEFs. The EXT index should be the expected 6875 // value of the first element. E.g. 6876 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 6877 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 6878 // ExpectedElt is the last mask index plus 1. 6879 Imm = ExpectedElt.getZExtValue(); 6880 6881 // There are two difference cases requiring to reverse input vectors. 6882 // For example, for vector <4 x i32> we have the following cases, 6883 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 6884 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 6885 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 6886 // to reverse two input vectors. 6887 if (Imm < NumElts) 6888 ReverseEXT = true; 6889 else 6890 Imm -= NumElts; 6891 6892 return true; 6893 } 6894 6895 /// isREVMask - Check if a vector shuffle corresponds to a REV 6896 /// instruction with the specified blocksize. (The order of the elements 6897 /// within each block of the vector is reversed.) 6898 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6899 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 6900 "Only possible block sizes for REV are: 16, 32, 64"); 6901 6902 unsigned EltSz = VT.getScalarSizeInBits(); 6903 if (EltSz == 64) 6904 return false; 6905 6906 unsigned NumElts = VT.getVectorNumElements(); 6907 unsigned BlockElts = M[0] + 1; 6908 // If the first shuffle index is UNDEF, be optimistic. 6909 if (M[0] < 0) 6910 BlockElts = BlockSize / EltSz; 6911 6912 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6913 return false; 6914 6915 for (unsigned i = 0; i < NumElts; ++i) { 6916 if (M[i] < 0) 6917 continue; // ignore UNDEF indices 6918 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 6919 return false; 6920 } 6921 6922 return true; 6923 } 6924 6925 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6926 unsigned NumElts = VT.getVectorNumElements(); 6927 if (NumElts % 2 != 0) 6928 return false; 6929 WhichResult = (M[0] == 0 ? 0 : 1); 6930 unsigned Idx = WhichResult * NumElts / 2; 6931 for (unsigned i = 0; i != NumElts; i += 2) { 6932 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6933 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 6934 return false; 6935 Idx += 1; 6936 } 6937 6938 return true; 6939 } 6940 6941 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6942 unsigned NumElts = VT.getVectorNumElements(); 6943 WhichResult = (M[0] == 0 ? 0 : 1); 6944 for (unsigned i = 0; i != NumElts; ++i) { 6945 if (M[i] < 0) 6946 continue; // ignore UNDEF indices 6947 if ((unsigned)M[i] != 2 * i + WhichResult) 6948 return false; 6949 } 6950 6951 return true; 6952 } 6953 6954 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6955 unsigned NumElts = VT.getVectorNumElements(); 6956 if (NumElts % 2 != 0) 6957 return false; 6958 WhichResult = (M[0] == 0 ? 0 : 1); 6959 for (unsigned i = 0; i < NumElts; i += 2) { 6960 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 6961 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 6962 return false; 6963 } 6964 return true; 6965 } 6966 6967 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 6968 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6969 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6970 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6971 unsigned NumElts = VT.getVectorNumElements(); 6972 if (NumElts % 2 != 0) 6973 return false; 6974 WhichResult = (M[0] == 0 ? 0 : 1); 6975 unsigned Idx = WhichResult * NumElts / 2; 6976 for (unsigned i = 0; i != NumElts; i += 2) { 6977 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6978 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 6979 return false; 6980 Idx += 1; 6981 } 6982 6983 return true; 6984 } 6985 6986 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 6987 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6988 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6989 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6990 unsigned Half = VT.getVectorNumElements() / 2; 6991 WhichResult = (M[0] == 0 ? 0 : 1); 6992 for (unsigned j = 0; j != 2; ++j) { 6993 unsigned Idx = WhichResult; 6994 for (unsigned i = 0; i != Half; ++i) { 6995 int MIdx = M[i + j * Half]; 6996 if (MIdx >= 0 && (unsigned)MIdx != Idx) 6997 return false; 6998 Idx += 2; 6999 } 7000 } 7001 7002 return true; 7003 } 7004 7005 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 7006 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7007 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7008 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7009 unsigned NumElts = VT.getVectorNumElements(); 7010 if (NumElts % 2 != 0) 7011 return false; 7012 WhichResult = (M[0] == 0 ? 0 : 1); 7013 for (unsigned i = 0; i < NumElts; i += 2) { 7014 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 7015 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 7016 return false; 7017 } 7018 return true; 7019 } 7020 7021 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 7022 bool &DstIsLeft, int &Anomaly) { 7023 if (M.size() != static_cast<size_t>(NumInputElements)) 7024 return false; 7025 7026 int NumLHSMatch = 0, NumRHSMatch = 0; 7027 int LastLHSMismatch = -1, LastRHSMismatch = -1; 7028 7029 for (int i = 0; i < NumInputElements; ++i) { 7030 if (M[i] == -1) { 7031 ++NumLHSMatch; 7032 ++NumRHSMatch; 7033 continue; 7034 } 7035 7036 if (M[i] == i) 7037 ++NumLHSMatch; 7038 else 7039 LastLHSMismatch = i; 7040 7041 if (M[i] == i + NumInputElements) 7042 ++NumRHSMatch; 7043 else 7044 LastRHSMismatch = i; 7045 } 7046 7047 if (NumLHSMatch == NumInputElements - 1) { 7048 DstIsLeft = true; 7049 Anomaly = LastLHSMismatch; 7050 return true; 7051 } else if (NumRHSMatch == NumInputElements - 1) { 7052 DstIsLeft = false; 7053 Anomaly = LastRHSMismatch; 7054 return true; 7055 } 7056 7057 return false; 7058 } 7059 7060 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 7061 if (VT.getSizeInBits() != 128) 7062 return false; 7063 7064 unsigned NumElts = VT.getVectorNumElements(); 7065 7066 for (int I = 0, E = NumElts / 2; I != E; I++) { 7067 if (Mask[I] != I) 7068 return false; 7069 } 7070 7071 int Offset = NumElts / 2; 7072 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 7073 if (Mask[I] != I + SplitLHS * Offset) 7074 return false; 7075 } 7076 7077 return true; 7078 } 7079 7080 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 7081 SDLoc DL(Op); 7082 EVT VT = Op.getValueType(); 7083 SDValue V0 = Op.getOperand(0); 7084 SDValue V1 = Op.getOperand(1); 7085 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 7086 7087 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 7088 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 7089 return SDValue(); 7090 7091 bool SplitV0 = V0.getValueSizeInBits() == 128; 7092 7093 if (!isConcatMask(Mask, VT, SplitV0)) 7094 return SDValue(); 7095 7096 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 7097 if (SplitV0) { 7098 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 7099 DAG.getConstant(0, DL, MVT::i64)); 7100 } 7101 if (V1.getValueSizeInBits() == 128) { 7102 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 7103 DAG.getConstant(0, DL, MVT::i64)); 7104 } 7105 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 7106 } 7107 7108 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7109 /// the specified operations to build the shuffle. 7110 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7111 SDValue RHS, SelectionDAG &DAG, 7112 const SDLoc &dl) { 7113 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7114 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 7115 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 7116 7117 enum { 7118 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7119 OP_VREV, 7120 OP_VDUP0, 7121 OP_VDUP1, 7122 OP_VDUP2, 7123 OP_VDUP3, 7124 OP_VEXT1, 7125 OP_VEXT2, 7126 OP_VEXT3, 7127 OP_VUZPL, // VUZP, left result 7128 OP_VUZPR, // VUZP, right result 7129 OP_VZIPL, // VZIP, left result 7130 OP_VZIPR, // VZIP, right result 7131 OP_VTRNL, // VTRN, left result 7132 OP_VTRNR // VTRN, right result 7133 }; 7134 7135 if (OpNum == OP_COPY) { 7136 if (LHSID == (1 * 9 + 2) * 9 + 3) 7137 return LHS; 7138 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 7139 return RHS; 7140 } 7141 7142 SDValue OpLHS, OpRHS; 7143 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7144 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7145 EVT VT = OpLHS.getValueType(); 7146 7147 switch (OpNum) { 7148 default: 7149 llvm_unreachable("Unknown shuffle opcode!"); 7150 case OP_VREV: 7151 // VREV divides the vector in half and swaps within the half. 7152 if (VT.getVectorElementType() == MVT::i32 || 7153 VT.getVectorElementType() == MVT::f32) 7154 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 7155 // vrev <4 x i16> -> REV32 7156 if (VT.getVectorElementType() == MVT::i16 || 7157 VT.getVectorElementType() == MVT::f16) 7158 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 7159 // vrev <4 x i8> -> REV16 7160 assert(VT.getVectorElementType() == MVT::i8); 7161 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 7162 case OP_VDUP0: 7163 case OP_VDUP1: 7164 case OP_VDUP2: 7165 case OP_VDUP3: { 7166 EVT EltTy = VT.getVectorElementType(); 7167 unsigned Opcode; 7168 if (EltTy == MVT::i8) 7169 Opcode = AArch64ISD::DUPLANE8; 7170 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 7171 Opcode = AArch64ISD::DUPLANE16; 7172 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 7173 Opcode = AArch64ISD::DUPLANE32; 7174 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 7175 Opcode = AArch64ISD::DUPLANE64; 7176 else 7177 llvm_unreachable("Invalid vector element type?"); 7178 7179 if (VT.getSizeInBits() == 64) 7180 OpLHS = WidenVector(OpLHS, DAG); 7181 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 7182 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 7183 } 7184 case OP_VEXT1: 7185 case OP_VEXT2: 7186 case OP_VEXT3: { 7187 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 7188 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 7189 DAG.getConstant(Imm, dl, MVT::i32)); 7190 } 7191 case OP_VUZPL: 7192 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 7193 OpRHS); 7194 case OP_VUZPR: 7195 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 7196 OpRHS); 7197 case OP_VZIPL: 7198 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 7199 OpRHS); 7200 case OP_VZIPR: 7201 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 7202 OpRHS); 7203 case OP_VTRNL: 7204 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 7205 OpRHS); 7206 case OP_VTRNR: 7207 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 7208 OpRHS); 7209 } 7210 } 7211 7212 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 7213 SelectionDAG &DAG) { 7214 // Check to see if we can use the TBL instruction. 7215 SDValue V1 = Op.getOperand(0); 7216 SDValue V2 = Op.getOperand(1); 7217 SDLoc DL(Op); 7218 7219 EVT EltVT = Op.getValueType().getVectorElementType(); 7220 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 7221 7222 SmallVector<SDValue, 8> TBLMask; 7223 for (int Val : ShuffleMask) { 7224 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 7225 unsigned Offset = Byte + Val * BytesPerElt; 7226 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 7227 } 7228 } 7229 7230 MVT IndexVT = MVT::v8i8; 7231 unsigned IndexLen = 8; 7232 if (Op.getValueSizeInBits() == 128) { 7233 IndexVT = MVT::v16i8; 7234 IndexLen = 16; 7235 } 7236 7237 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 7238 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 7239 7240 SDValue Shuffle; 7241 if (V2.getNode()->isUndef()) { 7242 if (IndexLen == 8) 7243 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 7244 Shuffle = DAG.getNode( 7245 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7246 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 7247 DAG.getBuildVector(IndexVT, DL, 7248 makeArrayRef(TBLMask.data(), IndexLen))); 7249 } else { 7250 if (IndexLen == 8) { 7251 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 7252 Shuffle = DAG.getNode( 7253 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7254 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 7255 DAG.getBuildVector(IndexVT, DL, 7256 makeArrayRef(TBLMask.data(), IndexLen))); 7257 } else { 7258 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 7259 // cannot currently represent the register constraints on the input 7260 // table registers. 7261 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 7262 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 7263 // IndexLen)); 7264 Shuffle = DAG.getNode( 7265 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7266 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 7267 V2Cst, DAG.getBuildVector(IndexVT, DL, 7268 makeArrayRef(TBLMask.data(), IndexLen))); 7269 } 7270 } 7271 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 7272 } 7273 7274 static unsigned getDUPLANEOp(EVT EltType) { 7275 if (EltType == MVT::i8) 7276 return AArch64ISD::DUPLANE8; 7277 if (EltType == MVT::i16 || EltType == MVT::f16) 7278 return AArch64ISD::DUPLANE16; 7279 if (EltType == MVT::i32 || EltType == MVT::f32) 7280 return AArch64ISD::DUPLANE32; 7281 if (EltType == MVT::i64 || EltType == MVT::f64) 7282 return AArch64ISD::DUPLANE64; 7283 7284 llvm_unreachable("Invalid vector element type?"); 7285 } 7286 7287 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7288 SelectionDAG &DAG) const { 7289 SDLoc dl(Op); 7290 EVT VT = Op.getValueType(); 7291 7292 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7293 7294 // Convert shuffles that are directly supported on NEON to target-specific 7295 // DAG nodes, instead of keeping them as shuffles and matching them again 7296 // during code selection. This is more efficient and avoids the possibility 7297 // of inconsistencies between legalization and selection. 7298 ArrayRef<int> ShuffleMask = SVN->getMask(); 7299 7300 SDValue V1 = Op.getOperand(0); 7301 SDValue V2 = Op.getOperand(1); 7302 7303 if (SVN->isSplat()) { 7304 int Lane = SVN->getSplatIndex(); 7305 // If this is undef splat, generate it via "just" vdup, if possible. 7306 if (Lane == -1) 7307 Lane = 0; 7308 7309 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 7310 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 7311 V1.getOperand(0)); 7312 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 7313 // constant. If so, we can just reference the lane's definition directly. 7314 if (V1.getOpcode() == ISD::BUILD_VECTOR && 7315 !isa<ConstantSDNode>(V1.getOperand(Lane))) 7316 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 7317 7318 // Otherwise, duplicate from the lane of the input vector. 7319 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 7320 7321 // Try to eliminate a bitcasted extract subvector before a DUPLANE. 7322 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) { 7323 // Match: dup (bitcast (extract_subv X, C)), LaneC 7324 if (BitCast.getOpcode() != ISD::BITCAST || 7325 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR) 7326 return false; 7327 7328 // The extract index must align in the destination type. That may not 7329 // happen if the bitcast is from narrow to wide type. 7330 SDValue Extract = BitCast.getOperand(0); 7331 unsigned ExtIdx = Extract.getConstantOperandVal(1); 7332 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits(); 7333 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth; 7334 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits(); 7335 if (ExtIdxInBits % CastedEltBitWidth != 0) 7336 return false; 7337 7338 // Update the lane value by offsetting with the scaled extract index. 7339 LaneC += ExtIdxInBits / CastedEltBitWidth; 7340 7341 // Determine the casted vector type of the wide vector input. 7342 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC' 7343 // Examples: 7344 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3 7345 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5 7346 unsigned SrcVecNumElts = 7347 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth; 7348 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(), 7349 SrcVecNumElts); 7350 return true; 7351 }; 7352 MVT CastVT; 7353 if (getScaledOffsetDup(V1, Lane, CastVT)) { 7354 V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0)); 7355 } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 7356 // The lane is incremented by the index of the extract. 7357 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3 7358 Lane += V1.getConstantOperandVal(1); 7359 V1 = V1.getOperand(0); 7360 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 7361 // The lane is decremented if we are splatting from the 2nd operand. 7362 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1 7363 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 7364 Lane -= Idx * VT.getVectorNumElements() / 2; 7365 V1 = WidenVector(V1.getOperand(Idx), DAG); 7366 } else if (VT.getSizeInBits() == 64) { 7367 // Widen the operand to 128-bit register with undef. 7368 V1 = WidenVector(V1, DAG); 7369 } 7370 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 7371 } 7372 7373 if (isREVMask(ShuffleMask, VT, 64)) 7374 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 7375 if (isREVMask(ShuffleMask, VT, 32)) 7376 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 7377 if (isREVMask(ShuffleMask, VT, 16)) 7378 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 7379 7380 bool ReverseEXT = false; 7381 unsigned Imm; 7382 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 7383 if (ReverseEXT) 7384 std::swap(V1, V2); 7385 Imm *= getExtFactor(V1); 7386 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 7387 DAG.getConstant(Imm, dl, MVT::i32)); 7388 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 7389 Imm *= getExtFactor(V1); 7390 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 7391 DAG.getConstant(Imm, dl, MVT::i32)); 7392 } 7393 7394 unsigned WhichResult; 7395 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 7396 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7397 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7398 } 7399 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 7400 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7401 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7402 } 7403 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 7404 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7405 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7406 } 7407 7408 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7409 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7410 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7411 } 7412 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7413 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7414 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7415 } 7416 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7417 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7418 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7419 } 7420 7421 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 7422 return Concat; 7423 7424 bool DstIsLeft; 7425 int Anomaly; 7426 int NumInputElements = V1.getValueType().getVectorNumElements(); 7427 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 7428 SDValue DstVec = DstIsLeft ? V1 : V2; 7429 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 7430 7431 SDValue SrcVec = V1; 7432 int SrcLane = ShuffleMask[Anomaly]; 7433 if (SrcLane >= NumInputElements) { 7434 SrcVec = V2; 7435 SrcLane -= VT.getVectorNumElements(); 7436 } 7437 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 7438 7439 EVT ScalarVT = VT.getVectorElementType(); 7440 7441 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 7442 ScalarVT = MVT::i32; 7443 7444 return DAG.getNode( 7445 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 7446 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 7447 DstLaneV); 7448 } 7449 7450 // If the shuffle is not directly supported and it has 4 elements, use 7451 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7452 unsigned NumElts = VT.getVectorNumElements(); 7453 if (NumElts == 4) { 7454 unsigned PFIndexes[4]; 7455 for (unsigned i = 0; i != 4; ++i) { 7456 if (ShuffleMask[i] < 0) 7457 PFIndexes[i] = 8; 7458 else 7459 PFIndexes[i] = ShuffleMask[i]; 7460 } 7461 7462 // Compute the index in the perfect shuffle table. 7463 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7464 PFIndexes[2] * 9 + PFIndexes[3]; 7465 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7466 unsigned Cost = (PFEntry >> 30); 7467 7468 if (Cost <= 4) 7469 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7470 } 7471 7472 return GenerateTBL(Op, ShuffleMask, DAG); 7473 } 7474 7475 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 7476 SelectionDAG &DAG) const { 7477 SDLoc dl(Op); 7478 EVT VT = Op.getValueType(); 7479 EVT ElemVT = VT.getScalarType(); 7480 7481 SDValue SplatVal = Op.getOperand(0); 7482 7483 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 7484 // FPRs don't have this restriction. 7485 switch (ElemVT.getSimpleVT().SimpleTy) { 7486 case MVT::i8: 7487 case MVT::i16: 7488 case MVT::i32: 7489 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 7490 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 7491 case MVT::i64: 7492 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7493 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 7494 case MVT::i1: { 7495 // The general case of i1. There isn't any natural way to do this, 7496 // so we use some trickery with whilelo. 7497 // TODO: Add special cases for splat of constant true/false. 7498 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7499 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal, 7500 DAG.getValueType(MVT::i1)); 7501 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, 7502 MVT::i64); 7503 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID, 7504 DAG.getConstant(0, dl, MVT::i64), SplatVal); 7505 } 7506 // TODO: we can support float types, but haven't added patterns yet. 7507 case MVT::f16: 7508 case MVT::f32: 7509 case MVT::f64: 7510 default: 7511 report_fatal_error("Unsupported SPLAT_VECTOR input operand type"); 7512 } 7513 } 7514 7515 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 7516 APInt &UndefBits) { 7517 EVT VT = BVN->getValueType(0); 7518 APInt SplatBits, SplatUndef; 7519 unsigned SplatBitSize; 7520 bool HasAnyUndefs; 7521 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7522 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 7523 7524 for (unsigned i = 0; i < NumSplats; ++i) { 7525 CnstBits <<= SplatBitSize; 7526 UndefBits <<= SplatBitSize; 7527 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 7528 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 7529 } 7530 7531 return true; 7532 } 7533 7534 return false; 7535 } 7536 7537 // Try 64-bit splatted SIMD immediate. 7538 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7539 const APInt &Bits) { 7540 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7541 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7542 EVT VT = Op.getValueType(); 7543 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 7544 7545 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 7546 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 7547 7548 SDLoc dl(Op); 7549 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7550 DAG.getConstant(Value, dl, MVT::i32)); 7551 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7552 } 7553 } 7554 7555 return SDValue(); 7556 } 7557 7558 // Try 32-bit splatted SIMD immediate. 7559 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7560 const APInt &Bits, 7561 const SDValue *LHS = nullptr) { 7562 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7563 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7564 EVT VT = Op.getValueType(); 7565 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7566 bool isAdvSIMDModImm = false; 7567 uint64_t Shift; 7568 7569 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 7570 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 7571 Shift = 0; 7572 } 7573 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 7574 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 7575 Shift = 8; 7576 } 7577 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 7578 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 7579 Shift = 16; 7580 } 7581 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 7582 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 7583 Shift = 24; 7584 } 7585 7586 if (isAdvSIMDModImm) { 7587 SDLoc dl(Op); 7588 SDValue Mov; 7589 7590 if (LHS) 7591 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7592 DAG.getConstant(Value, dl, MVT::i32), 7593 DAG.getConstant(Shift, dl, MVT::i32)); 7594 else 7595 Mov = DAG.getNode(NewOp, dl, MovTy, 7596 DAG.getConstant(Value, dl, MVT::i32), 7597 DAG.getConstant(Shift, dl, MVT::i32)); 7598 7599 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7600 } 7601 } 7602 7603 return SDValue(); 7604 } 7605 7606 // Try 16-bit splatted SIMD immediate. 7607 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7608 const APInt &Bits, 7609 const SDValue *LHS = nullptr) { 7610 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7611 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7612 EVT VT = Op.getValueType(); 7613 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 7614 bool isAdvSIMDModImm = false; 7615 uint64_t Shift; 7616 7617 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 7618 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 7619 Shift = 0; 7620 } 7621 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 7622 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 7623 Shift = 8; 7624 } 7625 7626 if (isAdvSIMDModImm) { 7627 SDLoc dl(Op); 7628 SDValue Mov; 7629 7630 if (LHS) 7631 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7632 DAG.getConstant(Value, dl, MVT::i32), 7633 DAG.getConstant(Shift, dl, MVT::i32)); 7634 else 7635 Mov = DAG.getNode(NewOp, dl, MovTy, 7636 DAG.getConstant(Value, dl, MVT::i32), 7637 DAG.getConstant(Shift, dl, MVT::i32)); 7638 7639 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7640 } 7641 } 7642 7643 return SDValue(); 7644 } 7645 7646 // Try 32-bit splatted SIMD immediate with shifted ones. 7647 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 7648 SelectionDAG &DAG, const APInt &Bits) { 7649 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7650 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7651 EVT VT = Op.getValueType(); 7652 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7653 bool isAdvSIMDModImm = false; 7654 uint64_t Shift; 7655 7656 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 7657 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 7658 Shift = 264; 7659 } 7660 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 7661 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 7662 Shift = 272; 7663 } 7664 7665 if (isAdvSIMDModImm) { 7666 SDLoc dl(Op); 7667 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7668 DAG.getConstant(Value, dl, MVT::i32), 7669 DAG.getConstant(Shift, dl, MVT::i32)); 7670 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7671 } 7672 } 7673 7674 return SDValue(); 7675 } 7676 7677 // Try 8-bit splatted SIMD immediate. 7678 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7679 const APInt &Bits) { 7680 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7681 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7682 EVT VT = Op.getValueType(); 7683 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 7684 7685 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 7686 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 7687 7688 SDLoc dl(Op); 7689 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7690 DAG.getConstant(Value, dl, MVT::i32)); 7691 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7692 } 7693 } 7694 7695 return SDValue(); 7696 } 7697 7698 // Try FP splatted SIMD immediate. 7699 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7700 const APInt &Bits) { 7701 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7702 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7703 EVT VT = Op.getValueType(); 7704 bool isWide = (VT.getSizeInBits() == 128); 7705 MVT MovTy; 7706 bool isAdvSIMDModImm = false; 7707 7708 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 7709 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 7710 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 7711 } 7712 else if (isWide && 7713 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 7714 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 7715 MovTy = MVT::v2f64; 7716 } 7717 7718 if (isAdvSIMDModImm) { 7719 SDLoc dl(Op); 7720 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7721 DAG.getConstant(Value, dl, MVT::i32)); 7722 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7723 } 7724 } 7725 7726 return SDValue(); 7727 } 7728 7729 // Specialized code to quickly find if PotentialBVec is a BuildVector that 7730 // consists of only the same constant int value, returned in reference arg 7731 // ConstVal 7732 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 7733 uint64_t &ConstVal) { 7734 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 7735 if (!Bvec) 7736 return false; 7737 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 7738 if (!FirstElt) 7739 return false; 7740 EVT VT = Bvec->getValueType(0); 7741 unsigned NumElts = VT.getVectorNumElements(); 7742 for (unsigned i = 1; i < NumElts; ++i) 7743 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 7744 return false; 7745 ConstVal = FirstElt->getZExtValue(); 7746 return true; 7747 } 7748 7749 static unsigned getIntrinsicID(const SDNode *N) { 7750 unsigned Opcode = N->getOpcode(); 7751 switch (Opcode) { 7752 default: 7753 return Intrinsic::not_intrinsic; 7754 case ISD::INTRINSIC_WO_CHAIN: { 7755 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7756 if (IID < Intrinsic::num_intrinsics) 7757 return IID; 7758 return Intrinsic::not_intrinsic; 7759 } 7760 } 7761 } 7762 7763 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 7764 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 7765 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 7766 // Also, logical shift right -> sri, with the same structure. 7767 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 7768 EVT VT = N->getValueType(0); 7769 7770 if (!VT.isVector()) 7771 return SDValue(); 7772 7773 SDLoc DL(N); 7774 7775 // Is the first op an AND? 7776 const SDValue And = N->getOperand(0); 7777 if (And.getOpcode() != ISD::AND) 7778 return SDValue(); 7779 7780 // Is the second op an shl or lshr? 7781 SDValue Shift = N->getOperand(1); 7782 // This will have been turned into: AArch64ISD::VSHL vector, #shift 7783 // or AArch64ISD::VLSHR vector, #shift 7784 unsigned ShiftOpc = Shift.getOpcode(); 7785 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 7786 return SDValue(); 7787 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 7788 7789 // Is the shift amount constant? 7790 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7791 if (!C2node) 7792 return SDValue(); 7793 7794 // Is the and mask vector all constant? 7795 uint64_t C1; 7796 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 7797 return SDValue(); 7798 7799 // Is C1 == ~C2, taking into account how much one can shift elements of a 7800 // particular size? 7801 uint64_t C2 = C2node->getZExtValue(); 7802 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 7803 if (C2 > ElemSizeInBits) 7804 return SDValue(); 7805 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 7806 if ((C1 & ElemMask) != (~C2 & ElemMask)) 7807 return SDValue(); 7808 7809 SDValue X = And.getOperand(0); 7810 SDValue Y = Shift.getOperand(0); 7811 7812 unsigned Intrin = 7813 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 7814 SDValue ResultSLI = 7815 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7816 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 7817 Shift.getOperand(1)); 7818 7819 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 7820 LLVM_DEBUG(N->dump(&DAG)); 7821 LLVM_DEBUG(dbgs() << "into: \n"); 7822 LLVM_DEBUG(ResultSLI->dump(&DAG)); 7823 7824 ++NumShiftInserts; 7825 return ResultSLI; 7826 } 7827 7828 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 7829 SelectionDAG &DAG) const { 7830 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 7831 if (EnableAArch64SlrGeneration) { 7832 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 7833 return Res; 7834 } 7835 7836 EVT VT = Op.getValueType(); 7837 7838 SDValue LHS = Op.getOperand(0); 7839 BuildVectorSDNode *BVN = 7840 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 7841 if (!BVN) { 7842 // OR commutes, so try swapping the operands. 7843 LHS = Op.getOperand(1); 7844 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 7845 } 7846 if (!BVN) 7847 return Op; 7848 7849 APInt DefBits(VT.getSizeInBits(), 0); 7850 APInt UndefBits(VT.getSizeInBits(), 0); 7851 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7852 SDValue NewOp; 7853 7854 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7855 DefBits, &LHS)) || 7856 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7857 DefBits, &LHS))) 7858 return NewOp; 7859 7860 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7861 UndefBits, &LHS)) || 7862 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7863 UndefBits, &LHS))) 7864 return NewOp; 7865 } 7866 7867 // We can always fall back to a non-immediate OR. 7868 return Op; 7869 } 7870 7871 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 7872 // be truncated to fit element width. 7873 static SDValue NormalizeBuildVector(SDValue Op, 7874 SelectionDAG &DAG) { 7875 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7876 SDLoc dl(Op); 7877 EVT VT = Op.getValueType(); 7878 EVT EltTy= VT.getVectorElementType(); 7879 7880 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 7881 return Op; 7882 7883 SmallVector<SDValue, 16> Ops; 7884 for (SDValue Lane : Op->ops()) { 7885 // For integer vectors, type legalization would have promoted the 7886 // operands already. Otherwise, if Op is a floating-point splat 7887 // (with operands cast to integers), then the only possibilities 7888 // are constants and UNDEFs. 7889 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 7890 APInt LowBits(EltTy.getSizeInBits(), 7891 CstLane->getZExtValue()); 7892 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 7893 } else if (Lane.getNode()->isUndef()) { 7894 Lane = DAG.getUNDEF(MVT::i32); 7895 } else { 7896 assert(Lane.getValueType() == MVT::i32 && 7897 "Unexpected BUILD_VECTOR operand type"); 7898 } 7899 Ops.push_back(Lane); 7900 } 7901 return DAG.getBuildVector(VT, dl, Ops); 7902 } 7903 7904 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 7905 EVT VT = Op.getValueType(); 7906 7907 APInt DefBits(VT.getSizeInBits(), 0); 7908 APInt UndefBits(VT.getSizeInBits(), 0); 7909 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7910 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7911 SDValue NewOp; 7912 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 7913 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7914 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 7915 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7916 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 7917 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 7918 return NewOp; 7919 7920 DefBits = ~DefBits; 7921 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 7922 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 7923 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 7924 return NewOp; 7925 7926 DefBits = UndefBits; 7927 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 7928 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7929 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 7930 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7931 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 7932 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 7933 return NewOp; 7934 7935 DefBits = ~UndefBits; 7936 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 7937 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 7938 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 7939 return NewOp; 7940 } 7941 7942 return SDValue(); 7943 } 7944 7945 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 7946 SelectionDAG &DAG) const { 7947 EVT VT = Op.getValueType(); 7948 7949 // Try to build a simple constant vector. 7950 Op = NormalizeBuildVector(Op, DAG); 7951 if (VT.isInteger()) { 7952 // Certain vector constants, used to express things like logical NOT and 7953 // arithmetic NEG, are passed through unmodified. This allows special 7954 // patterns for these operations to match, which will lower these constants 7955 // to whatever is proven necessary. 7956 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7957 if (BVN->isConstant()) 7958 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 7959 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 7960 APInt Val(BitSize, 7961 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 7962 if (Val.isNullValue() || Val.isAllOnesValue()) 7963 return Op; 7964 } 7965 } 7966 7967 if (SDValue V = ConstantBuildVector(Op, DAG)) 7968 return V; 7969 7970 // Scan through the operands to find some interesting properties we can 7971 // exploit: 7972 // 1) If only one value is used, we can use a DUP, or 7973 // 2) if only the low element is not undef, we can just insert that, or 7974 // 3) if only one constant value is used (w/ some non-constant lanes), 7975 // we can splat the constant value into the whole vector then fill 7976 // in the non-constant lanes. 7977 // 4) FIXME: If different constant values are used, but we can intelligently 7978 // select the values we'll be overwriting for the non-constant 7979 // lanes such that we can directly materialize the vector 7980 // some other way (MOVI, e.g.), we can be sneaky. 7981 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 7982 SDLoc dl(Op); 7983 unsigned NumElts = VT.getVectorNumElements(); 7984 bool isOnlyLowElement = true; 7985 bool usesOnlyOneValue = true; 7986 bool usesOnlyOneConstantValue = true; 7987 bool isConstant = true; 7988 bool AllLanesExtractElt = true; 7989 unsigned NumConstantLanes = 0; 7990 SDValue Value; 7991 SDValue ConstantValue; 7992 for (unsigned i = 0; i < NumElts; ++i) { 7993 SDValue V = Op.getOperand(i); 7994 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7995 AllLanesExtractElt = false; 7996 if (V.isUndef()) 7997 continue; 7998 if (i > 0) 7999 isOnlyLowElement = false; 8000 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 8001 isConstant = false; 8002 8003 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 8004 ++NumConstantLanes; 8005 if (!ConstantValue.getNode()) 8006 ConstantValue = V; 8007 else if (ConstantValue != V) 8008 usesOnlyOneConstantValue = false; 8009 } 8010 8011 if (!Value.getNode()) 8012 Value = V; 8013 else if (V != Value) 8014 usesOnlyOneValue = false; 8015 } 8016 8017 if (!Value.getNode()) { 8018 LLVM_DEBUG( 8019 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 8020 return DAG.getUNDEF(VT); 8021 } 8022 8023 // Convert BUILD_VECTOR where all elements but the lowest are undef into 8024 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 8025 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 8026 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 8027 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 8028 "SCALAR_TO_VECTOR node\n"); 8029 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 8030 } 8031 8032 if (AllLanesExtractElt) { 8033 SDNode *Vector = nullptr; 8034 bool Even = false; 8035 bool Odd = false; 8036 // Check whether the extract elements match the Even pattern <0,2,4,...> or 8037 // the Odd pattern <1,3,5,...>. 8038 for (unsigned i = 0; i < NumElts; ++i) { 8039 SDValue V = Op.getOperand(i); 8040 const SDNode *N = V.getNode(); 8041 if (!isa<ConstantSDNode>(N->getOperand(1))) 8042 break; 8043 SDValue N0 = N->getOperand(0); 8044 8045 // All elements are extracted from the same vector. 8046 if (!Vector) { 8047 Vector = N0.getNode(); 8048 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 8049 // BUILD_VECTOR. 8050 if (VT.getVectorElementType() != 8051 N0.getValueType().getVectorElementType()) 8052 break; 8053 } else if (Vector != N0.getNode()) { 8054 Odd = false; 8055 Even = false; 8056 break; 8057 } 8058 8059 // Extracted values are either at Even indices <0,2,4,...> or at Odd 8060 // indices <1,3,5,...>. 8061 uint64_t Val = N->getConstantOperandVal(1); 8062 if (Val == 2 * i) { 8063 Even = true; 8064 continue; 8065 } 8066 if (Val - 1 == 2 * i) { 8067 Odd = true; 8068 continue; 8069 } 8070 8071 // Something does not match: abort. 8072 Odd = false; 8073 Even = false; 8074 break; 8075 } 8076 if (Even || Odd) { 8077 SDValue LHS = 8078 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 8079 DAG.getConstant(0, dl, MVT::i64)); 8080 SDValue RHS = 8081 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 8082 DAG.getConstant(NumElts, dl, MVT::i64)); 8083 8084 if (Even && !Odd) 8085 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 8086 RHS); 8087 if (Odd && !Even) 8088 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 8089 RHS); 8090 } 8091 } 8092 8093 // Use DUP for non-constant splats. For f32 constant splats, reduce to 8094 // i32 and try again. 8095 if (usesOnlyOneValue) { 8096 if (!isConstant) { 8097 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8098 Value.getValueType() != VT) { 8099 LLVM_DEBUG( 8100 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 8101 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 8102 } 8103 8104 // This is actually a DUPLANExx operation, which keeps everything vectory. 8105 8106 SDValue Lane = Value.getOperand(1); 8107 Value = Value.getOperand(0); 8108 if (Value.getValueSizeInBits() == 64) { 8109 LLVM_DEBUG( 8110 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 8111 "widening it\n"); 8112 Value = WidenVector(Value, DAG); 8113 } 8114 8115 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 8116 return DAG.getNode(Opcode, dl, VT, Value, Lane); 8117 } 8118 8119 if (VT.getVectorElementType().isFloatingPoint()) { 8120 SmallVector<SDValue, 8> Ops; 8121 EVT EltTy = VT.getVectorElementType(); 8122 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 8123 "Unsupported floating-point vector type"); 8124 LLVM_DEBUG( 8125 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 8126 "BITCASTS, and try again\n"); 8127 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 8128 for (unsigned i = 0; i < NumElts; ++i) 8129 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 8130 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 8131 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 8132 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 8133 Val.dump();); 8134 Val = LowerBUILD_VECTOR(Val, DAG); 8135 if (Val.getNode()) 8136 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8137 } 8138 } 8139 8140 // If there was only one constant value used and for more than one lane, 8141 // start by splatting that value, then replace the non-constant lanes. This 8142 // is better than the default, which will perform a separate initialization 8143 // for each lane. 8144 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 8145 // Firstly, try to materialize the splat constant. 8146 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 8147 Val = ConstantBuildVector(Vec, DAG); 8148 if (!Val) { 8149 // Otherwise, materialize the constant and splat it. 8150 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 8151 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 8152 } 8153 8154 // Now insert the non-constant lanes. 8155 for (unsigned i = 0; i < NumElts; ++i) { 8156 SDValue V = Op.getOperand(i); 8157 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 8158 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 8159 // Note that type legalization likely mucked about with the VT of the 8160 // source operand, so we may have to convert it here before inserting. 8161 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 8162 } 8163 return Val; 8164 } 8165 8166 // This will generate a load from the constant pool. 8167 if (isConstant) { 8168 LLVM_DEBUG( 8169 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 8170 "expansion\n"); 8171 return SDValue(); 8172 } 8173 8174 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 8175 if (NumElts >= 4) { 8176 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 8177 return shuffle; 8178 } 8179 8180 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 8181 // know the default expansion would otherwise fall back on something even 8182 // worse. For a vector with one or two non-undef values, that's 8183 // scalar_to_vector for the elements followed by a shuffle (provided the 8184 // shuffle is valid for the target) and materialization element by element 8185 // on the stack followed by a load for everything else. 8186 if (!isConstant && !usesOnlyOneValue) { 8187 LLVM_DEBUG( 8188 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 8189 "of INSERT_VECTOR_ELT\n"); 8190 8191 SDValue Vec = DAG.getUNDEF(VT); 8192 SDValue Op0 = Op.getOperand(0); 8193 unsigned i = 0; 8194 8195 // Use SCALAR_TO_VECTOR for lane zero to 8196 // a) Avoid a RMW dependency on the full vector register, and 8197 // b) Allow the register coalescer to fold away the copy if the 8198 // value is already in an S or D register, and we're forced to emit an 8199 // INSERT_SUBREG that we can't fold anywhere. 8200 // 8201 // We also allow types like i8 and i16 which are illegal scalar but legal 8202 // vector element types. After type-legalization the inserted value is 8203 // extended (i32) and it is safe to cast them to the vector type by ignoring 8204 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 8205 if (!Op0.isUndef()) { 8206 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 8207 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 8208 ++i; 8209 } 8210 LLVM_DEBUG(if (i < NumElts) dbgs() 8211 << "Creating nodes for the other vector elements:\n";); 8212 for (; i < NumElts; ++i) { 8213 SDValue V = Op.getOperand(i); 8214 if (V.isUndef()) 8215 continue; 8216 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 8217 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 8218 } 8219 return Vec; 8220 } 8221 8222 LLVM_DEBUG( 8223 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 8224 "better alternative\n"); 8225 return SDValue(); 8226 } 8227 8228 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8229 SelectionDAG &DAG) const { 8230 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 8231 8232 // Check for non-constant or out of range lane. 8233 EVT VT = Op.getOperand(0).getValueType(); 8234 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8235 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 8236 return SDValue(); 8237 8238 8239 // Insertion/extraction are legal for V128 types. 8240 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 8241 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 8242 VT == MVT::v8f16) 8243 return Op; 8244 8245 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 8246 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 8247 return SDValue(); 8248 8249 // For V64 types, we perform insertion by expanding the value 8250 // to a V128 type and perform the insertion on that. 8251 SDLoc DL(Op); 8252 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 8253 EVT WideTy = WideVec.getValueType(); 8254 8255 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 8256 Op.getOperand(1), Op.getOperand(2)); 8257 // Re-narrow the resultant vector. 8258 return NarrowVector(Node, DAG); 8259 } 8260 8261 SDValue 8262 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8263 SelectionDAG &DAG) const { 8264 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 8265 8266 // Check for non-constant or out of range lane. 8267 EVT VT = Op.getOperand(0).getValueType(); 8268 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8269 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 8270 return SDValue(); 8271 8272 8273 // Insertion/extraction are legal for V128 types. 8274 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 8275 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 8276 VT == MVT::v8f16) 8277 return Op; 8278 8279 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 8280 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 8281 return SDValue(); 8282 8283 // For V64 types, we perform extraction by expanding the value 8284 // to a V128 type and perform the extraction on that. 8285 SDLoc DL(Op); 8286 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 8287 EVT WideTy = WideVec.getValueType(); 8288 8289 EVT ExtrTy = WideTy.getVectorElementType(); 8290 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 8291 ExtrTy = MVT::i32; 8292 8293 // For extractions, we just return the result directly. 8294 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 8295 Op.getOperand(1)); 8296 } 8297 8298 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 8299 SelectionDAG &DAG) const { 8300 EVT VT = Op.getOperand(0).getValueType(); 8301 SDLoc dl(Op); 8302 // Just in case... 8303 if (!VT.isVector()) 8304 return SDValue(); 8305 8306 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8307 if (!Cst) 8308 return SDValue(); 8309 unsigned Val = Cst->getZExtValue(); 8310 8311 unsigned Size = Op.getValueSizeInBits(); 8312 8313 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 8314 if (Val == 0) 8315 return Op; 8316 8317 // If this is extracting the upper 64-bits of a 128-bit vector, we match 8318 // that directly. 8319 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 8320 return Op; 8321 8322 return SDValue(); 8323 } 8324 8325 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 8326 if (VT.getVectorNumElements() == 4 && 8327 (VT.is128BitVector() || VT.is64BitVector())) { 8328 unsigned PFIndexes[4]; 8329 for (unsigned i = 0; i != 4; ++i) { 8330 if (M[i] < 0) 8331 PFIndexes[i] = 8; 8332 else 8333 PFIndexes[i] = M[i]; 8334 } 8335 8336 // Compute the index in the perfect shuffle table. 8337 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 8338 PFIndexes[2] * 9 + PFIndexes[3]; 8339 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8340 unsigned Cost = (PFEntry >> 30); 8341 8342 if (Cost <= 4) 8343 return true; 8344 } 8345 8346 bool DummyBool; 8347 int DummyInt; 8348 unsigned DummyUnsigned; 8349 8350 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 8351 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 8352 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 8353 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 8354 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 8355 isZIPMask(M, VT, DummyUnsigned) || 8356 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 8357 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 8358 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 8359 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 8360 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 8361 } 8362 8363 /// getVShiftImm - Check if this is a valid build_vector for the immediate 8364 /// operand of a vector shift operation, where all the elements of the 8365 /// build_vector must have the same constant integer value. 8366 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 8367 // Ignore bit_converts. 8368 while (Op.getOpcode() == ISD::BITCAST) 8369 Op = Op.getOperand(0); 8370 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8371 APInt SplatBits, SplatUndef; 8372 unsigned SplatBitSize; 8373 bool HasAnyUndefs; 8374 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 8375 HasAnyUndefs, ElementBits) || 8376 SplatBitSize > ElementBits) 8377 return false; 8378 Cnt = SplatBits.getSExtValue(); 8379 return true; 8380 } 8381 8382 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 8383 /// operand of a vector shift left operation. That value must be in the range: 8384 /// 0 <= Value < ElementBits for a left shift; or 8385 /// 0 <= Value <= ElementBits for a long left shift. 8386 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 8387 assert(VT.isVector() && "vector shift count is not a vector type"); 8388 int64_t ElementBits = VT.getScalarSizeInBits(); 8389 if (!getVShiftImm(Op, ElementBits, Cnt)) 8390 return false; 8391 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 8392 } 8393 8394 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 8395 /// operand of a vector shift right operation. The value must be in the range: 8396 /// 1 <= Value <= ElementBits for a right shift; or 8397 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 8398 assert(VT.isVector() && "vector shift count is not a vector type"); 8399 int64_t ElementBits = VT.getScalarSizeInBits(); 8400 if (!getVShiftImm(Op, ElementBits, Cnt)) 8401 return false; 8402 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 8403 } 8404 8405 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 8406 SelectionDAG &DAG) const { 8407 EVT VT = Op.getValueType(); 8408 SDLoc DL(Op); 8409 int64_t Cnt; 8410 8411 if (!Op.getOperand(1).getValueType().isVector()) 8412 return Op; 8413 unsigned EltSize = VT.getScalarSizeInBits(); 8414 8415 switch (Op.getOpcode()) { 8416 default: 8417 llvm_unreachable("unexpected shift opcode"); 8418 8419 case ISD::SHL: 8420 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 8421 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 8422 DAG.getConstant(Cnt, DL, MVT::i32)); 8423 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8424 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 8425 MVT::i32), 8426 Op.getOperand(0), Op.getOperand(1)); 8427 case ISD::SRA: 8428 case ISD::SRL: 8429 // Right shift immediate 8430 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 8431 unsigned Opc = 8432 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 8433 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 8434 DAG.getConstant(Cnt, DL, MVT::i32)); 8435 } 8436 8437 // Right shift register. Note, there is not a shift right register 8438 // instruction, but the shift left register instruction takes a signed 8439 // value, where negative numbers specify a right shift. 8440 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 8441 : Intrinsic::aarch64_neon_ushl; 8442 // negate the shift amount 8443 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 8444 SDValue NegShiftLeft = 8445 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8446 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 8447 NegShift); 8448 return NegShiftLeft; 8449 } 8450 8451 return SDValue(); 8452 } 8453 8454 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 8455 AArch64CC::CondCode CC, bool NoNans, EVT VT, 8456 const SDLoc &dl, SelectionDAG &DAG) { 8457 EVT SrcVT = LHS.getValueType(); 8458 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 8459 "function only supposed to emit natural comparisons"); 8460 8461 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 8462 APInt CnstBits(VT.getSizeInBits(), 0); 8463 APInt UndefBits(VT.getSizeInBits(), 0); 8464 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 8465 bool IsZero = IsCnst && (CnstBits == 0); 8466 8467 if (SrcVT.getVectorElementType().isFloatingPoint()) { 8468 switch (CC) { 8469 default: 8470 return SDValue(); 8471 case AArch64CC::NE: { 8472 SDValue Fcmeq; 8473 if (IsZero) 8474 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8475 else 8476 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8477 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 8478 } 8479 case AArch64CC::EQ: 8480 if (IsZero) 8481 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8482 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8483 case AArch64CC::GE: 8484 if (IsZero) 8485 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 8486 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 8487 case AArch64CC::GT: 8488 if (IsZero) 8489 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 8490 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 8491 case AArch64CC::LS: 8492 if (IsZero) 8493 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 8494 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 8495 case AArch64CC::LT: 8496 if (!NoNans) 8497 return SDValue(); 8498 // If we ignore NaNs then we can use to the MI implementation. 8499 LLVM_FALLTHROUGH; 8500 case AArch64CC::MI: 8501 if (IsZero) 8502 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 8503 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 8504 } 8505 } 8506 8507 switch (CC) { 8508 default: 8509 return SDValue(); 8510 case AArch64CC::NE: { 8511 SDValue Cmeq; 8512 if (IsZero) 8513 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8514 else 8515 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8516 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 8517 } 8518 case AArch64CC::EQ: 8519 if (IsZero) 8520 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8521 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8522 case AArch64CC::GE: 8523 if (IsZero) 8524 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 8525 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 8526 case AArch64CC::GT: 8527 if (IsZero) 8528 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 8529 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 8530 case AArch64CC::LE: 8531 if (IsZero) 8532 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 8533 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 8534 case AArch64CC::LS: 8535 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 8536 case AArch64CC::LO: 8537 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 8538 case AArch64CC::LT: 8539 if (IsZero) 8540 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 8541 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 8542 case AArch64CC::HI: 8543 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 8544 case AArch64CC::HS: 8545 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 8546 } 8547 } 8548 8549 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 8550 SelectionDAG &DAG) const { 8551 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8552 SDValue LHS = Op.getOperand(0); 8553 SDValue RHS = Op.getOperand(1); 8554 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 8555 SDLoc dl(Op); 8556 8557 if (LHS.getValueType().getVectorElementType().isInteger()) { 8558 assert(LHS.getValueType() == RHS.getValueType()); 8559 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 8560 SDValue Cmp = 8561 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 8562 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8563 } 8564 8565 const bool FullFP16 = 8566 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 8567 8568 // Make v4f16 (only) fcmp operations utilise vector instructions 8569 // v8f16 support will be a litle more complicated 8570 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 8571 if (LHS.getValueType().getVectorNumElements() == 4) { 8572 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 8573 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 8574 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 8575 DAG.ReplaceAllUsesWith(Op, NewSetcc); 8576 CmpVT = MVT::v4i32; 8577 } else 8578 return SDValue(); 8579 } 8580 8581 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 8582 LHS.getValueType().getVectorElementType() != MVT::f128); 8583 8584 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 8585 // clean. Some of them require two branches to implement. 8586 AArch64CC::CondCode CC1, CC2; 8587 bool ShouldInvert; 8588 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 8589 8590 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 8591 SDValue Cmp = 8592 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 8593 if (!Cmp.getNode()) 8594 return SDValue(); 8595 8596 if (CC2 != AArch64CC::AL) { 8597 SDValue Cmp2 = 8598 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 8599 if (!Cmp2.getNode()) 8600 return SDValue(); 8601 8602 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 8603 } 8604 8605 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8606 8607 if (ShouldInvert) 8608 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 8609 8610 return Cmp; 8611 } 8612 8613 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 8614 SelectionDAG &DAG) { 8615 SDValue VecOp = ScalarOp.getOperand(0); 8616 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 8617 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 8618 DAG.getConstant(0, DL, MVT::i64)); 8619 } 8620 8621 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 8622 SelectionDAG &DAG) const { 8623 SDLoc dl(Op); 8624 switch (Op.getOpcode()) { 8625 case ISD::VECREDUCE_ADD: 8626 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 8627 case ISD::VECREDUCE_SMAX: 8628 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 8629 case ISD::VECREDUCE_SMIN: 8630 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 8631 case ISD::VECREDUCE_UMAX: 8632 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 8633 case ISD::VECREDUCE_UMIN: 8634 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 8635 case ISD::VECREDUCE_FMAX: { 8636 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 8637 return DAG.getNode( 8638 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8639 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 8640 Op.getOperand(0)); 8641 } 8642 case ISD::VECREDUCE_FMIN: { 8643 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 8644 return DAG.getNode( 8645 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8646 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 8647 Op.getOperand(0)); 8648 } 8649 default: 8650 llvm_unreachable("Unhandled reduction"); 8651 } 8652 } 8653 8654 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 8655 SelectionDAG &DAG) const { 8656 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8657 if (!Subtarget.hasLSE()) 8658 return SDValue(); 8659 8660 // LSE has an atomic load-add instruction, but not a load-sub. 8661 SDLoc dl(Op); 8662 MVT VT = Op.getSimpleValueType(); 8663 SDValue RHS = Op.getOperand(2); 8664 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8665 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 8666 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 8667 Op.getOperand(0), Op.getOperand(1), RHS, 8668 AN->getMemOperand()); 8669 } 8670 8671 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 8672 SelectionDAG &DAG) const { 8673 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8674 if (!Subtarget.hasLSE()) 8675 return SDValue(); 8676 8677 // LSE has an atomic load-clear instruction, but not a load-and. 8678 SDLoc dl(Op); 8679 MVT VT = Op.getSimpleValueType(); 8680 SDValue RHS = Op.getOperand(2); 8681 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8682 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 8683 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 8684 Op.getOperand(0), Op.getOperand(1), RHS, 8685 AN->getMemOperand()); 8686 } 8687 8688 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 8689 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 8690 SDLoc dl(Op); 8691 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8692 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 8693 8694 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 8695 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 8696 if (Subtarget->hasCustomCallingConv()) 8697 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 8698 8699 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 8700 DAG.getConstant(4, dl, MVT::i64)); 8701 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 8702 Chain = 8703 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 8704 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 8705 DAG.getRegisterMask(Mask), Chain.getValue(1)); 8706 // To match the actual intent better, we should read the output from X15 here 8707 // again (instead of potentially spilling it to the stack), but rereading Size 8708 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 8709 // here. 8710 8711 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 8712 DAG.getConstant(4, dl, MVT::i64)); 8713 return Chain; 8714 } 8715 8716 SDValue 8717 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 8718 SelectionDAG &DAG) const { 8719 assert(Subtarget->isTargetWindows() && 8720 "Only Windows alloca probing supported"); 8721 SDLoc dl(Op); 8722 // Get the inputs. 8723 SDNode *Node = Op.getNode(); 8724 SDValue Chain = Op.getOperand(0); 8725 SDValue Size = Op.getOperand(1); 8726 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8727 EVT VT = Node->getValueType(0); 8728 8729 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 8730 "no-stack-arg-probe")) { 8731 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8732 Chain = SP.getValue(1); 8733 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8734 if (Align) 8735 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8736 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8737 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8738 SDValue Ops[2] = {SP, Chain}; 8739 return DAG.getMergeValues(Ops, dl); 8740 } 8741 8742 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 8743 8744 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 8745 8746 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8747 Chain = SP.getValue(1); 8748 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8749 if (Align) 8750 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8751 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8752 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8753 8754 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 8755 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 8756 8757 SDValue Ops[2] = {SP, Chain}; 8758 return DAG.getMergeValues(Ops, dl); 8759 } 8760 8761 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op, 8762 SelectionDAG &DAG) const { 8763 EVT VT = Op.getValueType(); 8764 assert(VT != MVT::i64 && "Expected illegal VSCALE node"); 8765 8766 SDLoc DL(Op); 8767 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue(); 8768 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)), 8769 DL, VT); 8770 } 8771 8772 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 8773 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 8774 /// specified in the intrinsic calls. 8775 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 8776 const CallInst &I, 8777 MachineFunction &MF, 8778 unsigned Intrinsic) const { 8779 auto &DL = I.getModule()->getDataLayout(); 8780 switch (Intrinsic) { 8781 case Intrinsic::aarch64_neon_ld2: 8782 case Intrinsic::aarch64_neon_ld3: 8783 case Intrinsic::aarch64_neon_ld4: 8784 case Intrinsic::aarch64_neon_ld1x2: 8785 case Intrinsic::aarch64_neon_ld1x3: 8786 case Intrinsic::aarch64_neon_ld1x4: 8787 case Intrinsic::aarch64_neon_ld2lane: 8788 case Intrinsic::aarch64_neon_ld3lane: 8789 case Intrinsic::aarch64_neon_ld4lane: 8790 case Intrinsic::aarch64_neon_ld2r: 8791 case Intrinsic::aarch64_neon_ld3r: 8792 case Intrinsic::aarch64_neon_ld4r: { 8793 Info.opc = ISD::INTRINSIC_W_CHAIN; 8794 // Conservatively set memVT to the entire set of vectors loaded. 8795 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 8796 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8797 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8798 Info.offset = 0; 8799 Info.align.reset(); 8800 // volatile loads with NEON intrinsics not supported 8801 Info.flags = MachineMemOperand::MOLoad; 8802 return true; 8803 } 8804 case Intrinsic::aarch64_neon_st2: 8805 case Intrinsic::aarch64_neon_st3: 8806 case Intrinsic::aarch64_neon_st4: 8807 case Intrinsic::aarch64_neon_st1x2: 8808 case Intrinsic::aarch64_neon_st1x3: 8809 case Intrinsic::aarch64_neon_st1x4: 8810 case Intrinsic::aarch64_neon_st2lane: 8811 case Intrinsic::aarch64_neon_st3lane: 8812 case Intrinsic::aarch64_neon_st4lane: { 8813 Info.opc = ISD::INTRINSIC_VOID; 8814 // Conservatively set memVT to the entire set of vectors stored. 8815 unsigned NumElts = 0; 8816 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 8817 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 8818 if (!ArgTy->isVectorTy()) 8819 break; 8820 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 8821 } 8822 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8823 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8824 Info.offset = 0; 8825 Info.align.reset(); 8826 // volatile stores with NEON intrinsics not supported 8827 Info.flags = MachineMemOperand::MOStore; 8828 return true; 8829 } 8830 case Intrinsic::aarch64_ldaxr: 8831 case Intrinsic::aarch64_ldxr: { 8832 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 8833 Info.opc = ISD::INTRINSIC_W_CHAIN; 8834 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8835 Info.ptrVal = I.getArgOperand(0); 8836 Info.offset = 0; 8837 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8838 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8839 return true; 8840 } 8841 case Intrinsic::aarch64_stlxr: 8842 case Intrinsic::aarch64_stxr: { 8843 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 8844 Info.opc = ISD::INTRINSIC_W_CHAIN; 8845 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8846 Info.ptrVal = I.getArgOperand(1); 8847 Info.offset = 0; 8848 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8849 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8850 return true; 8851 } 8852 case Intrinsic::aarch64_ldaxp: 8853 case Intrinsic::aarch64_ldxp: 8854 Info.opc = ISD::INTRINSIC_W_CHAIN; 8855 Info.memVT = MVT::i128; 8856 Info.ptrVal = I.getArgOperand(0); 8857 Info.offset = 0; 8858 Info.align = Align(16); 8859 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8860 return true; 8861 case Intrinsic::aarch64_stlxp: 8862 case Intrinsic::aarch64_stxp: 8863 Info.opc = ISD::INTRINSIC_W_CHAIN; 8864 Info.memVT = MVT::i128; 8865 Info.ptrVal = I.getArgOperand(2); 8866 Info.offset = 0; 8867 Info.align = Align(16); 8868 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8869 return true; 8870 case Intrinsic::aarch64_sve_ldnt1: { 8871 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 8872 Info.opc = ISD::INTRINSIC_W_CHAIN; 8873 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8874 Info.ptrVal = I.getArgOperand(1); 8875 Info.offset = 0; 8876 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8877 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal; 8878 return true; 8879 } 8880 case Intrinsic::aarch64_sve_stnt1: { 8881 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType()); 8882 Info.opc = ISD::INTRINSIC_W_CHAIN; 8883 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8884 Info.ptrVal = I.getArgOperand(2); 8885 Info.offset = 0; 8886 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8887 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal; 8888 return true; 8889 } 8890 default: 8891 break; 8892 } 8893 8894 return false; 8895 } 8896 8897 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 8898 ISD::LoadExtType ExtTy, 8899 EVT NewVT) const { 8900 // TODO: This may be worth removing. Check regression tests for diffs. 8901 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 8902 return false; 8903 8904 // If we're reducing the load width in order to avoid having to use an extra 8905 // instruction to do extension then it's probably a good idea. 8906 if (ExtTy != ISD::NON_EXTLOAD) 8907 return true; 8908 // Don't reduce load width if it would prevent us from combining a shift into 8909 // the offset. 8910 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 8911 assert(Mem); 8912 const SDValue &Base = Mem->getBasePtr(); 8913 if (Base.getOpcode() == ISD::ADD && 8914 Base.getOperand(1).getOpcode() == ISD::SHL && 8915 Base.getOperand(1).hasOneUse() && 8916 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 8917 // The shift can be combined if it matches the size of the value being 8918 // loaded (and so reducing the width would make it not match). 8919 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 8920 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 8921 if (ShiftAmount == Log2_32(LoadBytes)) 8922 return false; 8923 } 8924 // We have no reason to disallow reducing the load width, so allow it. 8925 return true; 8926 } 8927 8928 // Truncations from 64-bit GPR to 32-bit GPR is free. 8929 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 8930 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 8931 return false; 8932 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 8933 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 8934 return NumBits1 > NumBits2; 8935 } 8936 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 8937 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 8938 return false; 8939 unsigned NumBits1 = VT1.getSizeInBits(); 8940 unsigned NumBits2 = VT2.getSizeInBits(); 8941 return NumBits1 > NumBits2; 8942 } 8943 8944 /// Check if it is profitable to hoist instruction in then/else to if. 8945 /// Not profitable if I and it's user can form a FMA instruction 8946 /// because we prefer FMSUB/FMADD. 8947 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 8948 if (I->getOpcode() != Instruction::FMul) 8949 return true; 8950 8951 if (!I->hasOneUse()) 8952 return true; 8953 8954 Instruction *User = I->user_back(); 8955 8956 if (User && 8957 !(User->getOpcode() == Instruction::FSub || 8958 User->getOpcode() == Instruction::FAdd)) 8959 return true; 8960 8961 const TargetOptions &Options = getTargetMachine().Options; 8962 const Function *F = I->getFunction(); 8963 const DataLayout &DL = F->getParent()->getDataLayout(); 8964 Type *Ty = User->getOperand(0)->getType(); 8965 8966 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) && 8967 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 8968 (Options.AllowFPOpFusion == FPOpFusion::Fast || 8969 Options.UnsafeFPMath)); 8970 } 8971 8972 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 8973 // 64-bit GPR. 8974 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 8975 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 8976 return false; 8977 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 8978 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 8979 return NumBits1 == 32 && NumBits2 == 64; 8980 } 8981 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 8982 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 8983 return false; 8984 unsigned NumBits1 = VT1.getSizeInBits(); 8985 unsigned NumBits2 = VT2.getSizeInBits(); 8986 return NumBits1 == 32 && NumBits2 == 64; 8987 } 8988 8989 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 8990 EVT VT1 = Val.getValueType(); 8991 if (isZExtFree(VT1, VT2)) { 8992 return true; 8993 } 8994 8995 if (Val.getOpcode() != ISD::LOAD) 8996 return false; 8997 8998 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 8999 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 9000 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 9001 VT1.getSizeInBits() <= 32); 9002 } 9003 9004 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 9005 if (isa<FPExtInst>(Ext)) 9006 return false; 9007 9008 // Vector types are not free. 9009 if (Ext->getType()->isVectorTy()) 9010 return false; 9011 9012 for (const Use &U : Ext->uses()) { 9013 // The extension is free if we can fold it with a left shift in an 9014 // addressing mode or an arithmetic operation: add, sub, and cmp. 9015 9016 // Is there a shift? 9017 const Instruction *Instr = cast<Instruction>(U.getUser()); 9018 9019 // Is this a constant shift? 9020 switch (Instr->getOpcode()) { 9021 case Instruction::Shl: 9022 if (!isa<ConstantInt>(Instr->getOperand(1))) 9023 return false; 9024 break; 9025 case Instruction::GetElementPtr: { 9026 gep_type_iterator GTI = gep_type_begin(Instr); 9027 auto &DL = Ext->getModule()->getDataLayout(); 9028 std::advance(GTI, U.getOperandNo()-1); 9029 Type *IdxTy = GTI.getIndexedType(); 9030 // This extension will end up with a shift because of the scaling factor. 9031 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 9032 // Get the shift amount based on the scaling factor: 9033 // log2(sizeof(IdxTy)) - log2(8). 9034 uint64_t ShiftAmt = 9035 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 9036 // Is the constant foldable in the shift of the addressing mode? 9037 // I.e., shift amount is between 1 and 4 inclusive. 9038 if (ShiftAmt == 0 || ShiftAmt > 4) 9039 return false; 9040 break; 9041 } 9042 case Instruction::Trunc: 9043 // Check if this is a noop. 9044 // trunc(sext ty1 to ty2) to ty1. 9045 if (Instr->getType() == Ext->getOperand(0)->getType()) 9046 continue; 9047 LLVM_FALLTHROUGH; 9048 default: 9049 return false; 9050 } 9051 9052 // At this point we can use the bfm family, so this extension is free 9053 // for that use. 9054 } 9055 return true; 9056 } 9057 9058 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 9059 /// or upper half of the vector elements. 9060 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 9061 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 9062 auto *FullVT = cast<VectorType>(FullV->getType()); 9063 auto *HalfVT = cast<VectorType>(HalfV->getType()); 9064 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth(); 9065 }; 9066 9067 auto extractHalf = [](Value *FullV, Value *HalfV) { 9068 auto *FullVT = cast<VectorType>(FullV->getType()); 9069 auto *HalfVT = cast<VectorType>(HalfV->getType()); 9070 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 9071 }; 9072 9073 Constant *M1, *M2; 9074 Value *S1Op1, *S2Op1; 9075 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) || 9076 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2)))) 9077 return false; 9078 9079 // Check that the operands are half as wide as the result and we extract 9080 // half of the elements of the input vectors. 9081 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 9082 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 9083 return false; 9084 9085 // Check the mask extracts either the lower or upper half of vector 9086 // elements. 9087 int M1Start = -1; 9088 int M2Start = -1; 9089 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2; 9090 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 9091 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 9092 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 9093 return false; 9094 9095 return true; 9096 } 9097 9098 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 9099 /// of the vector elements. 9100 static bool areExtractExts(Value *Ext1, Value *Ext2) { 9101 auto areExtDoubled = [](Instruction *Ext) { 9102 return Ext->getType()->getScalarSizeInBits() == 9103 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 9104 }; 9105 9106 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 9107 !match(Ext2, m_ZExtOrSExt(m_Value())) || 9108 !areExtDoubled(cast<Instruction>(Ext1)) || 9109 !areExtDoubled(cast<Instruction>(Ext2))) 9110 return false; 9111 9112 return true; 9113 } 9114 9115 /// Check if sinking \p I's operands to I's basic block is profitable, because 9116 /// the operands can be folded into a target instruction, e.g. 9117 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 9118 bool AArch64TargetLowering::shouldSinkOperands( 9119 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 9120 if (!I->getType()->isVectorTy()) 9121 return false; 9122 9123 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 9124 switch (II->getIntrinsicID()) { 9125 case Intrinsic::aarch64_neon_umull: 9126 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 9127 return false; 9128 Ops.push_back(&II->getOperandUse(0)); 9129 Ops.push_back(&II->getOperandUse(1)); 9130 return true; 9131 default: 9132 return false; 9133 } 9134 } 9135 9136 switch (I->getOpcode()) { 9137 case Instruction::Sub: 9138 case Instruction::Add: { 9139 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 9140 return false; 9141 9142 // If the exts' operands extract either the lower or upper elements, we 9143 // can sink them too. 9144 auto Ext1 = cast<Instruction>(I->getOperand(0)); 9145 auto Ext2 = cast<Instruction>(I->getOperand(1)); 9146 if (areExtractShuffleVectors(Ext1, Ext2)) { 9147 Ops.push_back(&Ext1->getOperandUse(0)); 9148 Ops.push_back(&Ext2->getOperandUse(0)); 9149 } 9150 9151 Ops.push_back(&I->getOperandUse(0)); 9152 Ops.push_back(&I->getOperandUse(1)); 9153 9154 return true; 9155 } 9156 default: 9157 return false; 9158 } 9159 return false; 9160 } 9161 9162 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 9163 unsigned &RequiredAligment) const { 9164 if (!LoadedType.isSimple() || 9165 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 9166 return false; 9167 // Cyclone supports unaligned accesses. 9168 RequiredAligment = 0; 9169 unsigned NumBits = LoadedType.getSizeInBits(); 9170 return NumBits == 32 || NumBits == 64; 9171 } 9172 9173 /// A helper function for determining the number of interleaved accesses we 9174 /// will generate when lowering accesses of the given type. 9175 unsigned 9176 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 9177 const DataLayout &DL) const { 9178 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 9179 } 9180 9181 MachineMemOperand::Flags 9182 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const { 9183 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 9184 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 9185 return MOStridedAccess; 9186 return MachineMemOperand::MONone; 9187 } 9188 9189 bool AArch64TargetLowering::isLegalInterleavedAccessType( 9190 VectorType *VecTy, const DataLayout &DL) const { 9191 9192 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 9193 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 9194 9195 // Ensure the number of vector elements is greater than 1. 9196 if (VecTy->getNumElements() < 2) 9197 return false; 9198 9199 // Ensure the element type is legal. 9200 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 9201 return false; 9202 9203 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 9204 // 128 will be split into multiple interleaved accesses. 9205 return VecSize == 64 || VecSize % 128 == 0; 9206 } 9207 9208 /// Lower an interleaved load into a ldN intrinsic. 9209 /// 9210 /// E.g. Lower an interleaved load (Factor = 2): 9211 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 9212 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 9213 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 9214 /// 9215 /// Into: 9216 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 9217 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 9218 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 9219 bool AArch64TargetLowering::lowerInterleavedLoad( 9220 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 9221 ArrayRef<unsigned> Indices, unsigned Factor) const { 9222 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 9223 "Invalid interleave factor"); 9224 assert(!Shuffles.empty() && "Empty shufflevector input"); 9225 assert(Shuffles.size() == Indices.size() && 9226 "Unmatched number of shufflevectors and indices"); 9227 9228 const DataLayout &DL = LI->getModule()->getDataLayout(); 9229 9230 VectorType *VecTy = Shuffles[0]->getType(); 9231 9232 // Skip if we do not have NEON and skip illegal vector types. We can 9233 // "legalize" wide vector types into multiple interleaved accesses as long as 9234 // the vector types are divisible by 128. 9235 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 9236 return false; 9237 9238 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 9239 9240 // A pointer vector can not be the return type of the ldN intrinsics. Need to 9241 // load integer vectors first and then convert to pointer vectors. 9242 Type *EltTy = VecTy->getVectorElementType(); 9243 if (EltTy->isPointerTy()) 9244 VecTy = 9245 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 9246 9247 IRBuilder<> Builder(LI); 9248 9249 // The base address of the load. 9250 Value *BaseAddr = LI->getPointerOperand(); 9251 9252 if (NumLoads > 1) { 9253 // If we're going to generate more than one load, reset the sub-vector type 9254 // to something legal. 9255 VecTy = VectorType::get(VecTy->getVectorElementType(), 9256 VecTy->getVectorNumElements() / NumLoads); 9257 9258 // We will compute the pointer operand of each load from the original base 9259 // address using GEPs. Cast the base address to a pointer to the scalar 9260 // element type. 9261 BaseAddr = Builder.CreateBitCast( 9262 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 9263 LI->getPointerAddressSpace())); 9264 } 9265 9266 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 9267 Type *Tys[2] = {VecTy, PtrTy}; 9268 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 9269 Intrinsic::aarch64_neon_ld3, 9270 Intrinsic::aarch64_neon_ld4}; 9271 Function *LdNFunc = 9272 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 9273 9274 // Holds sub-vectors extracted from the load intrinsic return values. The 9275 // sub-vectors are associated with the shufflevector instructions they will 9276 // replace. 9277 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 9278 9279 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 9280 9281 // If we're generating more than one load, compute the base address of 9282 // subsequent loads as an offset from the previous. 9283 if (LoadCount > 0) 9284 BaseAddr = 9285 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 9286 VecTy->getVectorNumElements() * Factor); 9287 9288 CallInst *LdN = Builder.CreateCall( 9289 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 9290 9291 // Extract and store the sub-vectors returned by the load intrinsic. 9292 for (unsigned i = 0; i < Shuffles.size(); i++) { 9293 ShuffleVectorInst *SVI = Shuffles[i]; 9294 unsigned Index = Indices[i]; 9295 9296 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 9297 9298 // Convert the integer vector to pointer vector if the element is pointer. 9299 if (EltTy->isPointerTy()) 9300 SubVec = Builder.CreateIntToPtr( 9301 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 9302 VecTy->getVectorNumElements())); 9303 SubVecs[SVI].push_back(SubVec); 9304 } 9305 } 9306 9307 // Replace uses of the shufflevector instructions with the sub-vectors 9308 // returned by the load intrinsic. If a shufflevector instruction is 9309 // associated with more than one sub-vector, those sub-vectors will be 9310 // concatenated into a single wide vector. 9311 for (ShuffleVectorInst *SVI : Shuffles) { 9312 auto &SubVec = SubVecs[SVI]; 9313 auto *WideVec = 9314 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 9315 SVI->replaceAllUsesWith(WideVec); 9316 } 9317 9318 return true; 9319 } 9320 9321 /// Lower an interleaved store into a stN intrinsic. 9322 /// 9323 /// E.g. Lower an interleaved store (Factor = 3): 9324 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 9325 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 9326 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 9327 /// 9328 /// Into: 9329 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 9330 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 9331 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 9332 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 9333 /// 9334 /// Note that the new shufflevectors will be removed and we'll only generate one 9335 /// st3 instruction in CodeGen. 9336 /// 9337 /// Example for a more general valid mask (Factor 3). Lower: 9338 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 9339 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 9340 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 9341 /// 9342 /// Into: 9343 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 9344 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 9345 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 9346 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 9347 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 9348 ShuffleVectorInst *SVI, 9349 unsigned Factor) const { 9350 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 9351 "Invalid interleave factor"); 9352 9353 VectorType *VecTy = SVI->getType(); 9354 assert(VecTy->getVectorNumElements() % Factor == 0 && 9355 "Invalid interleaved store"); 9356 9357 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 9358 Type *EltTy = VecTy->getVectorElementType(); 9359 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 9360 9361 const DataLayout &DL = SI->getModule()->getDataLayout(); 9362 9363 // Skip if we do not have NEON and skip illegal vector types. We can 9364 // "legalize" wide vector types into multiple interleaved accesses as long as 9365 // the vector types are divisible by 128. 9366 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 9367 return false; 9368 9369 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 9370 9371 Value *Op0 = SVI->getOperand(0); 9372 Value *Op1 = SVI->getOperand(1); 9373 IRBuilder<> Builder(SI); 9374 9375 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 9376 // vectors to integer vectors. 9377 if (EltTy->isPointerTy()) { 9378 Type *IntTy = DL.getIntPtrType(EltTy); 9379 unsigned NumOpElts = Op0->getType()->getVectorNumElements(); 9380 9381 // Convert to the corresponding integer vector. 9382 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 9383 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 9384 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 9385 9386 SubVecTy = VectorType::get(IntTy, LaneLen); 9387 } 9388 9389 // The base address of the store. 9390 Value *BaseAddr = SI->getPointerOperand(); 9391 9392 if (NumStores > 1) { 9393 // If we're going to generate more than one store, reset the lane length 9394 // and sub-vector type to something legal. 9395 LaneLen /= NumStores; 9396 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 9397 9398 // We will compute the pointer operand of each store from the original base 9399 // address using GEPs. Cast the base address to a pointer to the scalar 9400 // element type. 9401 BaseAddr = Builder.CreateBitCast( 9402 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 9403 SI->getPointerAddressSpace())); 9404 } 9405 9406 auto Mask = SVI->getShuffleMask(); 9407 9408 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 9409 Type *Tys[2] = {SubVecTy, PtrTy}; 9410 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 9411 Intrinsic::aarch64_neon_st3, 9412 Intrinsic::aarch64_neon_st4}; 9413 Function *StNFunc = 9414 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 9415 9416 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 9417 9418 SmallVector<Value *, 5> Ops; 9419 9420 // Split the shufflevector operands into sub vectors for the new stN call. 9421 for (unsigned i = 0; i < Factor; i++) { 9422 unsigned IdxI = StoreCount * LaneLen * Factor + i; 9423 if (Mask[IdxI] >= 0) { 9424 Ops.push_back(Builder.CreateShuffleVector( 9425 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 9426 } else { 9427 unsigned StartMask = 0; 9428 for (unsigned j = 1; j < LaneLen; j++) { 9429 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 9430 if (Mask[IdxJ * Factor + IdxI] >= 0) { 9431 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 9432 break; 9433 } 9434 } 9435 // Note: Filling undef gaps with random elements is ok, since 9436 // those elements were being written anyway (with undefs). 9437 // In the case of all undefs we're defaulting to using elems from 0 9438 // Note: StartMask cannot be negative, it's checked in 9439 // isReInterleaveMask 9440 Ops.push_back(Builder.CreateShuffleVector( 9441 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 9442 } 9443 } 9444 9445 // If we generating more than one store, we compute the base address of 9446 // subsequent stores as an offset from the previous. 9447 if (StoreCount > 0) 9448 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 9449 BaseAddr, LaneLen * Factor); 9450 9451 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 9452 Builder.CreateCall(StNFunc, Ops); 9453 } 9454 return true; 9455 } 9456 9457 9458 EVT AArch64TargetLowering::getOptimalMemOpType( 9459 const MemOp &Op, const AttributeList &FuncAttributes) const { 9460 bool CanImplicitFloat = 9461 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9462 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9463 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9464 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9465 // taken one instruction to materialize the v2i64 zero and one store (with 9466 // restrictive addressing mode). Just do i64 stores. 9467 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 9468 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 9469 if (Op.isAligned(AlignCheck)) 9470 return true; 9471 bool Fast; 9472 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9473 &Fast) && 9474 Fast; 9475 }; 9476 9477 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 9478 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 9479 return MVT::v2i64; 9480 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 9481 return MVT::f128; 9482 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 9483 return MVT::i64; 9484 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 9485 return MVT::i32; 9486 return MVT::Other; 9487 } 9488 9489 LLT AArch64TargetLowering::getOptimalMemOpLLT( 9490 const MemOp &Op, const AttributeList &FuncAttributes) const { 9491 bool CanImplicitFloat = 9492 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9493 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9494 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9495 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9496 // taken one instruction to materialize the v2i64 zero and one store (with 9497 // restrictive addressing mode). Just do i64 stores. 9498 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 9499 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 9500 if (Op.isAligned(AlignCheck)) 9501 return true; 9502 bool Fast; 9503 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9504 &Fast) && 9505 Fast; 9506 }; 9507 9508 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 9509 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 9510 return LLT::vector(2, 64); 9511 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 9512 return LLT::scalar(128); 9513 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 9514 return LLT::scalar(64); 9515 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 9516 return LLT::scalar(32); 9517 return LLT(); 9518 } 9519 9520 // 12-bit optionally shifted immediates are legal for adds. 9521 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 9522 if (Immed == std::numeric_limits<int64_t>::min()) { 9523 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 9524 << ": avoid UB for INT64_MIN\n"); 9525 return false; 9526 } 9527 // Same encoding for add/sub, just flip the sign. 9528 Immed = std::abs(Immed); 9529 bool IsLegal = ((Immed >> 12) == 0 || 9530 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 9531 LLVM_DEBUG(dbgs() << "Is " << Immed 9532 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 9533 return IsLegal; 9534 } 9535 9536 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 9537 // immediates is the same as for an add or a sub. 9538 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 9539 return isLegalAddImmediate(Immed); 9540 } 9541 9542 /// isLegalAddressingMode - Return true if the addressing mode represented 9543 /// by AM is legal for this target, for a load/store of the specified type. 9544 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 9545 const AddrMode &AM, Type *Ty, 9546 unsigned AS, Instruction *I) const { 9547 // AArch64 has five basic addressing modes: 9548 // reg 9549 // reg + 9-bit signed offset 9550 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 9551 // reg1 + reg2 9552 // reg + SIZE_IN_BYTES * reg 9553 9554 // No global is ever allowed as a base. 9555 if (AM.BaseGV) 9556 return false; 9557 9558 // No reg+reg+imm addressing. 9559 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 9560 return false; 9561 9562 // FIXME: Update this method to support scalable addressing modes. 9563 if (Ty->isVectorTy() && Ty->getVectorIsScalable()) 9564 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale; 9565 9566 // check reg + imm case: 9567 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 9568 uint64_t NumBytes = 0; 9569 if (Ty->isSized()) { 9570 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 9571 NumBytes = NumBits / 8; 9572 if (!isPowerOf2_64(NumBits)) 9573 NumBytes = 0; 9574 } 9575 9576 if (!AM.Scale) { 9577 int64_t Offset = AM.BaseOffs; 9578 9579 // 9-bit signed offset 9580 if (isInt<9>(Offset)) 9581 return true; 9582 9583 // 12-bit unsigned offset 9584 unsigned shift = Log2_64(NumBytes); 9585 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 9586 // Must be a multiple of NumBytes (NumBytes is a power of 2) 9587 (Offset >> shift) << shift == Offset) 9588 return true; 9589 return false; 9590 } 9591 9592 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 9593 9594 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 9595 } 9596 9597 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 9598 // Consider splitting large offset of struct or array. 9599 return true; 9600 } 9601 9602 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 9603 const AddrMode &AM, Type *Ty, 9604 unsigned AS) const { 9605 // Scaling factors are not free at all. 9606 // Operands | Rt Latency 9607 // ------------------------------------------- 9608 // Rt, [Xn, Xm] | 4 9609 // ------------------------------------------- 9610 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 9611 // Rt, [Xn, Wm, <extend> #imm] | 9612 if (isLegalAddressingMode(DL, AM, Ty, AS)) 9613 // Scale represents reg2 * scale, thus account for 1 if 9614 // it is not equal to 0 or 1. 9615 return AM.Scale != 0 && AM.Scale != 1; 9616 return -1; 9617 } 9618 9619 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd( 9620 const MachineFunction &MF, EVT VT) const { 9621 VT = VT.getScalarType(); 9622 9623 if (!VT.isSimple()) 9624 return false; 9625 9626 switch (VT.getSimpleVT().SimpleTy) { 9627 case MVT::f32: 9628 case MVT::f64: 9629 return true; 9630 default: 9631 break; 9632 } 9633 9634 return false; 9635 } 9636 9637 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 9638 Type *Ty) const { 9639 switch (Ty->getScalarType()->getTypeID()) { 9640 case Type::FloatTyID: 9641 case Type::DoubleTyID: 9642 return true; 9643 default: 9644 return false; 9645 } 9646 } 9647 9648 const MCPhysReg * 9649 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 9650 // LR is a callee-save register, but we must treat it as clobbered by any call 9651 // site. Hence we include LR in the scratch registers, which are in turn added 9652 // as implicit-defs for stackmaps and patchpoints. 9653 static const MCPhysReg ScratchRegs[] = { 9654 AArch64::X16, AArch64::X17, AArch64::LR, 0 9655 }; 9656 return ScratchRegs; 9657 } 9658 9659 bool 9660 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 9661 CombineLevel Level) const { 9662 N = N->getOperand(0).getNode(); 9663 EVT VT = N->getValueType(0); 9664 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 9665 // it with shift to let it be lowered to UBFX. 9666 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 9667 isa<ConstantSDNode>(N->getOperand(1))) { 9668 uint64_t TruncMask = N->getConstantOperandVal(1); 9669 if (isMask_64(TruncMask) && 9670 N->getOperand(0).getOpcode() == ISD::SRL && 9671 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 9672 return false; 9673 } 9674 return true; 9675 } 9676 9677 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 9678 Type *Ty) const { 9679 assert(Ty->isIntegerTy()); 9680 9681 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 9682 if (BitSize == 0) 9683 return false; 9684 9685 int64_t Val = Imm.getSExtValue(); 9686 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 9687 return true; 9688 9689 if ((int64_t)Val < 0) 9690 Val = ~Val; 9691 if (BitSize == 32) 9692 Val &= (1LL << 32) - 1; 9693 9694 unsigned LZ = countLeadingZeros((uint64_t)Val); 9695 unsigned Shift = (63 - LZ) / 16; 9696 // MOVZ is free so return true for one or fewer MOVK. 9697 return Shift < 3; 9698 } 9699 9700 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 9701 unsigned Index) const { 9702 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 9703 return false; 9704 9705 return (Index == 0 || Index == ResVT.getVectorNumElements()); 9706 } 9707 9708 /// Turn vector tests of the signbit in the form of: 9709 /// xor (sra X, elt_size(X)-1), -1 9710 /// into: 9711 /// cmge X, X, #0 9712 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 9713 const AArch64Subtarget *Subtarget) { 9714 EVT VT = N->getValueType(0); 9715 if (!Subtarget->hasNEON() || !VT.isVector()) 9716 return SDValue(); 9717 9718 // There must be a shift right algebraic before the xor, and the xor must be a 9719 // 'not' operation. 9720 SDValue Shift = N->getOperand(0); 9721 SDValue Ones = N->getOperand(1); 9722 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 9723 !ISD::isBuildVectorAllOnes(Ones.getNode())) 9724 return SDValue(); 9725 9726 // The shift should be smearing the sign bit across each vector element. 9727 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 9728 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 9729 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 9730 return SDValue(); 9731 9732 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 9733 } 9734 9735 // Generate SUBS and CSEL for integer abs. 9736 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 9737 EVT VT = N->getValueType(0); 9738 9739 SDValue N0 = N->getOperand(0); 9740 SDValue N1 = N->getOperand(1); 9741 SDLoc DL(N); 9742 9743 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 9744 // and change it to SUB and CSEL. 9745 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 9746 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 9747 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 9748 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 9749 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 9750 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 9751 N0.getOperand(0)); 9752 // Generate SUBS & CSEL. 9753 SDValue Cmp = 9754 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 9755 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 9756 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 9757 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 9758 SDValue(Cmp.getNode(), 1)); 9759 } 9760 return SDValue(); 9761 } 9762 9763 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 9764 TargetLowering::DAGCombinerInfo &DCI, 9765 const AArch64Subtarget *Subtarget) { 9766 if (DCI.isBeforeLegalizeOps()) 9767 return SDValue(); 9768 9769 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 9770 return Cmp; 9771 9772 return performIntegerAbsCombine(N, DAG); 9773 } 9774 9775 SDValue 9776 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9777 SelectionDAG &DAG, 9778 SmallVectorImpl<SDNode *> &Created) const { 9779 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 9780 if (isIntDivCheap(N->getValueType(0), Attr)) 9781 return SDValue(N,0); // Lower SDIV as SDIV 9782 9783 // fold (sdiv X, pow2) 9784 EVT VT = N->getValueType(0); 9785 if ((VT != MVT::i32 && VT != MVT::i64) || 9786 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 9787 return SDValue(); 9788 9789 SDLoc DL(N); 9790 SDValue N0 = N->getOperand(0); 9791 unsigned Lg2 = Divisor.countTrailingZeros(); 9792 SDValue Zero = DAG.getConstant(0, DL, VT); 9793 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 9794 9795 // Add (N0 < 0) ? Pow2 - 1 : 0; 9796 SDValue CCVal; 9797 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 9798 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 9799 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 9800 9801 Created.push_back(Cmp.getNode()); 9802 Created.push_back(Add.getNode()); 9803 Created.push_back(CSel.getNode()); 9804 9805 // Divide by pow2. 9806 SDValue SRA = 9807 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 9808 9809 // If we're dividing by a positive value, we're done. Otherwise, we must 9810 // negate the result. 9811 if (Divisor.isNonNegative()) 9812 return SRA; 9813 9814 Created.push_back(SRA.getNode()); 9815 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 9816 } 9817 9818 static bool IsSVECntIntrinsic(SDValue S) { 9819 switch(getIntrinsicID(S.getNode())) { 9820 default: 9821 break; 9822 case Intrinsic::aarch64_sve_cntb: 9823 case Intrinsic::aarch64_sve_cnth: 9824 case Intrinsic::aarch64_sve_cntw: 9825 case Intrinsic::aarch64_sve_cntd: 9826 return true; 9827 } 9828 return false; 9829 } 9830 9831 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 9832 TargetLowering::DAGCombinerInfo &DCI, 9833 const AArch64Subtarget *Subtarget) { 9834 if (DCI.isBeforeLegalizeOps()) 9835 return SDValue(); 9836 9837 // The below optimizations require a constant RHS. 9838 if (!isa<ConstantSDNode>(N->getOperand(1))) 9839 return SDValue(); 9840 9841 SDValue N0 = N->getOperand(0); 9842 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 9843 const APInt &ConstValue = C->getAPIntValue(); 9844 9845 // Allow the scaling to be folded into the `cnt` instruction by preventing 9846 // the scaling to be obscured here. This makes it easier to pattern match. 9847 if (IsSVECntIntrinsic(N0) || 9848 (N0->getOpcode() == ISD::TRUNCATE && 9849 (IsSVECntIntrinsic(N0->getOperand(0))))) 9850 if (ConstValue.sge(1) && ConstValue.sle(16)) 9851 return SDValue(); 9852 9853 // Multiplication of a power of two plus/minus one can be done more 9854 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 9855 // future CPUs have a cheaper MADD instruction, this may need to be 9856 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 9857 // 64-bit is 5 cycles, so this is always a win. 9858 // More aggressively, some multiplications N0 * C can be lowered to 9859 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 9860 // e.g. 6=3*2=(2+1)*2. 9861 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 9862 // which equals to (1+2)*16-(1+2). 9863 // TrailingZeroes is used to test if the mul can be lowered to 9864 // shift+add+shift. 9865 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 9866 if (TrailingZeroes) { 9867 // Conservatively do not lower to shift+add+shift if the mul might be 9868 // folded into smul or umul. 9869 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 9870 isZeroExtended(N0.getNode(), DAG))) 9871 return SDValue(); 9872 // Conservatively do not lower to shift+add+shift if the mul might be 9873 // folded into madd or msub. 9874 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 9875 N->use_begin()->getOpcode() == ISD::SUB)) 9876 return SDValue(); 9877 } 9878 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 9879 // and shift+add+shift. 9880 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 9881 9882 unsigned ShiftAmt, AddSubOpc; 9883 // Is the shifted value the LHS operand of the add/sub? 9884 bool ShiftValUseIsN0 = true; 9885 // Do we need to negate the result? 9886 bool NegateResult = false; 9887 9888 if (ConstValue.isNonNegative()) { 9889 // (mul x, 2^N + 1) => (add (shl x, N), x) 9890 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9891 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 9892 APInt SCVMinus1 = ShiftedConstValue - 1; 9893 APInt CVPlus1 = ConstValue + 1; 9894 if (SCVMinus1.isPowerOf2()) { 9895 ShiftAmt = SCVMinus1.logBase2(); 9896 AddSubOpc = ISD::ADD; 9897 } else if (CVPlus1.isPowerOf2()) { 9898 ShiftAmt = CVPlus1.logBase2(); 9899 AddSubOpc = ISD::SUB; 9900 } else 9901 return SDValue(); 9902 } else { 9903 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9904 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9905 APInt CVNegPlus1 = -ConstValue + 1; 9906 APInt CVNegMinus1 = -ConstValue - 1; 9907 if (CVNegPlus1.isPowerOf2()) { 9908 ShiftAmt = CVNegPlus1.logBase2(); 9909 AddSubOpc = ISD::SUB; 9910 ShiftValUseIsN0 = false; 9911 } else if (CVNegMinus1.isPowerOf2()) { 9912 ShiftAmt = CVNegMinus1.logBase2(); 9913 AddSubOpc = ISD::ADD; 9914 NegateResult = true; 9915 } else 9916 return SDValue(); 9917 } 9918 9919 SDLoc DL(N); 9920 EVT VT = N->getValueType(0); 9921 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 9922 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 9923 9924 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 9925 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 9926 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 9927 assert(!(NegateResult && TrailingZeroes) && 9928 "NegateResult and TrailingZeroes cannot both be true for now."); 9929 // Negate the result. 9930 if (NegateResult) 9931 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 9932 // Shift the result. 9933 if (TrailingZeroes) 9934 return DAG.getNode(ISD::SHL, DL, VT, Res, 9935 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 9936 return Res; 9937 } 9938 9939 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 9940 SelectionDAG &DAG) { 9941 // Take advantage of vector comparisons producing 0 or -1 in each lane to 9942 // optimize away operation when it's from a constant. 9943 // 9944 // The general transformation is: 9945 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 9946 // AND(VECTOR_CMP(x,y), constant2) 9947 // constant2 = UNARYOP(constant) 9948 9949 // Early exit if this isn't a vector operation, the operand of the 9950 // unary operation isn't a bitwise AND, or if the sizes of the operations 9951 // aren't the same. 9952 EVT VT = N->getValueType(0); 9953 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 9954 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 9955 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 9956 return SDValue(); 9957 9958 // Now check that the other operand of the AND is a constant. We could 9959 // make the transformation for non-constant splats as well, but it's unclear 9960 // that would be a benefit as it would not eliminate any operations, just 9961 // perform one more step in scalar code before moving to the vector unit. 9962 if (BuildVectorSDNode *BV = 9963 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 9964 // Bail out if the vector isn't a constant. 9965 if (!BV->isConstant()) 9966 return SDValue(); 9967 9968 // Everything checks out. Build up the new and improved node. 9969 SDLoc DL(N); 9970 EVT IntVT = BV->getValueType(0); 9971 // Create a new constant of the appropriate type for the transformed 9972 // DAG. 9973 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 9974 // The AND node needs bitcasts to/from an integer vector type around it. 9975 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 9976 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 9977 N->getOperand(0)->getOperand(0), MaskConst); 9978 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 9979 return Res; 9980 } 9981 9982 return SDValue(); 9983 } 9984 9985 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 9986 const AArch64Subtarget *Subtarget) { 9987 // First try to optimize away the conversion when it's conditionally from 9988 // a constant. Vectors only. 9989 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 9990 return Res; 9991 9992 EVT VT = N->getValueType(0); 9993 if (VT != MVT::f32 && VT != MVT::f64) 9994 return SDValue(); 9995 9996 // Only optimize when the source and destination types have the same width. 9997 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 9998 return SDValue(); 9999 10000 // If the result of an integer load is only used by an integer-to-float 10001 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 10002 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 10003 SDValue N0 = N->getOperand(0); 10004 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10005 // Do not change the width of a volatile load. 10006 !cast<LoadSDNode>(N0)->isVolatile()) { 10007 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10008 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 10009 LN0->getPointerInfo(), LN0->getAlignment(), 10010 LN0->getMemOperand()->getFlags()); 10011 10012 // Make sure successors of the original load stay after it by updating them 10013 // to use the new Chain. 10014 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 10015 10016 unsigned Opcode = 10017 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 10018 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 10019 } 10020 10021 return SDValue(); 10022 } 10023 10024 /// Fold a floating-point multiply by power of two into floating-point to 10025 /// fixed-point conversion. 10026 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 10027 TargetLowering::DAGCombinerInfo &DCI, 10028 const AArch64Subtarget *Subtarget) { 10029 if (!Subtarget->hasNEON()) 10030 return SDValue(); 10031 10032 if (!N->getValueType(0).isSimple()) 10033 return SDValue(); 10034 10035 SDValue Op = N->getOperand(0); 10036 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10037 Op.getOpcode() != ISD::FMUL) 10038 return SDValue(); 10039 10040 SDValue ConstVec = Op->getOperand(1); 10041 if (!isa<BuildVectorSDNode>(ConstVec)) 10042 return SDValue(); 10043 10044 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10045 uint32_t FloatBits = FloatTy.getSizeInBits(); 10046 if (FloatBits != 32 && FloatBits != 64) 10047 return SDValue(); 10048 10049 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10050 uint32_t IntBits = IntTy.getSizeInBits(); 10051 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 10052 return SDValue(); 10053 10054 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 10055 if (IntBits > FloatBits) 10056 return SDValue(); 10057 10058 BitVector UndefElements; 10059 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10060 int32_t Bits = IntBits == 64 ? 64 : 32; 10061 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 10062 if (C == -1 || C == 0 || C > Bits) 10063 return SDValue(); 10064 10065 MVT ResTy; 10066 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10067 switch (NumLanes) { 10068 default: 10069 return SDValue(); 10070 case 2: 10071 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 10072 break; 10073 case 4: 10074 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 10075 break; 10076 } 10077 10078 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 10079 return SDValue(); 10080 10081 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 10082 "Illegal vector type after legalization"); 10083 10084 SDLoc DL(N); 10085 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 10086 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 10087 : Intrinsic::aarch64_neon_vcvtfp2fxu; 10088 SDValue FixConv = 10089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 10090 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 10091 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 10092 // We can handle smaller integers by generating an extra trunc. 10093 if (IntBits < FloatBits) 10094 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 10095 10096 return FixConv; 10097 } 10098 10099 /// Fold a floating-point divide by power of two into fixed-point to 10100 /// floating-point conversion. 10101 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 10102 TargetLowering::DAGCombinerInfo &DCI, 10103 const AArch64Subtarget *Subtarget) { 10104 if (!Subtarget->hasNEON()) 10105 return SDValue(); 10106 10107 SDValue Op = N->getOperand(0); 10108 unsigned Opc = Op->getOpcode(); 10109 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10110 !Op.getOperand(0).getValueType().isSimple() || 10111 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 10112 return SDValue(); 10113 10114 SDValue ConstVec = N->getOperand(1); 10115 if (!isa<BuildVectorSDNode>(ConstVec)) 10116 return SDValue(); 10117 10118 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10119 int32_t IntBits = IntTy.getSizeInBits(); 10120 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 10121 return SDValue(); 10122 10123 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10124 int32_t FloatBits = FloatTy.getSizeInBits(); 10125 if (FloatBits != 32 && FloatBits != 64) 10126 return SDValue(); 10127 10128 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 10129 if (IntBits > FloatBits) 10130 return SDValue(); 10131 10132 BitVector UndefElements; 10133 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10134 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 10135 if (C == -1 || C == 0 || C > FloatBits) 10136 return SDValue(); 10137 10138 MVT ResTy; 10139 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10140 switch (NumLanes) { 10141 default: 10142 return SDValue(); 10143 case 2: 10144 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 10145 break; 10146 case 4: 10147 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 10148 break; 10149 } 10150 10151 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 10152 return SDValue(); 10153 10154 SDLoc DL(N); 10155 SDValue ConvInput = Op.getOperand(0); 10156 bool IsSigned = Opc == ISD::SINT_TO_FP; 10157 if (IntBits < FloatBits) 10158 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 10159 ResTy, ConvInput); 10160 10161 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 10162 : Intrinsic::aarch64_neon_vcvtfxu2fp; 10163 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 10164 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 10165 DAG.getConstant(C, DL, MVT::i32)); 10166 } 10167 10168 /// An EXTR instruction is made up of two shifts, ORed together. This helper 10169 /// searches for and classifies those shifts. 10170 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 10171 bool &FromHi) { 10172 if (N.getOpcode() == ISD::SHL) 10173 FromHi = false; 10174 else if (N.getOpcode() == ISD::SRL) 10175 FromHi = true; 10176 else 10177 return false; 10178 10179 if (!isa<ConstantSDNode>(N.getOperand(1))) 10180 return false; 10181 10182 ShiftAmount = N->getConstantOperandVal(1); 10183 Src = N->getOperand(0); 10184 return true; 10185 } 10186 10187 /// EXTR instruction extracts a contiguous chunk of bits from two existing 10188 /// registers viewed as a high/low pair. This function looks for the pattern: 10189 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 10190 /// with an EXTR. Can't quite be done in TableGen because the two immediates 10191 /// aren't independent. 10192 static SDValue tryCombineToEXTR(SDNode *N, 10193 TargetLowering::DAGCombinerInfo &DCI) { 10194 SelectionDAG &DAG = DCI.DAG; 10195 SDLoc DL(N); 10196 EVT VT = N->getValueType(0); 10197 10198 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 10199 10200 if (VT != MVT::i32 && VT != MVT::i64) 10201 return SDValue(); 10202 10203 SDValue LHS; 10204 uint32_t ShiftLHS = 0; 10205 bool LHSFromHi = false; 10206 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 10207 return SDValue(); 10208 10209 SDValue RHS; 10210 uint32_t ShiftRHS = 0; 10211 bool RHSFromHi = false; 10212 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 10213 return SDValue(); 10214 10215 // If they're both trying to come from the high part of the register, they're 10216 // not really an EXTR. 10217 if (LHSFromHi == RHSFromHi) 10218 return SDValue(); 10219 10220 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 10221 return SDValue(); 10222 10223 if (LHSFromHi) { 10224 std::swap(LHS, RHS); 10225 std::swap(ShiftLHS, ShiftRHS); 10226 } 10227 10228 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 10229 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 10230 } 10231 10232 static SDValue tryCombineToBSL(SDNode *N, 10233 TargetLowering::DAGCombinerInfo &DCI) { 10234 EVT VT = N->getValueType(0); 10235 SelectionDAG &DAG = DCI.DAG; 10236 SDLoc DL(N); 10237 10238 if (!VT.isVector()) 10239 return SDValue(); 10240 10241 SDValue N0 = N->getOperand(0); 10242 if (N0.getOpcode() != ISD::AND) 10243 return SDValue(); 10244 10245 SDValue N1 = N->getOperand(1); 10246 if (N1.getOpcode() != ISD::AND) 10247 return SDValue(); 10248 10249 // We only have to look for constant vectors here since the general, variable 10250 // case can be handled in TableGen. 10251 unsigned Bits = VT.getScalarSizeInBits(); 10252 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 10253 for (int i = 1; i >= 0; --i) 10254 for (int j = 1; j >= 0; --j) { 10255 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 10256 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 10257 if (!BVN0 || !BVN1) 10258 continue; 10259 10260 bool FoundMatch = true; 10261 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 10262 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 10263 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 10264 if (!CN0 || !CN1 || 10265 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 10266 FoundMatch = false; 10267 break; 10268 } 10269 } 10270 10271 if (FoundMatch) 10272 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0), 10273 N0->getOperand(1 - i), N1->getOperand(1 - j)); 10274 } 10275 10276 return SDValue(); 10277 } 10278 10279 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 10280 const AArch64Subtarget *Subtarget) { 10281 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 10282 SelectionDAG &DAG = DCI.DAG; 10283 EVT VT = N->getValueType(0); 10284 10285 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10286 return SDValue(); 10287 10288 if (SDValue Res = tryCombineToEXTR(N, DCI)) 10289 return Res; 10290 10291 if (SDValue Res = tryCombineToBSL(N, DCI)) 10292 return Res; 10293 10294 return SDValue(); 10295 } 10296 10297 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) { 10298 if (!MemVT.getVectorElementType().isSimple()) 10299 return false; 10300 10301 uint64_t MaskForTy = 0ull; 10302 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) { 10303 case MVT::i8: 10304 MaskForTy = 0xffull; 10305 break; 10306 case MVT::i16: 10307 MaskForTy = 0xffffull; 10308 break; 10309 case MVT::i32: 10310 MaskForTy = 0xffffffffull; 10311 break; 10312 default: 10313 return false; 10314 break; 10315 } 10316 10317 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR) 10318 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) 10319 return Op0->getAPIntValue().getLimitedValue() == MaskForTy; 10320 10321 return false; 10322 } 10323 10324 static SDValue performSVEAndCombine(SDNode *N, 10325 TargetLowering::DAGCombinerInfo &DCI) { 10326 if (DCI.isBeforeLegalizeOps()) 10327 return SDValue(); 10328 10329 SDValue Src = N->getOperand(0); 10330 SDValue Mask = N->getOperand(1); 10331 10332 if (!Src.hasOneUse()) 10333 return SDValue(); 10334 10335 EVT MemVT; 10336 10337 // SVE load instructions perform an implicit zero-extend, which makes them 10338 // perfect candidates for combining. 10339 switch (Src->getOpcode()) { 10340 case AArch64ISD::LDNF1: 10341 case AArch64ISD::LDFF1: 10342 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT(); 10343 break; 10344 case AArch64ISD::GLD1: 10345 case AArch64ISD::GLD1_SCALED: 10346 case AArch64ISD::GLD1_SXTW: 10347 case AArch64ISD::GLD1_SXTW_SCALED: 10348 case AArch64ISD::GLD1_UXTW: 10349 case AArch64ISD::GLD1_UXTW_SCALED: 10350 case AArch64ISD::GLD1_IMM: 10351 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT(); 10352 break; 10353 default: 10354 return SDValue(); 10355 } 10356 10357 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT)) 10358 return Src; 10359 10360 return SDValue(); 10361 } 10362 10363 static SDValue performANDCombine(SDNode *N, 10364 TargetLowering::DAGCombinerInfo &DCI) { 10365 SelectionDAG &DAG = DCI.DAG; 10366 SDValue LHS = N->getOperand(0); 10367 EVT VT = N->getValueType(0); 10368 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10369 return SDValue(); 10370 10371 if (VT.isScalableVector()) 10372 return performSVEAndCombine(N, DCI); 10373 10374 BuildVectorSDNode *BVN = 10375 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 10376 if (!BVN) 10377 return SDValue(); 10378 10379 // AND does not accept an immediate, so check if we can use a BIC immediate 10380 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 10381 // pattern in isel, because some immediates may be lowered to the preferred 10382 // (and x, (movi imm)) form, even though an mvni representation also exists. 10383 APInt DefBits(VT.getSizeInBits(), 0); 10384 APInt UndefBits(VT.getSizeInBits(), 0); 10385 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 10386 SDValue NewOp; 10387 10388 DefBits = ~DefBits; 10389 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 10390 DefBits, &LHS)) || 10391 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 10392 DefBits, &LHS))) 10393 return NewOp; 10394 10395 UndefBits = ~UndefBits; 10396 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 10397 UndefBits, &LHS)) || 10398 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 10399 UndefBits, &LHS))) 10400 return NewOp; 10401 } 10402 10403 return SDValue(); 10404 } 10405 10406 static SDValue performSRLCombine(SDNode *N, 10407 TargetLowering::DAGCombinerInfo &DCI) { 10408 SelectionDAG &DAG = DCI.DAG; 10409 EVT VT = N->getValueType(0); 10410 if (VT != MVT::i32 && VT != MVT::i64) 10411 return SDValue(); 10412 10413 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 10414 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 10415 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 10416 SDValue N0 = N->getOperand(0); 10417 if (N0.getOpcode() == ISD::BSWAP) { 10418 SDLoc DL(N); 10419 SDValue N1 = N->getOperand(1); 10420 SDValue N00 = N0.getOperand(0); 10421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10422 uint64_t ShiftAmt = C->getZExtValue(); 10423 if (VT == MVT::i32 && ShiftAmt == 16 && 10424 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 10425 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 10426 if (VT == MVT::i64 && ShiftAmt == 32 && 10427 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 10428 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 10429 } 10430 } 10431 return SDValue(); 10432 } 10433 10434 static SDValue performConcatVectorsCombine(SDNode *N, 10435 TargetLowering::DAGCombinerInfo &DCI, 10436 SelectionDAG &DAG) { 10437 SDLoc dl(N); 10438 EVT VT = N->getValueType(0); 10439 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 10440 10441 // Optimize concat_vectors of truncated vectors, where the intermediate 10442 // type is illegal, to avoid said illegality, e.g., 10443 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 10444 // (v2i16 (truncate (v2i64))))) 10445 // -> 10446 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 10447 // (v4i32 (bitcast (v2i64))), 10448 // <0, 2, 4, 6>))) 10449 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 10450 // on both input and result type, so we might generate worse code. 10451 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 10452 if (N->getNumOperands() == 2 && 10453 N0->getOpcode() == ISD::TRUNCATE && 10454 N1->getOpcode() == ISD::TRUNCATE) { 10455 SDValue N00 = N0->getOperand(0); 10456 SDValue N10 = N1->getOperand(0); 10457 EVT N00VT = N00.getValueType(); 10458 10459 if (N00VT == N10.getValueType() && 10460 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 10461 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 10462 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 10463 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 10464 for (size_t i = 0; i < Mask.size(); ++i) 10465 Mask[i] = i * 2; 10466 return DAG.getNode(ISD::TRUNCATE, dl, VT, 10467 DAG.getVectorShuffle( 10468 MidVT, dl, 10469 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 10470 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 10471 } 10472 } 10473 10474 // Wait 'til after everything is legalized to try this. That way we have 10475 // legal vector types and such. 10476 if (DCI.isBeforeLegalizeOps()) 10477 return SDValue(); 10478 10479 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 10480 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 10481 // canonicalise to that. 10482 if (N0 == N1 && VT.getVectorNumElements() == 2) { 10483 assert(VT.getScalarSizeInBits() == 64); 10484 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 10485 DAG.getConstant(0, dl, MVT::i64)); 10486 } 10487 10488 // Canonicalise concat_vectors so that the right-hand vector has as few 10489 // bit-casts as possible before its real operation. The primary matching 10490 // destination for these operations will be the narrowing "2" instructions, 10491 // which depend on the operation being performed on this right-hand vector. 10492 // For example, 10493 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 10494 // becomes 10495 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 10496 10497 if (N1->getOpcode() != ISD::BITCAST) 10498 return SDValue(); 10499 SDValue RHS = N1->getOperand(0); 10500 MVT RHSTy = RHS.getValueType().getSimpleVT(); 10501 // If the RHS is not a vector, this is not the pattern we're looking for. 10502 if (!RHSTy.isVector()) 10503 return SDValue(); 10504 10505 LLVM_DEBUG( 10506 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 10507 10508 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 10509 RHSTy.getVectorNumElements() * 2); 10510 return DAG.getNode(ISD::BITCAST, dl, VT, 10511 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 10512 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 10513 RHS)); 10514 } 10515 10516 static SDValue tryCombineFixedPointConvert(SDNode *N, 10517 TargetLowering::DAGCombinerInfo &DCI, 10518 SelectionDAG &DAG) { 10519 // Wait until after everything is legalized to try this. That way we have 10520 // legal vector types and such. 10521 if (DCI.isBeforeLegalizeOps()) 10522 return SDValue(); 10523 // Transform a scalar conversion of a value from a lane extract into a 10524 // lane extract of a vector conversion. E.g., from foo1 to foo2: 10525 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 10526 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 10527 // 10528 // The second form interacts better with instruction selection and the 10529 // register allocator to avoid cross-class register copies that aren't 10530 // coalescable due to a lane reference. 10531 10532 // Check the operand and see if it originates from a lane extract. 10533 SDValue Op1 = N->getOperand(1); 10534 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10535 // Yep, no additional predication needed. Perform the transform. 10536 SDValue IID = N->getOperand(0); 10537 SDValue Shift = N->getOperand(2); 10538 SDValue Vec = Op1.getOperand(0); 10539 SDValue Lane = Op1.getOperand(1); 10540 EVT ResTy = N->getValueType(0); 10541 EVT VecResTy; 10542 SDLoc DL(N); 10543 10544 // The vector width should be 128 bits by the time we get here, even 10545 // if it started as 64 bits (the extract_vector handling will have 10546 // done so). 10547 assert(Vec.getValueSizeInBits() == 128 && 10548 "unexpected vector size on extract_vector_elt!"); 10549 if (Vec.getValueType() == MVT::v4i32) 10550 VecResTy = MVT::v4f32; 10551 else if (Vec.getValueType() == MVT::v2i64) 10552 VecResTy = MVT::v2f64; 10553 else 10554 llvm_unreachable("unexpected vector type!"); 10555 10556 SDValue Convert = 10557 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 10558 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 10559 } 10560 return SDValue(); 10561 } 10562 10563 // AArch64 high-vector "long" operations are formed by performing the non-high 10564 // version on an extract_subvector of each operand which gets the high half: 10565 // 10566 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 10567 // 10568 // However, there are cases which don't have an extract_high explicitly, but 10569 // have another operation that can be made compatible with one for free. For 10570 // example: 10571 // 10572 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 10573 // 10574 // This routine does the actual conversion of such DUPs, once outer routines 10575 // have determined that everything else is in order. 10576 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 10577 // similarly here. 10578 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 10579 switch (N.getOpcode()) { 10580 case AArch64ISD::DUP: 10581 case AArch64ISD::DUPLANE8: 10582 case AArch64ISD::DUPLANE16: 10583 case AArch64ISD::DUPLANE32: 10584 case AArch64ISD::DUPLANE64: 10585 case AArch64ISD::MOVI: 10586 case AArch64ISD::MOVIshift: 10587 case AArch64ISD::MOVIedit: 10588 case AArch64ISD::MOVImsl: 10589 case AArch64ISD::MVNIshift: 10590 case AArch64ISD::MVNImsl: 10591 break; 10592 default: 10593 // FMOV could be supported, but isn't very useful, as it would only occur 10594 // if you passed a bitcast' floating point immediate to an eligible long 10595 // integer op (addl, smull, ...). 10596 return SDValue(); 10597 } 10598 10599 MVT NarrowTy = N.getSimpleValueType(); 10600 if (!NarrowTy.is64BitVector()) 10601 return SDValue(); 10602 10603 MVT ElementTy = NarrowTy.getVectorElementType(); 10604 unsigned NumElems = NarrowTy.getVectorNumElements(); 10605 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 10606 10607 SDLoc dl(N); 10608 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 10609 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 10610 DAG.getConstant(NumElems, dl, MVT::i64)); 10611 } 10612 10613 static bool isEssentiallyExtractHighSubvector(SDValue N) { 10614 if (N.getOpcode() == ISD::BITCAST) 10615 N = N.getOperand(0); 10616 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10617 return false; 10618 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 10619 N.getOperand(0).getValueType().getVectorNumElements() / 2; 10620 } 10621 10622 /// Helper structure to keep track of ISD::SET_CC operands. 10623 struct GenericSetCCInfo { 10624 const SDValue *Opnd0; 10625 const SDValue *Opnd1; 10626 ISD::CondCode CC; 10627 }; 10628 10629 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 10630 struct AArch64SetCCInfo { 10631 const SDValue *Cmp; 10632 AArch64CC::CondCode CC; 10633 }; 10634 10635 /// Helper structure to keep track of SetCC information. 10636 union SetCCInfo { 10637 GenericSetCCInfo Generic; 10638 AArch64SetCCInfo AArch64; 10639 }; 10640 10641 /// Helper structure to be able to read SetCC information. If set to 10642 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 10643 /// GenericSetCCInfo. 10644 struct SetCCInfoAndKind { 10645 SetCCInfo Info; 10646 bool IsAArch64; 10647 }; 10648 10649 /// Check whether or not \p Op is a SET_CC operation, either a generic or 10650 /// an 10651 /// AArch64 lowered one. 10652 /// \p SetCCInfo is filled accordingly. 10653 /// \post SetCCInfo is meanginfull only when this function returns true. 10654 /// \return True when Op is a kind of SET_CC operation. 10655 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 10656 // If this is a setcc, this is straight forward. 10657 if (Op.getOpcode() == ISD::SETCC) { 10658 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 10659 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 10660 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10661 SetCCInfo.IsAArch64 = false; 10662 return true; 10663 } 10664 // Otherwise, check if this is a matching csel instruction. 10665 // In other words: 10666 // - csel 1, 0, cc 10667 // - csel 0, 1, !cc 10668 if (Op.getOpcode() != AArch64ISD::CSEL) 10669 return false; 10670 // Set the information about the operands. 10671 // TODO: we want the operands of the Cmp not the csel 10672 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 10673 SetCCInfo.IsAArch64 = true; 10674 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 10675 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10676 10677 // Check that the operands matches the constraints: 10678 // (1) Both operands must be constants. 10679 // (2) One must be 1 and the other must be 0. 10680 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 10681 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10682 10683 // Check (1). 10684 if (!TValue || !FValue) 10685 return false; 10686 10687 // Check (2). 10688 if (!TValue->isOne()) { 10689 // Update the comparison when we are interested in !cc. 10690 std::swap(TValue, FValue); 10691 SetCCInfo.Info.AArch64.CC = 10692 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 10693 } 10694 return TValue->isOne() && FValue->isNullValue(); 10695 } 10696 10697 // Returns true if Op is setcc or zext of setcc. 10698 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 10699 if (isSetCC(Op, Info)) 10700 return true; 10701 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 10702 isSetCC(Op->getOperand(0), Info)); 10703 } 10704 10705 // The folding we want to perform is: 10706 // (add x, [zext] (setcc cc ...) ) 10707 // --> 10708 // (csel x, (add x, 1), !cc ...) 10709 // 10710 // The latter will get matched to a CSINC instruction. 10711 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 10712 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 10713 SDValue LHS = Op->getOperand(0); 10714 SDValue RHS = Op->getOperand(1); 10715 SetCCInfoAndKind InfoAndKind; 10716 10717 // If neither operand is a SET_CC, give up. 10718 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 10719 std::swap(LHS, RHS); 10720 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 10721 return SDValue(); 10722 } 10723 10724 // FIXME: This could be generatized to work for FP comparisons. 10725 EVT CmpVT = InfoAndKind.IsAArch64 10726 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 10727 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 10728 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 10729 return SDValue(); 10730 10731 SDValue CCVal; 10732 SDValue Cmp; 10733 SDLoc dl(Op); 10734 if (InfoAndKind.IsAArch64) { 10735 CCVal = DAG.getConstant( 10736 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 10737 MVT::i32); 10738 Cmp = *InfoAndKind.Info.AArch64.Cmp; 10739 } else 10740 Cmp = getAArch64Cmp( 10741 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, 10742 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG, 10743 dl); 10744 10745 EVT VT = Op->getValueType(0); 10746 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 10747 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 10748 } 10749 10750 // The basic add/sub long vector instructions have variants with "2" on the end 10751 // which act on the high-half of their inputs. They are normally matched by 10752 // patterns like: 10753 // 10754 // (add (zeroext (extract_high LHS)), 10755 // (zeroext (extract_high RHS))) 10756 // -> uaddl2 vD, vN, vM 10757 // 10758 // However, if one of the extracts is something like a duplicate, this 10759 // instruction can still be used profitably. This function puts the DAG into a 10760 // more appropriate form for those patterns to trigger. 10761 static SDValue performAddSubLongCombine(SDNode *N, 10762 TargetLowering::DAGCombinerInfo &DCI, 10763 SelectionDAG &DAG) { 10764 if (DCI.isBeforeLegalizeOps()) 10765 return SDValue(); 10766 10767 MVT VT = N->getSimpleValueType(0); 10768 if (!VT.is128BitVector()) { 10769 if (N->getOpcode() == ISD::ADD) 10770 return performSetccAddFolding(N, DAG); 10771 return SDValue(); 10772 } 10773 10774 // Make sure both branches are extended in the same way. 10775 SDValue LHS = N->getOperand(0); 10776 SDValue RHS = N->getOperand(1); 10777 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 10778 LHS.getOpcode() != ISD::SIGN_EXTEND) || 10779 LHS.getOpcode() != RHS.getOpcode()) 10780 return SDValue(); 10781 10782 unsigned ExtType = LHS.getOpcode(); 10783 10784 // It's not worth doing if at least one of the inputs isn't already an 10785 // extract, but we don't know which it'll be so we have to try both. 10786 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 10787 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 10788 if (!RHS.getNode()) 10789 return SDValue(); 10790 10791 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 10792 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 10793 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 10794 if (!LHS.getNode()) 10795 return SDValue(); 10796 10797 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 10798 } 10799 10800 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 10801 } 10802 10803 // Massage DAGs which we can use the high-half "long" operations on into 10804 // something isel will recognize better. E.g. 10805 // 10806 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 10807 // (aarch64_neon_umull (extract_high (v2i64 vec))) 10808 // (extract_high (v2i64 (dup128 scalar))))) 10809 // 10810 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 10811 TargetLowering::DAGCombinerInfo &DCI, 10812 SelectionDAG &DAG) { 10813 if (DCI.isBeforeLegalizeOps()) 10814 return SDValue(); 10815 10816 SDValue LHS = N->getOperand(1); 10817 SDValue RHS = N->getOperand(2); 10818 assert(LHS.getValueType().is64BitVector() && 10819 RHS.getValueType().is64BitVector() && 10820 "unexpected shape for long operation"); 10821 10822 // Either node could be a DUP, but it's not worth doing both of them (you'd 10823 // just as well use the non-high version) so look for a corresponding extract 10824 // operation on the other "wing". 10825 if (isEssentiallyExtractHighSubvector(LHS)) { 10826 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 10827 if (!RHS.getNode()) 10828 return SDValue(); 10829 } else if (isEssentiallyExtractHighSubvector(RHS)) { 10830 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 10831 if (!LHS.getNode()) 10832 return SDValue(); 10833 } 10834 10835 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 10836 N->getOperand(0), LHS, RHS); 10837 } 10838 10839 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 10840 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 10841 unsigned ElemBits = ElemTy.getSizeInBits(); 10842 10843 int64_t ShiftAmount; 10844 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 10845 APInt SplatValue, SplatUndef; 10846 unsigned SplatBitSize; 10847 bool HasAnyUndefs; 10848 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 10849 HasAnyUndefs, ElemBits) || 10850 SplatBitSize != ElemBits) 10851 return SDValue(); 10852 10853 ShiftAmount = SplatValue.getSExtValue(); 10854 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 10855 ShiftAmount = CVN->getSExtValue(); 10856 } else 10857 return SDValue(); 10858 10859 unsigned Opcode; 10860 bool IsRightShift; 10861 switch (IID) { 10862 default: 10863 llvm_unreachable("Unknown shift intrinsic"); 10864 case Intrinsic::aarch64_neon_sqshl: 10865 Opcode = AArch64ISD::SQSHL_I; 10866 IsRightShift = false; 10867 break; 10868 case Intrinsic::aarch64_neon_uqshl: 10869 Opcode = AArch64ISD::UQSHL_I; 10870 IsRightShift = false; 10871 break; 10872 case Intrinsic::aarch64_neon_srshl: 10873 Opcode = AArch64ISD::SRSHR_I; 10874 IsRightShift = true; 10875 break; 10876 case Intrinsic::aarch64_neon_urshl: 10877 Opcode = AArch64ISD::URSHR_I; 10878 IsRightShift = true; 10879 break; 10880 case Intrinsic::aarch64_neon_sqshlu: 10881 Opcode = AArch64ISD::SQSHLU_I; 10882 IsRightShift = false; 10883 break; 10884 case Intrinsic::aarch64_neon_sshl: 10885 case Intrinsic::aarch64_neon_ushl: 10886 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 10887 // left shift for positive shift amounts. Below, we only replace the current 10888 // node with VSHL, if this condition is met. 10889 Opcode = AArch64ISD::VSHL; 10890 IsRightShift = false; 10891 break; 10892 } 10893 10894 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 10895 SDLoc dl(N); 10896 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 10897 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 10898 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 10899 SDLoc dl(N); 10900 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 10901 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 10902 } 10903 10904 return SDValue(); 10905 } 10906 10907 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 10908 // the intrinsics must be legal and take an i32, this means there's almost 10909 // certainly going to be a zext in the DAG which we can eliminate. 10910 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 10911 SDValue AndN = N->getOperand(2); 10912 if (AndN.getOpcode() != ISD::AND) 10913 return SDValue(); 10914 10915 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 10916 if (!CMask || CMask->getZExtValue() != Mask) 10917 return SDValue(); 10918 10919 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 10920 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 10921 } 10922 10923 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 10924 SelectionDAG &DAG) { 10925 SDLoc dl(N); 10926 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 10927 DAG.getNode(Opc, dl, 10928 N->getOperand(1).getSimpleValueType(), 10929 N->getOperand(1)), 10930 DAG.getConstant(0, dl, MVT::i64)); 10931 } 10932 10933 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc, 10934 SelectionDAG &DAG) { 10935 SDLoc dl(N); 10936 LLVMContext &Ctx = *DAG.getContext(); 10937 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10938 10939 EVT VT = N->getValueType(0); 10940 SDValue Pred = N->getOperand(1); 10941 SDValue Data = N->getOperand(2); 10942 EVT DataVT = Data.getValueType(); 10943 10944 if (DataVT.getVectorElementType().isScalarInteger() && 10945 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) { 10946 if (!TLI.isTypeLegal(DataVT)) 10947 return SDValue(); 10948 10949 EVT OutputVT = EVT::getVectorVT(Ctx, VT, 10950 AArch64::NeonBitsPerVector / VT.getSizeInBits()); 10951 SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data); 10952 SDValue Zero = DAG.getConstant(0, dl, MVT::i64); 10953 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero); 10954 10955 return Result; 10956 } 10957 10958 return SDValue(); 10959 } 10960 10961 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) { 10962 SDLoc DL(N); 10963 SDValue Op1 = N->getOperand(1); 10964 SDValue Op2 = N->getOperand(2); 10965 EVT ScalarTy = Op1.getValueType(); 10966 10967 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) { 10968 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1); 10969 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2); 10970 } 10971 10972 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0), 10973 Op1, Op2); 10974 } 10975 10976 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) { 10977 SDLoc dl(N); 10978 SDValue Scalar = N->getOperand(3); 10979 EVT ScalarTy = Scalar.getValueType(); 10980 10981 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 10982 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 10983 10984 return DAG.getNode(AArch64ISD::DUP_PRED, dl, N->getValueType(0), 10985 N->getOperand(1), N->getOperand(2), Scalar); 10986 } 10987 10988 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) { 10989 SDLoc dl(N); 10990 LLVMContext &Ctx = *DAG.getContext(); 10991 EVT VT = N->getValueType(0); 10992 10993 assert(VT.isScalableVector() && "Expected a scalable vector."); 10994 10995 // Current lowering only supports the SVE-ACLE types. 10996 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 10997 return SDValue(); 10998 10999 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8; 11000 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8; 11001 EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true }); 11002 11003 // Convert everything to the domain of EXT (i.e bytes). 11004 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1)); 11005 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2)); 11006 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3), 11007 DAG.getConstant(ElemSize, dl, MVT::i32)); 11008 11009 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2); 11010 return DAG.getNode(ISD::BITCAST, dl, VT, EXT); 11011 } 11012 11013 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID, 11014 bool Invert, 11015 TargetLowering::DAGCombinerInfo &DCI, 11016 SelectionDAG &DAG) { 11017 if (DCI.isBeforeLegalize()) 11018 return SDValue(); 11019 11020 SDValue Comparator = N->getOperand(3); 11021 if (Comparator.getOpcode() == AArch64ISD::DUP || 11022 Comparator.getOpcode() == ISD::SPLAT_VECTOR) { 11023 unsigned IID = getIntrinsicID(N); 11024 EVT VT = N->getValueType(0); 11025 EVT CmpVT = N->getOperand(2).getValueType(); 11026 SDValue Pred = N->getOperand(1); 11027 SDValue Imm; 11028 SDLoc DL(N); 11029 11030 switch (IID) { 11031 default: 11032 llvm_unreachable("Called with wrong intrinsic!"); 11033 break; 11034 11035 // Signed comparisons 11036 case Intrinsic::aarch64_sve_cmpeq_wide: 11037 case Intrinsic::aarch64_sve_cmpne_wide: 11038 case Intrinsic::aarch64_sve_cmpge_wide: 11039 case Intrinsic::aarch64_sve_cmpgt_wide: 11040 case Intrinsic::aarch64_sve_cmplt_wide: 11041 case Intrinsic::aarch64_sve_cmple_wide: { 11042 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 11043 int64_t ImmVal = CN->getSExtValue(); 11044 if (ImmVal >= -16 && ImmVal <= 15) 11045 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 11046 else 11047 return SDValue(); 11048 } 11049 break; 11050 } 11051 // Unsigned comparisons 11052 case Intrinsic::aarch64_sve_cmphs_wide: 11053 case Intrinsic::aarch64_sve_cmphi_wide: 11054 case Intrinsic::aarch64_sve_cmplo_wide: 11055 case Intrinsic::aarch64_sve_cmpls_wide: { 11056 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 11057 uint64_t ImmVal = CN->getZExtValue(); 11058 if (ImmVal <= 127) 11059 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 11060 else 11061 return SDValue(); 11062 } 11063 break; 11064 } 11065 } 11066 11067 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm); 11068 SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64); 11069 SDValue Op0, Op1; 11070 if (Invert) { 11071 Op0 = Splat; 11072 Op1 = N->getOperand(2); 11073 } else { 11074 Op0 = N->getOperand(2); 11075 Op1 = Splat; 11076 } 11077 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11078 ID, Pred, Op0, Op1); 11079 } 11080 11081 return SDValue(); 11082 } 11083 11084 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op, 11085 AArch64CC::CondCode Cond) { 11086 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11087 11088 SDLoc DL(Op); 11089 assert(Op.getValueType().isScalableVector() && 11090 TLI.isTypeLegal(Op.getValueType()) && 11091 "Expected legal scalable vector type!"); 11092 11093 // Ensure target specific opcodes are using legal type. 11094 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 11095 SDValue TVal = DAG.getConstant(1, DL, OutVT); 11096 SDValue FVal = DAG.getConstant(0, DL, OutVT); 11097 11098 // Set condition code (CC) flags. 11099 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op); 11100 11101 // Convert CC to integer based on requested condition. 11102 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare. 11103 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32); 11104 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test); 11105 return DAG.getZExtOrTrunc(Res, DL, VT); 11106 } 11107 11108 static SDValue performIntrinsicCombine(SDNode *N, 11109 TargetLowering::DAGCombinerInfo &DCI, 11110 const AArch64Subtarget *Subtarget) { 11111 SelectionDAG &DAG = DCI.DAG; 11112 unsigned IID = getIntrinsicID(N); 11113 switch (IID) { 11114 default: 11115 break; 11116 case Intrinsic::aarch64_neon_vcvtfxs2fp: 11117 case Intrinsic::aarch64_neon_vcvtfxu2fp: 11118 return tryCombineFixedPointConvert(N, DCI, DAG); 11119 case Intrinsic::aarch64_neon_saddv: 11120 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 11121 case Intrinsic::aarch64_neon_uaddv: 11122 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 11123 case Intrinsic::aarch64_neon_sminv: 11124 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 11125 case Intrinsic::aarch64_neon_uminv: 11126 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 11127 case Intrinsic::aarch64_neon_smaxv: 11128 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 11129 case Intrinsic::aarch64_neon_umaxv: 11130 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 11131 case Intrinsic::aarch64_neon_fmax: 11132 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 11133 N->getOperand(1), N->getOperand(2)); 11134 case Intrinsic::aarch64_neon_fmin: 11135 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 11136 N->getOperand(1), N->getOperand(2)); 11137 case Intrinsic::aarch64_neon_fmaxnm: 11138 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 11139 N->getOperand(1), N->getOperand(2)); 11140 case Intrinsic::aarch64_neon_fminnm: 11141 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 11142 N->getOperand(1), N->getOperand(2)); 11143 case Intrinsic::aarch64_neon_smull: 11144 case Intrinsic::aarch64_neon_umull: 11145 case Intrinsic::aarch64_neon_pmull: 11146 case Intrinsic::aarch64_neon_sqdmull: 11147 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 11148 case Intrinsic::aarch64_neon_sqshl: 11149 case Intrinsic::aarch64_neon_uqshl: 11150 case Intrinsic::aarch64_neon_sqshlu: 11151 case Intrinsic::aarch64_neon_srshl: 11152 case Intrinsic::aarch64_neon_urshl: 11153 case Intrinsic::aarch64_neon_sshl: 11154 case Intrinsic::aarch64_neon_ushl: 11155 return tryCombineShiftImm(IID, N, DAG); 11156 case Intrinsic::aarch64_crc32b: 11157 case Intrinsic::aarch64_crc32cb: 11158 return tryCombineCRC32(0xff, N, DAG); 11159 case Intrinsic::aarch64_crc32h: 11160 case Intrinsic::aarch64_crc32ch: 11161 return tryCombineCRC32(0xffff, N, DAG); 11162 case Intrinsic::aarch64_sve_smaxv: 11163 return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG); 11164 case Intrinsic::aarch64_sve_umaxv: 11165 return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG); 11166 case Intrinsic::aarch64_sve_sminv: 11167 return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG); 11168 case Intrinsic::aarch64_sve_uminv: 11169 return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG); 11170 case Intrinsic::aarch64_sve_orv: 11171 return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG); 11172 case Intrinsic::aarch64_sve_eorv: 11173 return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG); 11174 case Intrinsic::aarch64_sve_andv: 11175 return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG); 11176 case Intrinsic::aarch64_sve_index: 11177 return LowerSVEIntrinsicIndex(N, DAG); 11178 case Intrinsic::aarch64_sve_dup: 11179 return LowerSVEIntrinsicDUP(N, DAG); 11180 case Intrinsic::aarch64_sve_ext: 11181 return LowerSVEIntrinsicEXT(N, DAG); 11182 case Intrinsic::aarch64_sve_cmpeq_wide: 11183 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq, 11184 false, DCI, DAG); 11185 case Intrinsic::aarch64_sve_cmpne_wide: 11186 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne, 11187 false, DCI, DAG); 11188 case Intrinsic::aarch64_sve_cmpge_wide: 11189 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge, 11190 false, DCI, DAG); 11191 case Intrinsic::aarch64_sve_cmpgt_wide: 11192 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt, 11193 false, DCI, DAG); 11194 case Intrinsic::aarch64_sve_cmplt_wide: 11195 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt, 11196 true, DCI, DAG); 11197 case Intrinsic::aarch64_sve_cmple_wide: 11198 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge, 11199 true, DCI, DAG); 11200 case Intrinsic::aarch64_sve_cmphs_wide: 11201 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, 11202 false, DCI, DAG); 11203 case Intrinsic::aarch64_sve_cmphi_wide: 11204 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, 11205 false, DCI, DAG); 11206 case Intrinsic::aarch64_sve_cmplo_wide: 11207 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true, 11208 DCI, DAG); 11209 case Intrinsic::aarch64_sve_cmpls_wide: 11210 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true, 11211 DCI, DAG); 11212 case Intrinsic::aarch64_sve_ptest_any: 11213 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11214 AArch64CC::ANY_ACTIVE); 11215 case Intrinsic::aarch64_sve_ptest_first: 11216 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11217 AArch64CC::FIRST_ACTIVE); 11218 case Intrinsic::aarch64_sve_ptest_last: 11219 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11220 AArch64CC::LAST_ACTIVE); 11221 } 11222 return SDValue(); 11223 } 11224 11225 static SDValue performExtendCombine(SDNode *N, 11226 TargetLowering::DAGCombinerInfo &DCI, 11227 SelectionDAG &DAG) { 11228 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 11229 // we can convert that DUP into another extract_high (of a bigger DUP), which 11230 // helps the backend to decide that an sabdl2 would be useful, saving a real 11231 // extract_high operation. 11232 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 11233 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 11234 SDNode *ABDNode = N->getOperand(0).getNode(); 11235 unsigned IID = getIntrinsicID(ABDNode); 11236 if (IID == Intrinsic::aarch64_neon_sabd || 11237 IID == Intrinsic::aarch64_neon_uabd) { 11238 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 11239 if (!NewABD.getNode()) 11240 return SDValue(); 11241 11242 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 11243 NewABD); 11244 } 11245 } 11246 11247 // This is effectively a custom type legalization for AArch64. 11248 // 11249 // Type legalization will split an extend of a small, legal, type to a larger 11250 // illegal type by first splitting the destination type, often creating 11251 // illegal source types, which then get legalized in isel-confusing ways, 11252 // leading to really terrible codegen. E.g., 11253 // %result = v8i32 sext v8i8 %value 11254 // becomes 11255 // %losrc = extract_subreg %value, ... 11256 // %hisrc = extract_subreg %value, ... 11257 // %lo = v4i32 sext v4i8 %losrc 11258 // %hi = v4i32 sext v4i8 %hisrc 11259 // Things go rapidly downhill from there. 11260 // 11261 // For AArch64, the [sz]ext vector instructions can only go up one element 11262 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 11263 // take two instructions. 11264 // 11265 // This implies that the most efficient way to do the extend from v8i8 11266 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 11267 // the normal splitting to happen for the v8i16->v8i32. 11268 11269 // This is pre-legalization to catch some cases where the default 11270 // type legalization will create ill-tempered code. 11271 if (!DCI.isBeforeLegalizeOps()) 11272 return SDValue(); 11273 11274 // We're only interested in cleaning things up for non-legal vector types 11275 // here. If both the source and destination are legal, things will just 11276 // work naturally without any fiddling. 11277 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11278 EVT ResVT = N->getValueType(0); 11279 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 11280 return SDValue(); 11281 // If the vector type isn't a simple VT, it's beyond the scope of what 11282 // we're worried about here. Let legalization do its thing and hope for 11283 // the best. 11284 SDValue Src = N->getOperand(0); 11285 EVT SrcVT = Src->getValueType(0); 11286 if (!ResVT.isSimple() || !SrcVT.isSimple()) 11287 return SDValue(); 11288 11289 // If the source VT is a 64-bit vector, we can play games and get the 11290 // better results we want. 11291 if (SrcVT.getSizeInBits() != 64) 11292 return SDValue(); 11293 11294 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 11295 unsigned ElementCount = SrcVT.getVectorNumElements(); 11296 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 11297 SDLoc DL(N); 11298 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 11299 11300 // Now split the rest of the operation into two halves, each with a 64 11301 // bit source. 11302 EVT LoVT, HiVT; 11303 SDValue Lo, Hi; 11304 unsigned NumElements = ResVT.getVectorNumElements(); 11305 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 11306 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 11307 ResVT.getVectorElementType(), NumElements / 2); 11308 11309 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 11310 LoVT.getVectorNumElements()); 11311 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 11312 DAG.getConstant(0, DL, MVT::i64)); 11313 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 11314 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 11315 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 11316 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 11317 11318 // Now combine the parts back together so we still have a single result 11319 // like the combiner expects. 11320 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 11321 } 11322 11323 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 11324 SDValue SplatVal, unsigned NumVecElts) { 11325 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 11326 unsigned OrigAlignment = St.getAlignment(); 11327 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 11328 11329 // Create scalar stores. This is at least as good as the code sequence for a 11330 // split unaligned store which is a dup.s, ext.b, and two stores. 11331 // Most of the time the three stores should be replaced by store pair 11332 // instructions (stp). 11333 SDLoc DL(&St); 11334 SDValue BasePtr = St.getBasePtr(); 11335 uint64_t BaseOffset = 0; 11336 11337 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 11338 SDValue NewST1 = 11339 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 11340 OrigAlignment, St.getMemOperand()->getFlags()); 11341 11342 // As this in ISel, we will not merge this add which may degrade results. 11343 if (BasePtr->getOpcode() == ISD::ADD && 11344 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 11345 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 11346 BasePtr = BasePtr->getOperand(0); 11347 } 11348 11349 unsigned Offset = EltOffset; 11350 while (--NumVecElts) { 11351 unsigned Alignment = MinAlign(OrigAlignment, Offset); 11352 SDValue OffsetPtr = 11353 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 11354 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 11355 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 11356 PtrInfo.getWithOffset(Offset), Alignment, 11357 St.getMemOperand()->getFlags()); 11358 Offset += EltOffset; 11359 } 11360 return NewST1; 11361 } 11362 11363 // Returns an SVE type that ContentTy can be trivially sign or zero extended 11364 // into. 11365 static MVT getSVEContainerType(EVT ContentTy) { 11366 assert(ContentTy.isSimple() && "No SVE containers for extended types"); 11367 11368 switch (ContentTy.getSimpleVT().SimpleTy) { 11369 default: 11370 llvm_unreachable("No known SVE container for this MVT type"); 11371 case MVT::nxv2i8: 11372 case MVT::nxv2i16: 11373 case MVT::nxv2i32: 11374 case MVT::nxv2i64: 11375 case MVT::nxv2f32: 11376 case MVT::nxv2f64: 11377 return MVT::nxv2i64; 11378 case MVT::nxv4i8: 11379 case MVT::nxv4i16: 11380 case MVT::nxv4i32: 11381 case MVT::nxv4f32: 11382 return MVT::nxv4i32; 11383 case MVT::nxv8i8: 11384 case MVT::nxv8i16: 11385 case MVT::nxv8f16: 11386 return MVT::nxv8i16; 11387 case MVT::nxv16i8: 11388 return MVT::nxv16i8; 11389 } 11390 } 11391 11392 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) { 11393 SDLoc DL(N); 11394 EVT VT = N->getValueType(0); 11395 EVT PtrTy = N->getOperand(3).getValueType(); 11396 11397 EVT LoadVT = VT; 11398 if (VT.isFloatingPoint()) 11399 LoadVT = VT.changeTypeToInteger(); 11400 11401 auto *MINode = cast<MemIntrinsicSDNode>(N); 11402 SDValue PassThru = DAG.getConstant(0, DL, LoadVT); 11403 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(), 11404 MINode->getOperand(3), DAG.getUNDEF(PtrTy), 11405 MINode->getOperand(2), PassThru, 11406 MINode->getMemoryVT(), MINode->getMemOperand(), 11407 ISD::UNINDEXED, ISD::NON_EXTLOAD, false); 11408 11409 if (VT.isFloatingPoint()) { 11410 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) }; 11411 return DAG.getMergeValues(Ops, DL); 11412 } 11413 11414 return L; 11415 } 11416 11417 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) { 11418 SDLoc DL(N); 11419 11420 SDValue Data = N->getOperand(2); 11421 EVT DataVT = Data.getValueType(); 11422 EVT PtrTy = N->getOperand(4).getValueType(); 11423 11424 if (DataVT.isFloatingPoint()) 11425 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data); 11426 11427 auto *MINode = cast<MemIntrinsicSDNode>(N); 11428 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4), 11429 DAG.getUNDEF(PtrTy), MINode->getOperand(3), 11430 MINode->getMemoryVT(), MINode->getMemOperand(), 11431 ISD::UNINDEXED, false, false); 11432 } 11433 11434 static SDValue performLDNF1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) { 11435 SDLoc DL(N); 11436 EVT VT = N->getValueType(0); 11437 11438 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 11439 return SDValue(); 11440 11441 EVT ContainerVT = VT; 11442 if (ContainerVT.isInteger()) 11443 ContainerVT = getSVEContainerType(ContainerVT); 11444 11445 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other); 11446 SDValue Ops[] = { N->getOperand(0), // Chain 11447 N->getOperand(2), // Pg 11448 N->getOperand(3), // Base 11449 DAG.getValueType(VT) }; 11450 11451 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops); 11452 SDValue LoadChain = SDValue(Load.getNode(), 1); 11453 11454 if (ContainerVT.isInteger() && (VT != ContainerVT)) 11455 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0)); 11456 11457 return DAG.getMergeValues({ Load, LoadChain }, DL); 11458 } 11459 11460 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 11461 /// load store optimizer pass will merge them to store pair stores. This should 11462 /// be better than a movi to create the vector zero followed by a vector store 11463 /// if the zero constant is not re-used, since one instructions and one register 11464 /// live range will be removed. 11465 /// 11466 /// For example, the final generated code should be: 11467 /// 11468 /// stp xzr, xzr, [x0] 11469 /// 11470 /// instead of: 11471 /// 11472 /// movi v0.2d, #0 11473 /// str q0, [x0] 11474 /// 11475 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 11476 SDValue StVal = St.getValue(); 11477 EVT VT = StVal.getValueType(); 11478 11479 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 11480 // 2, 3 or 4 i32 elements. 11481 int NumVecElts = VT.getVectorNumElements(); 11482 if (!(((NumVecElts == 2 || NumVecElts == 3) && 11483 VT.getVectorElementType().getSizeInBits() == 64) || 11484 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 11485 VT.getVectorElementType().getSizeInBits() == 32))) 11486 return SDValue(); 11487 11488 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 11489 return SDValue(); 11490 11491 // If the zero constant has more than one use then the vector store could be 11492 // better since the constant mov will be amortized and stp q instructions 11493 // should be able to be formed. 11494 if (!StVal.hasOneUse()) 11495 return SDValue(); 11496 11497 // If the store is truncating then it's going down to i16 or smaller, which 11498 // means it can be implemented in a single store anyway. 11499 if (St.isTruncatingStore()) 11500 return SDValue(); 11501 11502 // If the immediate offset of the address operand is too large for the stp 11503 // instruction, then bail out. 11504 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 11505 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 11506 if (Offset < -512 || Offset > 504) 11507 return SDValue(); 11508 } 11509 11510 for (int I = 0; I < NumVecElts; ++I) { 11511 SDValue EltVal = StVal.getOperand(I); 11512 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 11513 return SDValue(); 11514 } 11515 11516 // Use a CopyFromReg WZR/XZR here to prevent 11517 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 11518 SDLoc DL(&St); 11519 unsigned ZeroReg; 11520 EVT ZeroVT; 11521 if (VT.getVectorElementType().getSizeInBits() == 32) { 11522 ZeroReg = AArch64::WZR; 11523 ZeroVT = MVT::i32; 11524 } else { 11525 ZeroReg = AArch64::XZR; 11526 ZeroVT = MVT::i64; 11527 } 11528 SDValue SplatVal = 11529 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 11530 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 11531 } 11532 11533 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 11534 /// value. The load store optimizer pass will merge them to store pair stores. 11535 /// This has better performance than a splat of the scalar followed by a split 11536 /// vector store. Even if the stores are not merged it is four stores vs a dup, 11537 /// followed by an ext.b and two stores. 11538 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 11539 SDValue StVal = St.getValue(); 11540 EVT VT = StVal.getValueType(); 11541 11542 // Don't replace floating point stores, they possibly won't be transformed to 11543 // stp because of the store pair suppress pass. 11544 if (VT.isFloatingPoint()) 11545 return SDValue(); 11546 11547 // We can express a splat as store pair(s) for 2 or 4 elements. 11548 unsigned NumVecElts = VT.getVectorNumElements(); 11549 if (NumVecElts != 4 && NumVecElts != 2) 11550 return SDValue(); 11551 11552 // If the store is truncating then it's going down to i16 or smaller, which 11553 // means it can be implemented in a single store anyway. 11554 if (St.isTruncatingStore()) 11555 return SDValue(); 11556 11557 // Check that this is a splat. 11558 // Make sure that each of the relevant vector element locations are inserted 11559 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 11560 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 11561 SDValue SplatVal; 11562 for (unsigned I = 0; I < NumVecElts; ++I) { 11563 // Check for insert vector elements. 11564 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 11565 return SDValue(); 11566 11567 // Check that same value is inserted at each vector element. 11568 if (I == 0) 11569 SplatVal = StVal.getOperand(1); 11570 else if (StVal.getOperand(1) != SplatVal) 11571 return SDValue(); 11572 11573 // Check insert element index. 11574 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 11575 if (!CIndex) 11576 return SDValue(); 11577 uint64_t IndexVal = CIndex->getZExtValue(); 11578 if (IndexVal >= NumVecElts) 11579 return SDValue(); 11580 IndexNotInserted.reset(IndexVal); 11581 11582 StVal = StVal.getOperand(0); 11583 } 11584 // Check that all vector element locations were inserted to. 11585 if (IndexNotInserted.any()) 11586 return SDValue(); 11587 11588 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 11589 } 11590 11591 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 11592 SelectionDAG &DAG, 11593 const AArch64Subtarget *Subtarget) { 11594 11595 StoreSDNode *S = cast<StoreSDNode>(N); 11596 if (S->isVolatile() || S->isIndexed()) 11597 return SDValue(); 11598 11599 SDValue StVal = S->getValue(); 11600 EVT VT = StVal.getValueType(); 11601 if (!VT.isVector()) 11602 return SDValue(); 11603 11604 // If we get a splat of zeros, convert this vector store to a store of 11605 // scalars. They will be merged into store pairs of xzr thereby removing one 11606 // instruction and one register. 11607 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 11608 return ReplacedZeroSplat; 11609 11610 // FIXME: The logic for deciding if an unaligned store should be split should 11611 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 11612 // a call to that function here. 11613 11614 if (!Subtarget->isMisaligned128StoreSlow()) 11615 return SDValue(); 11616 11617 // Don't split at -Oz. 11618 if (DAG.getMachineFunction().getFunction().hasMinSize()) 11619 return SDValue(); 11620 11621 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 11622 // those up regresses performance on micro-benchmarks and olden/bh. 11623 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 11624 return SDValue(); 11625 11626 // Split unaligned 16B stores. They are terrible for performance. 11627 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 11628 // extensions can use this to mark that it does not want splitting to happen 11629 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 11630 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 11631 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 11632 S->getAlignment() <= 2) 11633 return SDValue(); 11634 11635 // If we get a splat of a scalar convert this vector store to a store of 11636 // scalars. They will be merged into store pairs thereby removing two 11637 // instructions. 11638 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 11639 return ReplacedSplat; 11640 11641 SDLoc DL(S); 11642 11643 // Split VT into two. 11644 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 11645 unsigned NumElts = HalfVT.getVectorNumElements(); 11646 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 11647 DAG.getConstant(0, DL, MVT::i64)); 11648 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 11649 DAG.getConstant(NumElts, DL, MVT::i64)); 11650 SDValue BasePtr = S->getBasePtr(); 11651 SDValue NewST1 = 11652 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 11653 S->getAlignment(), S->getMemOperand()->getFlags()); 11654 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 11655 DAG.getConstant(8, DL, MVT::i64)); 11656 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 11657 S->getPointerInfo(), S->getAlignment(), 11658 S->getMemOperand()->getFlags()); 11659 } 11660 11661 /// Target-specific DAG combine function for post-increment LD1 (lane) and 11662 /// post-increment LD1R. 11663 static SDValue performPostLD1Combine(SDNode *N, 11664 TargetLowering::DAGCombinerInfo &DCI, 11665 bool IsLaneOp) { 11666 if (DCI.isBeforeLegalizeOps()) 11667 return SDValue(); 11668 11669 SelectionDAG &DAG = DCI.DAG; 11670 EVT VT = N->getValueType(0); 11671 11672 unsigned LoadIdx = IsLaneOp ? 1 : 0; 11673 SDNode *LD = N->getOperand(LoadIdx).getNode(); 11674 // If it is not LOAD, can not do such combine. 11675 if (LD->getOpcode() != ISD::LOAD) 11676 return SDValue(); 11677 11678 // The vector lane must be a constant in the LD1LANE opcode. 11679 SDValue Lane; 11680 if (IsLaneOp) { 11681 Lane = N->getOperand(2); 11682 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 11683 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 11684 return SDValue(); 11685 } 11686 11687 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 11688 EVT MemVT = LoadSDN->getMemoryVT(); 11689 // Check if memory operand is the same type as the vector element. 11690 if (MemVT != VT.getVectorElementType()) 11691 return SDValue(); 11692 11693 // Check if there are other uses. If so, do not combine as it will introduce 11694 // an extra load. 11695 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 11696 ++UI) { 11697 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 11698 continue; 11699 if (*UI != N) 11700 return SDValue(); 11701 } 11702 11703 SDValue Addr = LD->getOperand(1); 11704 SDValue Vector = N->getOperand(0); 11705 // Search for a use of the address operand that is an increment. 11706 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 11707 Addr.getNode()->use_end(); UI != UE; ++UI) { 11708 SDNode *User = *UI; 11709 if (User->getOpcode() != ISD::ADD 11710 || UI.getUse().getResNo() != Addr.getResNo()) 11711 continue; 11712 11713 // If the increment is a constant, it must match the memory ref size. 11714 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11715 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 11716 uint32_t IncVal = CInc->getZExtValue(); 11717 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 11718 if (IncVal != NumBytes) 11719 continue; 11720 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 11721 } 11722 11723 // To avoid cycle construction make sure that neither the load nor the add 11724 // are predecessors to each other or the Vector. 11725 SmallPtrSet<const SDNode *, 32> Visited; 11726 SmallVector<const SDNode *, 16> Worklist; 11727 Visited.insert(Addr.getNode()); 11728 Worklist.push_back(User); 11729 Worklist.push_back(LD); 11730 Worklist.push_back(Vector.getNode()); 11731 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 11732 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11733 continue; 11734 11735 SmallVector<SDValue, 8> Ops; 11736 Ops.push_back(LD->getOperand(0)); // Chain 11737 if (IsLaneOp) { 11738 Ops.push_back(Vector); // The vector to be inserted 11739 Ops.push_back(Lane); // The lane to be inserted in the vector 11740 } 11741 Ops.push_back(Addr); 11742 Ops.push_back(Inc); 11743 11744 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 11745 SDVTList SDTys = DAG.getVTList(Tys); 11746 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 11747 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 11748 MemVT, 11749 LoadSDN->getMemOperand()); 11750 11751 // Update the uses. 11752 SDValue NewResults[] = { 11753 SDValue(LD, 0), // The result of load 11754 SDValue(UpdN.getNode(), 2) // Chain 11755 }; 11756 DCI.CombineTo(LD, NewResults); 11757 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 11758 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 11759 11760 break; 11761 } 11762 return SDValue(); 11763 } 11764 11765 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 11766 /// address translation. 11767 static bool performTBISimplification(SDValue Addr, 11768 TargetLowering::DAGCombinerInfo &DCI, 11769 SelectionDAG &DAG) { 11770 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 11771 KnownBits Known; 11772 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 11773 !DCI.isBeforeLegalizeOps()); 11774 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11775 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 11776 DCI.CommitTargetLoweringOpt(TLO); 11777 return true; 11778 } 11779 return false; 11780 } 11781 11782 static SDValue performSTORECombine(SDNode *N, 11783 TargetLowering::DAGCombinerInfo &DCI, 11784 SelectionDAG &DAG, 11785 const AArch64Subtarget *Subtarget) { 11786 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 11787 return Split; 11788 11789 if (Subtarget->supportsAddressTopByteIgnored() && 11790 performTBISimplification(N->getOperand(2), DCI, DAG)) 11791 return SDValue(N, 0); 11792 11793 return SDValue(); 11794 } 11795 11796 11797 /// Target-specific DAG combine function for NEON load/store intrinsics 11798 /// to merge base address updates. 11799 static SDValue performNEONPostLDSTCombine(SDNode *N, 11800 TargetLowering::DAGCombinerInfo &DCI, 11801 SelectionDAG &DAG) { 11802 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11803 return SDValue(); 11804 11805 unsigned AddrOpIdx = N->getNumOperands() - 1; 11806 SDValue Addr = N->getOperand(AddrOpIdx); 11807 11808 // Search for a use of the address operand that is an increment. 11809 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11810 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11811 SDNode *User = *UI; 11812 if (User->getOpcode() != ISD::ADD || 11813 UI.getUse().getResNo() != Addr.getResNo()) 11814 continue; 11815 11816 // Check that the add is independent of the load/store. Otherwise, folding 11817 // it would create a cycle. 11818 SmallPtrSet<const SDNode *, 32> Visited; 11819 SmallVector<const SDNode *, 16> Worklist; 11820 Visited.insert(Addr.getNode()); 11821 Worklist.push_back(N); 11822 Worklist.push_back(User); 11823 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11824 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11825 continue; 11826 11827 // Find the new opcode for the updating load/store. 11828 bool IsStore = false; 11829 bool IsLaneOp = false; 11830 bool IsDupOp = false; 11831 unsigned NewOpc = 0; 11832 unsigned NumVecs = 0; 11833 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11834 switch (IntNo) { 11835 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11836 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 11837 NumVecs = 2; break; 11838 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 11839 NumVecs = 3; break; 11840 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 11841 NumVecs = 4; break; 11842 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 11843 NumVecs = 2; IsStore = true; break; 11844 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 11845 NumVecs = 3; IsStore = true; break; 11846 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 11847 NumVecs = 4; IsStore = true; break; 11848 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 11849 NumVecs = 2; break; 11850 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 11851 NumVecs = 3; break; 11852 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 11853 NumVecs = 4; break; 11854 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 11855 NumVecs = 2; IsStore = true; break; 11856 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 11857 NumVecs = 3; IsStore = true; break; 11858 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 11859 NumVecs = 4; IsStore = true; break; 11860 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 11861 NumVecs = 2; IsDupOp = true; break; 11862 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 11863 NumVecs = 3; IsDupOp = true; break; 11864 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 11865 NumVecs = 4; IsDupOp = true; break; 11866 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 11867 NumVecs = 2; IsLaneOp = true; break; 11868 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 11869 NumVecs = 3; IsLaneOp = true; break; 11870 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 11871 NumVecs = 4; IsLaneOp = true; break; 11872 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 11873 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 11874 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 11875 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 11876 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 11877 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 11878 } 11879 11880 EVT VecTy; 11881 if (IsStore) 11882 VecTy = N->getOperand(2).getValueType(); 11883 else 11884 VecTy = N->getValueType(0); 11885 11886 // If the increment is a constant, it must match the memory ref size. 11887 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11888 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 11889 uint32_t IncVal = CInc->getZExtValue(); 11890 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11891 if (IsLaneOp || IsDupOp) 11892 NumBytes /= VecTy.getVectorNumElements(); 11893 if (IncVal != NumBytes) 11894 continue; 11895 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 11896 } 11897 SmallVector<SDValue, 8> Ops; 11898 Ops.push_back(N->getOperand(0)); // Incoming chain 11899 // Load lane and store have vector list as input. 11900 if (IsLaneOp || IsStore) 11901 for (unsigned i = 2; i < AddrOpIdx; ++i) 11902 Ops.push_back(N->getOperand(i)); 11903 Ops.push_back(Addr); // Base register 11904 Ops.push_back(Inc); 11905 11906 // Return Types. 11907 EVT Tys[6]; 11908 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 11909 unsigned n; 11910 for (n = 0; n < NumResultVecs; ++n) 11911 Tys[n] = VecTy; 11912 Tys[n++] = MVT::i64; // Type of write back register 11913 Tys[n] = MVT::Other; // Type of the chain 11914 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 11915 11916 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 11917 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 11918 MemInt->getMemoryVT(), 11919 MemInt->getMemOperand()); 11920 11921 // Update the uses. 11922 std::vector<SDValue> NewResults; 11923 for (unsigned i = 0; i < NumResultVecs; ++i) { 11924 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11925 } 11926 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 11927 DCI.CombineTo(N, NewResults); 11928 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11929 11930 break; 11931 } 11932 return SDValue(); 11933 } 11934 11935 // Checks to see if the value is the prescribed width and returns information 11936 // about its extension mode. 11937 static 11938 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 11939 ExtType = ISD::NON_EXTLOAD; 11940 switch(V.getNode()->getOpcode()) { 11941 default: 11942 return false; 11943 case ISD::LOAD: { 11944 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 11945 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 11946 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 11947 ExtType = LoadNode->getExtensionType(); 11948 return true; 11949 } 11950 return false; 11951 } 11952 case ISD::AssertSext: { 11953 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 11954 if ((TypeNode->getVT() == MVT::i8 && width == 8) 11955 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 11956 ExtType = ISD::SEXTLOAD; 11957 return true; 11958 } 11959 return false; 11960 } 11961 case ISD::AssertZext: { 11962 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 11963 if ((TypeNode->getVT() == MVT::i8 && width == 8) 11964 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 11965 ExtType = ISD::ZEXTLOAD; 11966 return true; 11967 } 11968 return false; 11969 } 11970 case ISD::Constant: 11971 case ISD::TargetConstant: { 11972 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 11973 1LL << (width - 1); 11974 } 11975 } 11976 11977 return true; 11978 } 11979 11980 // This function does a whole lot of voodoo to determine if the tests are 11981 // equivalent without and with a mask. Essentially what happens is that given a 11982 // DAG resembling: 11983 // 11984 // +-------------+ +-------------+ +-------------+ +-------------+ 11985 // | Input | | AddConstant | | CompConstant| | CC | 11986 // +-------------+ +-------------+ +-------------+ +-------------+ 11987 // | | | | 11988 // V V | +----------+ 11989 // +-------------+ +----+ | | 11990 // | ADD | |0xff| | | 11991 // +-------------+ +----+ | | 11992 // | | | | 11993 // V V | | 11994 // +-------------+ | | 11995 // | AND | | | 11996 // +-------------+ | | 11997 // | | | 11998 // +-----+ | | 11999 // | | | 12000 // V V V 12001 // +-------------+ 12002 // | CMP | 12003 // +-------------+ 12004 // 12005 // The AND node may be safely removed for some combinations of inputs. In 12006 // particular we need to take into account the extension type of the Input, 12007 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 12008 // width of the input (this can work for any width inputs, the above graph is 12009 // specific to 8 bits. 12010 // 12011 // The specific equations were worked out by generating output tables for each 12012 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 12013 // problem was simplified by working with 4 bit inputs, which means we only 12014 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 12015 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 12016 // patterns present in both extensions (0,7). For every distinct set of 12017 // AddConstant and CompConstants bit patterns we can consider the masked and 12018 // unmasked versions to be equivalent if the result of this function is true for 12019 // all 16 distinct bit patterns of for the current extension type of Input (w0). 12020 // 12021 // sub w8, w0, w1 12022 // and w10, w8, #0x0f 12023 // cmp w8, w2 12024 // cset w9, AArch64CC 12025 // cmp w10, w2 12026 // cset w11, AArch64CC 12027 // cmp w9, w11 12028 // cset w0, eq 12029 // ret 12030 // 12031 // Since the above function shows when the outputs are equivalent it defines 12032 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 12033 // would be expensive to run during compiles. The equations below were written 12034 // in a test harness that confirmed they gave equivalent outputs to the above 12035 // for all inputs function, so they can be used determine if the removal is 12036 // legal instead. 12037 // 12038 // isEquivalentMaskless() is the code for testing if the AND can be removed 12039 // factored out of the DAG recognition as the DAG can take several forms. 12040 12041 static bool isEquivalentMaskless(unsigned CC, unsigned width, 12042 ISD::LoadExtType ExtType, int AddConstant, 12043 int CompConstant) { 12044 // By being careful about our equations and only writing the in term 12045 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 12046 // make them generally applicable to all bit widths. 12047 int MaxUInt = (1 << width); 12048 12049 // For the purposes of these comparisons sign extending the type is 12050 // equivalent to zero extending the add and displacing it by half the integer 12051 // width. Provided we are careful and make sure our equations are valid over 12052 // the whole range we can just adjust the input and avoid writing equations 12053 // for sign extended inputs. 12054 if (ExtType == ISD::SEXTLOAD) 12055 AddConstant -= (1 << (width-1)); 12056 12057 switch(CC) { 12058 case AArch64CC::LE: 12059 case AArch64CC::GT: 12060 if ((AddConstant == 0) || 12061 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 12062 (AddConstant >= 0 && CompConstant < 0) || 12063 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 12064 return true; 12065 break; 12066 case AArch64CC::LT: 12067 case AArch64CC::GE: 12068 if ((AddConstant == 0) || 12069 (AddConstant >= 0 && CompConstant <= 0) || 12070 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 12071 return true; 12072 break; 12073 case AArch64CC::HI: 12074 case AArch64CC::LS: 12075 if ((AddConstant >= 0 && CompConstant < 0) || 12076 (AddConstant <= 0 && CompConstant >= -1 && 12077 CompConstant < AddConstant + MaxUInt)) 12078 return true; 12079 break; 12080 case AArch64CC::PL: 12081 case AArch64CC::MI: 12082 if ((AddConstant == 0) || 12083 (AddConstant > 0 && CompConstant <= 0) || 12084 (AddConstant < 0 && CompConstant <= AddConstant)) 12085 return true; 12086 break; 12087 case AArch64CC::LO: 12088 case AArch64CC::HS: 12089 if ((AddConstant >= 0 && CompConstant <= 0) || 12090 (AddConstant <= 0 && CompConstant >= 0 && 12091 CompConstant <= AddConstant + MaxUInt)) 12092 return true; 12093 break; 12094 case AArch64CC::EQ: 12095 case AArch64CC::NE: 12096 if ((AddConstant > 0 && CompConstant < 0) || 12097 (AddConstant < 0 && CompConstant >= 0 && 12098 CompConstant < AddConstant + MaxUInt) || 12099 (AddConstant >= 0 && CompConstant >= 0 && 12100 CompConstant >= AddConstant) || 12101 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 12102 return true; 12103 break; 12104 case AArch64CC::VS: 12105 case AArch64CC::VC: 12106 case AArch64CC::AL: 12107 case AArch64CC::NV: 12108 return true; 12109 case AArch64CC::Invalid: 12110 break; 12111 } 12112 12113 return false; 12114 } 12115 12116 static 12117 SDValue performCONDCombine(SDNode *N, 12118 TargetLowering::DAGCombinerInfo &DCI, 12119 SelectionDAG &DAG, unsigned CCIndex, 12120 unsigned CmpIndex) { 12121 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 12122 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 12123 unsigned CondOpcode = SubsNode->getOpcode(); 12124 12125 if (CondOpcode != AArch64ISD::SUBS) 12126 return SDValue(); 12127 12128 // There is a SUBS feeding this condition. Is it fed by a mask we can 12129 // use? 12130 12131 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 12132 unsigned MaskBits = 0; 12133 12134 if (AndNode->getOpcode() != ISD::AND) 12135 return SDValue(); 12136 12137 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 12138 uint32_t CNV = CN->getZExtValue(); 12139 if (CNV == 255) 12140 MaskBits = 8; 12141 else if (CNV == 65535) 12142 MaskBits = 16; 12143 } 12144 12145 if (!MaskBits) 12146 return SDValue(); 12147 12148 SDValue AddValue = AndNode->getOperand(0); 12149 12150 if (AddValue.getOpcode() != ISD::ADD) 12151 return SDValue(); 12152 12153 // The basic dag structure is correct, grab the inputs and validate them. 12154 12155 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 12156 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 12157 SDValue SubsInputValue = SubsNode->getOperand(1); 12158 12159 // The mask is present and the provenance of all the values is a smaller type, 12160 // lets see if the mask is superfluous. 12161 12162 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 12163 !isa<ConstantSDNode>(SubsInputValue.getNode())) 12164 return SDValue(); 12165 12166 ISD::LoadExtType ExtType; 12167 12168 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 12169 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 12170 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 12171 return SDValue(); 12172 12173 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 12174 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 12175 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 12176 return SDValue(); 12177 12178 // The AND is not necessary, remove it. 12179 12180 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 12181 SubsNode->getValueType(1)); 12182 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 12183 12184 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 12185 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 12186 12187 return SDValue(N, 0); 12188 } 12189 12190 // Optimize compare with zero and branch. 12191 static SDValue performBRCONDCombine(SDNode *N, 12192 TargetLowering::DAGCombinerInfo &DCI, 12193 SelectionDAG &DAG) { 12194 MachineFunction &MF = DAG.getMachineFunction(); 12195 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 12196 // will not be produced, as they are conditional branch instructions that do 12197 // not set flags. 12198 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 12199 return SDValue(); 12200 12201 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 12202 N = NV.getNode(); 12203 SDValue Chain = N->getOperand(0); 12204 SDValue Dest = N->getOperand(1); 12205 SDValue CCVal = N->getOperand(2); 12206 SDValue Cmp = N->getOperand(3); 12207 12208 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 12209 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 12210 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 12211 return SDValue(); 12212 12213 unsigned CmpOpc = Cmp.getOpcode(); 12214 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 12215 return SDValue(); 12216 12217 // Only attempt folding if there is only one use of the flag and no use of the 12218 // value. 12219 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 12220 return SDValue(); 12221 12222 SDValue LHS = Cmp.getOperand(0); 12223 SDValue RHS = Cmp.getOperand(1); 12224 12225 assert(LHS.getValueType() == RHS.getValueType() && 12226 "Expected the value type to be the same for both operands!"); 12227 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 12228 return SDValue(); 12229 12230 if (isNullConstant(LHS)) 12231 std::swap(LHS, RHS); 12232 12233 if (!isNullConstant(RHS)) 12234 return SDValue(); 12235 12236 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 12237 LHS.getOpcode() == ISD::SRL) 12238 return SDValue(); 12239 12240 // Fold the compare into the branch instruction. 12241 SDValue BR; 12242 if (CC == AArch64CC::EQ) 12243 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 12244 else 12245 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 12246 12247 // Do not add new nodes to DAG combiner worklist. 12248 DCI.CombineTo(N, BR, false); 12249 12250 return SDValue(); 12251 } 12252 12253 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 12254 // as well as whether the test should be inverted. This code is required to 12255 // catch these cases (as opposed to standard dag combines) because 12256 // AArch64ISD::TBZ is matched during legalization. 12257 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 12258 SelectionDAG &DAG) { 12259 12260 if (!Op->hasOneUse()) 12261 return Op; 12262 12263 // We don't handle undef/constant-fold cases below, as they should have 12264 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 12265 // etc.) 12266 12267 // (tbz (trunc x), b) -> (tbz x, b) 12268 // This case is just here to enable more of the below cases to be caught. 12269 if (Op->getOpcode() == ISD::TRUNCATE && 12270 Bit < Op->getValueType(0).getSizeInBits()) { 12271 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12272 } 12273 12274 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 12275 if (Op->getOpcode() == ISD::ANY_EXTEND && 12276 Bit < Op->getOperand(0).getValueSizeInBits()) { 12277 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12278 } 12279 12280 if (Op->getNumOperands() != 2) 12281 return Op; 12282 12283 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12284 if (!C) 12285 return Op; 12286 12287 switch (Op->getOpcode()) { 12288 default: 12289 return Op; 12290 12291 // (tbz (and x, m), b) -> (tbz x, b) 12292 case ISD::AND: 12293 if ((C->getZExtValue() >> Bit) & 1) 12294 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12295 return Op; 12296 12297 // (tbz (shl x, c), b) -> (tbz x, b-c) 12298 case ISD::SHL: 12299 if (C->getZExtValue() <= Bit && 12300 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 12301 Bit = Bit - C->getZExtValue(); 12302 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12303 } 12304 return Op; 12305 12306 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 12307 case ISD::SRA: 12308 Bit = Bit + C->getZExtValue(); 12309 if (Bit >= Op->getValueType(0).getSizeInBits()) 12310 Bit = Op->getValueType(0).getSizeInBits() - 1; 12311 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12312 12313 // (tbz (srl x, c), b) -> (tbz x, b+c) 12314 case ISD::SRL: 12315 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 12316 Bit = Bit + C->getZExtValue(); 12317 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12318 } 12319 return Op; 12320 12321 // (tbz (xor x, -1), b) -> (tbnz x, b) 12322 case ISD::XOR: 12323 if ((C->getZExtValue() >> Bit) & 1) 12324 Invert = !Invert; 12325 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12326 } 12327 } 12328 12329 // Optimize test single bit zero/non-zero and branch. 12330 static SDValue performTBZCombine(SDNode *N, 12331 TargetLowering::DAGCombinerInfo &DCI, 12332 SelectionDAG &DAG) { 12333 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12334 bool Invert = false; 12335 SDValue TestSrc = N->getOperand(1); 12336 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 12337 12338 if (TestSrc == NewTestSrc) 12339 return SDValue(); 12340 12341 unsigned NewOpc = N->getOpcode(); 12342 if (Invert) { 12343 if (NewOpc == AArch64ISD::TBZ) 12344 NewOpc = AArch64ISD::TBNZ; 12345 else { 12346 assert(NewOpc == AArch64ISD::TBNZ); 12347 NewOpc = AArch64ISD::TBZ; 12348 } 12349 } 12350 12351 SDLoc DL(N); 12352 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 12353 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 12354 } 12355 12356 // vselect (v1i1 setcc) -> 12357 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 12358 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 12359 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 12360 // such VSELECT. 12361 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 12362 SDValue N0 = N->getOperand(0); 12363 EVT CCVT = N0.getValueType(); 12364 12365 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 12366 CCVT.getVectorElementType() != MVT::i1) 12367 return SDValue(); 12368 12369 EVT ResVT = N->getValueType(0); 12370 EVT CmpVT = N0.getOperand(0).getValueType(); 12371 // Only combine when the result type is of the same size as the compared 12372 // operands. 12373 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 12374 return SDValue(); 12375 12376 SDValue IfTrue = N->getOperand(1); 12377 SDValue IfFalse = N->getOperand(2); 12378 SDValue SetCC = 12379 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 12380 N0.getOperand(0), N0.getOperand(1), 12381 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 12382 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 12383 IfTrue, IfFalse); 12384 } 12385 12386 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 12387 /// the compare-mask instructions rather than going via NZCV, even if LHS and 12388 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 12389 /// with a vector one followed by a DUP shuffle on the result. 12390 static SDValue performSelectCombine(SDNode *N, 12391 TargetLowering::DAGCombinerInfo &DCI) { 12392 SelectionDAG &DAG = DCI.DAG; 12393 SDValue N0 = N->getOperand(0); 12394 EVT ResVT = N->getValueType(0); 12395 12396 if (N0.getOpcode() != ISD::SETCC) 12397 return SDValue(); 12398 12399 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 12400 // scalar SetCCResultType. We also don't expect vectors, because we assume 12401 // that selects fed by vector SETCCs are canonicalized to VSELECT. 12402 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 12403 "Scalar-SETCC feeding SELECT has unexpected result type!"); 12404 12405 // If NumMaskElts == 0, the comparison is larger than select result. The 12406 // largest real NEON comparison is 64-bits per lane, which means the result is 12407 // at most 32-bits and an illegal vector. Just bail out for now. 12408 EVT SrcVT = N0.getOperand(0).getValueType(); 12409 12410 // Don't try to do this optimization when the setcc itself has i1 operands. 12411 // There are no legal vectors of i1, so this would be pointless. 12412 if (SrcVT == MVT::i1) 12413 return SDValue(); 12414 12415 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 12416 if (!ResVT.isVector() || NumMaskElts == 0) 12417 return SDValue(); 12418 12419 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 12420 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 12421 12422 // Also bail out if the vector CCVT isn't the same size as ResVT. 12423 // This can happen if the SETCC operand size doesn't divide the ResVT size 12424 // (e.g., f64 vs v3f32). 12425 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 12426 return SDValue(); 12427 12428 // Make sure we didn't create illegal types, if we're not supposed to. 12429 assert(DCI.isBeforeLegalize() || 12430 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 12431 12432 // First perform a vector comparison, where lane 0 is the one we're interested 12433 // in. 12434 SDLoc DL(N0); 12435 SDValue LHS = 12436 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 12437 SDValue RHS = 12438 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 12439 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 12440 12441 // Now duplicate the comparison mask we want across all other lanes. 12442 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 12443 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 12444 Mask = DAG.getNode(ISD::BITCAST, DL, 12445 ResVT.changeVectorElementTypeToInteger(), Mask); 12446 12447 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 12448 } 12449 12450 /// Get rid of unnecessary NVCASTs (that don't change the type). 12451 static SDValue performNVCASTCombine(SDNode *N) { 12452 if (N->getValueType(0) == N->getOperand(0).getValueType()) 12453 return N->getOperand(0); 12454 12455 return SDValue(); 12456 } 12457 12458 // If all users of the globaladdr are of the form (globaladdr + constant), find 12459 // the smallest constant, fold it into the globaladdr's offset and rewrite the 12460 // globaladdr as (globaladdr + constant) - constant. 12461 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 12462 const AArch64Subtarget *Subtarget, 12463 const TargetMachine &TM) { 12464 auto *GN = cast<GlobalAddressSDNode>(N); 12465 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 12466 AArch64II::MO_NO_FLAG) 12467 return SDValue(); 12468 12469 uint64_t MinOffset = -1ull; 12470 for (SDNode *N : GN->uses()) { 12471 if (N->getOpcode() != ISD::ADD) 12472 return SDValue(); 12473 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 12474 if (!C) 12475 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12476 if (!C) 12477 return SDValue(); 12478 MinOffset = std::min(MinOffset, C->getZExtValue()); 12479 } 12480 uint64_t Offset = MinOffset + GN->getOffset(); 12481 12482 // Require that the new offset is larger than the existing one. Otherwise, we 12483 // can end up oscillating between two possible DAGs, for example, 12484 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 12485 if (Offset <= uint64_t(GN->getOffset())) 12486 return SDValue(); 12487 12488 // Check whether folding this offset is legal. It must not go out of bounds of 12489 // the referenced object to avoid violating the code model, and must be 12490 // smaller than 2^21 because this is the largest offset expressible in all 12491 // object formats. 12492 // 12493 // This check also prevents us from folding negative offsets, which will end 12494 // up being treated in the same way as large positive ones. They could also 12495 // cause code model violations, and aren't really common enough to matter. 12496 if (Offset >= (1 << 21)) 12497 return SDValue(); 12498 12499 const GlobalValue *GV = GN->getGlobal(); 12500 Type *T = GV->getValueType(); 12501 if (!T->isSized() || 12502 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 12503 return SDValue(); 12504 12505 SDLoc DL(GN); 12506 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 12507 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 12508 DAG.getConstant(MinOffset, DL, MVT::i64)); 12509 } 12510 12511 static SDValue performST1ScatterCombine(SDNode *N, SelectionDAG &DAG, 12512 unsigned Opcode, 12513 bool OnlyPackedOffsets = true) { 12514 const SDValue Src = N->getOperand(2); 12515 const EVT SrcVT = Src->getValueType(0); 12516 assert(SrcVT.isScalableVector() && 12517 "Scatter stores are only possible for SVE vectors"); 12518 12519 SDLoc DL(N); 12520 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT(); 12521 12522 // Make sure that source data will fit into an SVE register 12523 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 12524 return SDValue(); 12525 12526 // For FPs, ACLE only supports _packed_ single and double precision types. 12527 if (SrcElVT.isFloatingPoint()) 12528 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64)) 12529 return SDValue(); 12530 12531 // Depending on the addressing mode, this is either a pointer or a vector of 12532 // pointers (that fits into one register) 12533 SDValue Base = N->getOperand(4); 12534 // Depending on the addressing mode, this is either a single offset or a 12535 // vector of offsets (that fits into one register) 12536 SDValue Offset = N->getOperand(5); 12537 12538 // SST1_IMM requires that the offset is an immediate: 12539 // * multiple of #SizeInBytes 12540 // * in the range [0, 31 x #SizeInBytes] 12541 // where #SizeInBytes is the size in bytes of the stored 12542 // items. For immediates outside that range and non-immediate scalar offsets use 12543 // SST1 or SST1_UXTW instead. 12544 if (Opcode == AArch64ISD::SST1_IMM) { 12545 uint64_t MaxIndex = 31; 12546 uint64_t SrcElSize = SrcElVT.getStoreSize().getKnownMinSize(); 12547 12548 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 12549 if (nullptr == OffsetConst || 12550 OffsetConst->getZExtValue() > MaxIndex * SrcElSize || 12551 OffsetConst->getZExtValue() % SrcElSize) { 12552 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 12553 Opcode = AArch64ISD::SST1_UXTW; 12554 else 12555 Opcode = AArch64ISD::SST1; 12556 12557 std::swap(Base, Offset); 12558 } 12559 } 12560 12561 auto &TLI = DAG.getTargetLoweringInfo(); 12562 if (!TLI.isTypeLegal(Base.getValueType())) 12563 return SDValue(); 12564 12565 // Some scatter store variants allow unpacked offsets, but only as nxv2i32 12566 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 12567 // nxv2i64. Legalize accordingly. 12568 if (!OnlyPackedOffsets && 12569 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 12570 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 12571 12572 if (!TLI.isTypeLegal(Offset.getValueType())) 12573 return SDValue(); 12574 12575 // Source value type that is representable in hardware 12576 EVT HwSrcVt = getSVEContainerType(SrcVT); 12577 12578 // Keep the original type of the input data to store - this is needed to 12579 // differentiate between ST1B, ST1H, ST1W and ST1D. For FP values we want the 12580 // integer equivalent, so just use HwSrcVt. 12581 SDValue InputVT = DAG.getValueType(SrcVT); 12582 if (SrcVT.isFloatingPoint()) 12583 InputVT = DAG.getValueType(HwSrcVt); 12584 12585 SDVTList VTs = DAG.getVTList(MVT::Other); 12586 SDValue SrcNew; 12587 12588 if (Src.getValueType().isFloatingPoint()) 12589 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src); 12590 else 12591 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src); 12592 12593 SDValue Ops[] = {N->getOperand(0), // Chain 12594 SrcNew, 12595 N->getOperand(3), // Pg 12596 Base, 12597 Offset, 12598 InputVT}; 12599 12600 return DAG.getNode(Opcode, DL, VTs, Ops); 12601 } 12602 12603 static SDValue performLD1GatherCombine(SDNode *N, SelectionDAG &DAG, 12604 unsigned Opcode, 12605 bool OnlyPackedOffsets = true) { 12606 EVT RetVT = N->getValueType(0); 12607 assert(RetVT.isScalableVector() && 12608 "Gather loads are only possible for SVE vectors"); 12609 SDLoc DL(N); 12610 12611 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 12612 return SDValue(); 12613 12614 // Depending on the addressing mode, this is either a pointer or a vector of 12615 // pointers (that fits into one register) 12616 SDValue Base = N->getOperand(3); 12617 // Depending on the addressing mode, this is either a single offset or a 12618 // vector of offsets (that fits into one register) 12619 SDValue Offset = N->getOperand(4); 12620 12621 // GLD1_IMM requires that the offset is an immediate: 12622 // * multiple of #SizeInBytes 12623 // * in the range [0, 31 x #SizeInBytes] 12624 // where #SizeInBytes is the size in bytes of the loaded items. For immediates 12625 // outside that range and non-immediate scalar offsets use GLD1 or GLD1_UXTW 12626 // instead. 12627 if (Opcode == AArch64ISD::GLD1_IMM) { 12628 uint64_t MaxIndex = 31; 12629 uint64_t RetElSize = RetVT.getVectorElementType() 12630 .getSimpleVT() 12631 .getStoreSize() 12632 .getKnownMinSize(); 12633 12634 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 12635 if (nullptr == OffsetConst || 12636 OffsetConst->getZExtValue() > MaxIndex * RetElSize || 12637 OffsetConst->getZExtValue() % RetElSize) { 12638 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 12639 Opcode = AArch64ISD::GLD1_UXTW; 12640 else 12641 Opcode = AArch64ISD::GLD1; 12642 12643 std::swap(Base, Offset); 12644 } 12645 } 12646 12647 auto &TLI = DAG.getTargetLoweringInfo(); 12648 if (!TLI.isTypeLegal(Base.getValueType())) 12649 return SDValue(); 12650 12651 // Some gather load variants allow unpacked offsets, but only as nxv2i32 12652 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 12653 // nxv2i64. Legalize accordingly. 12654 if (!OnlyPackedOffsets && 12655 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 12656 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 12657 12658 // Return value type that is representable in hardware 12659 EVT HwRetVt = getSVEContainerType(RetVT); 12660 12661 // Keep the original output value type around - this will better inform 12662 // optimisations (e.g. instruction folding when load is followed by 12663 // zext/sext). This will only be used for ints, so the value for FPs 12664 // doesn't matter. 12665 SDValue OutVT = DAG.getValueType(RetVT); 12666 if (RetVT.isFloatingPoint()) 12667 OutVT = DAG.getValueType(HwRetVt); 12668 12669 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other); 12670 SDValue Ops[] = {N->getOperand(0), // Chain 12671 N->getOperand(2), // Pg 12672 Base, Offset, OutVT}; 12673 12674 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops); 12675 SDValue LoadChain = SDValue(Load.getNode(), 1); 12676 12677 if (RetVT.isInteger() && (RetVT != HwRetVt)) 12678 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0)); 12679 12680 // If the original return value was FP, bitcast accordingly. Doing it here 12681 // means that we can avoid adding TableGen patterns for FPs. 12682 if (RetVT.isFloatingPoint()) 12683 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0)); 12684 12685 return DAG.getMergeValues({Load, LoadChain}, DL); 12686 } 12687 12688 12689 static SDValue 12690 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12691 SelectionDAG &DAG) { 12692 if (DCI.isBeforeLegalizeOps()) 12693 return SDValue(); 12694 12695 SDValue Src = N->getOperand(0); 12696 unsigned Opc = Src->getOpcode(); 12697 12698 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates 12699 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes. 12700 unsigned NewOpc; 12701 unsigned MemVTOpNum = 4; 12702 switch (Opc) { 12703 case AArch64ISD::LDNF1: 12704 NewOpc = AArch64ISD::LDNF1S; 12705 MemVTOpNum = 3; 12706 break; 12707 case AArch64ISD::LDFF1: 12708 NewOpc = AArch64ISD::LDFF1S; 12709 MemVTOpNum = 3; 12710 break; 12711 case AArch64ISD::GLD1: 12712 NewOpc = AArch64ISD::GLD1S; 12713 break; 12714 case AArch64ISD::GLD1_SCALED: 12715 NewOpc = AArch64ISD::GLD1S_SCALED; 12716 break; 12717 case AArch64ISD::GLD1_SXTW: 12718 NewOpc = AArch64ISD::GLD1S_SXTW; 12719 break; 12720 case AArch64ISD::GLD1_SXTW_SCALED: 12721 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED; 12722 break; 12723 case AArch64ISD::GLD1_UXTW: 12724 NewOpc = AArch64ISD::GLD1S_UXTW; 12725 break; 12726 case AArch64ISD::GLD1_UXTW_SCALED: 12727 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED; 12728 break; 12729 case AArch64ISD::GLD1_IMM: 12730 NewOpc = AArch64ISD::GLD1S_IMM; 12731 break; 12732 default: 12733 return SDValue(); 12734 } 12735 12736 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 12737 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT(); 12738 12739 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse()) 12740 return SDValue(); 12741 12742 EVT DstVT = N->getValueType(0); 12743 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other); 12744 12745 SmallVector<SDValue, 5> Ops; 12746 for (unsigned I = 0; I < Src->getNumOperands(); ++I) 12747 Ops.push_back(Src->getOperand(I)); 12748 12749 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops); 12750 DCI.CombineTo(N, ExtLoad); 12751 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1)); 12752 12753 // Return N so it doesn't get rechecked 12754 return SDValue(N, 0); 12755 } 12756 12757 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 12758 DAGCombinerInfo &DCI) const { 12759 SelectionDAG &DAG = DCI.DAG; 12760 switch (N->getOpcode()) { 12761 default: 12762 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 12763 break; 12764 case ISD::ADD: 12765 case ISD::SUB: 12766 return performAddSubLongCombine(N, DCI, DAG); 12767 case ISD::XOR: 12768 return performXorCombine(N, DAG, DCI, Subtarget); 12769 case ISD::MUL: 12770 return performMulCombine(N, DAG, DCI, Subtarget); 12771 case ISD::SINT_TO_FP: 12772 case ISD::UINT_TO_FP: 12773 return performIntToFpCombine(N, DAG, Subtarget); 12774 case ISD::FP_TO_SINT: 12775 case ISD::FP_TO_UINT: 12776 return performFpToIntCombine(N, DAG, DCI, Subtarget); 12777 case ISD::FDIV: 12778 return performFDivCombine(N, DAG, DCI, Subtarget); 12779 case ISD::OR: 12780 return performORCombine(N, DCI, Subtarget); 12781 case ISD::AND: 12782 return performANDCombine(N, DCI); 12783 case ISD::SRL: 12784 return performSRLCombine(N, DCI); 12785 case ISD::INTRINSIC_WO_CHAIN: 12786 return performIntrinsicCombine(N, DCI, Subtarget); 12787 case ISD::ANY_EXTEND: 12788 case ISD::ZERO_EXTEND: 12789 case ISD::SIGN_EXTEND: 12790 return performExtendCombine(N, DCI, DAG); 12791 case ISD::SIGN_EXTEND_INREG: 12792 return performSignExtendInRegCombine(N, DCI, DAG); 12793 case ISD::CONCAT_VECTORS: 12794 return performConcatVectorsCombine(N, DCI, DAG); 12795 case ISD::SELECT: 12796 return performSelectCombine(N, DCI); 12797 case ISD::VSELECT: 12798 return performVSelectCombine(N, DCI.DAG); 12799 case ISD::LOAD: 12800 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 12801 return SDValue(N, 0); 12802 break; 12803 case ISD::STORE: 12804 return performSTORECombine(N, DCI, DAG, Subtarget); 12805 case AArch64ISD::BRCOND: 12806 return performBRCONDCombine(N, DCI, DAG); 12807 case AArch64ISD::TBNZ: 12808 case AArch64ISD::TBZ: 12809 return performTBZCombine(N, DCI, DAG); 12810 case AArch64ISD::CSEL: 12811 return performCONDCombine(N, DCI, DAG, 2, 3); 12812 case AArch64ISD::DUP: 12813 return performPostLD1Combine(N, DCI, false); 12814 case AArch64ISD::NVCAST: 12815 return performNVCASTCombine(N); 12816 case ISD::INSERT_VECTOR_ELT: 12817 return performPostLD1Combine(N, DCI, true); 12818 case ISD::INTRINSIC_VOID: 12819 case ISD::INTRINSIC_W_CHAIN: 12820 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12821 case Intrinsic::aarch64_neon_ld2: 12822 case Intrinsic::aarch64_neon_ld3: 12823 case Intrinsic::aarch64_neon_ld4: 12824 case Intrinsic::aarch64_neon_ld1x2: 12825 case Intrinsic::aarch64_neon_ld1x3: 12826 case Intrinsic::aarch64_neon_ld1x4: 12827 case Intrinsic::aarch64_neon_ld2lane: 12828 case Intrinsic::aarch64_neon_ld3lane: 12829 case Intrinsic::aarch64_neon_ld4lane: 12830 case Intrinsic::aarch64_neon_ld2r: 12831 case Intrinsic::aarch64_neon_ld3r: 12832 case Intrinsic::aarch64_neon_ld4r: 12833 case Intrinsic::aarch64_neon_st2: 12834 case Intrinsic::aarch64_neon_st3: 12835 case Intrinsic::aarch64_neon_st4: 12836 case Intrinsic::aarch64_neon_st1x2: 12837 case Intrinsic::aarch64_neon_st1x3: 12838 case Intrinsic::aarch64_neon_st1x4: 12839 case Intrinsic::aarch64_neon_st2lane: 12840 case Intrinsic::aarch64_neon_st3lane: 12841 case Intrinsic::aarch64_neon_st4lane: 12842 return performNEONPostLDSTCombine(N, DCI, DAG); 12843 case Intrinsic::aarch64_sve_ldnt1: 12844 return performLDNT1Combine(N, DAG); 12845 case Intrinsic::aarch64_sve_ldnf1: 12846 return performLDNF1Combine(N, DAG, AArch64ISD::LDNF1); 12847 case Intrinsic::aarch64_sve_ldff1: 12848 return performLDNF1Combine(N, DAG, AArch64ISD::LDFF1); 12849 case Intrinsic::aarch64_sve_stnt1: 12850 return performSTNT1Combine(N, DAG); 12851 case Intrinsic::aarch64_sve_ld1_gather: 12852 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1); 12853 case Intrinsic::aarch64_sve_ld1_gather_index: 12854 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SCALED); 12855 case Intrinsic::aarch64_sve_ld1_gather_sxtw: 12856 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW, 12857 /*OnlyPackedOffsets=*/false); 12858 case Intrinsic::aarch64_sve_ld1_gather_uxtw: 12859 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW, 12860 /*OnlyPackedOffsets=*/false); 12861 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index: 12862 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED, 12863 /*OnlyPackedOffsets=*/false); 12864 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index: 12865 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED, 12866 /*OnlyPackedOffsets=*/false); 12867 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset: 12868 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_IMM); 12869 case Intrinsic::aarch64_sve_st1_scatter: 12870 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1); 12871 case Intrinsic::aarch64_sve_st1_scatter_index: 12872 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SCALED); 12873 case Intrinsic::aarch64_sve_st1_scatter_sxtw: 12874 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW, 12875 /*OnlyPackedOffsets=*/false); 12876 case Intrinsic::aarch64_sve_st1_scatter_uxtw: 12877 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW, 12878 /*OnlyPackedOffsets=*/false); 12879 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index: 12880 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED, 12881 /*OnlyPackedOffsets=*/false); 12882 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index: 12883 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED, 12884 /*OnlyPackedOffsets=*/false); 12885 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset: 12886 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_IMM); 12887 default: 12888 break; 12889 } 12890 break; 12891 case ISD::GlobalAddress: 12892 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 12893 } 12894 return SDValue(); 12895 } 12896 12897 // Check if the return value is used as only a return value, as otherwise 12898 // we can't perform a tail-call. In particular, we need to check for 12899 // target ISD nodes that are returns and any other "odd" constructs 12900 // that the generic analysis code won't necessarily catch. 12901 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 12902 SDValue &Chain) const { 12903 if (N->getNumValues() != 1) 12904 return false; 12905 if (!N->hasNUsesOfValue(1, 0)) 12906 return false; 12907 12908 SDValue TCChain = Chain; 12909 SDNode *Copy = *N->use_begin(); 12910 if (Copy->getOpcode() == ISD::CopyToReg) { 12911 // If the copy has a glue operand, we conservatively assume it isn't safe to 12912 // perform a tail call. 12913 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 12914 MVT::Glue) 12915 return false; 12916 TCChain = Copy->getOperand(0); 12917 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 12918 return false; 12919 12920 bool HasRet = false; 12921 for (SDNode *Node : Copy->uses()) { 12922 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 12923 return false; 12924 HasRet = true; 12925 } 12926 12927 if (!HasRet) 12928 return false; 12929 12930 Chain = TCChain; 12931 return true; 12932 } 12933 12934 // Return whether the an instruction can potentially be optimized to a tail 12935 // call. This will cause the optimizers to attempt to move, or duplicate, 12936 // return instructions to help enable tail call optimizations for this 12937 // instruction. 12938 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 12939 return CI->isTailCall(); 12940 } 12941 12942 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 12943 SDValue &Offset, 12944 ISD::MemIndexedMode &AM, 12945 bool &IsInc, 12946 SelectionDAG &DAG) const { 12947 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 12948 return false; 12949 12950 Base = Op->getOperand(0); 12951 // All of the indexed addressing mode instructions take a signed 12952 // 9 bit immediate offset. 12953 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 12954 int64_t RHSC = RHS->getSExtValue(); 12955 if (Op->getOpcode() == ISD::SUB) 12956 RHSC = -(uint64_t)RHSC; 12957 if (!isInt<9>(RHSC)) 12958 return false; 12959 IsInc = (Op->getOpcode() == ISD::ADD); 12960 Offset = Op->getOperand(1); 12961 return true; 12962 } 12963 return false; 12964 } 12965 12966 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12967 SDValue &Offset, 12968 ISD::MemIndexedMode &AM, 12969 SelectionDAG &DAG) const { 12970 EVT VT; 12971 SDValue Ptr; 12972 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12973 VT = LD->getMemoryVT(); 12974 Ptr = LD->getBasePtr(); 12975 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12976 VT = ST->getMemoryVT(); 12977 Ptr = ST->getBasePtr(); 12978 } else 12979 return false; 12980 12981 bool IsInc; 12982 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 12983 return false; 12984 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 12985 return true; 12986 } 12987 12988 bool AArch64TargetLowering::getPostIndexedAddressParts( 12989 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 12990 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 12991 EVT VT; 12992 SDValue Ptr; 12993 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12994 VT = LD->getMemoryVT(); 12995 Ptr = LD->getBasePtr(); 12996 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12997 VT = ST->getMemoryVT(); 12998 Ptr = ST->getBasePtr(); 12999 } else 13000 return false; 13001 13002 bool IsInc; 13003 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 13004 return false; 13005 // Post-indexing updates the base, so it's not a valid transform 13006 // if that's not the same as the load's pointer. 13007 if (Ptr != Base) 13008 return false; 13009 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 13010 return true; 13011 } 13012 13013 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 13014 SelectionDAG &DAG) { 13015 SDLoc DL(N); 13016 SDValue Op = N->getOperand(0); 13017 13018 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 13019 return; 13020 13021 Op = SDValue( 13022 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 13023 DAG.getUNDEF(MVT::i32), Op, 13024 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 13025 0); 13026 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 13027 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 13028 } 13029 13030 static void ReplaceReductionResults(SDNode *N, 13031 SmallVectorImpl<SDValue> &Results, 13032 SelectionDAG &DAG, unsigned InterOp, 13033 unsigned AcrossOp) { 13034 EVT LoVT, HiVT; 13035 SDValue Lo, Hi; 13036 SDLoc dl(N); 13037 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 13038 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 13039 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 13040 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 13041 Results.push_back(SplitVal); 13042 } 13043 13044 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 13045 SDLoc DL(N); 13046 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 13047 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 13048 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 13049 DAG.getConstant(64, DL, MVT::i64))); 13050 return std::make_pair(Lo, Hi); 13051 } 13052 13053 // Create an even/odd pair of X registers holding integer value V. 13054 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 13055 SDLoc dl(V.getNode()); 13056 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 13057 SDValue VHi = DAG.getAnyExtOrTrunc( 13058 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 13059 dl, MVT::i64); 13060 if (DAG.getDataLayout().isBigEndian()) 13061 std::swap (VLo, VHi); 13062 SDValue RegClass = 13063 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 13064 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 13065 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 13066 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 13067 return SDValue( 13068 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 13069 } 13070 13071 static void ReplaceCMP_SWAP_128Results(SDNode *N, 13072 SmallVectorImpl<SDValue> &Results, 13073 SelectionDAG &DAG, 13074 const AArch64Subtarget *Subtarget) { 13075 assert(N->getValueType(0) == MVT::i128 && 13076 "AtomicCmpSwap on types less than 128 should be legal"); 13077 13078 if (Subtarget->hasLSE()) { 13079 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 13080 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 13081 SDValue Ops[] = { 13082 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 13083 createGPRPairNode(DAG, N->getOperand(3)), // Store value 13084 N->getOperand(1), // Ptr 13085 N->getOperand(0), // Chain in 13086 }; 13087 13088 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 13089 13090 unsigned Opcode; 13091 switch (MemOp->getOrdering()) { 13092 case AtomicOrdering::Monotonic: 13093 Opcode = AArch64::CASPX; 13094 break; 13095 case AtomicOrdering::Acquire: 13096 Opcode = AArch64::CASPAX; 13097 break; 13098 case AtomicOrdering::Release: 13099 Opcode = AArch64::CASPLX; 13100 break; 13101 case AtomicOrdering::AcquireRelease: 13102 case AtomicOrdering::SequentiallyConsistent: 13103 Opcode = AArch64::CASPALX; 13104 break; 13105 default: 13106 llvm_unreachable("Unexpected ordering!"); 13107 } 13108 13109 MachineSDNode *CmpSwap = DAG.getMachineNode( 13110 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 13111 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 13112 13113 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 13114 if (DAG.getDataLayout().isBigEndian()) 13115 std::swap(SubReg1, SubReg2); 13116 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 13117 SDValue(CmpSwap, 0)); 13118 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 13119 SDValue(CmpSwap, 0)); 13120 Results.push_back( 13121 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi)); 13122 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 13123 return; 13124 } 13125 13126 auto Desired = splitInt128(N->getOperand(2), DAG); 13127 auto New = splitInt128(N->getOperand(3), DAG); 13128 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 13129 New.first, New.second, N->getOperand(0)}; 13130 SDNode *CmpSwap = DAG.getMachineNode( 13131 AArch64::CMP_SWAP_128, SDLoc(N), 13132 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 13133 13134 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 13135 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 13136 13137 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 13138 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1))); 13139 Results.push_back(SDValue(CmpSwap, 3)); 13140 } 13141 13142 void AArch64TargetLowering::ReplaceNodeResults( 13143 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 13144 switch (N->getOpcode()) { 13145 default: 13146 llvm_unreachable("Don't know how to custom expand this"); 13147 case ISD::BITCAST: 13148 ReplaceBITCASTResults(N, Results, DAG); 13149 return; 13150 case ISD::VECREDUCE_ADD: 13151 case ISD::VECREDUCE_SMAX: 13152 case ISD::VECREDUCE_SMIN: 13153 case ISD::VECREDUCE_UMAX: 13154 case ISD::VECREDUCE_UMIN: 13155 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 13156 return; 13157 13158 case AArch64ISD::SADDV: 13159 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 13160 return; 13161 case AArch64ISD::UADDV: 13162 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 13163 return; 13164 case AArch64ISD::SMINV: 13165 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 13166 return; 13167 case AArch64ISD::UMINV: 13168 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 13169 return; 13170 case AArch64ISD::SMAXV: 13171 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 13172 return; 13173 case AArch64ISD::UMAXV: 13174 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 13175 return; 13176 case ISD::FP_TO_UINT: 13177 case ISD::FP_TO_SINT: 13178 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 13179 // Let normal code take care of it by not adding anything to Results. 13180 return; 13181 case ISD::ATOMIC_CMP_SWAP: 13182 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 13183 return; 13184 case ISD::LOAD: { 13185 assert(SDValue(N, 0).getValueType() == MVT::i128 && 13186 "unexpected load's value type"); 13187 LoadSDNode *LoadNode = cast<LoadSDNode>(N); 13188 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) { 13189 // Non-volatile loads are optimized later in AArch64's load/store 13190 // optimizer. 13191 return; 13192 } 13193 13194 SDValue Result = DAG.getMemIntrinsicNode( 13195 AArch64ISD::LDP, SDLoc(N), 13196 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}), 13197 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(), 13198 LoadNode->getMemOperand()); 13199 13200 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 13201 Result.getValue(0), Result.getValue(1)); 13202 Results.append({Pair, Result.getValue(2) /* Chain */}); 13203 return; 13204 } 13205 case ISD::INTRINSIC_WO_CHAIN: { 13206 EVT VT = N->getValueType(0); 13207 assert((VT == MVT::i8 || VT == MVT::i16) && 13208 "custom lowering for unexpected type"); 13209 13210 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0)); 13211 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13212 switch (IntID) { 13213 default: 13214 return; 13215 case Intrinsic::aarch64_sve_clasta_n: { 13216 SDLoc DL(N); 13217 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 13218 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32, 13219 N->getOperand(1), Op2, N->getOperand(3)); 13220 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13221 return; 13222 } 13223 case Intrinsic::aarch64_sve_clastb_n: { 13224 SDLoc DL(N); 13225 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 13226 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32, 13227 N->getOperand(1), Op2, N->getOperand(3)); 13228 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13229 return; 13230 } 13231 case Intrinsic::aarch64_sve_lasta: { 13232 SDLoc DL(N); 13233 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32, 13234 N->getOperand(1), N->getOperand(2)); 13235 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13236 return; 13237 } 13238 case Intrinsic::aarch64_sve_lastb: { 13239 SDLoc DL(N); 13240 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32, 13241 N->getOperand(1), N->getOperand(2)); 13242 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13243 return; 13244 } 13245 } 13246 } 13247 } 13248 } 13249 13250 bool AArch64TargetLowering::useLoadStackGuardNode() const { 13251 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 13252 return TargetLowering::useLoadStackGuardNode(); 13253 return true; 13254 } 13255 13256 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 13257 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13258 // reciprocal if there are three or more FDIVs. 13259 return 3; 13260 } 13261 13262 TargetLoweringBase::LegalizeTypeAction 13263 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 13264 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 13265 // v4i16, v2i32 instead of to promote. 13266 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 13267 VT == MVT::v1f32) 13268 return TypeWidenVector; 13269 13270 return TargetLoweringBase::getPreferredVectorAction(VT); 13271 } 13272 13273 // Loads and stores less than 128-bits are already atomic; ones above that 13274 // are doomed anyway, so defer to the default libcall and blame the OS when 13275 // things go wrong. 13276 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13277 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13278 return Size == 128; 13279 } 13280 13281 // Loads and stores less than 128-bits are already atomic; ones above that 13282 // are doomed anyway, so defer to the default libcall and blame the OS when 13283 // things go wrong. 13284 TargetLowering::AtomicExpansionKind 13285 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13286 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13287 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 13288 } 13289 13290 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 13291 TargetLowering::AtomicExpansionKind 13292 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13293 if (AI->isFloatingPointOperation()) 13294 return AtomicExpansionKind::CmpXChg; 13295 13296 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13297 if (Size > 128) return AtomicExpansionKind::None; 13298 // Nand not supported in LSE. 13299 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 13300 // Leave 128 bits to LLSC. 13301 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 13302 } 13303 13304 TargetLowering::AtomicExpansionKind 13305 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 13306 AtomicCmpXchgInst *AI) const { 13307 // If subtarget has LSE, leave cmpxchg intact for codegen. 13308 if (Subtarget->hasLSE()) 13309 return AtomicExpansionKind::None; 13310 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13311 // implement cmpxchg without spilling. If the address being exchanged is also 13312 // on the stack and close enough to the spill slot, this can lead to a 13313 // situation where the monitor always gets cleared and the atomic operation 13314 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13315 if (getTargetMachine().getOptLevel() == 0) 13316 return AtomicExpansionKind::None; 13317 return AtomicExpansionKind::LLSC; 13318 } 13319 13320 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13321 AtomicOrdering Ord) const { 13322 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13323 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13324 bool IsAcquire = isAcquireOrStronger(Ord); 13325 13326 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 13327 // intrinsic must return {i64, i64} and we have to recombine them into a 13328 // single i128 here. 13329 if (ValTy->getPrimitiveSizeInBits() == 128) { 13330 Intrinsic::ID Int = 13331 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 13332 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 13333 13334 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13335 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 13336 13337 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13338 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13339 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13340 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13341 return Builder.CreateOr( 13342 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 13343 } 13344 13345 Type *Tys[] = { Addr->getType() }; 13346 Intrinsic::ID Int = 13347 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 13348 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 13349 13350 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 13351 13352 const DataLayout &DL = M->getDataLayout(); 13353 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 13354 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 13355 13356 return Builder.CreateBitCast(Trunc, EltTy); 13357 } 13358 13359 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13360 IRBuilder<> &Builder) const { 13361 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13362 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 13363 } 13364 13365 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 13366 Value *Val, Value *Addr, 13367 AtomicOrdering Ord) const { 13368 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13369 bool IsRelease = isReleaseOrStronger(Ord); 13370 13371 // Since the intrinsics must have legal type, the i128 intrinsics take two 13372 // parameters: "i64, i64". We must marshal Val into the appropriate form 13373 // before the call. 13374 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 13375 Intrinsic::ID Int = 13376 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 13377 Function *Stxr = Intrinsic::getDeclaration(M, Int); 13378 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 13379 13380 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 13381 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 13382 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13383 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 13384 } 13385 13386 Intrinsic::ID Int = 13387 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 13388 Type *Tys[] = { Addr->getType() }; 13389 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 13390 13391 const DataLayout &DL = M->getDataLayout(); 13392 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 13393 Val = Builder.CreateBitCast(Val, IntValTy); 13394 13395 return Builder.CreateCall(Stxr, 13396 {Builder.CreateZExtOrBitCast( 13397 Val, Stxr->getFunctionType()->getParamType(0)), 13398 Addr}); 13399 } 13400 13401 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 13402 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13403 return Ty->isArrayTy(); 13404 } 13405 13406 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 13407 EVT) const { 13408 return false; 13409 } 13410 13411 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 13412 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 13413 Function *ThreadPointerFunc = 13414 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 13415 return IRB.CreatePointerCast( 13416 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 13417 Offset), 13418 IRB.getInt8PtrTy()->getPointerTo(0)); 13419 } 13420 13421 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 13422 // Android provides a fixed TLS slot for the stack cookie. See the definition 13423 // of TLS_SLOT_STACK_GUARD in 13424 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 13425 if (Subtarget->isTargetAndroid()) 13426 return UseTlsOffset(IRB, 0x28); 13427 13428 // Fuchsia is similar. 13429 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 13430 if (Subtarget->isTargetFuchsia()) 13431 return UseTlsOffset(IRB, -0x10); 13432 13433 return TargetLowering::getIRStackGuard(IRB); 13434 } 13435 13436 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 13437 // MSVC CRT provides functionalities for stack protection. 13438 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 13439 // MSVC CRT has a global variable holding security cookie. 13440 M.getOrInsertGlobal("__security_cookie", 13441 Type::getInt8PtrTy(M.getContext())); 13442 13443 // MSVC CRT has a function to validate security cookie. 13444 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 13445 "__security_check_cookie", Type::getVoidTy(M.getContext()), 13446 Type::getInt8PtrTy(M.getContext())); 13447 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 13448 F->setCallingConv(CallingConv::Win64); 13449 F->addAttribute(1, Attribute::AttrKind::InReg); 13450 } 13451 return; 13452 } 13453 TargetLowering::insertSSPDeclarations(M); 13454 } 13455 13456 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 13457 // MSVC CRT has a global variable holding security cookie. 13458 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 13459 return M.getGlobalVariable("__security_cookie"); 13460 return TargetLowering::getSDagStackGuard(M); 13461 } 13462 13463 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 13464 // MSVC CRT has a function to validate security cookie. 13465 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 13466 return M.getFunction("__security_check_cookie"); 13467 return TargetLowering::getSSPStackGuardCheck(M); 13468 } 13469 13470 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 13471 // Android provides a fixed TLS slot for the SafeStack pointer. See the 13472 // definition of TLS_SLOT_SAFESTACK in 13473 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 13474 if (Subtarget->isTargetAndroid()) 13475 return UseTlsOffset(IRB, 0x48); 13476 13477 // Fuchsia is similar. 13478 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 13479 if (Subtarget->isTargetFuchsia()) 13480 return UseTlsOffset(IRB, -0x8); 13481 13482 return TargetLowering::getSafeStackPointerLocation(IRB); 13483 } 13484 13485 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 13486 const Instruction &AndI) const { 13487 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 13488 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 13489 // may be beneficial to sink in other cases, but we would have to check that 13490 // the cmp would not get folded into the br to form a cbz for these to be 13491 // beneficial. 13492 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 13493 if (!Mask) 13494 return false; 13495 return Mask->getValue().isPowerOf2(); 13496 } 13497 13498 bool AArch64TargetLowering:: 13499 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 13500 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 13501 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 13502 SelectionDAG &DAG) const { 13503 // Does baseline recommend not to perform the fold by default? 13504 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 13505 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 13506 return false; 13507 // Else, if this is a vector shift, prefer 'shl'. 13508 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 13509 } 13510 13511 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 13512 SDNode *N) const { 13513 if (DAG.getMachineFunction().getFunction().hasMinSize() && 13514 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin()) 13515 return false; 13516 return true; 13517 } 13518 13519 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13520 // Update IsSplitCSR in AArch64unctionInfo. 13521 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 13522 AFI->setIsSplitCSR(true); 13523 } 13524 13525 void AArch64TargetLowering::insertCopiesSplitCSR( 13526 MachineBasicBlock *Entry, 13527 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13528 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 13529 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13530 if (!IStart) 13531 return; 13532 13533 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13534 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13535 MachineBasicBlock::iterator MBBI = Entry->begin(); 13536 for (const MCPhysReg *I = IStart; *I; ++I) { 13537 const TargetRegisterClass *RC = nullptr; 13538 if (AArch64::GPR64RegClass.contains(*I)) 13539 RC = &AArch64::GPR64RegClass; 13540 else if (AArch64::FPR64RegClass.contains(*I)) 13541 RC = &AArch64::FPR64RegClass; 13542 else 13543 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13544 13545 Register NewVR = MRI->createVirtualRegister(RC); 13546 // Create copy from CSR to a virtual register. 13547 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13548 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13549 // nounwind. If we want to generalize this later, we may need to emit 13550 // CFI pseudo-instructions. 13551 assert(Entry->getParent()->getFunction().hasFnAttribute( 13552 Attribute::NoUnwind) && 13553 "Function should be nounwind in insertCopiesSplitCSR!"); 13554 Entry->addLiveIn(*I); 13555 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13556 .addReg(*I); 13557 13558 // Insert the copy-back instructions right before the terminator. 13559 for (auto *Exit : Exits) 13560 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13561 TII->get(TargetOpcode::COPY), *I) 13562 .addReg(NewVR); 13563 } 13564 } 13565 13566 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 13567 // Integer division on AArch64 is expensive. However, when aggressively 13568 // optimizing for code size, we prefer to use a div instruction, as it is 13569 // usually smaller than the alternative sequence. 13570 // The exception to this is vector division. Since AArch64 doesn't have vector 13571 // integer division, leaving the division as-is is a loss even in terms of 13572 // size, because it will have to be scalarized, while the alternative code 13573 // sequence can be performed in vector form. 13574 bool OptSize = 13575 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 13576 return OptSize && !VT.isVector(); 13577 } 13578 13579 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 13580 // We want inc-of-add for scalars and sub-of-not for vectors. 13581 return VT.isScalarInteger(); 13582 } 13583 13584 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 13585 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 13586 } 13587 13588 unsigned 13589 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 13590 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 13591 return getPointerTy(DL).getSizeInBits(); 13592 13593 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 13594 } 13595 13596 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 13597 MF.getFrameInfo().computeMaxCallFrameSize(MF); 13598 TargetLoweringBase::finalizeLowering(MF); 13599 } 13600 13601 // Unlike X86, we let frame lowering assign offsets to all catch objects. 13602 bool AArch64TargetLowering::needsFixedCatchObjects() const { 13603 return false; 13604 } 13605