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 "AArch64ExpandImm.h" 14 #include "AArch64ISelLowering.h" 15 #include "AArch64CallingConvention.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/Module.h" 62 #include "llvm/IR/OperandTraits.h" 63 #include "llvm/IR/PatternMatch.h" 64 #include "llvm/IR/Type.h" 65 #include "llvm/IR/Use.h" 66 #include "llvm/IR/Value.h" 67 #include "llvm/MC/MCRegisterInfo.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/CodeGen.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Compiler.h" 72 #include "llvm/Support/Debug.h" 73 #include "llvm/Support/ErrorHandling.h" 74 #include "llvm/Support/KnownBits.h" 75 #include "llvm/Support/MachineValueType.h" 76 #include "llvm/Support/MathExtras.h" 77 #include "llvm/Support/raw_ostream.h" 78 #include "llvm/Target/TargetMachine.h" 79 #include "llvm/Target/TargetOptions.h" 80 #include <algorithm> 81 #include <bitset> 82 #include <cassert> 83 #include <cctype> 84 #include <cstdint> 85 #include <cstdlib> 86 #include <iterator> 87 #include <limits> 88 #include <tuple> 89 #include <utility> 90 #include <vector> 91 92 using namespace llvm; 93 using namespace llvm::PatternMatch; 94 95 #define DEBUG_TYPE "aarch64-lower" 96 97 STATISTIC(NumTailCalls, "Number of tail calls"); 98 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 99 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 100 101 static cl::opt<bool> 102 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 103 cl::desc("Allow AArch64 SLI/SRI formation"), 104 cl::init(false)); 105 106 // FIXME: The necessary dtprel relocations don't seem to be supported 107 // well in the GNU bfd and gold linkers at the moment. Therefore, by 108 // default, for now, fall back to GeneralDynamic code generation. 109 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 110 "aarch64-elf-ldtls-generation", cl::Hidden, 111 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 112 cl::init(false)); 113 114 static cl::opt<bool> 115 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 116 cl::desc("Enable AArch64 logical imm instruction " 117 "optimization"), 118 cl::init(true)); 119 120 /// Value type used for condition codes. 121 static const MVT MVT_CC = MVT::i32; 122 123 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 124 const AArch64Subtarget &STI) 125 : TargetLowering(TM), Subtarget(&STI) { 126 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 127 // we have to make something up. Arbitrarily, choose ZeroOrOne. 128 setBooleanContents(ZeroOrOneBooleanContent); 129 // When comparing vectors the result sets the different elements in the 130 // vector to all-one or all-zero. 131 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 132 133 // Set up the register classes. 134 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 135 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 136 137 if (Subtarget->hasFPARMv8()) { 138 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 139 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 140 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 141 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 142 } 143 144 if (Subtarget->hasNEON()) { 145 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 146 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 147 // Someone set us up the NEON. 148 addDRTypeForNEON(MVT::v2f32); 149 addDRTypeForNEON(MVT::v8i8); 150 addDRTypeForNEON(MVT::v4i16); 151 addDRTypeForNEON(MVT::v2i32); 152 addDRTypeForNEON(MVT::v1i64); 153 addDRTypeForNEON(MVT::v1f64); 154 addDRTypeForNEON(MVT::v4f16); 155 156 addQRTypeForNEON(MVT::v4f32); 157 addQRTypeForNEON(MVT::v2f64); 158 addQRTypeForNEON(MVT::v16i8); 159 addQRTypeForNEON(MVT::v8i16); 160 addQRTypeForNEON(MVT::v4i32); 161 addQRTypeForNEON(MVT::v2i64); 162 addQRTypeForNEON(MVT::v8f16); 163 } 164 165 if (Subtarget->hasSVE()) { 166 // Add legal sve predicate types 167 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 168 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 169 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 170 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 171 172 // Add legal sve data types 173 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 174 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 175 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 176 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 177 178 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 179 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 180 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 181 addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass); 182 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 183 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 184 addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass); 185 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 186 } 187 188 // Compute derived properties from the register classes 189 computeRegisterProperties(Subtarget->getRegisterInfo()); 190 191 // Provide all sorts of operation actions 192 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 193 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 194 setOperationAction(ISD::SETCC, MVT::i32, Custom); 195 setOperationAction(ISD::SETCC, MVT::i64, Custom); 196 setOperationAction(ISD::SETCC, MVT::f16, Custom); 197 setOperationAction(ISD::SETCC, MVT::f32, Custom); 198 setOperationAction(ISD::SETCC, MVT::f64, Custom); 199 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 200 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 201 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 202 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 203 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 204 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 205 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 206 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 207 setOperationAction(ISD::SELECT, MVT::i32, Custom); 208 setOperationAction(ISD::SELECT, MVT::i64, Custom); 209 setOperationAction(ISD::SELECT, MVT::f16, Custom); 210 setOperationAction(ISD::SELECT, MVT::f32, Custom); 211 setOperationAction(ISD::SELECT, MVT::f64, Custom); 212 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 213 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 214 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 215 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 216 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 217 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 218 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 219 220 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 221 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 222 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 223 224 setOperationAction(ISD::FREM, MVT::f32, Expand); 225 setOperationAction(ISD::FREM, MVT::f64, Expand); 226 setOperationAction(ISD::FREM, MVT::f80, Expand); 227 228 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 229 230 // Custom lowering hooks are needed for XOR 231 // to fold it into CSINC/CSINV. 232 setOperationAction(ISD::XOR, MVT::i32, Custom); 233 setOperationAction(ISD::XOR, MVT::i64, Custom); 234 235 // Virtually no operation on f128 is legal, but LLVM can't expand them when 236 // there's a valid register class, so we need custom operations in most cases. 237 setOperationAction(ISD::FABS, MVT::f128, Expand); 238 setOperationAction(ISD::FADD, MVT::f128, Custom); 239 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 240 setOperationAction(ISD::FCOS, MVT::f128, Expand); 241 setOperationAction(ISD::FDIV, MVT::f128, Custom); 242 setOperationAction(ISD::FMA, MVT::f128, Expand); 243 setOperationAction(ISD::FMUL, MVT::f128, Custom); 244 setOperationAction(ISD::FNEG, MVT::f128, Expand); 245 setOperationAction(ISD::FPOW, MVT::f128, Expand); 246 setOperationAction(ISD::FREM, MVT::f128, Expand); 247 setOperationAction(ISD::FRINT, MVT::f128, Expand); 248 setOperationAction(ISD::FSIN, MVT::f128, Expand); 249 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 250 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 251 setOperationAction(ISD::FSUB, MVT::f128, Custom); 252 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 253 setOperationAction(ISD::SETCC, MVT::f128, Custom); 254 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 255 setOperationAction(ISD::SELECT, MVT::f128, Custom); 256 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 257 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 258 259 // Lowering for many of the conversions is actually specified by the non-f128 260 // type. The LowerXXX function will be trivial when f128 isn't involved. 261 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 262 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 263 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 264 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 265 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 266 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 267 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 268 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 269 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 270 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 271 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 272 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 273 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 274 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 275 276 // Variable arguments. 277 setOperationAction(ISD::VASTART, MVT::Other, Custom); 278 setOperationAction(ISD::VAARG, MVT::Other, Custom); 279 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 280 setOperationAction(ISD::VAEND, MVT::Other, Expand); 281 282 // Variable-sized objects. 283 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 284 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 285 286 if (Subtarget->isTargetWindows()) 287 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 288 else 289 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 290 291 // Constant pool entries 292 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 293 294 // BlockAddress 295 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 296 297 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 298 setOperationAction(ISD::ADDC, MVT::i32, Custom); 299 setOperationAction(ISD::ADDE, MVT::i32, Custom); 300 setOperationAction(ISD::SUBC, MVT::i32, Custom); 301 setOperationAction(ISD::SUBE, MVT::i32, Custom); 302 setOperationAction(ISD::ADDC, MVT::i64, Custom); 303 setOperationAction(ISD::ADDE, MVT::i64, Custom); 304 setOperationAction(ISD::SUBC, MVT::i64, Custom); 305 setOperationAction(ISD::SUBE, MVT::i64, Custom); 306 307 // AArch64 lacks both left-rotate and popcount instructions. 308 setOperationAction(ISD::ROTL, MVT::i32, Expand); 309 setOperationAction(ISD::ROTL, MVT::i64, Expand); 310 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 311 setOperationAction(ISD::ROTL, VT, Expand); 312 setOperationAction(ISD::ROTR, VT, Expand); 313 } 314 315 // AArch64 doesn't have {U|S}MUL_LOHI. 316 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 317 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 318 319 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 320 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 321 322 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 323 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 324 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 325 setOperationAction(ISD::SDIVREM, VT, Expand); 326 setOperationAction(ISD::UDIVREM, VT, Expand); 327 } 328 setOperationAction(ISD::SREM, MVT::i32, Expand); 329 setOperationAction(ISD::SREM, MVT::i64, Expand); 330 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 331 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 332 setOperationAction(ISD::UREM, MVT::i32, Expand); 333 setOperationAction(ISD::UREM, MVT::i64, Expand); 334 335 // Custom lower Add/Sub/Mul with overflow. 336 setOperationAction(ISD::SADDO, MVT::i32, Custom); 337 setOperationAction(ISD::SADDO, MVT::i64, Custom); 338 setOperationAction(ISD::UADDO, MVT::i32, Custom); 339 setOperationAction(ISD::UADDO, MVT::i64, Custom); 340 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 341 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 342 setOperationAction(ISD::USUBO, MVT::i32, Custom); 343 setOperationAction(ISD::USUBO, MVT::i64, Custom); 344 setOperationAction(ISD::SMULO, MVT::i32, Custom); 345 setOperationAction(ISD::SMULO, MVT::i64, Custom); 346 setOperationAction(ISD::UMULO, MVT::i32, Custom); 347 setOperationAction(ISD::UMULO, MVT::i64, Custom); 348 349 setOperationAction(ISD::FSIN, MVT::f32, Expand); 350 setOperationAction(ISD::FSIN, MVT::f64, Expand); 351 setOperationAction(ISD::FCOS, MVT::f32, Expand); 352 setOperationAction(ISD::FCOS, MVT::f64, Expand); 353 setOperationAction(ISD::FPOW, MVT::f32, Expand); 354 setOperationAction(ISD::FPOW, MVT::f64, Expand); 355 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 357 if (Subtarget->hasFullFP16()) 358 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 359 else 360 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 361 362 setOperationAction(ISD::FREM, MVT::f16, Promote); 363 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 364 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 365 setOperationAction(ISD::FPOW, MVT::f16, Promote); 366 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 367 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 368 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 369 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 370 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 371 setOperationAction(ISD::FCOS, MVT::f16, Promote); 372 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 373 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 374 setOperationAction(ISD::FSIN, MVT::f16, Promote); 375 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 376 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 377 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 378 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 379 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 380 setOperationAction(ISD::FEXP, MVT::f16, Promote); 381 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 382 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 383 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 384 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 385 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 386 setOperationAction(ISD::FLOG, MVT::f16, Promote); 387 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 388 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 389 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 390 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 391 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 392 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 393 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 394 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 395 396 if (!Subtarget->hasFullFP16()) { 397 setOperationAction(ISD::SELECT, MVT::f16, Promote); 398 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 399 setOperationAction(ISD::SETCC, MVT::f16, Promote); 400 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 401 setOperationAction(ISD::FADD, MVT::f16, Promote); 402 setOperationAction(ISD::FSUB, MVT::f16, Promote); 403 setOperationAction(ISD::FMUL, MVT::f16, Promote); 404 setOperationAction(ISD::FDIV, MVT::f16, Promote); 405 setOperationAction(ISD::FMA, MVT::f16, Promote); 406 setOperationAction(ISD::FNEG, MVT::f16, Promote); 407 setOperationAction(ISD::FABS, MVT::f16, Promote); 408 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 409 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 410 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 411 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 412 setOperationAction(ISD::FRINT, MVT::f16, Promote); 413 setOperationAction(ISD::FROUND, MVT::f16, Promote); 414 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 415 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 416 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 417 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 418 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 419 420 // promote v4f16 to v4f32 when that is known to be safe. 421 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 422 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 423 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 424 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 425 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 426 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 427 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 428 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 429 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 430 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 431 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 432 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 433 434 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 435 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 436 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 437 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 438 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 439 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 440 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 441 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 442 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 443 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 444 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 445 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 446 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 447 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 448 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 449 450 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 451 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 452 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 453 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 454 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 455 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 456 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 457 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 458 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 459 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 460 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 461 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 462 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 463 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 464 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 465 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 466 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 467 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 468 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 469 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 470 } 471 472 // AArch64 has implementations of a lot of rounding-like FP operations. 473 for (MVT Ty : {MVT::f32, MVT::f64}) { 474 setOperationAction(ISD::FFLOOR, Ty, Legal); 475 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 476 setOperationAction(ISD::FCEIL, Ty, Legal); 477 setOperationAction(ISD::FRINT, Ty, Legal); 478 setOperationAction(ISD::FTRUNC, Ty, Legal); 479 setOperationAction(ISD::FROUND, Ty, Legal); 480 setOperationAction(ISD::FMINNUM, Ty, Legal); 481 setOperationAction(ISD::FMAXNUM, Ty, Legal); 482 setOperationAction(ISD::FMINIMUM, Ty, Legal); 483 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 484 setOperationAction(ISD::LROUND, Ty, Legal); 485 setOperationAction(ISD::LLROUND, Ty, Legal); 486 setOperationAction(ISD::LRINT, Ty, Legal); 487 setOperationAction(ISD::LLRINT, Ty, Legal); 488 } 489 490 if (Subtarget->hasFullFP16()) { 491 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 492 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 493 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 494 setOperationAction(ISD::FRINT, MVT::f16, Legal); 495 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 496 setOperationAction(ISD::FROUND, MVT::f16, Legal); 497 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 498 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 499 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 500 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 501 } 502 503 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 504 505 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 506 507 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 508 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 509 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 510 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 511 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 512 513 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 514 // This requires the Performance Monitors extension. 515 if (Subtarget->hasPerfMon()) 516 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 517 518 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 519 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 520 // Issue __sincos_stret if available. 521 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 522 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 523 } else { 524 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 525 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 526 } 527 528 // Make floating-point constants legal for the large code model, so they don't 529 // become loads from the constant pool. 530 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 531 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 532 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 533 } 534 535 // AArch64 does not have floating-point extending loads, i1 sign-extending 536 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 537 for (MVT VT : MVT::fp_valuetypes()) { 538 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 539 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 540 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 541 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 542 } 543 for (MVT VT : MVT::integer_valuetypes()) 544 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 545 546 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 547 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 548 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 549 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 550 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 551 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 552 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 553 554 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 555 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 556 557 // Indexed loads and stores are supported. 558 for (unsigned im = (unsigned)ISD::PRE_INC; 559 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 560 setIndexedLoadAction(im, MVT::i8, Legal); 561 setIndexedLoadAction(im, MVT::i16, Legal); 562 setIndexedLoadAction(im, MVT::i32, Legal); 563 setIndexedLoadAction(im, MVT::i64, Legal); 564 setIndexedLoadAction(im, MVT::f64, Legal); 565 setIndexedLoadAction(im, MVT::f32, Legal); 566 setIndexedLoadAction(im, MVT::f16, Legal); 567 setIndexedStoreAction(im, MVT::i8, Legal); 568 setIndexedStoreAction(im, MVT::i16, Legal); 569 setIndexedStoreAction(im, MVT::i32, Legal); 570 setIndexedStoreAction(im, MVT::i64, Legal); 571 setIndexedStoreAction(im, MVT::f64, Legal); 572 setIndexedStoreAction(im, MVT::f32, Legal); 573 setIndexedStoreAction(im, MVT::f16, Legal); 574 } 575 576 // Trap. 577 setOperationAction(ISD::TRAP, MVT::Other, Legal); 578 if (Subtarget->isTargetWindows()) 579 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 580 581 // We combine OR nodes for bitfield operations. 582 setTargetDAGCombine(ISD::OR); 583 // Try to create BICs for vector ANDs. 584 setTargetDAGCombine(ISD::AND); 585 586 // Vector add and sub nodes may conceal a high-half opportunity. 587 // Also, try to fold ADD into CSINC/CSINV.. 588 setTargetDAGCombine(ISD::ADD); 589 setTargetDAGCombine(ISD::SUB); 590 setTargetDAGCombine(ISD::SRL); 591 setTargetDAGCombine(ISD::XOR); 592 setTargetDAGCombine(ISD::SINT_TO_FP); 593 setTargetDAGCombine(ISD::UINT_TO_FP); 594 595 setTargetDAGCombine(ISD::FP_TO_SINT); 596 setTargetDAGCombine(ISD::FP_TO_UINT); 597 setTargetDAGCombine(ISD::FDIV); 598 599 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 600 601 setTargetDAGCombine(ISD::ANY_EXTEND); 602 setTargetDAGCombine(ISD::ZERO_EXTEND); 603 setTargetDAGCombine(ISD::SIGN_EXTEND); 604 setTargetDAGCombine(ISD::BITCAST); 605 setTargetDAGCombine(ISD::CONCAT_VECTORS); 606 setTargetDAGCombine(ISD::STORE); 607 if (Subtarget->supportsAddressTopByteIgnored()) 608 setTargetDAGCombine(ISD::LOAD); 609 610 setTargetDAGCombine(ISD::MUL); 611 612 setTargetDAGCombine(ISD::SELECT); 613 setTargetDAGCombine(ISD::VSELECT); 614 615 setTargetDAGCombine(ISD::INTRINSIC_VOID); 616 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 617 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 618 619 setTargetDAGCombine(ISD::GlobalAddress); 620 621 // In case of strict alignment, avoid an excessive number of byte wide stores. 622 MaxStoresPerMemsetOptSize = 8; 623 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 624 ? MaxStoresPerMemsetOptSize : 32; 625 626 MaxGluedStoresPerMemcpy = 4; 627 MaxStoresPerMemcpyOptSize = 4; 628 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 629 ? MaxStoresPerMemcpyOptSize : 16; 630 631 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 632 633 MaxLoadsPerMemcmpOptSize = 4; 634 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 635 ? MaxLoadsPerMemcmpOptSize : 8; 636 637 setStackPointerRegisterToSaveRestore(AArch64::SP); 638 639 setSchedulingPreference(Sched::Hybrid); 640 641 EnableExtLdPromotion = true; 642 643 // Set required alignment. 644 setMinFunctionAlignment(Align(4)); 645 // Set preferred alignments. 646 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 647 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 648 649 // Only change the limit for entries in a jump table if specified by 650 // the sub target, but not at the command line. 651 unsigned MaxJT = STI.getMaximumJumpTableSize(); 652 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 653 setMaximumJumpTableSize(MaxJT); 654 655 setHasExtractBitsInsn(true); 656 657 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 658 659 if (Subtarget->hasNEON()) { 660 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 661 // silliness like this: 662 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 663 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 664 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 665 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 666 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 667 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 668 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 669 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 670 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 671 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 672 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 673 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 674 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 675 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 676 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 677 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 678 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 679 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 680 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 681 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 682 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 683 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 684 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 685 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 686 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 687 688 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 689 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 690 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 691 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 692 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 693 694 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 695 696 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 697 // elements smaller than i32, so promote the input to i32 first. 698 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 699 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 700 // i8 vector elements also need promotion to i32 for v8i8 701 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 702 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 703 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 704 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 705 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 706 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 707 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 708 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 709 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 710 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 711 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 712 713 if (Subtarget->hasFullFP16()) { 714 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 715 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 716 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 717 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 718 } else { 719 // when AArch64 doesn't have fullfp16 support, promote the input 720 // to i32 first. 721 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 722 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 723 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 724 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 725 } 726 727 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 728 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 729 730 // AArch64 doesn't have MUL.2d: 731 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 732 // Custom handling for some quad-vector types to detect MULL. 733 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 734 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 735 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 736 737 // Vector reductions 738 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 739 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 740 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 741 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 742 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 743 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 744 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 745 } 746 for (MVT VT : { MVT::v4f16, MVT::v2f32, 747 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 748 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 749 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 750 } 751 752 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 753 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 754 // Likewise, narrowing and extending vector loads/stores aren't handled 755 // directly. 756 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 757 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 758 759 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 760 setOperationAction(ISD::MULHS, VT, Legal); 761 setOperationAction(ISD::MULHU, VT, Legal); 762 } else { 763 setOperationAction(ISD::MULHS, VT, Expand); 764 setOperationAction(ISD::MULHU, VT, Expand); 765 } 766 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 767 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 768 769 setOperationAction(ISD::BSWAP, VT, Expand); 770 setOperationAction(ISD::CTTZ, VT, Expand); 771 772 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 773 setTruncStoreAction(VT, InnerVT, Expand); 774 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 775 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 776 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 777 } 778 } 779 780 // AArch64 has implementations of a lot of rounding-like FP operations. 781 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 782 setOperationAction(ISD::FFLOOR, Ty, Legal); 783 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 784 setOperationAction(ISD::FCEIL, Ty, Legal); 785 setOperationAction(ISD::FRINT, Ty, Legal); 786 setOperationAction(ISD::FTRUNC, Ty, Legal); 787 setOperationAction(ISD::FROUND, Ty, Legal); 788 } 789 790 if (Subtarget->hasFullFP16()) { 791 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 792 setOperationAction(ISD::FFLOOR, Ty, Legal); 793 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 794 setOperationAction(ISD::FCEIL, Ty, Legal); 795 setOperationAction(ISD::FRINT, Ty, Legal); 796 setOperationAction(ISD::FTRUNC, Ty, Legal); 797 setOperationAction(ISD::FROUND, Ty, Legal); 798 } 799 } 800 801 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 802 } 803 804 if (Subtarget->hasSVE()) { 805 for (MVT VT : MVT::integer_scalable_vector_valuetypes()) { 806 if (isTypeLegal(VT) && VT.getVectorElementType() != MVT::i1) 807 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 808 } 809 } 810 811 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 812 } 813 814 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 815 assert(VT.isVector() && "VT should be a vector type"); 816 817 if (VT.isFloatingPoint()) { 818 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 819 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 820 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 821 } 822 823 // Mark vector float intrinsics as expand. 824 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 825 setOperationAction(ISD::FSIN, VT, Expand); 826 setOperationAction(ISD::FCOS, VT, Expand); 827 setOperationAction(ISD::FPOW, VT, Expand); 828 setOperationAction(ISD::FLOG, VT, Expand); 829 setOperationAction(ISD::FLOG2, VT, Expand); 830 setOperationAction(ISD::FLOG10, VT, Expand); 831 setOperationAction(ISD::FEXP, VT, Expand); 832 setOperationAction(ISD::FEXP2, VT, Expand); 833 834 // But we do support custom-lowering for FCOPYSIGN. 835 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 836 } 837 838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 839 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 840 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 841 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 842 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 843 setOperationAction(ISD::SRA, VT, Custom); 844 setOperationAction(ISD::SRL, VT, Custom); 845 setOperationAction(ISD::SHL, VT, Custom); 846 setOperationAction(ISD::OR, VT, Custom); 847 setOperationAction(ISD::SETCC, VT, Custom); 848 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 849 850 setOperationAction(ISD::SELECT, VT, Expand); 851 setOperationAction(ISD::SELECT_CC, VT, Expand); 852 setOperationAction(ISD::VSELECT, VT, Expand); 853 for (MVT InnerVT : MVT::all_valuetypes()) 854 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 855 856 // CNT supports only B element sizes, then use UADDLP to widen. 857 if (VT != MVT::v8i8 && VT != MVT::v16i8) 858 setOperationAction(ISD::CTPOP, VT, Custom); 859 860 setOperationAction(ISD::UDIV, VT, Expand); 861 setOperationAction(ISD::SDIV, VT, Expand); 862 setOperationAction(ISD::UREM, VT, Expand); 863 setOperationAction(ISD::SREM, VT, Expand); 864 setOperationAction(ISD::FREM, VT, Expand); 865 866 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 867 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 868 869 if (!VT.isFloatingPoint()) 870 setOperationAction(ISD::ABS, VT, Legal); 871 872 // [SU][MIN|MAX] are available for all NEON types apart from i64. 873 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 874 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 875 setOperationAction(Opcode, VT, Legal); 876 877 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 878 if (VT.isFloatingPoint() && 879 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 880 for (unsigned Opcode : 881 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 882 setOperationAction(Opcode, VT, Legal); 883 884 if (Subtarget->isLittleEndian()) { 885 for (unsigned im = (unsigned)ISD::PRE_INC; 886 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 887 setIndexedLoadAction(im, VT, Legal); 888 setIndexedStoreAction(im, VT, Legal); 889 } 890 } 891 } 892 893 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 894 addRegisterClass(VT, &AArch64::FPR64RegClass); 895 addTypeForNEON(VT, MVT::v2i32); 896 } 897 898 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 899 addRegisterClass(VT, &AArch64::FPR128RegClass); 900 addTypeForNEON(VT, MVT::v4i32); 901 } 902 903 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 904 EVT VT) const { 905 if (!VT.isVector()) 906 return MVT::i32; 907 return VT.changeVectorElementTypeToInteger(); 908 } 909 910 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 911 const APInt &Demanded, 912 TargetLowering::TargetLoweringOpt &TLO, 913 unsigned NewOpc) { 914 uint64_t OldImm = Imm, NewImm, Enc; 915 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 916 917 // Return if the immediate is already all zeros, all ones, a bimm32 or a 918 // bimm64. 919 if (Imm == 0 || Imm == Mask || 920 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 921 return false; 922 923 unsigned EltSize = Size; 924 uint64_t DemandedBits = Demanded.getZExtValue(); 925 926 // Clear bits that are not demanded. 927 Imm &= DemandedBits; 928 929 while (true) { 930 // The goal here is to set the non-demanded bits in a way that minimizes 931 // the number of switching between 0 and 1. In order to achieve this goal, 932 // we set the non-demanded bits to the value of the preceding demanded bits. 933 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 934 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 935 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 936 // The final result is 0b11000011. 937 uint64_t NonDemandedBits = ~DemandedBits; 938 uint64_t InvertedImm = ~Imm & DemandedBits; 939 uint64_t RotatedImm = 940 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 941 NonDemandedBits; 942 uint64_t Sum = RotatedImm + NonDemandedBits; 943 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 944 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 945 NewImm = (Imm | Ones) & Mask; 946 947 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 948 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 949 // we halve the element size and continue the search. 950 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 951 break; 952 953 // We cannot shrink the element size any further if it is 2-bits. 954 if (EltSize == 2) 955 return false; 956 957 EltSize /= 2; 958 Mask >>= EltSize; 959 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 960 961 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 962 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 963 return false; 964 965 // Merge the upper and lower halves of Imm and DemandedBits. 966 Imm |= Hi; 967 DemandedBits |= DemandedBitsHi; 968 } 969 970 ++NumOptimizedImms; 971 972 // Replicate the element across the register width. 973 while (EltSize < Size) { 974 NewImm |= NewImm << EltSize; 975 EltSize *= 2; 976 } 977 978 (void)OldImm; 979 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 980 "demanded bits should never be altered"); 981 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 982 983 // Create the new constant immediate node. 984 EVT VT = Op.getValueType(); 985 SDLoc DL(Op); 986 SDValue New; 987 988 // If the new constant immediate is all-zeros or all-ones, let the target 989 // independent DAG combine optimize this node. 990 if (NewImm == 0 || NewImm == OrigMask) { 991 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 992 TLO.DAG.getConstant(NewImm, DL, VT)); 993 // Otherwise, create a machine node so that target independent DAG combine 994 // doesn't undo this optimization. 995 } else { 996 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 997 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 998 New = SDValue( 999 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1000 } 1001 1002 return TLO.CombineTo(Op, New); 1003 } 1004 1005 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1006 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 1007 // Delay this optimization to as late as possible. 1008 if (!TLO.LegalOps) 1009 return false; 1010 1011 if (!EnableOptimizeLogicalImm) 1012 return false; 1013 1014 EVT VT = Op.getValueType(); 1015 if (VT.isVector()) 1016 return false; 1017 1018 unsigned Size = VT.getSizeInBits(); 1019 assert((Size == 32 || Size == 64) && 1020 "i32 or i64 is expected after legalization."); 1021 1022 // Exit early if we demand all bits. 1023 if (Demanded.countPopulation() == Size) 1024 return false; 1025 1026 unsigned NewOpc; 1027 switch (Op.getOpcode()) { 1028 default: 1029 return false; 1030 case ISD::AND: 1031 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1032 break; 1033 case ISD::OR: 1034 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1035 break; 1036 case ISD::XOR: 1037 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1038 break; 1039 } 1040 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1041 if (!C) 1042 return false; 1043 uint64_t Imm = C->getZExtValue(); 1044 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 1045 } 1046 1047 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1048 /// Mask are known to be either zero or one and return them Known. 1049 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1050 const SDValue Op, KnownBits &Known, 1051 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1052 switch (Op.getOpcode()) { 1053 default: 1054 break; 1055 case AArch64ISD::CSEL: { 1056 KnownBits Known2; 1057 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1058 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1059 Known.Zero &= Known2.Zero; 1060 Known.One &= Known2.One; 1061 break; 1062 } 1063 case AArch64ISD::LOADgot: 1064 case AArch64ISD::ADDlow: { 1065 if (!Subtarget->isTargetILP32()) 1066 break; 1067 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1068 Known.Zero = APInt::getHighBitsSet(64, 32); 1069 break; 1070 } 1071 case ISD::INTRINSIC_W_CHAIN: { 1072 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1073 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1074 switch (IntID) { 1075 default: return; 1076 case Intrinsic::aarch64_ldaxr: 1077 case Intrinsic::aarch64_ldxr: { 1078 unsigned BitWidth = Known.getBitWidth(); 1079 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1080 unsigned MemBits = VT.getScalarSizeInBits(); 1081 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1082 return; 1083 } 1084 } 1085 break; 1086 } 1087 case ISD::INTRINSIC_WO_CHAIN: 1088 case ISD::INTRINSIC_VOID: { 1089 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1090 switch (IntNo) { 1091 default: 1092 break; 1093 case Intrinsic::aarch64_neon_umaxv: 1094 case Intrinsic::aarch64_neon_uminv: { 1095 // Figure out the datatype of the vector operand. The UMINV instruction 1096 // will zero extend the result, so we can mark as known zero all the 1097 // bits larger than the element datatype. 32-bit or larget doesn't need 1098 // this as those are legal types and will be handled by isel directly. 1099 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1100 unsigned BitWidth = Known.getBitWidth(); 1101 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1102 assert(BitWidth >= 8 && "Unexpected width!"); 1103 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1104 Known.Zero |= Mask; 1105 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1106 assert(BitWidth >= 16 && "Unexpected width!"); 1107 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1108 Known.Zero |= Mask; 1109 } 1110 break; 1111 } break; 1112 } 1113 } 1114 } 1115 } 1116 1117 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1118 EVT) const { 1119 return MVT::i64; 1120 } 1121 1122 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1123 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1124 bool *Fast) const { 1125 if (Subtarget->requiresStrictAlign()) 1126 return false; 1127 1128 if (Fast) { 1129 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1130 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1131 // See comments in performSTORECombine() for more details about 1132 // these conditions. 1133 1134 // Code that uses clang vector extensions can mark that it 1135 // wants unaligned accesses to be treated as fast by 1136 // underspecifying alignment to be 1 or 2. 1137 Align <= 2 || 1138 1139 // Disregard v2i64. Memcpy lowering produces those and splitting 1140 // them regresses performance on micro-benchmarks and olden/bh. 1141 VT == MVT::v2i64; 1142 } 1143 return true; 1144 } 1145 1146 // Same as above but handling LLTs instead. 1147 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1148 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1149 bool *Fast) const { 1150 if (Subtarget->requiresStrictAlign()) 1151 return false; 1152 1153 if (Fast) { 1154 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1155 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1156 Ty.getSizeInBytes() != 16 || 1157 // See comments in performSTORECombine() for more details about 1158 // these conditions. 1159 1160 // Code that uses clang vector extensions can mark that it 1161 // wants unaligned accesses to be treated as fast by 1162 // underspecifying alignment to be 1 or 2. 1163 Align <= 2 || 1164 1165 // Disregard v2i64. Memcpy lowering produces those and splitting 1166 // them regresses performance on micro-benchmarks and olden/bh. 1167 Ty == LLT::vector(2, 64); 1168 } 1169 return true; 1170 } 1171 1172 FastISel * 1173 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1174 const TargetLibraryInfo *libInfo) const { 1175 return AArch64::createFastISel(funcInfo, libInfo); 1176 } 1177 1178 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1179 switch ((AArch64ISD::NodeType)Opcode) { 1180 case AArch64ISD::FIRST_NUMBER: break; 1181 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1182 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1183 case AArch64ISD::ADR: return "AArch64ISD::ADR"; 1184 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1185 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1186 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1187 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1188 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1189 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1190 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1191 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1192 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1193 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1194 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1195 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1196 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1197 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1198 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1199 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1200 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1201 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1202 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1203 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1204 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1205 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1206 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1207 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1208 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1209 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1210 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1211 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1212 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1213 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1214 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1215 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1216 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1217 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1218 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1219 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1220 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 1221 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1222 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1223 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1224 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1225 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1226 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1227 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1228 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1229 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1230 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1231 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1232 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1233 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1234 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1235 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1236 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1237 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1238 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1239 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1240 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1241 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1242 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1243 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1244 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1245 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1246 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1247 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1248 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1249 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1250 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1251 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1252 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1253 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1254 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1255 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1256 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1257 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1258 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1259 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1260 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1261 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1262 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1263 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1264 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1265 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1266 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1267 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1268 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1269 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1270 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1271 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1272 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1273 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1274 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1275 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1276 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1277 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1278 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1279 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1280 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1281 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1282 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1283 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1284 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1285 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1286 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1287 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1288 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1289 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1290 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1291 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1292 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1293 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1294 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1295 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1296 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1297 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1298 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1299 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1300 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1301 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1302 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1303 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1304 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1305 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1306 case AArch64ISD::STG: return "AArch64ISD::STG"; 1307 case AArch64ISD::STZG: return "AArch64ISD::STZG"; 1308 case AArch64ISD::ST2G: return "AArch64ISD::ST2G"; 1309 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G"; 1310 case AArch64ISD::SUNPKHI: return "AArch64ISD::SUNPKHI"; 1311 case AArch64ISD::SUNPKLO: return "AArch64ISD::SUNPKLO"; 1312 case AArch64ISD::UUNPKHI: return "AArch64ISD::UUNPKHI"; 1313 case AArch64ISD::UUNPKLO: return "AArch64ISD::UUNPKLO"; 1314 } 1315 return nullptr; 1316 } 1317 1318 MachineBasicBlock * 1319 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1320 MachineBasicBlock *MBB) const { 1321 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1322 // phi node: 1323 1324 // OrigBB: 1325 // [... previous instrs leading to comparison ...] 1326 // b.ne TrueBB 1327 // b EndBB 1328 // TrueBB: 1329 // ; Fallthrough 1330 // EndBB: 1331 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1332 1333 MachineFunction *MF = MBB->getParent(); 1334 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1335 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1336 DebugLoc DL = MI.getDebugLoc(); 1337 MachineFunction::iterator It = ++MBB->getIterator(); 1338 1339 Register DestReg = MI.getOperand(0).getReg(); 1340 Register IfTrueReg = MI.getOperand(1).getReg(); 1341 Register IfFalseReg = MI.getOperand(2).getReg(); 1342 unsigned CondCode = MI.getOperand(3).getImm(); 1343 bool NZCVKilled = MI.getOperand(4).isKill(); 1344 1345 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1346 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1347 MF->insert(It, TrueBB); 1348 MF->insert(It, EndBB); 1349 1350 // Transfer rest of current basic-block to EndBB 1351 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1352 MBB->end()); 1353 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1354 1355 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1356 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1357 MBB->addSuccessor(TrueBB); 1358 MBB->addSuccessor(EndBB); 1359 1360 // TrueBB falls through to the end. 1361 TrueBB->addSuccessor(EndBB); 1362 1363 if (!NZCVKilled) { 1364 TrueBB->addLiveIn(AArch64::NZCV); 1365 EndBB->addLiveIn(AArch64::NZCV); 1366 } 1367 1368 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1369 .addReg(IfTrueReg) 1370 .addMBB(TrueBB) 1371 .addReg(IfFalseReg) 1372 .addMBB(MBB); 1373 1374 MI.eraseFromParent(); 1375 return EndBB; 1376 } 1377 1378 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 1379 MachineInstr &MI, MachineBasicBlock *BB) const { 1380 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 1381 BB->getParent()->getFunction().getPersonalityFn())) && 1382 "SEH does not use catchret!"); 1383 return BB; 1384 } 1385 1386 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad( 1387 MachineInstr &MI, MachineBasicBlock *BB) const { 1388 MI.eraseFromParent(); 1389 return BB; 1390 } 1391 1392 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1393 MachineInstr &MI, MachineBasicBlock *BB) const { 1394 switch (MI.getOpcode()) { 1395 default: 1396 #ifndef NDEBUG 1397 MI.dump(); 1398 #endif 1399 llvm_unreachable("Unexpected instruction for custom inserter!"); 1400 1401 case AArch64::F128CSEL: 1402 return EmitF128CSEL(MI, BB); 1403 1404 case TargetOpcode::STACKMAP: 1405 case TargetOpcode::PATCHPOINT: 1406 return emitPatchPoint(MI, BB); 1407 1408 case AArch64::CATCHRET: 1409 return EmitLoweredCatchRet(MI, BB); 1410 case AArch64::CATCHPAD: 1411 return EmitLoweredCatchPad(MI, BB); 1412 } 1413 } 1414 1415 //===----------------------------------------------------------------------===// 1416 // AArch64 Lowering private implementation. 1417 //===----------------------------------------------------------------------===// 1418 1419 //===----------------------------------------------------------------------===// 1420 // Lowering Code 1421 //===----------------------------------------------------------------------===// 1422 1423 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1424 /// CC 1425 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1426 switch (CC) { 1427 default: 1428 llvm_unreachable("Unknown condition code!"); 1429 case ISD::SETNE: 1430 return AArch64CC::NE; 1431 case ISD::SETEQ: 1432 return AArch64CC::EQ; 1433 case ISD::SETGT: 1434 return AArch64CC::GT; 1435 case ISD::SETGE: 1436 return AArch64CC::GE; 1437 case ISD::SETLT: 1438 return AArch64CC::LT; 1439 case ISD::SETLE: 1440 return AArch64CC::LE; 1441 case ISD::SETUGT: 1442 return AArch64CC::HI; 1443 case ISD::SETUGE: 1444 return AArch64CC::HS; 1445 case ISD::SETULT: 1446 return AArch64CC::LO; 1447 case ISD::SETULE: 1448 return AArch64CC::LS; 1449 } 1450 } 1451 1452 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1453 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1454 AArch64CC::CondCode &CondCode, 1455 AArch64CC::CondCode &CondCode2) { 1456 CondCode2 = AArch64CC::AL; 1457 switch (CC) { 1458 default: 1459 llvm_unreachable("Unknown FP condition!"); 1460 case ISD::SETEQ: 1461 case ISD::SETOEQ: 1462 CondCode = AArch64CC::EQ; 1463 break; 1464 case ISD::SETGT: 1465 case ISD::SETOGT: 1466 CondCode = AArch64CC::GT; 1467 break; 1468 case ISD::SETGE: 1469 case ISD::SETOGE: 1470 CondCode = AArch64CC::GE; 1471 break; 1472 case ISD::SETOLT: 1473 CondCode = AArch64CC::MI; 1474 break; 1475 case ISD::SETOLE: 1476 CondCode = AArch64CC::LS; 1477 break; 1478 case ISD::SETONE: 1479 CondCode = AArch64CC::MI; 1480 CondCode2 = AArch64CC::GT; 1481 break; 1482 case ISD::SETO: 1483 CondCode = AArch64CC::VC; 1484 break; 1485 case ISD::SETUO: 1486 CondCode = AArch64CC::VS; 1487 break; 1488 case ISD::SETUEQ: 1489 CondCode = AArch64CC::EQ; 1490 CondCode2 = AArch64CC::VS; 1491 break; 1492 case ISD::SETUGT: 1493 CondCode = AArch64CC::HI; 1494 break; 1495 case ISD::SETUGE: 1496 CondCode = AArch64CC::PL; 1497 break; 1498 case ISD::SETLT: 1499 case ISD::SETULT: 1500 CondCode = AArch64CC::LT; 1501 break; 1502 case ISD::SETLE: 1503 case ISD::SETULE: 1504 CondCode = AArch64CC::LE; 1505 break; 1506 case ISD::SETNE: 1507 case ISD::SETUNE: 1508 CondCode = AArch64CC::NE; 1509 break; 1510 } 1511 } 1512 1513 /// Convert a DAG fp condition code to an AArch64 CC. 1514 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1515 /// should be AND'ed instead of OR'ed. 1516 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1517 AArch64CC::CondCode &CondCode, 1518 AArch64CC::CondCode &CondCode2) { 1519 CondCode2 = AArch64CC::AL; 1520 switch (CC) { 1521 default: 1522 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1523 assert(CondCode2 == AArch64CC::AL); 1524 break; 1525 case ISD::SETONE: 1526 // (a one b) 1527 // == ((a olt b) || (a ogt b)) 1528 // == ((a ord b) && (a une b)) 1529 CondCode = AArch64CC::VC; 1530 CondCode2 = AArch64CC::NE; 1531 break; 1532 case ISD::SETUEQ: 1533 // (a ueq b) 1534 // == ((a uno b) || (a oeq b)) 1535 // == ((a ule b) && (a uge b)) 1536 CondCode = AArch64CC::PL; 1537 CondCode2 = AArch64CC::LE; 1538 break; 1539 } 1540 } 1541 1542 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1543 /// CC usable with the vector instructions. Fewer operations are available 1544 /// without a real NZCV register, so we have to use less efficient combinations 1545 /// to get the same effect. 1546 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1547 AArch64CC::CondCode &CondCode, 1548 AArch64CC::CondCode &CondCode2, 1549 bool &Invert) { 1550 Invert = false; 1551 switch (CC) { 1552 default: 1553 // Mostly the scalar mappings work fine. 1554 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1555 break; 1556 case ISD::SETUO: 1557 Invert = true; 1558 LLVM_FALLTHROUGH; 1559 case ISD::SETO: 1560 CondCode = AArch64CC::MI; 1561 CondCode2 = AArch64CC::GE; 1562 break; 1563 case ISD::SETUEQ: 1564 case ISD::SETULT: 1565 case ISD::SETULE: 1566 case ISD::SETUGT: 1567 case ISD::SETUGE: 1568 // All of the compare-mask comparisons are ordered, but we can switch 1569 // between the two by a double inversion. E.g. ULE == !OGT. 1570 Invert = true; 1571 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1572 break; 1573 } 1574 } 1575 1576 static bool isLegalArithImmed(uint64_t C) { 1577 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1578 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1579 LLVM_DEBUG(dbgs() << "Is imm " << C 1580 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 1581 return IsLegal; 1582 } 1583 1584 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 1585 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 1586 // can be set differently by this operation. It comes down to whether 1587 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1588 // everything is fine. If not then the optimization is wrong. Thus general 1589 // comparisons are only valid if op2 != 0. 1590 // 1591 // So, finally, the only LLVM-native comparisons that don't mention C and V 1592 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1593 // the absence of information about op2. 1594 static bool isCMN(SDValue Op, ISD::CondCode CC) { 1595 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 1596 (CC == ISD::SETEQ || CC == ISD::SETNE); 1597 } 1598 1599 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1600 const SDLoc &dl, SelectionDAG &DAG) { 1601 EVT VT = LHS.getValueType(); 1602 const bool FullFP16 = 1603 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1604 1605 if (VT.isFloatingPoint()) { 1606 assert(VT != MVT::f128); 1607 if (VT == MVT::f16 && !FullFP16) { 1608 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1609 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1610 VT = MVT::f32; 1611 } 1612 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1613 } 1614 1615 // The CMP instruction is just an alias for SUBS, and representing it as 1616 // SUBS means that it's possible to get CSE with subtract operations. 1617 // A later phase can perform the optimization of setting the destination 1618 // register to WZR/XZR if it ends up being unused. 1619 unsigned Opcode = AArch64ISD::SUBS; 1620 1621 if (isCMN(RHS, CC)) { 1622 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 1623 Opcode = AArch64ISD::ADDS; 1624 RHS = RHS.getOperand(1); 1625 } else if (isCMN(LHS, CC)) { 1626 // As we are looking for EQ/NE compares, the operands can be commuted ; can 1627 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 1628 Opcode = AArch64ISD::ADDS; 1629 LHS = LHS.getOperand(1); 1630 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1631 !isUnsignedIntSetCC(CC)) { 1632 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1633 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1634 // of the signed comparisons. 1635 Opcode = AArch64ISD::ANDS; 1636 RHS = LHS.getOperand(1); 1637 LHS = LHS.getOperand(0); 1638 } 1639 1640 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1641 .getValue(1); 1642 } 1643 1644 /// \defgroup AArch64CCMP CMP;CCMP matching 1645 /// 1646 /// These functions deal with the formation of CMP;CCMP;... sequences. 1647 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1648 /// a comparison. They set the NZCV flags to a predefined value if their 1649 /// predicate is false. This allows to express arbitrary conjunctions, for 1650 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 1651 /// expressed as: 1652 /// cmp A 1653 /// ccmp B, inv(CB), CA 1654 /// check for CB flags 1655 /// 1656 /// This naturally lets us implement chains of AND operations with SETCC 1657 /// operands. And we can even implement some other situations by transforming 1658 /// them: 1659 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 1660 /// negating the flags used in a CCMP/FCCMP operations. 1661 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 1662 /// by negating the flags we test for afterwards. i.e. 1663 /// NEG (CMP CCMP CCCMP ...) can be implemented. 1664 /// - Note that we can only ever negate all previously processed results. 1665 /// What we can not implement by flipping the flags to test is a negation 1666 /// of two sub-trees (because the negation affects all sub-trees emitted so 1667 /// far, so the 2nd sub-tree we emit would also affect the first). 1668 /// With those tools we can implement some OR operations: 1669 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 1670 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 1671 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 1672 /// elimination rules from earlier to implement the whole thing as a 1673 /// CCMP/FCCMP chain. 1674 /// 1675 /// As complete example: 1676 /// or (or (setCA (cmp A)) (setCB (cmp B))) 1677 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1678 /// can be reassociated to: 1679 /// or (and (setCC (cmp C)) setCD (cmp D)) 1680 // (or (setCA (cmp A)) (setCB (cmp B))) 1681 /// can be transformed to: 1682 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 1683 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1684 /// which can be implemented as: 1685 /// cmp C 1686 /// ccmp D, inv(CD), CC 1687 /// ccmp A, CA, inv(CD) 1688 /// ccmp B, CB, inv(CA) 1689 /// check for CB flags 1690 /// 1691 /// A counterexample is "or (and A B) (and C D)" which translates to 1692 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 1693 /// can only implement 1 of the inner (not) operations, but not both! 1694 /// @{ 1695 1696 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1697 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1698 ISD::CondCode CC, SDValue CCOp, 1699 AArch64CC::CondCode Predicate, 1700 AArch64CC::CondCode OutCC, 1701 const SDLoc &DL, SelectionDAG &DAG) { 1702 unsigned Opcode = 0; 1703 const bool FullFP16 = 1704 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1705 1706 if (LHS.getValueType().isFloatingPoint()) { 1707 assert(LHS.getValueType() != MVT::f128); 1708 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 1709 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1710 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1711 } 1712 Opcode = AArch64ISD::FCCMP; 1713 } else if (RHS.getOpcode() == ISD::SUB) { 1714 SDValue SubOp0 = RHS.getOperand(0); 1715 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1716 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1717 Opcode = AArch64ISD::CCMN; 1718 RHS = RHS.getOperand(1); 1719 } 1720 } 1721 if (Opcode == 0) 1722 Opcode = AArch64ISD::CCMP; 1723 1724 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1725 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1726 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1727 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1728 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1729 } 1730 1731 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 1732 /// expressed as a conjunction. See \ref AArch64CCMP. 1733 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 1734 /// changing the conditions on the SETCC tests. 1735 /// (this means we can call emitConjunctionRec() with 1736 /// Negate==true on this sub-tree) 1737 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 1738 /// cannot do the negation naturally. We are required to 1739 /// emit the subtree first in this case. 1740 /// \param WillNegate Is true if are called when the result of this 1741 /// subexpression must be negated. This happens when the 1742 /// outer expression is an OR. We can use this fact to know 1743 /// that we have a double negation (or (or ...) ...) that 1744 /// can be implemented for free. 1745 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 1746 bool &MustBeFirst, bool WillNegate, 1747 unsigned Depth = 0) { 1748 if (!Val.hasOneUse()) 1749 return false; 1750 unsigned Opcode = Val->getOpcode(); 1751 if (Opcode == ISD::SETCC) { 1752 if (Val->getOperand(0).getValueType() == MVT::f128) 1753 return false; 1754 CanNegate = true; 1755 MustBeFirst = false; 1756 return true; 1757 } 1758 // Protect against exponential runtime and stack overflow. 1759 if (Depth > 6) 1760 return false; 1761 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1762 bool IsOR = Opcode == ISD::OR; 1763 SDValue O0 = Val->getOperand(0); 1764 SDValue O1 = Val->getOperand(1); 1765 bool CanNegateL; 1766 bool MustBeFirstL; 1767 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 1768 return false; 1769 bool CanNegateR; 1770 bool MustBeFirstR; 1771 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 1772 return false; 1773 1774 if (MustBeFirstL && MustBeFirstR) 1775 return false; 1776 1777 if (IsOR) { 1778 // For an OR expression we need to be able to naturally negate at least 1779 // one side or we cannot do the transformation at all. 1780 if (!CanNegateL && !CanNegateR) 1781 return false; 1782 // If we the result of the OR will be negated and we can naturally negate 1783 // the leafs, then this sub-tree as a whole negates naturally. 1784 CanNegate = WillNegate && CanNegateL && CanNegateR; 1785 // If we cannot naturally negate the whole sub-tree, then this must be 1786 // emitted first. 1787 MustBeFirst = !CanNegate; 1788 } else { 1789 assert(Opcode == ISD::AND && "Must be OR or AND"); 1790 // We cannot naturally negate an AND operation. 1791 CanNegate = false; 1792 MustBeFirst = MustBeFirstL || MustBeFirstR; 1793 } 1794 return true; 1795 } 1796 return false; 1797 } 1798 1799 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1800 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1801 /// Tries to transform the given i1 producing node @p Val to a series compare 1802 /// and conditional compare operations. @returns an NZCV flags producing node 1803 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1804 /// transformation was not possible. 1805 /// \p Negate is true if we want this sub-tree being negated just by changing 1806 /// SETCC conditions. 1807 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 1808 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1809 AArch64CC::CondCode Predicate) { 1810 // We're at a tree leaf, produce a conditional comparison operation. 1811 unsigned Opcode = Val->getOpcode(); 1812 if (Opcode == ISD::SETCC) { 1813 SDValue LHS = Val->getOperand(0); 1814 SDValue RHS = Val->getOperand(1); 1815 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1816 bool isInteger = LHS.getValueType().isInteger(); 1817 if (Negate) 1818 CC = getSetCCInverse(CC, isInteger); 1819 SDLoc DL(Val); 1820 // Determine OutCC and handle FP special case. 1821 if (isInteger) { 1822 OutCC = changeIntCCToAArch64CC(CC); 1823 } else { 1824 assert(LHS.getValueType().isFloatingPoint()); 1825 AArch64CC::CondCode ExtraCC; 1826 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1827 // Some floating point conditions can't be tested with a single condition 1828 // code. Construct an additional comparison in this case. 1829 if (ExtraCC != AArch64CC::AL) { 1830 SDValue ExtraCmp; 1831 if (!CCOp.getNode()) 1832 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1833 else 1834 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1835 ExtraCC, DL, DAG); 1836 CCOp = ExtraCmp; 1837 Predicate = ExtraCC; 1838 } 1839 } 1840 1841 // Produce a normal comparison if we are first in the chain 1842 if (!CCOp) 1843 return emitComparison(LHS, RHS, CC, DL, DAG); 1844 // Otherwise produce a ccmp. 1845 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1846 DAG); 1847 } 1848 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 1849 1850 bool IsOR = Opcode == ISD::OR; 1851 1852 SDValue LHS = Val->getOperand(0); 1853 bool CanNegateL; 1854 bool MustBeFirstL; 1855 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 1856 assert(ValidL && "Valid conjunction/disjunction tree"); 1857 (void)ValidL; 1858 1859 SDValue RHS = Val->getOperand(1); 1860 bool CanNegateR; 1861 bool MustBeFirstR; 1862 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 1863 assert(ValidR && "Valid conjunction/disjunction tree"); 1864 (void)ValidR; 1865 1866 // Swap sub-tree that must come first to the right side. 1867 if (MustBeFirstL) { 1868 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 1869 std::swap(LHS, RHS); 1870 std::swap(CanNegateL, CanNegateR); 1871 std::swap(MustBeFirstL, MustBeFirstR); 1872 } 1873 1874 bool NegateR; 1875 bool NegateAfterR; 1876 bool NegateL; 1877 bool NegateAfterAll; 1878 if (Opcode == ISD::OR) { 1879 // Swap the sub-tree that we can negate naturally to the left. 1880 if (!CanNegateL) { 1881 assert(CanNegateR && "at least one side must be negatable"); 1882 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 1883 assert(!Negate); 1884 std::swap(LHS, RHS); 1885 NegateR = false; 1886 NegateAfterR = true; 1887 } else { 1888 // Negate the left sub-tree if possible, otherwise negate the result. 1889 NegateR = CanNegateR; 1890 NegateAfterR = !CanNegateR; 1891 } 1892 NegateL = true; 1893 NegateAfterAll = !Negate; 1894 } else { 1895 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 1896 assert(!Negate && "Valid conjunction/disjunction tree"); 1897 1898 NegateL = false; 1899 NegateR = false; 1900 NegateAfterR = false; 1901 NegateAfterAll = false; 1902 } 1903 1904 // Emit sub-trees. 1905 AArch64CC::CondCode RHSCC; 1906 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 1907 if (NegateAfterR) 1908 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1909 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 1910 if (NegateAfterAll) 1911 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1912 return CmpL; 1913 } 1914 1915 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 1916 /// In some cases this is even possible with OR operations in the expression. 1917 /// See \ref AArch64CCMP. 1918 /// \see emitConjunctionRec(). 1919 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 1920 AArch64CC::CondCode &OutCC) { 1921 bool DummyCanNegate; 1922 bool DummyMustBeFirst; 1923 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 1924 return SDValue(); 1925 1926 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 1927 } 1928 1929 /// @} 1930 1931 /// Returns how profitable it is to fold a comparison's operand's shift and/or 1932 /// extension operations. 1933 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 1934 auto isSupportedExtend = [&](SDValue V) { 1935 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 1936 return true; 1937 1938 if (V.getOpcode() == ISD::AND) 1939 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 1940 uint64_t Mask = MaskCst->getZExtValue(); 1941 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 1942 } 1943 1944 return false; 1945 }; 1946 1947 if (!Op.hasOneUse()) 1948 return 0; 1949 1950 if (isSupportedExtend(Op)) 1951 return 1; 1952 1953 unsigned Opc = Op.getOpcode(); 1954 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 1955 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1956 uint64_t Shift = ShiftCst->getZExtValue(); 1957 if (isSupportedExtend(Op.getOperand(0))) 1958 return (Shift <= 4) ? 2 : 1; 1959 EVT VT = Op.getValueType(); 1960 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 1961 return 1; 1962 } 1963 1964 return 0; 1965 } 1966 1967 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1968 SDValue &AArch64cc, SelectionDAG &DAG, 1969 const SDLoc &dl) { 1970 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1971 EVT VT = RHS.getValueType(); 1972 uint64_t C = RHSC->getZExtValue(); 1973 if (!isLegalArithImmed(C)) { 1974 // Constant does not fit, try adjusting it by one? 1975 switch (CC) { 1976 default: 1977 break; 1978 case ISD::SETLT: 1979 case ISD::SETGE: 1980 if ((VT == MVT::i32 && C != 0x80000000 && 1981 isLegalArithImmed((uint32_t)(C - 1))) || 1982 (VT == MVT::i64 && C != 0x80000000ULL && 1983 isLegalArithImmed(C - 1ULL))) { 1984 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1985 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1986 RHS = DAG.getConstant(C, dl, VT); 1987 } 1988 break; 1989 case ISD::SETULT: 1990 case ISD::SETUGE: 1991 if ((VT == MVT::i32 && C != 0 && 1992 isLegalArithImmed((uint32_t)(C - 1))) || 1993 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1994 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1995 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1996 RHS = DAG.getConstant(C, dl, VT); 1997 } 1998 break; 1999 case ISD::SETLE: 2000 case ISD::SETGT: 2001 if ((VT == MVT::i32 && C != INT32_MAX && 2002 isLegalArithImmed((uint32_t)(C + 1))) || 2003 (VT == MVT::i64 && C != INT64_MAX && 2004 isLegalArithImmed(C + 1ULL))) { 2005 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2006 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2007 RHS = DAG.getConstant(C, dl, VT); 2008 } 2009 break; 2010 case ISD::SETULE: 2011 case ISD::SETUGT: 2012 if ((VT == MVT::i32 && C != UINT32_MAX && 2013 isLegalArithImmed((uint32_t)(C + 1))) || 2014 (VT == MVT::i64 && C != UINT64_MAX && 2015 isLegalArithImmed(C + 1ULL))) { 2016 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2017 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2018 RHS = DAG.getConstant(C, dl, VT); 2019 } 2020 break; 2021 } 2022 } 2023 } 2024 2025 // Comparisons are canonicalized so that the RHS operand is simpler than the 2026 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2027 // can fold some shift+extend operations on the RHS operand, so swap the 2028 // operands if that can be done. 2029 // 2030 // For example: 2031 // lsl w13, w11, #1 2032 // cmp w13, w12 2033 // can be turned into: 2034 // cmp w12, w11, lsl #1 2035 if (!isa<ConstantSDNode>(RHS) || 2036 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2037 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2038 2039 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2040 std::swap(LHS, RHS); 2041 CC = ISD::getSetCCSwappedOperands(CC); 2042 } 2043 } 2044 2045 SDValue Cmp; 2046 AArch64CC::CondCode AArch64CC; 2047 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2048 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2049 2050 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2051 // For the i8 operand, the largest immediate is 255, so this can be easily 2052 // encoded in the compare instruction. For the i16 operand, however, the 2053 // largest immediate cannot be encoded in the compare. 2054 // Therefore, use a sign extending load and cmn to avoid materializing the 2055 // -1 constant. For example, 2056 // movz w1, #65535 2057 // ldrh w0, [x0, #0] 2058 // cmp w0, w1 2059 // > 2060 // ldrsh w0, [x0, #0] 2061 // cmn w0, #1 2062 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2063 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2064 // ensure both the LHS and RHS are truly zero extended and to make sure the 2065 // transformation is profitable. 2066 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2067 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2068 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2069 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2070 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2071 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2072 SDValue SExt = 2073 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2074 DAG.getValueType(MVT::i16)); 2075 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2076 RHS.getValueType()), 2077 CC, dl, DAG); 2078 AArch64CC = changeIntCCToAArch64CC(CC); 2079 } 2080 } 2081 2082 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2083 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2084 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2085 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2086 } 2087 } 2088 } 2089 2090 if (!Cmp) { 2091 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2092 AArch64CC = changeIntCCToAArch64CC(CC); 2093 } 2094 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2095 return Cmp; 2096 } 2097 2098 static std::pair<SDValue, SDValue> 2099 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2100 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2101 "Unsupported value type"); 2102 SDValue Value, Overflow; 2103 SDLoc DL(Op); 2104 SDValue LHS = Op.getOperand(0); 2105 SDValue RHS = Op.getOperand(1); 2106 unsigned Opc = 0; 2107 switch (Op.getOpcode()) { 2108 default: 2109 llvm_unreachable("Unknown overflow instruction!"); 2110 case ISD::SADDO: 2111 Opc = AArch64ISD::ADDS; 2112 CC = AArch64CC::VS; 2113 break; 2114 case ISD::UADDO: 2115 Opc = AArch64ISD::ADDS; 2116 CC = AArch64CC::HS; 2117 break; 2118 case ISD::SSUBO: 2119 Opc = AArch64ISD::SUBS; 2120 CC = AArch64CC::VS; 2121 break; 2122 case ISD::USUBO: 2123 Opc = AArch64ISD::SUBS; 2124 CC = AArch64CC::LO; 2125 break; 2126 // Multiply needs a little bit extra work. 2127 case ISD::SMULO: 2128 case ISD::UMULO: { 2129 CC = AArch64CC::NE; 2130 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2131 if (Op.getValueType() == MVT::i32) { 2132 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2133 // For a 32 bit multiply with overflow check we want the instruction 2134 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2135 // need to generate the following pattern: 2136 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2137 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2138 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2139 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2140 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2141 DAG.getConstant(0, DL, MVT::i64)); 2142 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2143 // operation. We need to clear out the upper 32 bits, because we used a 2144 // widening multiply that wrote all 64 bits. In the end this should be a 2145 // noop. 2146 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2147 if (IsSigned) { 2148 // The signed overflow check requires more than just a simple check for 2149 // any bit set in the upper 32 bits of the result. These bits could be 2150 // just the sign bits of a negative number. To perform the overflow 2151 // check we have to arithmetic shift right the 32nd bit of the result by 2152 // 31 bits. Then we compare the result to the upper 32 bits. 2153 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2154 DAG.getConstant(32, DL, MVT::i64)); 2155 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2156 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2157 DAG.getConstant(31, DL, MVT::i64)); 2158 // It is important that LowerBits is last, otherwise the arithmetic 2159 // shift will not be folded into the compare (SUBS). 2160 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2161 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2162 .getValue(1); 2163 } else { 2164 // The overflow check for unsigned multiply is easy. We only need to 2165 // check if any of the upper 32 bits are set. This can be done with a 2166 // CMP (shifted register). For that we need to generate the following 2167 // pattern: 2168 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2169 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2170 DAG.getConstant(32, DL, MVT::i64)); 2171 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2172 Overflow = 2173 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2174 DAG.getConstant(0, DL, MVT::i64), 2175 UpperBits).getValue(1); 2176 } 2177 break; 2178 } 2179 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2180 // For the 64 bit multiply 2181 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2182 if (IsSigned) { 2183 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2184 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2185 DAG.getConstant(63, DL, MVT::i64)); 2186 // It is important that LowerBits is last, otherwise the arithmetic 2187 // shift will not be folded into the compare (SUBS). 2188 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2189 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2190 .getValue(1); 2191 } else { 2192 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2193 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2194 Overflow = 2195 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2196 DAG.getConstant(0, DL, MVT::i64), 2197 UpperBits).getValue(1); 2198 } 2199 break; 2200 } 2201 } // switch (...) 2202 2203 if (Opc) { 2204 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2205 2206 // Emit the AArch64 operation with overflow check. 2207 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2208 Overflow = Value.getValue(1); 2209 } 2210 return std::make_pair(Value, Overflow); 2211 } 2212 2213 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 2214 RTLIB::Libcall Call) const { 2215 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2216 MakeLibCallOptions CallOptions; 2217 return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first; 2218 } 2219 2220 // Returns true if the given Op is the overflow flag result of an overflow 2221 // intrinsic operation. 2222 static bool isOverflowIntrOpRes(SDValue Op) { 2223 unsigned Opc = Op.getOpcode(); 2224 return (Op.getResNo() == 1 && 2225 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 2226 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)); 2227 } 2228 2229 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 2230 SDValue Sel = Op.getOperand(0); 2231 SDValue Other = Op.getOperand(1); 2232 SDLoc dl(Sel); 2233 2234 // If the operand is an overflow checking operation, invert the condition 2235 // code and kill the Not operation. I.e., transform: 2236 // (xor (overflow_op_bool, 1)) 2237 // --> 2238 // (csel 1, 0, invert(cc), overflow_op_bool) 2239 // ... which later gets transformed to just a cset instruction with an 2240 // inverted condition code, rather than a cset + eor sequence. 2241 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) { 2242 // Only lower legal XALUO ops. 2243 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2244 return SDValue(); 2245 2246 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2247 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2248 AArch64CC::CondCode CC; 2249 SDValue Value, Overflow; 2250 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2251 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2252 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2253 CCVal, Overflow); 2254 } 2255 // If neither operand is a SELECT_CC, give up. 2256 if (Sel.getOpcode() != ISD::SELECT_CC) 2257 std::swap(Sel, Other); 2258 if (Sel.getOpcode() != ISD::SELECT_CC) 2259 return Op; 2260 2261 // The folding we want to perform is: 2262 // (xor x, (select_cc a, b, cc, 0, -1) ) 2263 // --> 2264 // (csel x, (xor x, -1), cc ...) 2265 // 2266 // The latter will get matched to a CSINV instruction. 2267 2268 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2269 SDValue LHS = Sel.getOperand(0); 2270 SDValue RHS = Sel.getOperand(1); 2271 SDValue TVal = Sel.getOperand(2); 2272 SDValue FVal = Sel.getOperand(3); 2273 2274 // FIXME: This could be generalized to non-integer comparisons. 2275 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2276 return Op; 2277 2278 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2279 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2280 2281 // The values aren't constants, this isn't the pattern we're looking for. 2282 if (!CFVal || !CTVal) 2283 return Op; 2284 2285 // We can commute the SELECT_CC by inverting the condition. This 2286 // might be needed to make this fit into a CSINV pattern. 2287 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2288 std::swap(TVal, FVal); 2289 std::swap(CTVal, CFVal); 2290 CC = ISD::getSetCCInverse(CC, true); 2291 } 2292 2293 // If the constants line up, perform the transform! 2294 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2295 SDValue CCVal; 2296 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2297 2298 FVal = Other; 2299 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2300 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2301 2302 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2303 CCVal, Cmp); 2304 } 2305 2306 return Op; 2307 } 2308 2309 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2310 EVT VT = Op.getValueType(); 2311 2312 // Let legalize expand this if it isn't a legal type yet. 2313 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2314 return SDValue(); 2315 2316 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2317 2318 unsigned Opc; 2319 bool ExtraOp = false; 2320 switch (Op.getOpcode()) { 2321 default: 2322 llvm_unreachable("Invalid code"); 2323 case ISD::ADDC: 2324 Opc = AArch64ISD::ADDS; 2325 break; 2326 case ISD::SUBC: 2327 Opc = AArch64ISD::SUBS; 2328 break; 2329 case ISD::ADDE: 2330 Opc = AArch64ISD::ADCS; 2331 ExtraOp = true; 2332 break; 2333 case ISD::SUBE: 2334 Opc = AArch64ISD::SBCS; 2335 ExtraOp = true; 2336 break; 2337 } 2338 2339 if (!ExtraOp) 2340 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2341 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2342 Op.getOperand(2)); 2343 } 2344 2345 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2346 // Let legalize expand this if it isn't a legal type yet. 2347 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2348 return SDValue(); 2349 2350 SDLoc dl(Op); 2351 AArch64CC::CondCode CC; 2352 // The actual operation that sets the overflow or carry flag. 2353 SDValue Value, Overflow; 2354 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2355 2356 // We use 0 and 1 as false and true values. 2357 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2358 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2359 2360 // We use an inverted condition, because the conditional select is inverted 2361 // too. This will allow it to be selected to a single instruction: 2362 // CSINC Wd, WZR, WZR, invert(cond). 2363 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2364 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2365 CCVal, Overflow); 2366 2367 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2368 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2369 } 2370 2371 // Prefetch operands are: 2372 // 1: Address to prefetch 2373 // 2: bool isWrite 2374 // 3: int locality (0 = no locality ... 3 = extreme locality) 2375 // 4: bool isDataCache 2376 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2377 SDLoc DL(Op); 2378 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2379 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2380 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2381 2382 bool IsStream = !Locality; 2383 // When the locality number is set 2384 if (Locality) { 2385 // The front-end should have filtered out the out-of-range values 2386 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2387 // The locality degree is the opposite of the cache speed. 2388 // Put the number the other way around. 2389 // The encoding starts at 0 for level 1 2390 Locality = 3 - Locality; 2391 } 2392 2393 // built the mask value encoding the expected behavior. 2394 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2395 (!IsData << 3) | // IsDataCache bit 2396 (Locality << 1) | // Cache level bits 2397 (unsigned)IsStream; // Stream bit 2398 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2399 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2400 } 2401 2402 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2403 SelectionDAG &DAG) const { 2404 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2405 2406 RTLIB::Libcall LC; 2407 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2408 2409 return LowerF128Call(Op, DAG, LC); 2410 } 2411 2412 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2413 SelectionDAG &DAG) const { 2414 if (Op.getOperand(0).getValueType() != MVT::f128) { 2415 // It's legal except when f128 is involved 2416 return Op; 2417 } 2418 2419 RTLIB::Libcall LC; 2420 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 2421 2422 // FP_ROUND node has a second operand indicating whether it is known to be 2423 // precise. That doesn't take part in the LibCall so we can't directly use 2424 // LowerF128Call. 2425 SDValue SrcVal = Op.getOperand(0); 2426 MakeLibCallOptions CallOptions; 2427 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions, 2428 SDLoc(Op)).first; 2429 } 2430 2431 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 2432 SelectionDAG &DAG) const { 2433 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2434 // Any additional optimization in this function should be recorded 2435 // in the cost tables. 2436 EVT InVT = Op.getOperand(0).getValueType(); 2437 EVT VT = Op.getValueType(); 2438 unsigned NumElts = InVT.getVectorNumElements(); 2439 2440 // f16 conversions are promoted to f32 when full fp16 is not supported. 2441 if (InVT.getVectorElementType() == MVT::f16 && 2442 !Subtarget->hasFullFP16()) { 2443 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2444 SDLoc dl(Op); 2445 return DAG.getNode( 2446 Op.getOpcode(), dl, Op.getValueType(), 2447 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2448 } 2449 2450 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2451 SDLoc dl(Op); 2452 SDValue Cv = 2453 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2454 Op.getOperand(0)); 2455 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2456 } 2457 2458 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2459 SDLoc dl(Op); 2460 MVT ExtVT = 2461 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2462 VT.getVectorNumElements()); 2463 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2464 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2465 } 2466 2467 // Type changing conversions are illegal. 2468 return Op; 2469 } 2470 2471 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2472 SelectionDAG &DAG) const { 2473 if (Op.getOperand(0).getValueType().isVector()) 2474 return LowerVectorFP_TO_INT(Op, DAG); 2475 2476 // f16 conversions are promoted to f32 when full fp16 is not supported. 2477 if (Op.getOperand(0).getValueType() == MVT::f16 && 2478 !Subtarget->hasFullFP16()) { 2479 SDLoc dl(Op); 2480 return DAG.getNode( 2481 Op.getOpcode(), dl, Op.getValueType(), 2482 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2483 } 2484 2485 if (Op.getOperand(0).getValueType() != MVT::f128) { 2486 // It's legal except when f128 is involved 2487 return Op; 2488 } 2489 2490 RTLIB::Libcall LC; 2491 if (Op.getOpcode() == ISD::FP_TO_SINT) 2492 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2493 else 2494 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2495 2496 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2497 MakeLibCallOptions CallOptions; 2498 return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first; 2499 } 2500 2501 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2502 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2503 // Any additional optimization in this function should be recorded 2504 // in the cost tables. 2505 EVT VT = Op.getValueType(); 2506 SDLoc dl(Op); 2507 SDValue In = Op.getOperand(0); 2508 EVT InVT = In.getValueType(); 2509 2510 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2511 MVT CastVT = 2512 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2513 InVT.getVectorNumElements()); 2514 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2515 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2516 } 2517 2518 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2519 unsigned CastOpc = 2520 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2521 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2522 In = DAG.getNode(CastOpc, dl, CastVT, In); 2523 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2524 } 2525 2526 return Op; 2527 } 2528 2529 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2530 SelectionDAG &DAG) const { 2531 if (Op.getValueType().isVector()) 2532 return LowerVectorINT_TO_FP(Op, DAG); 2533 2534 // f16 conversions are promoted to f32 when full fp16 is not supported. 2535 if (Op.getValueType() == MVT::f16 && 2536 !Subtarget->hasFullFP16()) { 2537 SDLoc dl(Op); 2538 return DAG.getNode( 2539 ISD::FP_ROUND, dl, MVT::f16, 2540 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2541 DAG.getIntPtrConstant(0, dl)); 2542 } 2543 2544 // i128 conversions are libcalls. 2545 if (Op.getOperand(0).getValueType() == MVT::i128) 2546 return SDValue(); 2547 2548 // Other conversions are legal, unless it's to the completely software-based 2549 // fp128. 2550 if (Op.getValueType() != MVT::f128) 2551 return Op; 2552 2553 RTLIB::Libcall LC; 2554 if (Op.getOpcode() == ISD::SINT_TO_FP) 2555 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2556 else 2557 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2558 2559 return LowerF128Call(Op, DAG, LC); 2560 } 2561 2562 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2563 SelectionDAG &DAG) const { 2564 // For iOS, we want to call an alternative entry point: __sincos_stret, 2565 // which returns the values in two S / D registers. 2566 SDLoc dl(Op); 2567 SDValue Arg = Op.getOperand(0); 2568 EVT ArgVT = Arg.getValueType(); 2569 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2570 2571 ArgListTy Args; 2572 ArgListEntry Entry; 2573 2574 Entry.Node = Arg; 2575 Entry.Ty = ArgTy; 2576 Entry.IsSExt = false; 2577 Entry.IsZExt = false; 2578 Args.push_back(Entry); 2579 2580 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 2581 : RTLIB::SINCOS_STRET_F32; 2582 const char *LibcallName = getLibcallName(LC); 2583 SDValue Callee = 2584 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2585 2586 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2587 TargetLowering::CallLoweringInfo CLI(DAG); 2588 CLI.setDebugLoc(dl) 2589 .setChain(DAG.getEntryNode()) 2590 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2591 2592 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2593 return CallResult.first; 2594 } 2595 2596 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2597 if (Op.getValueType() != MVT::f16) 2598 return SDValue(); 2599 2600 assert(Op.getOperand(0).getValueType() == MVT::i16); 2601 SDLoc DL(Op); 2602 2603 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2604 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2605 return SDValue( 2606 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2607 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2608 0); 2609 } 2610 2611 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2612 if (OrigVT.getSizeInBits() >= 64) 2613 return OrigVT; 2614 2615 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2616 2617 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2618 switch (OrigSimpleTy) { 2619 default: llvm_unreachable("Unexpected Vector Type"); 2620 case MVT::v2i8: 2621 case MVT::v2i16: 2622 return MVT::v2i32; 2623 case MVT::v4i8: 2624 return MVT::v4i16; 2625 } 2626 } 2627 2628 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2629 const EVT &OrigTy, 2630 const EVT &ExtTy, 2631 unsigned ExtOpcode) { 2632 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2633 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2634 // 64-bits we need to insert a new extension so that it will be 64-bits. 2635 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2636 if (OrigTy.getSizeInBits() >= 64) 2637 return N; 2638 2639 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2640 EVT NewVT = getExtensionTo64Bits(OrigTy); 2641 2642 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2643 } 2644 2645 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2646 bool isSigned) { 2647 EVT VT = N->getValueType(0); 2648 2649 if (N->getOpcode() != ISD::BUILD_VECTOR) 2650 return false; 2651 2652 for (const SDValue &Elt : N->op_values()) { 2653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2654 unsigned EltSize = VT.getScalarSizeInBits(); 2655 unsigned HalfSize = EltSize / 2; 2656 if (isSigned) { 2657 if (!isIntN(HalfSize, C->getSExtValue())) 2658 return false; 2659 } else { 2660 if (!isUIntN(HalfSize, C->getZExtValue())) 2661 return false; 2662 } 2663 continue; 2664 } 2665 return false; 2666 } 2667 2668 return true; 2669 } 2670 2671 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2672 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2673 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2674 N->getOperand(0)->getValueType(0), 2675 N->getValueType(0), 2676 N->getOpcode()); 2677 2678 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2679 EVT VT = N->getValueType(0); 2680 SDLoc dl(N); 2681 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2682 unsigned NumElts = VT.getVectorNumElements(); 2683 MVT TruncVT = MVT::getIntegerVT(EltSize); 2684 SmallVector<SDValue, 8> Ops; 2685 for (unsigned i = 0; i != NumElts; ++i) { 2686 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2687 const APInt &CInt = C->getAPIntValue(); 2688 // Element types smaller than 32 bits are not legal, so use i32 elements. 2689 // The values are implicitly truncated so sext vs. zext doesn't matter. 2690 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2691 } 2692 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2693 } 2694 2695 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2696 return N->getOpcode() == ISD::SIGN_EXTEND || 2697 isExtendedBUILD_VECTOR(N, DAG, true); 2698 } 2699 2700 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2701 return N->getOpcode() == ISD::ZERO_EXTEND || 2702 isExtendedBUILD_VECTOR(N, DAG, false); 2703 } 2704 2705 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2706 unsigned Opcode = N->getOpcode(); 2707 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2708 SDNode *N0 = N->getOperand(0).getNode(); 2709 SDNode *N1 = N->getOperand(1).getNode(); 2710 return N0->hasOneUse() && N1->hasOneUse() && 2711 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2712 } 2713 return false; 2714 } 2715 2716 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2717 unsigned Opcode = N->getOpcode(); 2718 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2719 SDNode *N0 = N->getOperand(0).getNode(); 2720 SDNode *N1 = N->getOperand(1).getNode(); 2721 return N0->hasOneUse() && N1->hasOneUse() && 2722 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2723 } 2724 return false; 2725 } 2726 2727 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 2728 SelectionDAG &DAG) const { 2729 // The rounding mode is in bits 23:22 of the FPSCR. 2730 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 2731 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 2732 // so that the shift + and get folded into a bitfield extract. 2733 SDLoc dl(Op); 2734 2735 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64, 2736 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, 2737 MVT::i64)); 2738 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 2739 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 2740 DAG.getConstant(1U << 22, dl, MVT::i32)); 2741 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 2742 DAG.getConstant(22, dl, MVT::i32)); 2743 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 2744 DAG.getConstant(3, dl, MVT::i32)); 2745 } 2746 2747 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2748 // Multiplications are only custom-lowered for 128-bit vectors so that 2749 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2750 EVT VT = Op.getValueType(); 2751 assert(VT.is128BitVector() && VT.isInteger() && 2752 "unexpected type for custom-lowering ISD::MUL"); 2753 SDNode *N0 = Op.getOperand(0).getNode(); 2754 SDNode *N1 = Op.getOperand(1).getNode(); 2755 unsigned NewOpc = 0; 2756 bool isMLA = false; 2757 bool isN0SExt = isSignExtended(N0, DAG); 2758 bool isN1SExt = isSignExtended(N1, DAG); 2759 if (isN0SExt && isN1SExt) 2760 NewOpc = AArch64ISD::SMULL; 2761 else { 2762 bool isN0ZExt = isZeroExtended(N0, DAG); 2763 bool isN1ZExt = isZeroExtended(N1, DAG); 2764 if (isN0ZExt && isN1ZExt) 2765 NewOpc = AArch64ISD::UMULL; 2766 else if (isN1SExt || isN1ZExt) { 2767 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2768 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2769 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2770 NewOpc = AArch64ISD::SMULL; 2771 isMLA = true; 2772 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2773 NewOpc = AArch64ISD::UMULL; 2774 isMLA = true; 2775 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2776 std::swap(N0, N1); 2777 NewOpc = AArch64ISD::UMULL; 2778 isMLA = true; 2779 } 2780 } 2781 2782 if (!NewOpc) { 2783 if (VT == MVT::v2i64) 2784 // Fall through to expand this. It is not legal. 2785 return SDValue(); 2786 else 2787 // Other vector multiplications are legal. 2788 return Op; 2789 } 2790 } 2791 2792 // Legalize to a S/UMULL instruction 2793 SDLoc DL(Op); 2794 SDValue Op0; 2795 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2796 if (!isMLA) { 2797 Op0 = skipExtensionForVectorMULL(N0, DAG); 2798 assert(Op0.getValueType().is64BitVector() && 2799 Op1.getValueType().is64BitVector() && 2800 "unexpected types for extended operands to VMULL"); 2801 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2802 } 2803 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2804 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2805 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2806 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2807 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2808 EVT Op1VT = Op1.getValueType(); 2809 return DAG.getNode(N0->getOpcode(), DL, VT, 2810 DAG.getNode(NewOpc, DL, VT, 2811 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2812 DAG.getNode(NewOpc, DL, VT, 2813 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2814 } 2815 2816 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2817 SelectionDAG &DAG) const { 2818 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2819 SDLoc dl(Op); 2820 switch (IntNo) { 2821 default: return SDValue(); // Don't custom lower most intrinsics. 2822 case Intrinsic::thread_pointer: { 2823 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2824 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2825 } 2826 case Intrinsic::aarch64_neon_abs: { 2827 EVT Ty = Op.getValueType(); 2828 if (Ty == MVT::i64) { 2829 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 2830 Op.getOperand(1)); 2831 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 2832 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 2833 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 2834 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 2835 } else { 2836 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 2837 } 2838 } 2839 case Intrinsic::aarch64_neon_smax: 2840 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2841 Op.getOperand(1), Op.getOperand(2)); 2842 case Intrinsic::aarch64_neon_umax: 2843 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2844 Op.getOperand(1), Op.getOperand(2)); 2845 case Intrinsic::aarch64_neon_smin: 2846 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2847 Op.getOperand(1), Op.getOperand(2)); 2848 case Intrinsic::aarch64_neon_umin: 2849 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2850 Op.getOperand(1), Op.getOperand(2)); 2851 2852 case Intrinsic::aarch64_sve_sunpkhi: 2853 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 2854 Op.getOperand(1)); 2855 case Intrinsic::aarch64_sve_sunpklo: 2856 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 2857 Op.getOperand(1)); 2858 case Intrinsic::aarch64_sve_uunpkhi: 2859 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 2860 Op.getOperand(1)); 2861 case Intrinsic::aarch64_sve_uunpklo: 2862 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 2863 Op.getOperand(1)); 2864 2865 case Intrinsic::localaddress: { 2866 const auto &MF = DAG.getMachineFunction(); 2867 const auto *RegInfo = Subtarget->getRegisterInfo(); 2868 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 2869 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 2870 Op.getSimpleValueType()); 2871 } 2872 2873 case Intrinsic::eh_recoverfp: { 2874 // FIXME: This needs to be implemented to correctly handle highly aligned 2875 // stack objects. For now we simply return the incoming FP. Refer D53541 2876 // for more details. 2877 SDValue FnOp = Op.getOperand(1); 2878 SDValue IncomingFPOp = Op.getOperand(2); 2879 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 2880 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 2881 if (!Fn) 2882 report_fatal_error( 2883 "llvm.eh.recoverfp must take a function as the first argument"); 2884 return IncomingFPOp; 2885 } 2886 } 2887 } 2888 2889 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 2890 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 2891 EVT VT, EVT MemVT, 2892 SelectionDAG &DAG) { 2893 assert(VT.isVector() && "VT should be a vector type"); 2894 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 2895 2896 SDValue Value = ST->getValue(); 2897 2898 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 2899 // the word lane which represent the v4i8 subvector. It optimizes the store 2900 // to: 2901 // 2902 // xtn v0.8b, v0.8h 2903 // str s0, [x0] 2904 2905 SDValue Undef = DAG.getUNDEF(MVT::i16); 2906 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 2907 {Undef, Undef, Undef, Undef}); 2908 2909 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 2910 Value, UndefVec); 2911 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 2912 2913 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 2914 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 2915 Trunc, DAG.getConstant(0, DL, MVT::i64)); 2916 2917 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 2918 ST->getBasePtr(), ST->getMemOperand()); 2919 } 2920 2921 // Custom lowering for any store, vector or scalar and/or default or with 2922 // a truncate operations. Currently only custom lower truncate operation 2923 // from vector v4i16 to v4i8. 2924 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 2925 SelectionDAG &DAG) const { 2926 SDLoc Dl(Op); 2927 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 2928 assert (StoreNode && "Can only custom lower store nodes"); 2929 2930 SDValue Value = StoreNode->getValue(); 2931 2932 EVT VT = Value.getValueType(); 2933 EVT MemVT = StoreNode->getMemoryVT(); 2934 2935 assert (VT.isVector() && "Can only custom lower vector store types"); 2936 2937 unsigned AS = StoreNode->getAddressSpace(); 2938 unsigned Align = StoreNode->getAlignment(); 2939 if (Align < MemVT.getStoreSize() && 2940 !allowsMisalignedMemoryAccesses( 2941 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) { 2942 return scalarizeVectorStore(StoreNode, DAG); 2943 } 2944 2945 if (StoreNode->isTruncatingStore()) { 2946 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 2947 } 2948 2949 return SDValue(); 2950 } 2951 2952 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2953 SelectionDAG &DAG) const { 2954 LLVM_DEBUG(dbgs() << "Custom lowering: "); 2955 LLVM_DEBUG(Op.dump()); 2956 2957 switch (Op.getOpcode()) { 2958 default: 2959 llvm_unreachable("unimplemented operand"); 2960 return SDValue(); 2961 case ISD::BITCAST: 2962 return LowerBITCAST(Op, DAG); 2963 case ISD::GlobalAddress: 2964 return LowerGlobalAddress(Op, DAG); 2965 case ISD::GlobalTLSAddress: 2966 return LowerGlobalTLSAddress(Op, DAG); 2967 case ISD::SETCC: 2968 return LowerSETCC(Op, DAG); 2969 case ISD::BR_CC: 2970 return LowerBR_CC(Op, DAG); 2971 case ISD::SELECT: 2972 return LowerSELECT(Op, DAG); 2973 case ISD::SELECT_CC: 2974 return LowerSELECT_CC(Op, DAG); 2975 case ISD::JumpTable: 2976 return LowerJumpTable(Op, DAG); 2977 case ISD::BR_JT: 2978 return LowerBR_JT(Op, DAG); 2979 case ISD::ConstantPool: 2980 return LowerConstantPool(Op, DAG); 2981 case ISD::BlockAddress: 2982 return LowerBlockAddress(Op, DAG); 2983 case ISD::VASTART: 2984 return LowerVASTART(Op, DAG); 2985 case ISD::VACOPY: 2986 return LowerVACOPY(Op, DAG); 2987 case ISD::VAARG: 2988 return LowerVAARG(Op, DAG); 2989 case ISD::ADDC: 2990 case ISD::ADDE: 2991 case ISD::SUBC: 2992 case ISD::SUBE: 2993 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2994 case ISD::SADDO: 2995 case ISD::UADDO: 2996 case ISD::SSUBO: 2997 case ISD::USUBO: 2998 case ISD::SMULO: 2999 case ISD::UMULO: 3000 return LowerXALUO(Op, DAG); 3001 case ISD::FADD: 3002 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 3003 case ISD::FSUB: 3004 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 3005 case ISD::FMUL: 3006 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 3007 case ISD::FDIV: 3008 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 3009 case ISD::FP_ROUND: 3010 return LowerFP_ROUND(Op, DAG); 3011 case ISD::FP_EXTEND: 3012 return LowerFP_EXTEND(Op, DAG); 3013 case ISD::FRAMEADDR: 3014 return LowerFRAMEADDR(Op, DAG); 3015 case ISD::SPONENTRY: 3016 return LowerSPONENTRY(Op, DAG); 3017 case ISD::RETURNADDR: 3018 return LowerRETURNADDR(Op, DAG); 3019 case ISD::ADDROFRETURNADDR: 3020 return LowerADDROFRETURNADDR(Op, DAG); 3021 case ISD::INSERT_VECTOR_ELT: 3022 return LowerINSERT_VECTOR_ELT(Op, DAG); 3023 case ISD::EXTRACT_VECTOR_ELT: 3024 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 3025 case ISD::BUILD_VECTOR: 3026 return LowerBUILD_VECTOR(Op, DAG); 3027 case ISD::VECTOR_SHUFFLE: 3028 return LowerVECTOR_SHUFFLE(Op, DAG); 3029 case ISD::SPLAT_VECTOR: 3030 return LowerSPLAT_VECTOR(Op, DAG); 3031 case ISD::EXTRACT_SUBVECTOR: 3032 return LowerEXTRACT_SUBVECTOR(Op, DAG); 3033 case ISD::SRA: 3034 case ISD::SRL: 3035 case ISD::SHL: 3036 return LowerVectorSRA_SRL_SHL(Op, DAG); 3037 case ISD::SHL_PARTS: 3038 return LowerShiftLeftParts(Op, DAG); 3039 case ISD::SRL_PARTS: 3040 case ISD::SRA_PARTS: 3041 return LowerShiftRightParts(Op, DAG); 3042 case ISD::CTPOP: 3043 return LowerCTPOP(Op, DAG); 3044 case ISD::FCOPYSIGN: 3045 return LowerFCOPYSIGN(Op, DAG); 3046 case ISD::OR: 3047 return LowerVectorOR(Op, DAG); 3048 case ISD::XOR: 3049 return LowerXOR(Op, DAG); 3050 case ISD::PREFETCH: 3051 return LowerPREFETCH(Op, DAG); 3052 case ISD::SINT_TO_FP: 3053 case ISD::UINT_TO_FP: 3054 return LowerINT_TO_FP(Op, DAG); 3055 case ISD::FP_TO_SINT: 3056 case ISD::FP_TO_UINT: 3057 return LowerFP_TO_INT(Op, DAG); 3058 case ISD::FSINCOS: 3059 return LowerFSINCOS(Op, DAG); 3060 case ISD::FLT_ROUNDS_: 3061 return LowerFLT_ROUNDS_(Op, DAG); 3062 case ISD::MUL: 3063 return LowerMUL(Op, DAG); 3064 case ISD::INTRINSIC_WO_CHAIN: 3065 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3066 case ISD::STORE: 3067 return LowerSTORE(Op, DAG); 3068 case ISD::VECREDUCE_ADD: 3069 case ISD::VECREDUCE_SMAX: 3070 case ISD::VECREDUCE_SMIN: 3071 case ISD::VECREDUCE_UMAX: 3072 case ISD::VECREDUCE_UMIN: 3073 case ISD::VECREDUCE_FMAX: 3074 case ISD::VECREDUCE_FMIN: 3075 return LowerVECREDUCE(Op, DAG); 3076 case ISD::ATOMIC_LOAD_SUB: 3077 return LowerATOMIC_LOAD_SUB(Op, DAG); 3078 case ISD::ATOMIC_LOAD_AND: 3079 return LowerATOMIC_LOAD_AND(Op, DAG); 3080 case ISD::DYNAMIC_STACKALLOC: 3081 return LowerDYNAMIC_STACKALLOC(Op, DAG); 3082 } 3083 } 3084 3085 //===----------------------------------------------------------------------===// 3086 // Calling Convention Implementation 3087 //===----------------------------------------------------------------------===// 3088 3089 /// Selects the correct CCAssignFn for a given CallingConvention value. 3090 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 3091 bool IsVarArg) const { 3092 switch (CC) { 3093 default: 3094 report_fatal_error("Unsupported calling convention."); 3095 case CallingConv::WebKit_JS: 3096 return CC_AArch64_WebKit_JS; 3097 case CallingConv::GHC: 3098 return CC_AArch64_GHC; 3099 case CallingConv::C: 3100 case CallingConv::Fast: 3101 case CallingConv::PreserveMost: 3102 case CallingConv::CXX_FAST_TLS: 3103 case CallingConv::Swift: 3104 if (Subtarget->isTargetWindows() && IsVarArg) 3105 return CC_AArch64_Win64_VarArg; 3106 if (!Subtarget->isTargetDarwin()) 3107 return CC_AArch64_AAPCS; 3108 if (!IsVarArg) 3109 return CC_AArch64_DarwinPCS; 3110 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 3111 : CC_AArch64_DarwinPCS_VarArg; 3112 case CallingConv::Win64: 3113 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 3114 case CallingConv::AArch64_VectorCall: 3115 return CC_AArch64_AAPCS; 3116 } 3117 } 3118 3119 CCAssignFn * 3120 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 3121 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 3122 : RetCC_AArch64_AAPCS; 3123 } 3124 3125 SDValue AArch64TargetLowering::LowerFormalArguments( 3126 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3127 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3128 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3129 MachineFunction &MF = DAG.getMachineFunction(); 3130 MachineFrameInfo &MFI = MF.getFrameInfo(); 3131 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3132 3133 // Assign locations to all of the incoming arguments. 3134 SmallVector<CCValAssign, 16> ArgLocs; 3135 DenseMap<unsigned, SDValue> CopiedRegs; 3136 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3137 *DAG.getContext()); 3138 3139 // At this point, Ins[].VT may already be promoted to i32. To correctly 3140 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3141 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3142 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 3143 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 3144 // LocVT. 3145 unsigned NumArgs = Ins.size(); 3146 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3147 unsigned CurArgIdx = 0; 3148 for (unsigned i = 0; i != NumArgs; ++i) { 3149 MVT ValVT = Ins[i].VT; 3150 if (Ins[i].isOrigArg()) { 3151 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 3152 CurArgIdx = Ins[i].getOrigArgIndex(); 3153 3154 // Get type of the original argument. 3155 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 3156 /*AllowUnknown*/ true); 3157 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 3158 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3159 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3160 ValVT = MVT::i8; 3161 else if (ActualMVT == MVT::i16) 3162 ValVT = MVT::i16; 3163 } 3164 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3165 bool Res = 3166 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 3167 assert(!Res && "Call operand has unhandled type"); 3168 (void)Res; 3169 } 3170 assert(ArgLocs.size() == Ins.size()); 3171 SmallVector<SDValue, 16> ArgValues; 3172 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3173 CCValAssign &VA = ArgLocs[i]; 3174 3175 if (Ins[i].Flags.isByVal()) { 3176 // Byval is used for HFAs in the PCS, but the system should work in a 3177 // non-compliant manner for larger structs. 3178 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3179 int Size = Ins[i].Flags.getByValSize(); 3180 unsigned NumRegs = (Size + 7) / 8; 3181 3182 // FIXME: This works on big-endian for composite byvals, which are the common 3183 // case. It should also work for fundamental types too. 3184 unsigned FrameIdx = 3185 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 3186 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 3187 InVals.push_back(FrameIdxN); 3188 3189 continue; 3190 } 3191 3192 SDValue ArgValue; 3193 if (VA.isRegLoc()) { 3194 // Arguments stored in registers. 3195 EVT RegVT = VA.getLocVT(); 3196 const TargetRegisterClass *RC; 3197 3198 if (RegVT == MVT::i32) 3199 RC = &AArch64::GPR32RegClass; 3200 else if (RegVT == MVT::i64) 3201 RC = &AArch64::GPR64RegClass; 3202 else if (RegVT == MVT::f16) 3203 RC = &AArch64::FPR16RegClass; 3204 else if (RegVT == MVT::f32) 3205 RC = &AArch64::FPR32RegClass; 3206 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 3207 RC = &AArch64::FPR64RegClass; 3208 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 3209 RC = &AArch64::FPR128RegClass; 3210 else if (RegVT.isScalableVector() && 3211 RegVT.getVectorElementType() == MVT::i1) 3212 RC = &AArch64::PPRRegClass; 3213 else if (RegVT.isScalableVector()) 3214 RC = &AArch64::ZPRRegClass; 3215 else 3216 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3217 3218 // Transform the arguments in physical registers into virtual ones. 3219 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3220 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3221 3222 // If this is an 8, 16 or 32-bit value, it is really passed promoted 3223 // to 64 bits. Insert an assert[sz]ext to capture this, then 3224 // truncate to the right size. 3225 switch (VA.getLocInfo()) { 3226 default: 3227 llvm_unreachable("Unknown loc info!"); 3228 case CCValAssign::Full: 3229 break; 3230 case CCValAssign::Indirect: 3231 assert(VA.getValVT().isScalableVector() && 3232 "Only scalable vectors can be passed indirectly"); 3233 llvm_unreachable("Spilling of SVE vectors not yet implemented"); 3234 case CCValAssign::BCvt: 3235 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 3236 break; 3237 case CCValAssign::AExt: 3238 case CCValAssign::SExt: 3239 case CCValAssign::ZExt: 3240 break; 3241 case CCValAssign::AExtUpper: 3242 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 3243 DAG.getConstant(32, DL, RegVT)); 3244 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 3245 break; 3246 } 3247 } else { // VA.isRegLoc() 3248 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 3249 unsigned ArgOffset = VA.getLocMemOffset(); 3250 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 3251 3252 uint32_t BEAlign = 0; 3253 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 3254 !Ins[i].Flags.isInConsecutiveRegs()) 3255 BEAlign = 8 - ArgSize; 3256 3257 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 3258 3259 // Create load nodes to retrieve arguments from the stack. 3260 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3261 3262 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 3263 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3264 MVT MemVT = VA.getValVT(); 3265 3266 switch (VA.getLocInfo()) { 3267 default: 3268 break; 3269 case CCValAssign::Trunc: 3270 case CCValAssign::BCvt: 3271 MemVT = VA.getLocVT(); 3272 break; 3273 case CCValAssign::Indirect: 3274 assert(VA.getValVT().isScalableVector() && 3275 "Only scalable vectors can be passed indirectly"); 3276 llvm_unreachable("Spilling of SVE vectors not yet implemented"); 3277 case CCValAssign::SExt: 3278 ExtType = ISD::SEXTLOAD; 3279 break; 3280 case CCValAssign::ZExt: 3281 ExtType = ISD::ZEXTLOAD; 3282 break; 3283 case CCValAssign::AExt: 3284 ExtType = ISD::EXTLOAD; 3285 break; 3286 } 3287 3288 ArgValue = DAG.getExtLoad( 3289 ExtType, DL, VA.getLocVT(), Chain, FIN, 3290 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3291 MemVT); 3292 3293 } 3294 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 3295 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 3296 ArgValue, DAG.getValueType(MVT::i32)); 3297 InVals.push_back(ArgValue); 3298 } 3299 3300 // varargs 3301 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3302 if (isVarArg) { 3303 if (!Subtarget->isTargetDarwin() || IsWin64) { 3304 // The AAPCS variadic function ABI is identical to the non-variadic 3305 // one. As a result there may be more arguments in registers and we should 3306 // save them for future reference. 3307 // Win64 variadic functions also pass arguments in registers, but all float 3308 // arguments are passed in integer registers. 3309 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 3310 } 3311 3312 // This will point to the next argument passed via stack. 3313 unsigned StackOffset = CCInfo.getNextStackOffset(); 3314 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 3315 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 3316 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 3317 3318 if (MFI.hasMustTailInVarArgFunc()) { 3319 SmallVector<MVT, 2> RegParmTypes; 3320 RegParmTypes.push_back(MVT::i64); 3321 RegParmTypes.push_back(MVT::f128); 3322 // Compute the set of forwarded registers. The rest are scratch. 3323 SmallVectorImpl<ForwardedRegister> &Forwards = 3324 FuncInfo->getForwardedMustTailRegParms(); 3325 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 3326 CC_AArch64_AAPCS); 3327 3328 // Conservatively forward X8, since it might be used for aggregate return. 3329 if (!CCInfo.isAllocated(AArch64::X8)) { 3330 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 3331 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 3332 } 3333 } 3334 } 3335 3336 // On Windows, InReg pointers must be returned, so record the pointer in a 3337 // virtual register at the start of the function so it can be returned in the 3338 // epilogue. 3339 if (IsWin64) { 3340 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 3341 if (Ins[I].Flags.isInReg()) { 3342 assert(!FuncInfo->getSRetReturnReg()); 3343 3344 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 3345 Register Reg = 3346 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 3347 FuncInfo->setSRetReturnReg(Reg); 3348 3349 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 3350 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3351 break; 3352 } 3353 } 3354 } 3355 3356 unsigned StackArgSize = CCInfo.getNextStackOffset(); 3357 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3358 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 3359 // This is a non-standard ABI so by fiat I say we're allowed to make full 3360 // use of the stack area to be popped, which must be aligned to 16 bytes in 3361 // any case: 3362 StackArgSize = alignTo(StackArgSize, 16); 3363 3364 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 3365 // a multiple of 16. 3366 FuncInfo->setArgumentStackToRestore(StackArgSize); 3367 3368 // This realignment carries over to the available bytes below. Our own 3369 // callers will guarantee the space is free by giving an aligned value to 3370 // CALLSEQ_START. 3371 } 3372 // Even if we're not expected to free up the space, it's useful to know how 3373 // much is there while considering tail calls (because we can reuse it). 3374 FuncInfo->setBytesInStackArgArea(StackArgSize); 3375 3376 if (Subtarget->hasCustomCallingConv()) 3377 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 3378 3379 return Chain; 3380 } 3381 3382 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 3383 SelectionDAG &DAG, 3384 const SDLoc &DL, 3385 SDValue &Chain) const { 3386 MachineFunction &MF = DAG.getMachineFunction(); 3387 MachineFrameInfo &MFI = MF.getFrameInfo(); 3388 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3389 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3390 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3391 3392 SmallVector<SDValue, 8> MemOps; 3393 3394 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 3395 AArch64::X3, AArch64::X4, AArch64::X5, 3396 AArch64::X6, AArch64::X7 }; 3397 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 3398 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 3399 3400 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 3401 int GPRIdx = 0; 3402 if (GPRSaveSize != 0) { 3403 if (IsWin64) { 3404 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 3405 if (GPRSaveSize & 15) 3406 // The extra size here, if triggered, will always be 8. 3407 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 3408 } else 3409 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 3410 3411 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 3412 3413 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 3414 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 3415 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 3416 SDValue Store = DAG.getStore( 3417 Val.getValue(1), DL, Val, FIN, 3418 IsWin64 3419 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 3420 GPRIdx, 3421 (i - FirstVariadicGPR) * 8) 3422 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 3423 MemOps.push_back(Store); 3424 FIN = 3425 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 3426 } 3427 } 3428 FuncInfo->setVarArgsGPRIndex(GPRIdx); 3429 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 3430 3431 if (Subtarget->hasFPARMv8() && !IsWin64) { 3432 static const MCPhysReg FPRArgRegs[] = { 3433 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 3434 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 3435 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 3436 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 3437 3438 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 3439 int FPRIdx = 0; 3440 if (FPRSaveSize != 0) { 3441 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 3442 3443 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 3444 3445 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 3446 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 3447 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 3448 3449 SDValue Store = DAG.getStore( 3450 Val.getValue(1), DL, Val, FIN, 3451 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 3452 MemOps.push_back(Store); 3453 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 3454 DAG.getConstant(16, DL, PtrVT)); 3455 } 3456 } 3457 FuncInfo->setVarArgsFPRIndex(FPRIdx); 3458 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 3459 } 3460 3461 if (!MemOps.empty()) { 3462 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3463 } 3464 } 3465 3466 /// LowerCallResult - Lower the result values of a call into the 3467 /// appropriate copies out of appropriate physical registers. 3468 SDValue AArch64TargetLowering::LowerCallResult( 3469 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 3470 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3471 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 3472 SDValue ThisVal) const { 3473 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3474 ? RetCC_AArch64_WebKit_JS 3475 : RetCC_AArch64_AAPCS; 3476 // Assign locations to each value returned by this call. 3477 SmallVector<CCValAssign, 16> RVLocs; 3478 DenseMap<unsigned, SDValue> CopiedRegs; 3479 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3480 *DAG.getContext()); 3481 CCInfo.AnalyzeCallResult(Ins, RetCC); 3482 3483 // Copy all of the result registers out of their specified physreg. 3484 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3485 CCValAssign VA = RVLocs[i]; 3486 3487 // Pass 'this' value directly from the argument to return value, to avoid 3488 // reg unit interference 3489 if (i == 0 && isThisReturn) { 3490 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3491 "unexpected return calling convention register assignment"); 3492 InVals.push_back(ThisVal); 3493 continue; 3494 } 3495 3496 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 3497 // allows one use of a physreg per block. 3498 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 3499 if (!Val) { 3500 Val = 3501 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3502 Chain = Val.getValue(1); 3503 InFlag = Val.getValue(2); 3504 CopiedRegs[VA.getLocReg()] = Val; 3505 } 3506 3507 switch (VA.getLocInfo()) { 3508 default: 3509 llvm_unreachable("Unknown loc info!"); 3510 case CCValAssign::Full: 3511 break; 3512 case CCValAssign::BCvt: 3513 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3514 break; 3515 case CCValAssign::AExtUpper: 3516 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 3517 DAG.getConstant(32, DL, VA.getLocVT())); 3518 LLVM_FALLTHROUGH; 3519 case CCValAssign::AExt: 3520 LLVM_FALLTHROUGH; 3521 case CCValAssign::ZExt: 3522 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 3523 break; 3524 } 3525 3526 InVals.push_back(Val); 3527 } 3528 3529 return Chain; 3530 } 3531 3532 /// Return true if the calling convention is one that we can guarantee TCO for. 3533 static bool canGuaranteeTCO(CallingConv::ID CC) { 3534 return CC == CallingConv::Fast; 3535 } 3536 3537 /// Return true if we might ever do TCO for calls with this calling convention. 3538 static bool mayTailCallThisCC(CallingConv::ID CC) { 3539 switch (CC) { 3540 case CallingConv::C: 3541 case CallingConv::PreserveMost: 3542 case CallingConv::Swift: 3543 return true; 3544 default: 3545 return canGuaranteeTCO(CC); 3546 } 3547 } 3548 3549 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3550 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3551 const SmallVectorImpl<ISD::OutputArg> &Outs, 3552 const SmallVectorImpl<SDValue> &OutVals, 3553 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3554 if (!mayTailCallThisCC(CalleeCC)) 3555 return false; 3556 3557 MachineFunction &MF = DAG.getMachineFunction(); 3558 const Function &CallerF = MF.getFunction(); 3559 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3560 bool CCMatch = CallerCC == CalleeCC; 3561 3562 // Byval parameters hand the function a pointer directly into the stack area 3563 // we want to reuse during a tail call. Working around this *is* possible (see 3564 // X86) but less efficient and uglier in LowerCall. 3565 for (Function::const_arg_iterator i = CallerF.arg_begin(), 3566 e = CallerF.arg_end(); 3567 i != e; ++i) { 3568 if (i->hasByValAttr()) 3569 return false; 3570 3571 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 3572 // In this case, it is necessary to save/restore X0 in the callee. Tail 3573 // call opt interferes with this. So we disable tail call opt when the 3574 // caller has an argument with "inreg" attribute. 3575 3576 // FIXME: Check whether the callee also has an "inreg" argument. 3577 if (i->hasInRegAttr()) 3578 return false; 3579 } 3580 3581 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3582 return canGuaranteeTCO(CalleeCC) && CCMatch; 3583 3584 // Externally-defined functions with weak linkage should not be 3585 // tail-called on AArch64 when the OS does not support dynamic 3586 // pre-emption of symbols, as the AAELF spec requires normal calls 3587 // to undefined weak functions to be replaced with a NOP or jump to the 3588 // next instruction. The behaviour of branch instructions in this 3589 // situation (as used for tail calls) is implementation-defined, so we 3590 // cannot rely on the linker replacing the tail call with a return. 3591 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3592 const GlobalValue *GV = G->getGlobal(); 3593 const Triple &TT = getTargetMachine().getTargetTriple(); 3594 if (GV->hasExternalWeakLinkage() && 3595 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3596 return false; 3597 } 3598 3599 // Now we search for cases where we can use a tail call without changing the 3600 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3601 // concept. 3602 3603 // I want anyone implementing a new calling convention to think long and hard 3604 // about this assert. 3605 assert((!isVarArg || CalleeCC == CallingConv::C) && 3606 "Unexpected variadic calling convention"); 3607 3608 LLVMContext &C = *DAG.getContext(); 3609 if (isVarArg && !Outs.empty()) { 3610 // At least two cases here: if caller is fastcc then we can't have any 3611 // memory arguments (we'd be expected to clean up the stack afterwards). If 3612 // caller is C then we could potentially use its argument area. 3613 3614 // FIXME: for now we take the most conservative of these in both cases: 3615 // disallow all variadic memory operands. 3616 SmallVector<CCValAssign, 16> ArgLocs; 3617 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3618 3619 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3620 for (const CCValAssign &ArgLoc : ArgLocs) 3621 if (!ArgLoc.isRegLoc()) 3622 return false; 3623 } 3624 3625 // Check that the call results are passed in the same way. 3626 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3627 CCAssignFnForCall(CalleeCC, isVarArg), 3628 CCAssignFnForCall(CallerCC, isVarArg))) 3629 return false; 3630 // The callee has to preserve all registers the caller needs to preserve. 3631 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3632 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3633 if (!CCMatch) { 3634 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3635 if (Subtarget->hasCustomCallingConv()) { 3636 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 3637 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 3638 } 3639 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3640 return false; 3641 } 3642 3643 // Nothing more to check if the callee is taking no arguments 3644 if (Outs.empty()) 3645 return true; 3646 3647 SmallVector<CCValAssign, 16> ArgLocs; 3648 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3649 3650 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3651 3652 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3653 3654 // If the stack arguments for this call do not fit into our own save area then 3655 // the call cannot be made tail. 3656 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3657 return false; 3658 3659 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3660 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3661 return false; 3662 3663 return true; 3664 } 3665 3666 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3667 SelectionDAG &DAG, 3668 MachineFrameInfo &MFI, 3669 int ClobberedFI) const { 3670 SmallVector<SDValue, 8> ArgChains; 3671 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3672 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3673 3674 // Include the original chain at the beginning of the list. When this is 3675 // used by target LowerCall hooks, this helps legalize find the 3676 // CALLSEQ_BEGIN node. 3677 ArgChains.push_back(Chain); 3678 3679 // Add a chain value for each stack argument corresponding 3680 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 3681 UE = DAG.getEntryNode().getNode()->use_end(); 3682 U != UE; ++U) 3683 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3684 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3685 if (FI->getIndex() < 0) { 3686 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 3687 int64_t InLastByte = InFirstByte; 3688 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 3689 3690 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 3691 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 3692 ArgChains.push_back(SDValue(L, 1)); 3693 } 3694 3695 // Build a tokenfactor for all the chains. 3696 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3697 } 3698 3699 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 3700 bool TailCallOpt) const { 3701 return CallCC == CallingConv::Fast && TailCallOpt; 3702 } 3703 3704 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 3705 /// and add input and output parameter nodes. 3706 SDValue 3707 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 3708 SmallVectorImpl<SDValue> &InVals) const { 3709 SelectionDAG &DAG = CLI.DAG; 3710 SDLoc &DL = CLI.DL; 3711 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3712 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3713 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3714 SDValue Chain = CLI.Chain; 3715 SDValue Callee = CLI.Callee; 3716 bool &IsTailCall = CLI.IsTailCall; 3717 CallingConv::ID CallConv = CLI.CallConv; 3718 bool IsVarArg = CLI.IsVarArg; 3719 3720 MachineFunction &MF = DAG.getMachineFunction(); 3721 MachineFunction::CallSiteInfo CSInfo; 3722 bool IsThisReturn = false; 3723 3724 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3725 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3726 bool IsSibCall = false; 3727 3728 if (IsTailCall) { 3729 // Check if it's really possible to do a tail call. 3730 IsTailCall = isEligibleForTailCallOptimization( 3731 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3732 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 3733 report_fatal_error("failed to perform tail call elimination on a call " 3734 "site marked musttail"); 3735 3736 // A sibling call is one where we're under the usual C ABI and not planning 3737 // to change that but can still do a tail call: 3738 if (!TailCallOpt && IsTailCall) 3739 IsSibCall = true; 3740 3741 if (IsTailCall) 3742 ++NumTailCalls; 3743 } 3744 3745 // Analyze operands of the call, assigning locations to each operand. 3746 SmallVector<CCValAssign, 16> ArgLocs; 3747 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3748 *DAG.getContext()); 3749 3750 if (IsVarArg) { 3751 // Handle fixed and variable vector arguments differently. 3752 // Variable vector arguments always go into memory. 3753 unsigned NumArgs = Outs.size(); 3754 3755 for (unsigned i = 0; i != NumArgs; ++i) { 3756 MVT ArgVT = Outs[i].VT; 3757 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3758 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3759 /*IsVarArg=*/ !Outs[i].IsFixed); 3760 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3761 assert(!Res && "Call operand has unhandled type"); 3762 (void)Res; 3763 } 3764 } else { 3765 // At this point, Outs[].VT may already be promoted to i32. To correctly 3766 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3767 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3768 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3769 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3770 // LocVT. 3771 unsigned NumArgs = Outs.size(); 3772 for (unsigned i = 0; i != NumArgs; ++i) { 3773 MVT ValVT = Outs[i].VT; 3774 // Get type of the original argument. 3775 EVT ActualVT = getValueType(DAG.getDataLayout(), 3776 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3777 /*AllowUnknown*/ true); 3778 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3779 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3780 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3781 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3782 ValVT = MVT::i8; 3783 else if (ActualMVT == MVT::i16) 3784 ValVT = MVT::i16; 3785 3786 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3787 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3788 assert(!Res && "Call operand has unhandled type"); 3789 (void)Res; 3790 } 3791 } 3792 3793 // Get a count of how many bytes are to be pushed on the stack. 3794 unsigned NumBytes = CCInfo.getNextStackOffset(); 3795 3796 if (IsSibCall) { 3797 // Since we're not changing the ABI to make this a tail call, the memory 3798 // operands are already available in the caller's incoming argument space. 3799 NumBytes = 0; 3800 } 3801 3802 // FPDiff is the byte offset of the call's argument area from the callee's. 3803 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3804 // by this amount for a tail call. In a sibling call it must be 0 because the 3805 // caller will deallocate the entire stack and the callee still expects its 3806 // arguments to begin at SP+0. Completely unused for non-tail calls. 3807 int FPDiff = 0; 3808 3809 if (IsTailCall && !IsSibCall) { 3810 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3811 3812 // Since callee will pop argument stack as a tail call, we must keep the 3813 // popped size 16-byte aligned. 3814 NumBytes = alignTo(NumBytes, 16); 3815 3816 // FPDiff will be negative if this tail call requires more space than we 3817 // would automatically have in our incoming argument space. Positive if we 3818 // can actually shrink the stack. 3819 FPDiff = NumReusableBytes - NumBytes; 3820 3821 // The stack pointer must be 16-byte aligned at all times it's used for a 3822 // memory operation, which in practice means at *all* times and in 3823 // particular across call boundaries. Therefore our own arguments started at 3824 // a 16-byte aligned SP and the delta applied for the tail call should 3825 // satisfy the same constraint. 3826 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3827 } 3828 3829 // Adjust the stack pointer for the new arguments... 3830 // These operations are automatically eliminated by the prolog/epilog pass 3831 if (!IsSibCall) 3832 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 3833 3834 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3835 getPointerTy(DAG.getDataLayout())); 3836 3837 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3838 SmallSet<unsigned, 8> RegsUsed; 3839 SmallVector<SDValue, 8> MemOpChains; 3840 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3841 3842 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) { 3843 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 3844 for (const auto &F : Forwards) { 3845 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 3846 RegsToPass.emplace_back(F.PReg, Val); 3847 } 3848 } 3849 3850 // Walk the register/memloc assignments, inserting copies/loads. 3851 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3852 ++i, ++realArgIdx) { 3853 CCValAssign &VA = ArgLocs[i]; 3854 SDValue Arg = OutVals[realArgIdx]; 3855 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3856 3857 // Promote the value if needed. 3858 switch (VA.getLocInfo()) { 3859 default: 3860 llvm_unreachable("Unknown loc info!"); 3861 case CCValAssign::Full: 3862 break; 3863 case CCValAssign::SExt: 3864 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3865 break; 3866 case CCValAssign::ZExt: 3867 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3868 break; 3869 case CCValAssign::AExt: 3870 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3871 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3872 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3873 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3874 } 3875 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3876 break; 3877 case CCValAssign::AExtUpper: 3878 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 3879 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3880 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 3881 DAG.getConstant(32, DL, VA.getLocVT())); 3882 break; 3883 case CCValAssign::BCvt: 3884 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 3885 break; 3886 case CCValAssign::Trunc: 3887 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 3888 break; 3889 case CCValAssign::FPExt: 3890 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3891 break; 3892 case CCValAssign::Indirect: 3893 assert(VA.getValVT().isScalableVector() && 3894 "Only scalable vectors can be passed indirectly"); 3895 llvm_unreachable("Spilling of SVE vectors not yet implemented"); 3896 } 3897 3898 if (VA.isRegLoc()) { 3899 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 3900 Outs[0].VT == MVT::i64) { 3901 assert(VA.getLocVT() == MVT::i64 && 3902 "unexpected calling convention register assignment"); 3903 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3904 "unexpected use of 'returned'"); 3905 IsThisReturn = true; 3906 } 3907 if (RegsUsed.count(VA.getLocReg())) { 3908 // If this register has already been used then we're trying to pack 3909 // parts of an [N x i32] into an X-register. The extension type will 3910 // take care of putting the two halves in the right place but we have to 3911 // combine them. 3912 SDValue &Bits = 3913 std::find_if(RegsToPass.begin(), RegsToPass.end(), 3914 [=](const std::pair<unsigned, SDValue> &Elt) { 3915 return Elt.first == VA.getLocReg(); 3916 }) 3917 ->second; 3918 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 3919 // Call site info is used for function's parameter entry value 3920 // tracking. For now we track only simple cases when parameter 3921 // is transferred through whole register. 3922 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(), 3923 [&VA](MachineFunction::ArgRegPair ArgReg) { 3924 return ArgReg.Reg == VA.getLocReg(); 3925 }), 3926 CSInfo.end()); 3927 } else { 3928 RegsToPass.emplace_back(VA.getLocReg(), Arg); 3929 RegsUsed.insert(VA.getLocReg()); 3930 const TargetOptions &Options = DAG.getTarget().Options; 3931 if (Options.EnableDebugEntryValues) 3932 CSInfo.emplace_back(VA.getLocReg(), i); 3933 } 3934 } else { 3935 assert(VA.isMemLoc()); 3936 3937 SDValue DstAddr; 3938 MachinePointerInfo DstInfo; 3939 3940 // FIXME: This works on big-endian for composite byvals, which are the 3941 // common case. It should also work for fundamental types too. 3942 uint32_t BEAlign = 0; 3943 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3944 : VA.getValVT().getSizeInBits(); 3945 OpSize = (OpSize + 7) / 8; 3946 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3947 !Flags.isInConsecutiveRegs()) { 3948 if (OpSize < 8) 3949 BEAlign = 8 - OpSize; 3950 } 3951 unsigned LocMemOffset = VA.getLocMemOffset(); 3952 int32_t Offset = LocMemOffset + BEAlign; 3953 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3954 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3955 3956 if (IsTailCall) { 3957 Offset = Offset + FPDiff; 3958 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 3959 3960 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3961 DstInfo = 3962 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3963 3964 // Make sure any stack arguments overlapping with where we're storing 3965 // are loaded before this eventual operation. Otherwise they'll be 3966 // clobbered. 3967 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3968 } else { 3969 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3970 3971 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3972 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3973 LocMemOffset); 3974 } 3975 3976 if (Outs[i].Flags.isByVal()) { 3977 SDValue SizeNode = 3978 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3979 SDValue Cpy = DAG.getMemcpy( 3980 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3981 /*isVol = */ false, /*AlwaysInline = */ false, 3982 /*isTailCall = */ false, 3983 DstInfo, MachinePointerInfo()); 3984 3985 MemOpChains.push_back(Cpy); 3986 } else { 3987 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3988 // promoted to a legal register type i32, we should truncate Arg back to 3989 // i1/i8/i16. 3990 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3991 VA.getValVT() == MVT::i16) 3992 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3993 3994 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 3995 MemOpChains.push_back(Store); 3996 } 3997 } 3998 } 3999 4000 if (!MemOpChains.empty()) 4001 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 4002 4003 // Build a sequence of copy-to-reg nodes chained together with token chain 4004 // and flag operands which copy the outgoing args into the appropriate regs. 4005 SDValue InFlag; 4006 for (auto &RegToPass : RegsToPass) { 4007 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 4008 RegToPass.second, InFlag); 4009 InFlag = Chain.getValue(1); 4010 } 4011 4012 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 4013 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 4014 // node so that legalize doesn't hack it. 4015 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4016 auto GV = G->getGlobal(); 4017 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) == 4018 AArch64II::MO_GOT) { 4019 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 4020 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4021 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) { 4022 assert(Subtarget->isTargetWindows() && 4023 "Windows is the only supported COFF target"); 4024 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT); 4025 } else { 4026 const GlobalValue *GV = G->getGlobal(); 4027 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 4028 } 4029 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4030 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4031 Subtarget->isTargetMachO()) { 4032 const char *Sym = S->getSymbol(); 4033 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 4034 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4035 } else { 4036 const char *Sym = S->getSymbol(); 4037 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 4038 } 4039 } 4040 4041 // We don't usually want to end the call-sequence here because we would tidy 4042 // the frame up *after* the call, however in the ABI-changing tail-call case 4043 // we've carefully laid out the parameters so that when sp is reset they'll be 4044 // in the correct location. 4045 if (IsTailCall && !IsSibCall) { 4046 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4047 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 4048 InFlag = Chain.getValue(1); 4049 } 4050 4051 std::vector<SDValue> Ops; 4052 Ops.push_back(Chain); 4053 Ops.push_back(Callee); 4054 4055 if (IsTailCall) { 4056 // Each tail call may have to adjust the stack by a different amount, so 4057 // this information must travel along with the operation for eventual 4058 // consumption by emitEpilogue. 4059 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 4060 } 4061 4062 // Add argument registers to the end of the list so that they are known live 4063 // into the call. 4064 for (auto &RegToPass : RegsToPass) 4065 Ops.push_back(DAG.getRegister(RegToPass.first, 4066 RegToPass.second.getValueType())); 4067 4068 // Check callee args/returns for SVE registers and set calling convention 4069 // accordingly. 4070 if (CallConv == CallingConv::C) { 4071 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 4072 return Out.VT.isScalableVector(); 4073 }); 4074 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 4075 return In.VT.isScalableVector(); 4076 }); 4077 4078 if (CalleeInSVE || CalleeOutSVE) 4079 CallConv = CallingConv::AArch64_SVE_VectorCall; 4080 } 4081 4082 // Add a register mask operand representing the call-preserved registers. 4083 const uint32_t *Mask; 4084 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4085 if (IsThisReturn) { 4086 // For 'this' returns, use the X0-preserving mask if applicable 4087 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 4088 if (!Mask) { 4089 IsThisReturn = false; 4090 Mask = TRI->getCallPreservedMask(MF, CallConv); 4091 } 4092 } else 4093 Mask = TRI->getCallPreservedMask(MF, CallConv); 4094 4095 if (Subtarget->hasCustomCallingConv()) 4096 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 4097 4098 if (TRI->isAnyArgRegReserved(MF)) 4099 TRI->emitReservedArgRegCallError(MF); 4100 4101 assert(Mask && "Missing call preserved mask for calling convention"); 4102 Ops.push_back(DAG.getRegisterMask(Mask)); 4103 4104 if (InFlag.getNode()) 4105 Ops.push_back(InFlag); 4106 4107 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4108 4109 // If we're doing a tall call, use a TC_RETURN here rather than an 4110 // actual call instruction. 4111 if (IsTailCall) { 4112 MF.getFrameInfo().setHasTailCall(); 4113 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 4114 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 4115 return Ret; 4116 } 4117 4118 // Returns a chain and a flag for retval copy to use. 4119 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 4120 InFlag = Chain.getValue(1); 4121 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 4122 4123 uint64_t CalleePopBytes = 4124 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 4125 4126 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4127 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 4128 InFlag, DL); 4129 if (!Ins.empty()) 4130 InFlag = Chain.getValue(1); 4131 4132 // Handle result values, copying them out of physregs into vregs that we 4133 // return. 4134 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 4135 InVals, IsThisReturn, 4136 IsThisReturn ? OutVals[0] : SDValue()); 4137 } 4138 4139 bool AArch64TargetLowering::CanLowerReturn( 4140 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 4141 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 4142 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4143 ? RetCC_AArch64_WebKit_JS 4144 : RetCC_AArch64_AAPCS; 4145 SmallVector<CCValAssign, 16> RVLocs; 4146 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 4147 return CCInfo.CheckReturn(Outs, RetCC); 4148 } 4149 4150 SDValue 4151 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 4152 bool isVarArg, 4153 const SmallVectorImpl<ISD::OutputArg> &Outs, 4154 const SmallVectorImpl<SDValue> &OutVals, 4155 const SDLoc &DL, SelectionDAG &DAG) const { 4156 auto &MF = DAG.getMachineFunction(); 4157 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4158 4159 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4160 ? RetCC_AArch64_WebKit_JS 4161 : RetCC_AArch64_AAPCS; 4162 SmallVector<CCValAssign, 16> RVLocs; 4163 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4164 *DAG.getContext()); 4165 CCInfo.AnalyzeReturn(Outs, RetCC); 4166 4167 // Copy the result values into the output registers. 4168 SDValue Flag; 4169 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 4170 SmallSet<unsigned, 4> RegsUsed; 4171 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 4172 ++i, ++realRVLocIdx) { 4173 CCValAssign &VA = RVLocs[i]; 4174 assert(VA.isRegLoc() && "Can only return in registers!"); 4175 SDValue Arg = OutVals[realRVLocIdx]; 4176 4177 switch (VA.getLocInfo()) { 4178 default: 4179 llvm_unreachable("Unknown loc info!"); 4180 case CCValAssign::Full: 4181 if (Outs[i].ArgVT == MVT::i1) { 4182 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 4183 // value. This is strictly redundant on Darwin (which uses "zeroext 4184 // i1"), but will be optimised out before ISel. 4185 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4186 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4187 } 4188 break; 4189 case CCValAssign::BCvt: 4190 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 4191 break; 4192 case CCValAssign::AExt: 4193 case CCValAssign::ZExt: 4194 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4195 break; 4196 case CCValAssign::AExtUpper: 4197 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4198 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4199 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4200 DAG.getConstant(32, DL, VA.getLocVT())); 4201 break; 4202 } 4203 4204 if (RegsUsed.count(VA.getLocReg())) { 4205 SDValue &Bits = 4206 std::find_if(RetVals.begin(), RetVals.end(), 4207 [=](const std::pair<unsigned, SDValue> &Elt) { 4208 return Elt.first == VA.getLocReg(); 4209 }) 4210 ->second; 4211 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4212 } else { 4213 RetVals.emplace_back(VA.getLocReg(), Arg); 4214 RegsUsed.insert(VA.getLocReg()); 4215 } 4216 } 4217 4218 SmallVector<SDValue, 4> RetOps(1, Chain); 4219 for (auto &RetVal : RetVals) { 4220 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 4221 Flag = Chain.getValue(1); 4222 RetOps.push_back( 4223 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 4224 } 4225 4226 // Windows AArch64 ABIs require that for returning structs by value we copy 4227 // the sret argument into X0 for the return. 4228 // We saved the argument into a virtual register in the entry block, 4229 // so now we copy the value out and into X0. 4230 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 4231 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 4232 getPointerTy(MF.getDataLayout())); 4233 4234 unsigned RetValReg = AArch64::X0; 4235 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 4236 Flag = Chain.getValue(1); 4237 4238 RetOps.push_back( 4239 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 4240 } 4241 4242 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4243 const MCPhysReg *I = 4244 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 4245 if (I) { 4246 for (; *I; ++I) { 4247 if (AArch64::GPR64RegClass.contains(*I)) 4248 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 4249 else if (AArch64::FPR64RegClass.contains(*I)) 4250 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 4251 else 4252 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 4253 } 4254 } 4255 4256 RetOps[0] = Chain; // Update chain. 4257 4258 // Add the flag if we have it. 4259 if (Flag.getNode()) 4260 RetOps.push_back(Flag); 4261 4262 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 4263 } 4264 4265 //===----------------------------------------------------------------------===// 4266 // Other Lowering Code 4267 //===----------------------------------------------------------------------===// 4268 4269 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 4270 SelectionDAG &DAG, 4271 unsigned Flag) const { 4272 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 4273 N->getOffset(), Flag); 4274 } 4275 4276 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 4277 SelectionDAG &DAG, 4278 unsigned Flag) const { 4279 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 4280 } 4281 4282 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 4283 SelectionDAG &DAG, 4284 unsigned Flag) const { 4285 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 4286 N->getOffset(), Flag); 4287 } 4288 4289 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 4290 SelectionDAG &DAG, 4291 unsigned Flag) const { 4292 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 4293 } 4294 4295 // (loadGOT sym) 4296 template <class NodeTy> 4297 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 4298 unsigned Flags) const { 4299 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 4300 SDLoc DL(N); 4301 EVT Ty = getPointerTy(DAG.getDataLayout()); 4302 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 4303 // FIXME: Once remat is capable of dealing with instructions with register 4304 // operands, expand this into two nodes instead of using a wrapper node. 4305 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 4306 } 4307 4308 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 4309 template <class NodeTy> 4310 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 4311 unsigned Flags) const { 4312 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 4313 SDLoc DL(N); 4314 EVT Ty = getPointerTy(DAG.getDataLayout()); 4315 const unsigned char MO_NC = AArch64II::MO_NC; 4316 return DAG.getNode( 4317 AArch64ISD::WrapperLarge, DL, Ty, 4318 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 4319 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 4320 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 4321 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 4322 } 4323 4324 // (addlow (adrp %hi(sym)) %lo(sym)) 4325 template <class NodeTy> 4326 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 4327 unsigned Flags) const { 4328 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 4329 SDLoc DL(N); 4330 EVT Ty = getPointerTy(DAG.getDataLayout()); 4331 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 4332 SDValue Lo = getTargetNode(N, Ty, DAG, 4333 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 4334 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 4335 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 4336 } 4337 4338 // (adr sym) 4339 template <class NodeTy> 4340 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 4341 unsigned Flags) const { 4342 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 4343 SDLoc DL(N); 4344 EVT Ty = getPointerTy(DAG.getDataLayout()); 4345 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 4346 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 4347 } 4348 4349 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 4350 SelectionDAG &DAG) const { 4351 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 4352 const GlobalValue *GV = GN->getGlobal(); 4353 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 4354 4355 if (OpFlags != AArch64II::MO_NO_FLAG) 4356 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 4357 "unexpected offset in global node"); 4358 4359 // This also catches the large code model case for Darwin, and tiny code 4360 // model with got relocations. 4361 if ((OpFlags & AArch64II::MO_GOT) != 0) { 4362 return getGOT(GN, DAG, OpFlags); 4363 } 4364 4365 SDValue Result; 4366 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4367 Result = getAddrLarge(GN, DAG, OpFlags); 4368 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 4369 Result = getAddrTiny(GN, DAG, OpFlags); 4370 } else { 4371 Result = getAddr(GN, DAG, OpFlags); 4372 } 4373 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4374 SDLoc DL(GN); 4375 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 4376 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 4377 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 4378 return Result; 4379 } 4380 4381 /// Convert a TLS address reference into the correct sequence of loads 4382 /// and calls to compute the variable's address (for Darwin, currently) and 4383 /// return an SDValue containing the final node. 4384 4385 /// Darwin only has one TLS scheme which must be capable of dealing with the 4386 /// fully general situation, in the worst case. This means: 4387 /// + "extern __thread" declaration. 4388 /// + Defined in a possibly unknown dynamic library. 4389 /// 4390 /// The general system is that each __thread variable has a [3 x i64] descriptor 4391 /// which contains information used by the runtime to calculate the address. The 4392 /// only part of this the compiler needs to know about is the first xword, which 4393 /// contains a function pointer that must be called with the address of the 4394 /// entire descriptor in "x0". 4395 /// 4396 /// Since this descriptor may be in a different unit, in general even the 4397 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 4398 /// is: 4399 /// adrp x0, _var@TLVPPAGE 4400 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 4401 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 4402 /// ; the function pointer 4403 /// blr x1 ; Uses descriptor address in x0 4404 /// ; Address of _var is now in x0. 4405 /// 4406 /// If the address of _var's descriptor *is* known to the linker, then it can 4407 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 4408 /// a slight efficiency gain. 4409 SDValue 4410 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 4411 SelectionDAG &DAG) const { 4412 assert(Subtarget->isTargetDarwin() && 4413 "This function expects a Darwin target"); 4414 4415 SDLoc DL(Op); 4416 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 4417 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 4418 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 4419 4420 SDValue TLVPAddr = 4421 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4422 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 4423 4424 // The first entry in the descriptor is a function pointer that we must call 4425 // to obtain the address of the variable. 4426 SDValue Chain = DAG.getEntryNode(); 4427 SDValue FuncTLVGet = DAG.getLoad( 4428 PtrMemVT, DL, Chain, DescAddr, 4429 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 4430 /* Alignment = */ PtrMemVT.getSizeInBits() / 8, 4431 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 4432 Chain = FuncTLVGet.getValue(1); 4433 4434 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 4435 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 4436 4437 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4438 MFI.setAdjustsStack(true); 4439 4440 // TLS calls preserve all registers except those that absolutely must be 4441 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 4442 // silly). 4443 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4444 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 4445 if (Subtarget->hasCustomCallingConv()) 4446 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 4447 4448 // Finally, we can make the call. This is just a degenerate version of a 4449 // normal AArch64 call node: x0 takes the address of the descriptor, and 4450 // returns the address of the variable in this thread. 4451 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 4452 Chain = 4453 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 4454 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 4455 DAG.getRegisterMask(Mask), Chain.getValue(1)); 4456 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 4457 } 4458 4459 /// When accessing thread-local variables under either the general-dynamic or 4460 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 4461 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 4462 /// is a function pointer to carry out the resolution. 4463 /// 4464 /// The sequence is: 4465 /// adrp x0, :tlsdesc:var 4466 /// ldr x1, [x0, #:tlsdesc_lo12:var] 4467 /// add x0, x0, #:tlsdesc_lo12:var 4468 /// .tlsdesccall var 4469 /// blr x1 4470 /// (TPIDR_EL0 offset now in x0) 4471 /// 4472 /// The above sequence must be produced unscheduled, to enable the linker to 4473 /// optimize/relax this sequence. 4474 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 4475 /// above sequence, and expanded really late in the compilation flow, to ensure 4476 /// the sequence is produced as per above. 4477 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 4478 const SDLoc &DL, 4479 SelectionDAG &DAG) const { 4480 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4481 4482 SDValue Chain = DAG.getEntryNode(); 4483 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4484 4485 Chain = 4486 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 4487 SDValue Glue = Chain.getValue(1); 4488 4489 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 4490 } 4491 4492 SDValue 4493 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 4494 SelectionDAG &DAG) const { 4495 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 4496 if (getTargetMachine().getCodeModel() == CodeModel::Large) 4497 report_fatal_error("ELF TLS only supported in small memory model"); 4498 // Different choices can be made for the maximum size of the TLS area for a 4499 // module. For the small address model, the default TLS size is 16MiB and the 4500 // maximum TLS size is 4GiB. 4501 // FIXME: add -mtls-size command line option and make it control the 16MiB 4502 // vs. 4GiB code sequence generation. 4503 // FIXME: add tiny codemodel support. We currently generate the same code as 4504 // small, which may be larger than needed. 4505 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4506 4507 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 4508 4509 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 4510 if (Model == TLSModel::LocalDynamic) 4511 Model = TLSModel::GeneralDynamic; 4512 } 4513 4514 SDValue TPOff; 4515 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4516 SDLoc DL(Op); 4517 const GlobalValue *GV = GA->getGlobal(); 4518 4519 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 4520 4521 if (Model == TLSModel::LocalExec) { 4522 SDValue HiVar = DAG.getTargetGlobalAddress( 4523 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4524 SDValue LoVar = DAG.getTargetGlobalAddress( 4525 GV, DL, PtrVT, 0, 4526 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4527 4528 SDValue TPWithOff_lo = 4529 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4530 HiVar, 4531 DAG.getTargetConstant(0, DL, MVT::i32)), 4532 0); 4533 SDValue TPWithOff = 4534 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 4535 LoVar, 4536 DAG.getTargetConstant(0, DL, MVT::i32)), 4537 0); 4538 return TPWithOff; 4539 } else if (Model == TLSModel::InitialExec) { 4540 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4541 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 4542 } else if (Model == TLSModel::LocalDynamic) { 4543 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 4544 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 4545 // the beginning of the module's TLS region, followed by a DTPREL offset 4546 // calculation. 4547 4548 // These accesses will need deduplicating if there's more than one. 4549 AArch64FunctionInfo *MFI = 4550 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4551 MFI->incNumLocalDynamicTLSAccesses(); 4552 4553 // The call needs a relocation too for linker relaxation. It doesn't make 4554 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4555 // the address. 4556 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 4557 AArch64II::MO_TLS); 4558 4559 // Now we can calculate the offset from TPIDR_EL0 to this module's 4560 // thread-local area. 4561 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4562 4563 // Now use :dtprel_whatever: operations to calculate this variable's offset 4564 // in its thread-storage area. 4565 SDValue HiVar = DAG.getTargetGlobalAddress( 4566 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4567 SDValue LoVar = DAG.getTargetGlobalAddress( 4568 GV, DL, MVT::i64, 0, 4569 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4570 4571 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 4572 DAG.getTargetConstant(0, DL, MVT::i32)), 4573 0); 4574 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 4575 DAG.getTargetConstant(0, DL, MVT::i32)), 4576 0); 4577 } else if (Model == TLSModel::GeneralDynamic) { 4578 // The call needs a relocation too for linker relaxation. It doesn't make 4579 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4580 // the address. 4581 SDValue SymAddr = 4582 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4583 4584 // Finally we can make a call to calculate the offset from tpidr_el0. 4585 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4586 } else 4587 llvm_unreachable("Unsupported ELF TLS access model"); 4588 4589 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4590 } 4591 4592 SDValue 4593 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 4594 SelectionDAG &DAG) const { 4595 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 4596 4597 SDValue Chain = DAG.getEntryNode(); 4598 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4599 SDLoc DL(Op); 4600 4601 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 4602 4603 // Load the ThreadLocalStoragePointer from the TEB 4604 // A pointer to the TLS array is located at offset 0x58 from the TEB. 4605 SDValue TLSArray = 4606 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 4607 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 4608 Chain = TLSArray.getValue(1); 4609 4610 // Load the TLS index from the C runtime; 4611 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 4612 // This also does the same as LOADgot, but using a generic i32 load, 4613 // while LOADgot only loads i64. 4614 SDValue TLSIndexHi = 4615 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 4616 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 4617 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4618 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 4619 SDValue TLSIndex = 4620 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 4621 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 4622 Chain = TLSIndex.getValue(1); 4623 4624 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 4625 // offset into the TLSArray. 4626 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 4627 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 4628 DAG.getConstant(3, DL, PtrVT)); 4629 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 4630 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 4631 MachinePointerInfo()); 4632 Chain = TLS.getValue(1); 4633 4634 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4635 const GlobalValue *GV = GA->getGlobal(); 4636 SDValue TGAHi = DAG.getTargetGlobalAddress( 4637 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4638 SDValue TGALo = DAG.getTargetGlobalAddress( 4639 GV, DL, PtrVT, 0, 4640 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4641 4642 // Add the offset from the start of the .tls section (section base). 4643 SDValue Addr = 4644 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 4645 DAG.getTargetConstant(0, DL, MVT::i32)), 4646 0); 4647 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 4648 return Addr; 4649 } 4650 4651 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 4652 SelectionDAG &DAG) const { 4653 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4654 if (DAG.getTarget().useEmulatedTLS()) 4655 return LowerToTLSEmulatedModel(GA, DAG); 4656 4657 if (Subtarget->isTargetDarwin()) 4658 return LowerDarwinGlobalTLSAddress(Op, DAG); 4659 if (Subtarget->isTargetELF()) 4660 return LowerELFGlobalTLSAddress(Op, DAG); 4661 if (Subtarget->isTargetWindows()) 4662 return LowerWindowsGlobalTLSAddress(Op, DAG); 4663 4664 llvm_unreachable("Unexpected platform trying to use TLS"); 4665 } 4666 4667 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4668 SDValue Chain = Op.getOperand(0); 4669 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4670 SDValue LHS = Op.getOperand(2); 4671 SDValue RHS = Op.getOperand(3); 4672 SDValue Dest = Op.getOperand(4); 4673 SDLoc dl(Op); 4674 4675 MachineFunction &MF = DAG.getMachineFunction(); 4676 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 4677 // will not be produced, as they are conditional branch instructions that do 4678 // not set flags. 4679 bool ProduceNonFlagSettingCondBr = 4680 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 4681 4682 // Handle f128 first, since lowering it will result in comparing the return 4683 // value of a libcall against zero, which is just what the rest of LowerBR_CC 4684 // is expecting to deal with. 4685 if (LHS.getValueType() == MVT::f128) { 4686 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 4687 4688 // If softenSetCCOperands returned a scalar, we need to compare the result 4689 // against zero to select between true and false values. 4690 if (!RHS.getNode()) { 4691 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4692 CC = ISD::SETNE; 4693 } 4694 } 4695 4696 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4697 // instruction. 4698 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 4699 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4700 // Only lower legal XALUO ops. 4701 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4702 return SDValue(); 4703 4704 // The actual operation with overflow check. 4705 AArch64CC::CondCode OFCC; 4706 SDValue Value, Overflow; 4707 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 4708 4709 if (CC == ISD::SETNE) 4710 OFCC = getInvertedCondCode(OFCC); 4711 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 4712 4713 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4714 Overflow); 4715 } 4716 4717 if (LHS.getValueType().isInteger()) { 4718 assert((LHS.getValueType() == RHS.getValueType()) && 4719 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4720 4721 // If the RHS of the comparison is zero, we can potentially fold this 4722 // to a specialized branch. 4723 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 4724 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 4725 if (CC == ISD::SETEQ) { 4726 // See if we can use a TBZ to fold in an AND as well. 4727 // TBZ has a smaller branch displacement than CBZ. If the offset is 4728 // out of bounds, a late MI-layer pass rewrites branches. 4729 // 403.gcc is an example that hits this case. 4730 if (LHS.getOpcode() == ISD::AND && 4731 isa<ConstantSDNode>(LHS.getOperand(1)) && 4732 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4733 SDValue Test = LHS.getOperand(0); 4734 uint64_t Mask = LHS.getConstantOperandVal(1); 4735 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 4736 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4737 Dest); 4738 } 4739 4740 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 4741 } else if (CC == ISD::SETNE) { 4742 // See if we can use a TBZ to fold in an AND as well. 4743 // TBZ has a smaller branch displacement than CBZ. If the offset is 4744 // out of bounds, a late MI-layer pass rewrites branches. 4745 // 403.gcc is an example that hits this case. 4746 if (LHS.getOpcode() == ISD::AND && 4747 isa<ConstantSDNode>(LHS.getOperand(1)) && 4748 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4749 SDValue Test = LHS.getOperand(0); 4750 uint64_t Mask = LHS.getConstantOperandVal(1); 4751 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 4752 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4753 Dest); 4754 } 4755 4756 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 4757 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 4758 // Don't combine AND since emitComparison converts the AND to an ANDS 4759 // (a.k.a. TST) and the test in the test bit and branch instruction 4760 // becomes redundant. This would also increase register pressure. 4761 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4762 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 4763 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4764 } 4765 } 4766 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 4767 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 4768 // Don't combine AND since emitComparison converts the AND to an ANDS 4769 // (a.k.a. TST) and the test in the test bit and branch instruction 4770 // becomes redundant. This would also increase register pressure. 4771 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4772 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 4773 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4774 } 4775 4776 SDValue CCVal; 4777 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4778 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4779 Cmp); 4780 } 4781 4782 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4783 LHS.getValueType() == MVT::f64); 4784 4785 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4786 // clean. Some of them require two branches to implement. 4787 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4788 AArch64CC::CondCode CC1, CC2; 4789 changeFPCCToAArch64CC(CC, CC1, CC2); 4790 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4791 SDValue BR1 = 4792 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 4793 if (CC2 != AArch64CC::AL) { 4794 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4795 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 4796 Cmp); 4797 } 4798 4799 return BR1; 4800 } 4801 4802 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 4803 SelectionDAG &DAG) const { 4804 EVT VT = Op.getValueType(); 4805 SDLoc DL(Op); 4806 4807 SDValue In1 = Op.getOperand(0); 4808 SDValue In2 = Op.getOperand(1); 4809 EVT SrcVT = In2.getValueType(); 4810 4811 if (SrcVT.bitsLT(VT)) 4812 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 4813 else if (SrcVT.bitsGT(VT)) 4814 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 4815 4816 EVT VecVT; 4817 uint64_t EltMask; 4818 SDValue VecVal1, VecVal2; 4819 4820 auto setVecVal = [&] (int Idx) { 4821 if (!VT.isVector()) { 4822 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4823 DAG.getUNDEF(VecVT), In1); 4824 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4825 DAG.getUNDEF(VecVT), In2); 4826 } else { 4827 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 4828 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 4829 } 4830 }; 4831 4832 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 4833 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 4834 EltMask = 0x80000000ULL; 4835 setVecVal(AArch64::ssub); 4836 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 4837 VecVT = MVT::v2i64; 4838 4839 // We want to materialize a mask with the high bit set, but the AdvSIMD 4840 // immediate moves cannot materialize that in a single instruction for 4841 // 64-bit elements. Instead, materialize zero and then negate it. 4842 EltMask = 0; 4843 4844 setVecVal(AArch64::dsub); 4845 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 4846 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 4847 EltMask = 0x8000ULL; 4848 setVecVal(AArch64::hsub); 4849 } else { 4850 llvm_unreachable("Invalid type for copysign!"); 4851 } 4852 4853 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 4854 4855 // If we couldn't materialize the mask above, then the mask vector will be 4856 // the zero vector, and we need to negate it here. 4857 if (VT == MVT::f64 || VT == MVT::v2f64) { 4858 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 4859 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 4860 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 4861 } 4862 4863 SDValue Sel = 4864 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 4865 4866 if (VT == MVT::f16) 4867 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 4868 if (VT == MVT::f32) 4869 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 4870 else if (VT == MVT::f64) 4871 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 4872 else 4873 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 4874 } 4875 4876 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 4877 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 4878 Attribute::NoImplicitFloat)) 4879 return SDValue(); 4880 4881 if (!Subtarget->hasNEON()) 4882 return SDValue(); 4883 4884 // While there is no integer popcount instruction, it can 4885 // be more efficiently lowered to the following sequence that uses 4886 // AdvSIMD registers/instructions as long as the copies to/from 4887 // the AdvSIMD registers are cheap. 4888 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 4889 // CNT V0.8B, V0.8B // 8xbyte pop-counts 4890 // ADDV B0, V0.8B // sum 8xbyte pop-counts 4891 // UMOV X0, V0.B[0] // copy byte result back to integer reg 4892 SDValue Val = Op.getOperand(0); 4893 SDLoc DL(Op); 4894 EVT VT = Op.getValueType(); 4895 4896 if (VT == MVT::i32 || VT == MVT::i64) { 4897 if (VT == MVT::i32) 4898 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 4899 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 4900 4901 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 4902 SDValue UaddLV = DAG.getNode( 4903 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 4904 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 4905 4906 if (VT == MVT::i64) 4907 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 4908 return UaddLV; 4909 } 4910 4911 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 4912 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 4913 "Unexpected type for custom ctpop lowering"); 4914 4915 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4916 Val = DAG.getBitcast(VT8Bit, Val); 4917 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 4918 4919 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 4920 unsigned EltSize = 8; 4921 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 4922 while (EltSize != VT.getScalarSizeInBits()) { 4923 EltSize *= 2; 4924 NumElts /= 2; 4925 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 4926 Val = DAG.getNode( 4927 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 4928 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 4929 } 4930 4931 return Val; 4932 } 4933 4934 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 4935 4936 if (Op.getValueType().isVector()) 4937 return LowerVSETCC(Op, DAG); 4938 4939 SDValue LHS = Op.getOperand(0); 4940 SDValue RHS = Op.getOperand(1); 4941 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 4942 SDLoc dl(Op); 4943 4944 // We chose ZeroOrOneBooleanContents, so use zero and one. 4945 EVT VT = Op.getValueType(); 4946 SDValue TVal = DAG.getConstant(1, dl, VT); 4947 SDValue FVal = DAG.getConstant(0, dl, VT); 4948 4949 // Handle f128 first, since one possible outcome is a normal integer 4950 // comparison which gets picked up by the next if statement. 4951 if (LHS.getValueType() == MVT::f128) { 4952 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 4953 4954 // If softenSetCCOperands returned a scalar, use it. 4955 if (!RHS.getNode()) { 4956 assert(LHS.getValueType() == Op.getValueType() && 4957 "Unexpected setcc expansion!"); 4958 return LHS; 4959 } 4960 } 4961 4962 if (LHS.getValueType().isInteger()) { 4963 SDValue CCVal; 4964 SDValue Cmp = 4965 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 4966 4967 // Note that we inverted the condition above, so we reverse the order of 4968 // the true and false operands here. This will allow the setcc to be 4969 // matched to a single CSINC instruction. 4970 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 4971 } 4972 4973 // Now we know we're dealing with FP values. 4974 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4975 LHS.getValueType() == MVT::f64); 4976 4977 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 4978 // and do the comparison. 4979 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4980 4981 AArch64CC::CondCode CC1, CC2; 4982 changeFPCCToAArch64CC(CC, CC1, CC2); 4983 if (CC2 == AArch64CC::AL) { 4984 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 4985 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4986 4987 // Note that we inverted the condition above, so we reverse the order of 4988 // the true and false operands here. This will allow the setcc to be 4989 // matched to a single CSINC instruction. 4990 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 4991 } else { 4992 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 4993 // totally clean. Some of them require two CSELs to implement. As is in 4994 // this case, we emit the first CSEL and then emit a second using the output 4995 // of the first as the RHS. We're effectively OR'ing the two CC's together. 4996 4997 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 4998 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4999 SDValue CS1 = 5000 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5001 5002 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5003 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5004 } 5005 } 5006 5007 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 5008 SDValue RHS, SDValue TVal, 5009 SDValue FVal, const SDLoc &dl, 5010 SelectionDAG &DAG) const { 5011 // Handle f128 first, because it will result in a comparison of some RTLIB 5012 // call result against zero. 5013 if (LHS.getValueType() == MVT::f128) { 5014 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5015 5016 // If softenSetCCOperands returned a scalar, we need to compare the result 5017 // against zero to select between true and false values. 5018 if (!RHS.getNode()) { 5019 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5020 CC = ISD::SETNE; 5021 } 5022 } 5023 5024 // Also handle f16, for which we need to do a f32 comparison. 5025 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 5026 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 5027 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 5028 } 5029 5030 // Next, handle integers. 5031 if (LHS.getValueType().isInteger()) { 5032 assert((LHS.getValueType() == RHS.getValueType()) && 5033 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5034 5035 unsigned Opcode = AArch64ISD::CSEL; 5036 5037 // If both the TVal and the FVal are constants, see if we can swap them in 5038 // order to for a CSINV or CSINC out of them. 5039 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 5040 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 5041 5042 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 5043 std::swap(TVal, FVal); 5044 std::swap(CTVal, CFVal); 5045 CC = ISD::getSetCCInverse(CC, true); 5046 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 5047 std::swap(TVal, FVal); 5048 std::swap(CTVal, CFVal); 5049 CC = ISD::getSetCCInverse(CC, true); 5050 } else if (TVal.getOpcode() == ISD::XOR) { 5051 // If TVal is a NOT we want to swap TVal and FVal so that we can match 5052 // with a CSINV rather than a CSEL. 5053 if (isAllOnesConstant(TVal.getOperand(1))) { 5054 std::swap(TVal, FVal); 5055 std::swap(CTVal, CFVal); 5056 CC = ISD::getSetCCInverse(CC, true); 5057 } 5058 } else if (TVal.getOpcode() == ISD::SUB) { 5059 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 5060 // that we can match with a CSNEG rather than a CSEL. 5061 if (isNullConstant(TVal.getOperand(0))) { 5062 std::swap(TVal, FVal); 5063 std::swap(CTVal, CFVal); 5064 CC = ISD::getSetCCInverse(CC, true); 5065 } 5066 } else if (CTVal && CFVal) { 5067 const int64_t TrueVal = CTVal->getSExtValue(); 5068 const int64_t FalseVal = CFVal->getSExtValue(); 5069 bool Swap = false; 5070 5071 // If both TVal and FVal are constants, see if FVal is the 5072 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 5073 // instead of a CSEL in that case. 5074 if (TrueVal == ~FalseVal) { 5075 Opcode = AArch64ISD::CSINV; 5076 } else if (TrueVal == -FalseVal) { 5077 Opcode = AArch64ISD::CSNEG; 5078 } else if (TVal.getValueType() == MVT::i32) { 5079 // If our operands are only 32-bit wide, make sure we use 32-bit 5080 // arithmetic for the check whether we can use CSINC. This ensures that 5081 // the addition in the check will wrap around properly in case there is 5082 // an overflow (which would not be the case if we do the check with 5083 // 64-bit arithmetic). 5084 const uint32_t TrueVal32 = CTVal->getZExtValue(); 5085 const uint32_t FalseVal32 = CFVal->getZExtValue(); 5086 5087 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 5088 Opcode = AArch64ISD::CSINC; 5089 5090 if (TrueVal32 > FalseVal32) { 5091 Swap = true; 5092 } 5093 } 5094 // 64-bit check whether we can use CSINC. 5095 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 5096 Opcode = AArch64ISD::CSINC; 5097 5098 if (TrueVal > FalseVal) { 5099 Swap = true; 5100 } 5101 } 5102 5103 // Swap TVal and FVal if necessary. 5104 if (Swap) { 5105 std::swap(TVal, FVal); 5106 std::swap(CTVal, CFVal); 5107 CC = ISD::getSetCCInverse(CC, true); 5108 } 5109 5110 if (Opcode != AArch64ISD::CSEL) { 5111 // Drop FVal since we can get its value by simply inverting/negating 5112 // TVal. 5113 FVal = TVal; 5114 } 5115 } 5116 5117 // Avoid materializing a constant when possible by reusing a known value in 5118 // a register. However, don't perform this optimization if the known value 5119 // is one, zero or negative one in the case of a CSEL. We can always 5120 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 5121 // FVal, respectively. 5122 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 5123 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 5124 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 5125 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5126 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 5127 // "a != C ? x : a" to avoid materializing C. 5128 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 5129 TVal = LHS; 5130 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 5131 FVal = LHS; 5132 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 5133 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 5134 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 5135 // avoid materializing C. 5136 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5137 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 5138 Opcode = AArch64ISD::CSINV; 5139 TVal = LHS; 5140 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 5141 } 5142 } 5143 5144 SDValue CCVal; 5145 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5146 EVT VT = TVal.getValueType(); 5147 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 5148 } 5149 5150 // Now we know we're dealing with FP values. 5151 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5152 LHS.getValueType() == MVT::f64); 5153 assert(LHS.getValueType() == RHS.getValueType()); 5154 EVT VT = TVal.getValueType(); 5155 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5156 5157 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5158 // clean. Some of them require two CSELs to implement. 5159 AArch64CC::CondCode CC1, CC2; 5160 changeFPCCToAArch64CC(CC, CC1, CC2); 5161 5162 if (DAG.getTarget().Options.UnsafeFPMath) { 5163 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 5164 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 5165 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 5166 if (RHSVal && RHSVal->isZero()) { 5167 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 5168 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 5169 5170 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 5171 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 5172 TVal = LHS; 5173 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 5174 CFVal && CFVal->isZero() && 5175 FVal.getValueType() == LHS.getValueType()) 5176 FVal = LHS; 5177 } 5178 } 5179 5180 // Emit first, and possibly only, CSEL. 5181 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5182 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5183 5184 // If we need a second CSEL, emit it, using the output of the first as the 5185 // RHS. We're effectively OR'ing the two CC's together. 5186 if (CC2 != AArch64CC::AL) { 5187 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5188 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5189 } 5190 5191 // Otherwise, return the output of the first CSEL. 5192 return CS1; 5193 } 5194 5195 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 5196 SelectionDAG &DAG) const { 5197 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5198 SDValue LHS = Op.getOperand(0); 5199 SDValue RHS = Op.getOperand(1); 5200 SDValue TVal = Op.getOperand(2); 5201 SDValue FVal = Op.getOperand(3); 5202 SDLoc DL(Op); 5203 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5204 } 5205 5206 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 5207 SelectionDAG &DAG) const { 5208 SDValue CCVal = Op->getOperand(0); 5209 SDValue TVal = Op->getOperand(1); 5210 SDValue FVal = Op->getOperand(2); 5211 SDLoc DL(Op); 5212 5213 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 5214 // instruction. 5215 if (isOverflowIntrOpRes(CCVal)) { 5216 // Only lower legal XALUO ops. 5217 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 5218 return SDValue(); 5219 5220 AArch64CC::CondCode OFCC; 5221 SDValue Value, Overflow; 5222 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 5223 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 5224 5225 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 5226 CCVal, Overflow); 5227 } 5228 5229 // Lower it the same way as we would lower a SELECT_CC node. 5230 ISD::CondCode CC; 5231 SDValue LHS, RHS; 5232 if (CCVal.getOpcode() == ISD::SETCC) { 5233 LHS = CCVal.getOperand(0); 5234 RHS = CCVal.getOperand(1); 5235 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 5236 } else { 5237 LHS = CCVal; 5238 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 5239 CC = ISD::SETNE; 5240 } 5241 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5242 } 5243 5244 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 5245 SelectionDAG &DAG) const { 5246 // Jump table entries as PC relative offsets. No additional tweaking 5247 // is necessary here. Just get the address of the jump table. 5248 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 5249 5250 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5251 !Subtarget->isTargetMachO()) { 5252 return getAddrLarge(JT, DAG); 5253 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5254 return getAddrTiny(JT, DAG); 5255 } 5256 return getAddr(JT, DAG); 5257 } 5258 5259 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 5260 SelectionDAG &DAG) const { 5261 // Jump table entries as PC relative offsets. No additional tweaking 5262 // is necessary here. Just get the address of the jump table. 5263 SDLoc DL(Op); 5264 SDValue JT = Op.getOperand(1); 5265 SDValue Entry = Op.getOperand(2); 5266 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 5267 5268 SDNode *Dest = 5269 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 5270 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 5271 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 5272 SDValue(Dest, 0)); 5273 } 5274 5275 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 5276 SelectionDAG &DAG) const { 5277 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 5278 5279 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5280 // Use the GOT for the large code model on iOS. 5281 if (Subtarget->isTargetMachO()) { 5282 return getGOT(CP, DAG); 5283 } 5284 return getAddrLarge(CP, DAG); 5285 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5286 return getAddrTiny(CP, DAG); 5287 } else { 5288 return getAddr(CP, DAG); 5289 } 5290 } 5291 5292 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 5293 SelectionDAG &DAG) const { 5294 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 5295 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5296 !Subtarget->isTargetMachO()) { 5297 return getAddrLarge(BA, DAG); 5298 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5299 return getAddrTiny(BA, DAG); 5300 } 5301 return getAddr(BA, DAG); 5302 } 5303 5304 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 5305 SelectionDAG &DAG) const { 5306 AArch64FunctionInfo *FuncInfo = 5307 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5308 5309 SDLoc DL(Op); 5310 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 5311 getPointerTy(DAG.getDataLayout())); 5312 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 5313 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5314 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5315 MachinePointerInfo(SV)); 5316 } 5317 5318 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 5319 SelectionDAG &DAG) const { 5320 AArch64FunctionInfo *FuncInfo = 5321 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5322 5323 SDLoc DL(Op); 5324 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 5325 ? FuncInfo->getVarArgsGPRIndex() 5326 : FuncInfo->getVarArgsStackIndex(), 5327 getPointerTy(DAG.getDataLayout())); 5328 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5329 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5330 MachinePointerInfo(SV)); 5331 } 5332 5333 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 5334 SelectionDAG &DAG) const { 5335 // The layout of the va_list struct is specified in the AArch64 Procedure Call 5336 // Standard, section B.3. 5337 MachineFunction &MF = DAG.getMachineFunction(); 5338 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5339 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5340 SDLoc DL(Op); 5341 5342 SDValue Chain = Op.getOperand(0); 5343 SDValue VAList = Op.getOperand(1); 5344 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5345 SmallVector<SDValue, 4> MemOps; 5346 5347 // void *__stack at offset 0 5348 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 5349 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 5350 MachinePointerInfo(SV), /* Alignment = */ 8)); 5351 5352 // void *__gr_top at offset 8 5353 int GPRSize = FuncInfo->getVarArgsGPRSize(); 5354 if (GPRSize > 0) { 5355 SDValue GRTop, GRTopAddr; 5356 5357 GRTopAddr = 5358 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 5359 5360 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 5361 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 5362 DAG.getConstant(GPRSize, DL, PtrVT)); 5363 5364 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 5365 MachinePointerInfo(SV, 8), 5366 /* Alignment = */ 8)); 5367 } 5368 5369 // void *__vr_top at offset 16 5370 int FPRSize = FuncInfo->getVarArgsFPRSize(); 5371 if (FPRSize > 0) { 5372 SDValue VRTop, VRTopAddr; 5373 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5374 DAG.getConstant(16, DL, PtrVT)); 5375 5376 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 5377 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 5378 DAG.getConstant(FPRSize, DL, PtrVT)); 5379 5380 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 5381 MachinePointerInfo(SV, 16), 5382 /* Alignment = */ 8)); 5383 } 5384 5385 // int __gr_offs at offset 24 5386 SDValue GROffsAddr = 5387 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 5388 MemOps.push_back(DAG.getStore( 5389 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 5390 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 5391 5392 // int __vr_offs at offset 28 5393 SDValue VROffsAddr = 5394 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 5395 MemOps.push_back(DAG.getStore( 5396 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 5397 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 5398 5399 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5400 } 5401 5402 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 5403 SelectionDAG &DAG) const { 5404 MachineFunction &MF = DAG.getMachineFunction(); 5405 5406 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 5407 return LowerWin64_VASTART(Op, DAG); 5408 else if (Subtarget->isTargetDarwin()) 5409 return LowerDarwin_VASTART(Op, DAG); 5410 else 5411 return LowerAAPCS_VASTART(Op, DAG); 5412 } 5413 5414 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 5415 SelectionDAG &DAG) const { 5416 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 5417 // pointer. 5418 SDLoc DL(Op); 5419 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 5420 unsigned VaListSize = (Subtarget->isTargetDarwin() || 5421 Subtarget->isTargetWindows()) ? PtrSize : 32; 5422 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 5423 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 5424 5425 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 5426 DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize, 5427 false, false, false, MachinePointerInfo(DestSV), 5428 MachinePointerInfo(SrcSV)); 5429 } 5430 5431 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 5432 assert(Subtarget->isTargetDarwin() && 5433 "automatic va_arg instruction only works on Darwin"); 5434 5435 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5436 EVT VT = Op.getValueType(); 5437 SDLoc DL(Op); 5438 SDValue Chain = Op.getOperand(0); 5439 SDValue Addr = Op.getOperand(1); 5440 unsigned Align = Op.getConstantOperandVal(3); 5441 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 5442 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5443 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 5444 SDValue VAList = 5445 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 5446 Chain = VAList.getValue(1); 5447 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 5448 5449 if (Align > MinSlotSize) { 5450 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 5451 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5452 DAG.getConstant(Align - 1, DL, PtrVT)); 5453 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 5454 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 5455 } 5456 5457 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 5458 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 5459 5460 // Scalar integer and FP values smaller than 64 bits are implicitly extended 5461 // up to 64 bits. At the very least, we have to increase the striding of the 5462 // vaargs list to match this, and for FP values we need to introduce 5463 // FP_ROUND nodes as well. 5464 if (VT.isInteger() && !VT.isVector()) 5465 ArgSize = std::max(ArgSize, MinSlotSize); 5466 bool NeedFPTrunc = false; 5467 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 5468 ArgSize = 8; 5469 NeedFPTrunc = true; 5470 } 5471 5472 // Increment the pointer, VAList, to the next vaarg 5473 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5474 DAG.getConstant(ArgSize, DL, PtrVT)); 5475 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 5476 5477 // Store the incremented VAList to the legalized pointer 5478 SDValue APStore = 5479 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 5480 5481 // Load the actual argument out of the pointer VAList 5482 if (NeedFPTrunc) { 5483 // Load the value as an f64. 5484 SDValue WideFP = 5485 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 5486 // Round the value down to an f32. 5487 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 5488 DAG.getIntPtrConstant(1, DL)); 5489 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 5490 // Merge the rounded value with the chain output of the load. 5491 return DAG.getMergeValues(Ops, DL); 5492 } 5493 5494 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 5495 } 5496 5497 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 5498 SelectionDAG &DAG) const { 5499 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5500 MFI.setFrameAddressIsTaken(true); 5501 5502 EVT VT = Op.getValueType(); 5503 SDLoc DL(Op); 5504 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5505 SDValue FrameAddr = 5506 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 5507 while (Depth--) 5508 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 5509 MachinePointerInfo()); 5510 5511 if (Subtarget->isTargetILP32()) 5512 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 5513 DAG.getValueType(VT)); 5514 5515 return FrameAddr; 5516 } 5517 5518 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 5519 SelectionDAG &DAG) const { 5520 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5521 5522 EVT VT = getPointerTy(DAG.getDataLayout()); 5523 SDLoc DL(Op); 5524 int FI = MFI.CreateFixedObject(4, 0, false); 5525 return DAG.getFrameIndex(FI, VT); 5526 } 5527 5528 #define GET_REGISTER_MATCHER 5529 #include "AArch64GenAsmMatcher.inc" 5530 5531 // FIXME? Maybe this could be a TableGen attribute on some registers and 5532 // this table could be generated automatically from RegInfo. 5533 Register AArch64TargetLowering:: 5534 getRegisterByName(const char* RegName, EVT VT, const MachineFunction &MF) const { 5535 Register Reg = MatchRegisterName(RegName); 5536 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 5537 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 5538 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 5539 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 5540 Reg = 0; 5541 } 5542 if (Reg) 5543 return Reg; 5544 report_fatal_error(Twine("Invalid register name \"" 5545 + StringRef(RegName) + "\".")); 5546 } 5547 5548 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 5549 SelectionDAG &DAG) const { 5550 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 5551 5552 EVT VT = Op.getValueType(); 5553 SDLoc DL(Op); 5554 5555 SDValue FrameAddr = 5556 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 5557 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5558 5559 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 5560 } 5561 5562 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 5563 SelectionDAG &DAG) const { 5564 MachineFunction &MF = DAG.getMachineFunction(); 5565 MachineFrameInfo &MFI = MF.getFrameInfo(); 5566 MFI.setReturnAddressIsTaken(true); 5567 5568 EVT VT = Op.getValueType(); 5569 SDLoc DL(Op); 5570 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5571 if (Depth) { 5572 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5573 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5574 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 5575 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 5576 MachinePointerInfo()); 5577 } 5578 5579 // Return LR, which contains the return address. Mark it an implicit live-in. 5580 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 5581 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5582 } 5583 5584 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5585 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 5586 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 5587 SelectionDAG &DAG) const { 5588 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5589 EVT VT = Op.getValueType(); 5590 unsigned VTBits = VT.getSizeInBits(); 5591 SDLoc dl(Op); 5592 SDValue ShOpLo = Op.getOperand(0); 5593 SDValue ShOpHi = Op.getOperand(1); 5594 SDValue ShAmt = Op.getOperand(2); 5595 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5596 5597 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5598 5599 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 5600 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 5601 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5602 5603 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 5604 // is "undef". We wanted 0, so CSEL it directly. 5605 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 5606 ISD::SETEQ, dl, DAG); 5607 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 5608 HiBitsForLo = 5609 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 5610 HiBitsForLo, CCVal, Cmp); 5611 5612 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 5613 DAG.getConstant(VTBits, dl, MVT::i64)); 5614 5615 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5616 SDValue LoForNormalShift = 5617 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 5618 5619 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 5620 dl, DAG); 5621 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 5622 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5623 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 5624 LoForNormalShift, CCVal, Cmp); 5625 5626 // AArch64 shifts larger than the register width are wrapped rather than 5627 // clamped, so we can't just emit "hi >> x". 5628 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5629 SDValue HiForBigShift = 5630 Opc == ISD::SRA 5631 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5632 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 5633 : DAG.getConstant(0, dl, VT); 5634 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 5635 HiForNormalShift, CCVal, Cmp); 5636 5637 SDValue Ops[2] = { Lo, Hi }; 5638 return DAG.getMergeValues(Ops, dl); 5639 } 5640 5641 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5642 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 5643 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 5644 SelectionDAG &DAG) const { 5645 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5646 EVT VT = Op.getValueType(); 5647 unsigned VTBits = VT.getSizeInBits(); 5648 SDLoc dl(Op); 5649 SDValue ShOpLo = Op.getOperand(0); 5650 SDValue ShOpHi = Op.getOperand(1); 5651 SDValue ShAmt = Op.getOperand(2); 5652 5653 assert(Op.getOpcode() == ISD::SHL_PARTS); 5654 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 5655 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 5656 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5657 5658 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 5659 // is "undef". We wanted 0, so CSEL it directly. 5660 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 5661 ISD::SETEQ, dl, DAG); 5662 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 5663 LoBitsForHi = 5664 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 5665 LoBitsForHi, CCVal, Cmp); 5666 5667 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 5668 DAG.getConstant(VTBits, dl, MVT::i64)); 5669 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5670 SDValue HiForNormalShift = 5671 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 5672 5673 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5674 5675 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 5676 dl, DAG); 5677 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 5678 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 5679 HiForNormalShift, CCVal, Cmp); 5680 5681 // AArch64 shifts of larger than register sizes are wrapped rather than 5682 // clamped, so we can't just emit "lo << a" if a is too big. 5683 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 5684 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5685 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 5686 LoForNormalShift, CCVal, Cmp); 5687 5688 SDValue Ops[2] = { Lo, Hi }; 5689 return DAG.getMergeValues(Ops, dl); 5690 } 5691 5692 bool AArch64TargetLowering::isOffsetFoldingLegal( 5693 const GlobalAddressSDNode *GA) const { 5694 // Offsets are folded in the DAG combine rather than here so that we can 5695 // intelligently choose an offset based on the uses. 5696 return false; 5697 } 5698 5699 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 5700 bool OptForSize) const { 5701 bool IsLegal = false; 5702 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 5703 // 16-bit case when target has full fp16 support. 5704 // FIXME: We should be able to handle f128 as well with a clever lowering. 5705 const APInt ImmInt = Imm.bitcastToAPInt(); 5706 if (VT == MVT::f64) 5707 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 5708 else if (VT == MVT::f32) 5709 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 5710 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 5711 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 5712 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 5713 // generate that fmov. 5714 5715 // If we can not materialize in immediate field for fmov, check if the 5716 // value can be encoded as the immediate operand of a logical instruction. 5717 // The immediate value will be created with either MOVZ, MOVN, or ORR. 5718 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 5719 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 5720 // however the mov+fmov sequence is always better because of the reduced 5721 // cache pressure. The timings are still the same if you consider 5722 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 5723 // movw+movk is fused). So we limit up to 2 instrdduction at most. 5724 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 5725 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 5726 Insn); 5727 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 5728 IsLegal = Insn.size() <= Limit; 5729 } 5730 5731 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 5732 << " imm value: "; Imm.dump();); 5733 return IsLegal; 5734 } 5735 5736 //===----------------------------------------------------------------------===// 5737 // AArch64 Optimization Hooks 5738 //===----------------------------------------------------------------------===// 5739 5740 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 5741 SDValue Operand, SelectionDAG &DAG, 5742 int &ExtraSteps) { 5743 EVT VT = Operand.getValueType(); 5744 if (ST->hasNEON() && 5745 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 5746 VT == MVT::f32 || VT == MVT::v1f32 || 5747 VT == MVT::v2f32 || VT == MVT::v4f32)) { 5748 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 5749 // For the reciprocal estimates, convergence is quadratic, so the number 5750 // of digits is doubled after each iteration. In ARMv8, the accuracy of 5751 // the initial estimate is 2^-8. Thus the number of extra steps to refine 5752 // the result for float (23 mantissa bits) is 2 and for double (52 5753 // mantissa bits) is 3. 5754 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 5755 5756 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 5757 } 5758 5759 return SDValue(); 5760 } 5761 5762 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 5763 SelectionDAG &DAG, int Enabled, 5764 int &ExtraSteps, 5765 bool &UseOneConst, 5766 bool Reciprocal) const { 5767 if (Enabled == ReciprocalEstimate::Enabled || 5768 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 5769 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 5770 DAG, ExtraSteps)) { 5771 SDLoc DL(Operand); 5772 EVT VT = Operand.getValueType(); 5773 5774 SDNodeFlags Flags; 5775 Flags.setAllowReassociation(true); 5776 5777 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 5778 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 5779 for (int i = ExtraSteps; i > 0; --i) { 5780 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 5781 Flags); 5782 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 5783 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5784 } 5785 if (!Reciprocal) { 5786 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 5787 VT); 5788 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 5789 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 5790 5791 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 5792 // Correct the result if the operand is 0.0. 5793 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 5794 VT, Eq, Operand, Estimate); 5795 } 5796 5797 ExtraSteps = 0; 5798 return Estimate; 5799 } 5800 5801 return SDValue(); 5802 } 5803 5804 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 5805 SelectionDAG &DAG, int Enabled, 5806 int &ExtraSteps) const { 5807 if (Enabled == ReciprocalEstimate::Enabled) 5808 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 5809 DAG, ExtraSteps)) { 5810 SDLoc DL(Operand); 5811 EVT VT = Operand.getValueType(); 5812 5813 SDNodeFlags Flags; 5814 Flags.setAllowReassociation(true); 5815 5816 // Newton reciprocal iteration: E * (2 - X * E) 5817 // AArch64 reciprocal iteration instruction: (2 - M * N) 5818 for (int i = ExtraSteps; i > 0; --i) { 5819 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 5820 Estimate, Flags); 5821 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5822 } 5823 5824 ExtraSteps = 0; 5825 return Estimate; 5826 } 5827 5828 return SDValue(); 5829 } 5830 5831 //===----------------------------------------------------------------------===// 5832 // AArch64 Inline Assembly Support 5833 //===----------------------------------------------------------------------===// 5834 5835 // Table of Constraints 5836 // TODO: This is the current set of constraints supported by ARM for the 5837 // compiler, not all of them may make sense. 5838 // 5839 // r - A general register 5840 // w - An FP/SIMD register of some size in the range v0-v31 5841 // x - An FP/SIMD register of some size in the range v0-v15 5842 // I - Constant that can be used with an ADD instruction 5843 // J - Constant that can be used with a SUB instruction 5844 // K - Constant that can be used with a 32-bit logical instruction 5845 // L - Constant that can be used with a 64-bit logical instruction 5846 // M - Constant that can be used as a 32-bit MOV immediate 5847 // N - Constant that can be used as a 64-bit MOV immediate 5848 // Q - A memory reference with base register and no offset 5849 // S - A symbolic address 5850 // Y - Floating point constant zero 5851 // Z - Integer constant zero 5852 // 5853 // Note that general register operands will be output using their 64-bit x 5854 // register name, whatever the size of the variable, unless the asm operand 5855 // is prefixed by the %w modifier. Floating-point and SIMD register operands 5856 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 5857 // %q modifier. 5858 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5859 // At this point, we have to lower this constraint to something else, so we 5860 // lower it to an "r" or "w". However, by doing this we will force the result 5861 // to be in register, while the X constraint is much more permissive. 5862 // 5863 // Although we are correct (we are free to emit anything, without 5864 // constraints), we might break use cases that would expect us to be more 5865 // efficient and emit something else. 5866 if (!Subtarget->hasFPARMv8()) 5867 return "r"; 5868 5869 if (ConstraintVT.isFloatingPoint()) 5870 return "w"; 5871 5872 if (ConstraintVT.isVector() && 5873 (ConstraintVT.getSizeInBits() == 64 || 5874 ConstraintVT.getSizeInBits() == 128)) 5875 return "w"; 5876 5877 return "r"; 5878 } 5879 5880 enum PredicateConstraint { 5881 Upl, 5882 Upa, 5883 Invalid 5884 }; 5885 5886 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 5887 PredicateConstraint P = PredicateConstraint::Invalid; 5888 if (Constraint == "Upa") 5889 P = PredicateConstraint::Upa; 5890 if (Constraint == "Upl") 5891 P = PredicateConstraint::Upl; 5892 return P; 5893 } 5894 5895 /// getConstraintType - Given a constraint letter, return the type of 5896 /// constraint it is for this target. 5897 AArch64TargetLowering::ConstraintType 5898 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 5899 if (Constraint.size() == 1) { 5900 switch (Constraint[0]) { 5901 default: 5902 break; 5903 case 'x': 5904 case 'w': 5905 case 'y': 5906 return C_RegisterClass; 5907 // An address with a single base register. Due to the way we 5908 // currently handle addresses it is the same as 'r'. 5909 case 'Q': 5910 return C_Memory; 5911 case 'I': 5912 case 'J': 5913 case 'K': 5914 case 'L': 5915 case 'M': 5916 case 'N': 5917 case 'Y': 5918 case 'Z': 5919 return C_Immediate; 5920 case 'z': 5921 case 'S': // A symbolic address 5922 return C_Other; 5923 } 5924 } else if (parsePredicateConstraint(Constraint) != 5925 PredicateConstraint::Invalid) 5926 return C_RegisterClass; 5927 return TargetLowering::getConstraintType(Constraint); 5928 } 5929 5930 /// Examine constraint type and operand type and determine a weight value. 5931 /// This object must already have been set up with the operand type 5932 /// and the current alternative constraint selected. 5933 TargetLowering::ConstraintWeight 5934 AArch64TargetLowering::getSingleConstraintMatchWeight( 5935 AsmOperandInfo &info, const char *constraint) const { 5936 ConstraintWeight weight = CW_Invalid; 5937 Value *CallOperandVal = info.CallOperandVal; 5938 // If we don't have a value, we can't do a match, 5939 // but allow it at the lowest weight. 5940 if (!CallOperandVal) 5941 return CW_Default; 5942 Type *type = CallOperandVal->getType(); 5943 // Look at the constraint type. 5944 switch (*constraint) { 5945 default: 5946 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 5947 break; 5948 case 'x': 5949 case 'w': 5950 case 'y': 5951 if (type->isFloatingPointTy() || type->isVectorTy()) 5952 weight = CW_Register; 5953 break; 5954 case 'z': 5955 weight = CW_Constant; 5956 break; 5957 case 'U': 5958 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 5959 weight = CW_Register; 5960 break; 5961 } 5962 return weight; 5963 } 5964 5965 std::pair<unsigned, const TargetRegisterClass *> 5966 AArch64TargetLowering::getRegForInlineAsmConstraint( 5967 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 5968 if (Constraint.size() == 1) { 5969 switch (Constraint[0]) { 5970 case 'r': 5971 if (VT.getSizeInBits() == 64) 5972 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 5973 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 5974 case 'w': 5975 if (!Subtarget->hasFPARMv8()) 5976 break; 5977 if (VT.isScalableVector()) 5978 return std::make_pair(0U, &AArch64::ZPRRegClass); 5979 if (VT.getSizeInBits() == 16) 5980 return std::make_pair(0U, &AArch64::FPR16RegClass); 5981 if (VT.getSizeInBits() == 32) 5982 return std::make_pair(0U, &AArch64::FPR32RegClass); 5983 if (VT.getSizeInBits() == 64) 5984 return std::make_pair(0U, &AArch64::FPR64RegClass); 5985 if (VT.getSizeInBits() == 128) 5986 return std::make_pair(0U, &AArch64::FPR128RegClass); 5987 break; 5988 // The instructions that this constraint is designed for can 5989 // only take 128-bit registers so just use that regclass. 5990 case 'x': 5991 if (!Subtarget->hasFPARMv8()) 5992 break; 5993 if (VT.isScalableVector()) 5994 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 5995 if (VT.getSizeInBits() == 128) 5996 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 5997 break; 5998 case 'y': 5999 if (!Subtarget->hasFPARMv8()) 6000 break; 6001 if (VT.isScalableVector()) 6002 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 6003 break; 6004 } 6005 } else { 6006 PredicateConstraint PC = parsePredicateConstraint(Constraint); 6007 if (PC != PredicateConstraint::Invalid) { 6008 assert(VT.isScalableVector()); 6009 bool restricted = (PC == PredicateConstraint::Upl); 6010 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 6011 : std::make_pair(0U, &AArch64::PPRRegClass); 6012 } 6013 } 6014 if (StringRef("{cc}").equals_lower(Constraint)) 6015 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 6016 6017 // Use the default implementation in TargetLowering to convert the register 6018 // constraint into a member of a register class. 6019 std::pair<unsigned, const TargetRegisterClass *> Res; 6020 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6021 6022 // Not found as a standard register? 6023 if (!Res.second) { 6024 unsigned Size = Constraint.size(); 6025 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 6026 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 6027 int RegNo; 6028 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 6029 if (!Failed && RegNo >= 0 && RegNo <= 31) { 6030 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 6031 // By default we'll emit v0-v31 for this unless there's a modifier where 6032 // we'll emit the correct register as well. 6033 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 6034 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 6035 Res.second = &AArch64::FPR64RegClass; 6036 } else { 6037 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 6038 Res.second = &AArch64::FPR128RegClass; 6039 } 6040 } 6041 } 6042 } 6043 6044 if (Res.second && !Subtarget->hasFPARMv8() && 6045 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 6046 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 6047 return std::make_pair(0U, nullptr); 6048 6049 return Res; 6050 } 6051 6052 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 6053 /// vector. If it is invalid, don't add anything to Ops. 6054 void AArch64TargetLowering::LowerAsmOperandForConstraint( 6055 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 6056 SelectionDAG &DAG) const { 6057 SDValue Result; 6058 6059 // Currently only support length 1 constraints. 6060 if (Constraint.length() != 1) 6061 return; 6062 6063 char ConstraintLetter = Constraint[0]; 6064 switch (ConstraintLetter) { 6065 default: 6066 break; 6067 6068 // This set of constraints deal with valid constants for various instructions. 6069 // Validate and return a target constant for them if we can. 6070 case 'z': { 6071 // 'z' maps to xzr or wzr so it needs an input of 0. 6072 if (!isNullConstant(Op)) 6073 return; 6074 6075 if (Op.getValueType() == MVT::i64) 6076 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 6077 else 6078 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 6079 break; 6080 } 6081 case 'S': { 6082 // An absolute symbolic address or label reference. 6083 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 6084 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 6085 GA->getValueType(0)); 6086 } else if (const BlockAddressSDNode *BA = 6087 dyn_cast<BlockAddressSDNode>(Op)) { 6088 Result = 6089 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 6090 } else if (const ExternalSymbolSDNode *ES = 6091 dyn_cast<ExternalSymbolSDNode>(Op)) { 6092 Result = 6093 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 6094 } else 6095 return; 6096 break; 6097 } 6098 6099 case 'I': 6100 case 'J': 6101 case 'K': 6102 case 'L': 6103 case 'M': 6104 case 'N': 6105 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 6106 if (!C) 6107 return; 6108 6109 // Grab the value and do some validation. 6110 uint64_t CVal = C->getZExtValue(); 6111 switch (ConstraintLetter) { 6112 // The I constraint applies only to simple ADD or SUB immediate operands: 6113 // i.e. 0 to 4095 with optional shift by 12 6114 // The J constraint applies only to ADD or SUB immediates that would be 6115 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 6116 // instruction [or vice versa], in other words -1 to -4095 with optional 6117 // left shift by 12. 6118 case 'I': 6119 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 6120 break; 6121 return; 6122 case 'J': { 6123 uint64_t NVal = -C->getSExtValue(); 6124 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 6125 CVal = C->getSExtValue(); 6126 break; 6127 } 6128 return; 6129 } 6130 // The K and L constraints apply *only* to logical immediates, including 6131 // what used to be the MOVI alias for ORR (though the MOVI alias has now 6132 // been removed and MOV should be used). So these constraints have to 6133 // distinguish between bit patterns that are valid 32-bit or 64-bit 6134 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 6135 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 6136 // versa. 6137 case 'K': 6138 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6139 break; 6140 return; 6141 case 'L': 6142 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6143 break; 6144 return; 6145 // The M and N constraints are a superset of K and L respectively, for use 6146 // with the MOV (immediate) alias. As well as the logical immediates they 6147 // also match 32 or 64-bit immediates that can be loaded either using a 6148 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 6149 // (M) or 64-bit 0x1234000000000000 (N) etc. 6150 // As a note some of this code is liberally stolen from the asm parser. 6151 case 'M': { 6152 if (!isUInt<32>(CVal)) 6153 return; 6154 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6155 break; 6156 if ((CVal & 0xFFFF) == CVal) 6157 break; 6158 if ((CVal & 0xFFFF0000ULL) == CVal) 6159 break; 6160 uint64_t NCVal = ~(uint32_t)CVal; 6161 if ((NCVal & 0xFFFFULL) == NCVal) 6162 break; 6163 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6164 break; 6165 return; 6166 } 6167 case 'N': { 6168 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6169 break; 6170 if ((CVal & 0xFFFFULL) == CVal) 6171 break; 6172 if ((CVal & 0xFFFF0000ULL) == CVal) 6173 break; 6174 if ((CVal & 0xFFFF00000000ULL) == CVal) 6175 break; 6176 if ((CVal & 0xFFFF000000000000ULL) == CVal) 6177 break; 6178 uint64_t NCVal = ~CVal; 6179 if ((NCVal & 0xFFFFULL) == NCVal) 6180 break; 6181 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6182 break; 6183 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 6184 break; 6185 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 6186 break; 6187 return; 6188 } 6189 default: 6190 return; 6191 } 6192 6193 // All assembler immediates are 64-bit integers. 6194 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 6195 break; 6196 } 6197 6198 if (Result.getNode()) { 6199 Ops.push_back(Result); 6200 return; 6201 } 6202 6203 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 6204 } 6205 6206 //===----------------------------------------------------------------------===// 6207 // AArch64 Advanced SIMD Support 6208 //===----------------------------------------------------------------------===// 6209 6210 /// WidenVector - Given a value in the V64 register class, produce the 6211 /// equivalent value in the V128 register class. 6212 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 6213 EVT VT = V64Reg.getValueType(); 6214 unsigned NarrowSize = VT.getVectorNumElements(); 6215 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6216 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 6217 SDLoc DL(V64Reg); 6218 6219 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 6220 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 6221 } 6222 6223 /// getExtFactor - Determine the adjustment factor for the position when 6224 /// generating an "extract from vector registers" instruction. 6225 static unsigned getExtFactor(SDValue &V) { 6226 EVT EltType = V.getValueType().getVectorElementType(); 6227 return EltType.getSizeInBits() / 8; 6228 } 6229 6230 /// NarrowVector - Given a value in the V128 register class, produce the 6231 /// equivalent value in the V64 register class. 6232 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 6233 EVT VT = V128Reg.getValueType(); 6234 unsigned WideSize = VT.getVectorNumElements(); 6235 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6236 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 6237 SDLoc DL(V128Reg); 6238 6239 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 6240 } 6241 6242 // Gather data to see if the operation can be modelled as a 6243 // shuffle in combination with VEXTs. 6244 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 6245 SelectionDAG &DAG) const { 6246 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6247 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 6248 SDLoc dl(Op); 6249 EVT VT = Op.getValueType(); 6250 unsigned NumElts = VT.getVectorNumElements(); 6251 6252 struct ShuffleSourceInfo { 6253 SDValue Vec; 6254 unsigned MinElt; 6255 unsigned MaxElt; 6256 6257 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6258 // be compatible with the shuffle we intend to construct. As a result 6259 // ShuffleVec will be some sliding window into the original Vec. 6260 SDValue ShuffleVec; 6261 6262 // Code should guarantee that element i in Vec starts at element "WindowBase 6263 // + i * WindowScale in ShuffleVec". 6264 int WindowBase; 6265 int WindowScale; 6266 6267 ShuffleSourceInfo(SDValue Vec) 6268 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 6269 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 6270 6271 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6272 }; 6273 6274 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6275 // node. 6276 SmallVector<ShuffleSourceInfo, 2> Sources; 6277 for (unsigned i = 0; i < NumElts; ++i) { 6278 SDValue V = Op.getOperand(i); 6279 if (V.isUndef()) 6280 continue; 6281 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6282 !isa<ConstantSDNode>(V.getOperand(1))) { 6283 LLVM_DEBUG( 6284 dbgs() << "Reshuffle failed: " 6285 "a shuffle can only come from building a vector from " 6286 "various elements of other vectors, provided their " 6287 "indices are constant\n"); 6288 return SDValue(); 6289 } 6290 6291 // Add this element source to the list if it's not already there. 6292 SDValue SourceVec = V.getOperand(0); 6293 auto Source = find(Sources, SourceVec); 6294 if (Source == Sources.end()) 6295 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6296 6297 // Update the minimum and maximum lane number seen. 6298 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6299 Source->MinElt = std::min(Source->MinElt, EltNo); 6300 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6301 } 6302 6303 if (Sources.size() > 2) { 6304 LLVM_DEBUG( 6305 dbgs() << "Reshuffle failed: currently only do something sane when at " 6306 "most two source vectors are involved\n"); 6307 return SDValue(); 6308 } 6309 6310 // Find out the smallest element size among result and two sources, and use 6311 // it as element size to build the shuffle_vector. 6312 EVT SmallestEltTy = VT.getVectorElementType(); 6313 for (auto &Source : Sources) { 6314 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6315 if (SrcEltTy.bitsLT(SmallestEltTy)) { 6316 SmallestEltTy = SrcEltTy; 6317 } 6318 } 6319 unsigned ResMultiplier = 6320 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6321 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6322 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6323 6324 // If the source vector is too wide or too narrow, we may nevertheless be able 6325 // to construct a compatible shuffle either by concatenating it with UNDEF or 6326 // extracting a suitable range of elements. 6327 for (auto &Src : Sources) { 6328 EVT SrcVT = Src.ShuffleVec.getValueType(); 6329 6330 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6331 continue; 6332 6333 // This stage of the search produces a source with the same element type as 6334 // the original, but with a total width matching the BUILD_VECTOR output. 6335 EVT EltVT = SrcVT.getVectorElementType(); 6336 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6337 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6338 6339 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6340 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 6341 // We can pad out the smaller vector for free, so if it's part of a 6342 // shuffle... 6343 Src.ShuffleVec = 6344 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6345 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6346 continue; 6347 } 6348 6349 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 6350 6351 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6352 LLVM_DEBUG( 6353 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 6354 return SDValue(); 6355 } 6356 6357 if (Src.MinElt >= NumSrcElts) { 6358 // The extraction can just take the second half 6359 Src.ShuffleVec = 6360 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6361 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6362 Src.WindowBase = -NumSrcElts; 6363 } else if (Src.MaxElt < NumSrcElts) { 6364 // The extraction can just take the first half 6365 Src.ShuffleVec = 6366 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6367 DAG.getConstant(0, dl, MVT::i64)); 6368 } else { 6369 // An actual VEXT is needed 6370 SDValue VEXTSrc1 = 6371 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6372 DAG.getConstant(0, dl, MVT::i64)); 6373 SDValue VEXTSrc2 = 6374 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6375 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6376 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 6377 6378 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 6379 VEXTSrc2, 6380 DAG.getConstant(Imm, dl, MVT::i32)); 6381 Src.WindowBase = -Src.MinElt; 6382 } 6383 } 6384 6385 // Another possible incompatibility occurs from the vector element types. We 6386 // can fix this by bitcasting the source vectors to the same type we intend 6387 // for the shuffle. 6388 for (auto &Src : Sources) { 6389 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6390 if (SrcEltTy == SmallestEltTy) 6391 continue; 6392 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6393 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6394 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6395 Src.WindowBase *= Src.WindowScale; 6396 } 6397 6398 // Final sanity check before we try to actually produce a shuffle. 6399 LLVM_DEBUG(for (auto Src 6400 : Sources) 6401 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6402 6403 // The stars all align, our next step is to produce the mask for the shuffle. 6404 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6405 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6406 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6407 SDValue Entry = Op.getOperand(i); 6408 if (Entry.isUndef()) 6409 continue; 6410 6411 auto Src = find(Sources, Entry.getOperand(0)); 6412 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6413 6414 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6415 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6416 // segment. 6417 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6418 int BitsDefined = 6419 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 6420 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6421 6422 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6423 // starting at the appropriate offset. 6424 int *LaneMask = &Mask[i * ResMultiplier]; 6425 6426 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6427 ExtractBase += NumElts * (Src - Sources.begin()); 6428 for (int j = 0; j < LanesDefined; ++j) 6429 LaneMask[j] = ExtractBase + j; 6430 } 6431 6432 // Final check before we try to produce nonsense... 6433 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 6434 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 6435 return SDValue(); 6436 } 6437 6438 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6439 for (unsigned i = 0; i < Sources.size(); ++i) 6440 ShuffleOps[i] = Sources[i].ShuffleVec; 6441 6442 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6443 ShuffleOps[1], Mask); 6444 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6445 6446 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 6447 dbgs() << "Reshuffle, creating node: "; V.dump();); 6448 6449 return V; 6450 } 6451 6452 // check if an EXT instruction can handle the shuffle mask when the 6453 // vector sources of the shuffle are the same. 6454 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6455 unsigned NumElts = VT.getVectorNumElements(); 6456 6457 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6458 if (M[0] < 0) 6459 return false; 6460 6461 Imm = M[0]; 6462 6463 // If this is a VEXT shuffle, the immediate value is the index of the first 6464 // element. The other shuffle indices must be the successive elements after 6465 // the first one. 6466 unsigned ExpectedElt = Imm; 6467 for (unsigned i = 1; i < NumElts; ++i) { 6468 // Increment the expected index. If it wraps around, just follow it 6469 // back to index zero and keep going. 6470 ++ExpectedElt; 6471 if (ExpectedElt == NumElts) 6472 ExpectedElt = 0; 6473 6474 if (M[i] < 0) 6475 continue; // ignore UNDEF indices 6476 if (ExpectedElt != static_cast<unsigned>(M[i])) 6477 return false; 6478 } 6479 6480 return true; 6481 } 6482 6483 // check if an EXT instruction can handle the shuffle mask when the 6484 // vector sources of the shuffle are different. 6485 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 6486 unsigned &Imm) { 6487 // Look for the first non-undef element. 6488 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 6489 6490 // Benefit form APInt to handle overflow when calculating expected element. 6491 unsigned NumElts = VT.getVectorNumElements(); 6492 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 6493 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 6494 // The following shuffle indices must be the successive elements after the 6495 // first real element. 6496 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 6497 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 6498 if (FirstWrongElt != M.end()) 6499 return false; 6500 6501 // The index of an EXT is the first element if it is not UNDEF. 6502 // Watch out for the beginning UNDEFs. The EXT index should be the expected 6503 // value of the first element. E.g. 6504 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 6505 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 6506 // ExpectedElt is the last mask index plus 1. 6507 Imm = ExpectedElt.getZExtValue(); 6508 6509 // There are two difference cases requiring to reverse input vectors. 6510 // For example, for vector <4 x i32> we have the following cases, 6511 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 6512 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 6513 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 6514 // to reverse two input vectors. 6515 if (Imm < NumElts) 6516 ReverseEXT = true; 6517 else 6518 Imm -= NumElts; 6519 6520 return true; 6521 } 6522 6523 /// isREVMask - Check if a vector shuffle corresponds to a REV 6524 /// instruction with the specified blocksize. (The order of the elements 6525 /// within each block of the vector is reversed.) 6526 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6527 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 6528 "Only possible block sizes for REV are: 16, 32, 64"); 6529 6530 unsigned EltSz = VT.getScalarSizeInBits(); 6531 if (EltSz == 64) 6532 return false; 6533 6534 unsigned NumElts = VT.getVectorNumElements(); 6535 unsigned BlockElts = M[0] + 1; 6536 // If the first shuffle index is UNDEF, be optimistic. 6537 if (M[0] < 0) 6538 BlockElts = BlockSize / EltSz; 6539 6540 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6541 return false; 6542 6543 for (unsigned i = 0; i < NumElts; ++i) { 6544 if (M[i] < 0) 6545 continue; // ignore UNDEF indices 6546 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 6547 return false; 6548 } 6549 6550 return true; 6551 } 6552 6553 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6554 unsigned NumElts = VT.getVectorNumElements(); 6555 if (NumElts % 2 != 0) 6556 return false; 6557 WhichResult = (M[0] == 0 ? 0 : 1); 6558 unsigned Idx = WhichResult * NumElts / 2; 6559 for (unsigned i = 0; i != NumElts; i += 2) { 6560 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6561 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 6562 return false; 6563 Idx += 1; 6564 } 6565 6566 return true; 6567 } 6568 6569 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6570 unsigned NumElts = VT.getVectorNumElements(); 6571 WhichResult = (M[0] == 0 ? 0 : 1); 6572 for (unsigned i = 0; i != NumElts; ++i) { 6573 if (M[i] < 0) 6574 continue; // ignore UNDEF indices 6575 if ((unsigned)M[i] != 2 * i + WhichResult) 6576 return false; 6577 } 6578 6579 return true; 6580 } 6581 6582 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6583 unsigned NumElts = VT.getVectorNumElements(); 6584 if (NumElts % 2 != 0) 6585 return false; 6586 WhichResult = (M[0] == 0 ? 0 : 1); 6587 for (unsigned i = 0; i < NumElts; i += 2) { 6588 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 6589 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 6590 return false; 6591 } 6592 return true; 6593 } 6594 6595 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 6596 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6597 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6598 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6599 unsigned NumElts = VT.getVectorNumElements(); 6600 if (NumElts % 2 != 0) 6601 return false; 6602 WhichResult = (M[0] == 0 ? 0 : 1); 6603 unsigned Idx = WhichResult * NumElts / 2; 6604 for (unsigned i = 0; i != NumElts; i += 2) { 6605 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6606 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 6607 return false; 6608 Idx += 1; 6609 } 6610 6611 return true; 6612 } 6613 6614 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 6615 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6616 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6617 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6618 unsigned Half = VT.getVectorNumElements() / 2; 6619 WhichResult = (M[0] == 0 ? 0 : 1); 6620 for (unsigned j = 0; j != 2; ++j) { 6621 unsigned Idx = WhichResult; 6622 for (unsigned i = 0; i != Half; ++i) { 6623 int MIdx = M[i + j * Half]; 6624 if (MIdx >= 0 && (unsigned)MIdx != Idx) 6625 return false; 6626 Idx += 2; 6627 } 6628 } 6629 6630 return true; 6631 } 6632 6633 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 6634 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6635 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6636 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6637 unsigned NumElts = VT.getVectorNumElements(); 6638 if (NumElts % 2 != 0) 6639 return false; 6640 WhichResult = (M[0] == 0 ? 0 : 1); 6641 for (unsigned i = 0; i < NumElts; i += 2) { 6642 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 6643 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 6644 return false; 6645 } 6646 return true; 6647 } 6648 6649 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 6650 bool &DstIsLeft, int &Anomaly) { 6651 if (M.size() != static_cast<size_t>(NumInputElements)) 6652 return false; 6653 6654 int NumLHSMatch = 0, NumRHSMatch = 0; 6655 int LastLHSMismatch = -1, LastRHSMismatch = -1; 6656 6657 for (int i = 0; i < NumInputElements; ++i) { 6658 if (M[i] == -1) { 6659 ++NumLHSMatch; 6660 ++NumRHSMatch; 6661 continue; 6662 } 6663 6664 if (M[i] == i) 6665 ++NumLHSMatch; 6666 else 6667 LastLHSMismatch = i; 6668 6669 if (M[i] == i + NumInputElements) 6670 ++NumRHSMatch; 6671 else 6672 LastRHSMismatch = i; 6673 } 6674 6675 if (NumLHSMatch == NumInputElements - 1) { 6676 DstIsLeft = true; 6677 Anomaly = LastLHSMismatch; 6678 return true; 6679 } else if (NumRHSMatch == NumInputElements - 1) { 6680 DstIsLeft = false; 6681 Anomaly = LastRHSMismatch; 6682 return true; 6683 } 6684 6685 return false; 6686 } 6687 6688 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 6689 if (VT.getSizeInBits() != 128) 6690 return false; 6691 6692 unsigned NumElts = VT.getVectorNumElements(); 6693 6694 for (int I = 0, E = NumElts / 2; I != E; I++) { 6695 if (Mask[I] != I) 6696 return false; 6697 } 6698 6699 int Offset = NumElts / 2; 6700 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 6701 if (Mask[I] != I + SplitLHS * Offset) 6702 return false; 6703 } 6704 6705 return true; 6706 } 6707 6708 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 6709 SDLoc DL(Op); 6710 EVT VT = Op.getValueType(); 6711 SDValue V0 = Op.getOperand(0); 6712 SDValue V1 = Op.getOperand(1); 6713 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 6714 6715 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 6716 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 6717 return SDValue(); 6718 6719 bool SplitV0 = V0.getValueSizeInBits() == 128; 6720 6721 if (!isConcatMask(Mask, VT, SplitV0)) 6722 return SDValue(); 6723 6724 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 6725 if (SplitV0) { 6726 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 6727 DAG.getConstant(0, DL, MVT::i64)); 6728 } 6729 if (V1.getValueSizeInBits() == 128) { 6730 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 6731 DAG.getConstant(0, DL, MVT::i64)); 6732 } 6733 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 6734 } 6735 6736 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6737 /// the specified operations to build the shuffle. 6738 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6739 SDValue RHS, SelectionDAG &DAG, 6740 const SDLoc &dl) { 6741 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6742 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 6743 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 6744 6745 enum { 6746 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6747 OP_VREV, 6748 OP_VDUP0, 6749 OP_VDUP1, 6750 OP_VDUP2, 6751 OP_VDUP3, 6752 OP_VEXT1, 6753 OP_VEXT2, 6754 OP_VEXT3, 6755 OP_VUZPL, // VUZP, left result 6756 OP_VUZPR, // VUZP, right result 6757 OP_VZIPL, // VZIP, left result 6758 OP_VZIPR, // VZIP, right result 6759 OP_VTRNL, // VTRN, left result 6760 OP_VTRNR // VTRN, right result 6761 }; 6762 6763 if (OpNum == OP_COPY) { 6764 if (LHSID == (1 * 9 + 2) * 9 + 3) 6765 return LHS; 6766 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 6767 return RHS; 6768 } 6769 6770 SDValue OpLHS, OpRHS; 6771 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6772 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6773 EVT VT = OpLHS.getValueType(); 6774 6775 switch (OpNum) { 6776 default: 6777 llvm_unreachable("Unknown shuffle opcode!"); 6778 case OP_VREV: 6779 // VREV divides the vector in half and swaps within the half. 6780 if (VT.getVectorElementType() == MVT::i32 || 6781 VT.getVectorElementType() == MVT::f32) 6782 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 6783 // vrev <4 x i16> -> REV32 6784 if (VT.getVectorElementType() == MVT::i16 || 6785 VT.getVectorElementType() == MVT::f16) 6786 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 6787 // vrev <4 x i8> -> REV16 6788 assert(VT.getVectorElementType() == MVT::i8); 6789 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 6790 case OP_VDUP0: 6791 case OP_VDUP1: 6792 case OP_VDUP2: 6793 case OP_VDUP3: { 6794 EVT EltTy = VT.getVectorElementType(); 6795 unsigned Opcode; 6796 if (EltTy == MVT::i8) 6797 Opcode = AArch64ISD::DUPLANE8; 6798 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 6799 Opcode = AArch64ISD::DUPLANE16; 6800 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 6801 Opcode = AArch64ISD::DUPLANE32; 6802 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 6803 Opcode = AArch64ISD::DUPLANE64; 6804 else 6805 llvm_unreachable("Invalid vector element type?"); 6806 6807 if (VT.getSizeInBits() == 64) 6808 OpLHS = WidenVector(OpLHS, DAG); 6809 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 6810 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 6811 } 6812 case OP_VEXT1: 6813 case OP_VEXT2: 6814 case OP_VEXT3: { 6815 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 6816 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 6817 DAG.getConstant(Imm, dl, MVT::i32)); 6818 } 6819 case OP_VUZPL: 6820 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 6821 OpRHS); 6822 case OP_VUZPR: 6823 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 6824 OpRHS); 6825 case OP_VZIPL: 6826 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 6827 OpRHS); 6828 case OP_VZIPR: 6829 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 6830 OpRHS); 6831 case OP_VTRNL: 6832 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 6833 OpRHS); 6834 case OP_VTRNR: 6835 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 6836 OpRHS); 6837 } 6838 } 6839 6840 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 6841 SelectionDAG &DAG) { 6842 // Check to see if we can use the TBL instruction. 6843 SDValue V1 = Op.getOperand(0); 6844 SDValue V2 = Op.getOperand(1); 6845 SDLoc DL(Op); 6846 6847 EVT EltVT = Op.getValueType().getVectorElementType(); 6848 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 6849 6850 SmallVector<SDValue, 8> TBLMask; 6851 for (int Val : ShuffleMask) { 6852 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 6853 unsigned Offset = Byte + Val * BytesPerElt; 6854 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 6855 } 6856 } 6857 6858 MVT IndexVT = MVT::v8i8; 6859 unsigned IndexLen = 8; 6860 if (Op.getValueSizeInBits() == 128) { 6861 IndexVT = MVT::v16i8; 6862 IndexLen = 16; 6863 } 6864 6865 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 6866 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 6867 6868 SDValue Shuffle; 6869 if (V2.getNode()->isUndef()) { 6870 if (IndexLen == 8) 6871 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 6872 Shuffle = DAG.getNode( 6873 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6874 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 6875 DAG.getBuildVector(IndexVT, DL, 6876 makeArrayRef(TBLMask.data(), IndexLen))); 6877 } else { 6878 if (IndexLen == 8) { 6879 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 6880 Shuffle = DAG.getNode( 6881 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6882 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 6883 DAG.getBuildVector(IndexVT, DL, 6884 makeArrayRef(TBLMask.data(), IndexLen))); 6885 } else { 6886 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 6887 // cannot currently represent the register constraints on the input 6888 // table registers. 6889 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 6890 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 6891 // IndexLen)); 6892 Shuffle = DAG.getNode( 6893 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6894 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 6895 V2Cst, DAG.getBuildVector(IndexVT, DL, 6896 makeArrayRef(TBLMask.data(), IndexLen))); 6897 } 6898 } 6899 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 6900 } 6901 6902 static unsigned getDUPLANEOp(EVT EltType) { 6903 if (EltType == MVT::i8) 6904 return AArch64ISD::DUPLANE8; 6905 if (EltType == MVT::i16 || EltType == MVT::f16) 6906 return AArch64ISD::DUPLANE16; 6907 if (EltType == MVT::i32 || EltType == MVT::f32) 6908 return AArch64ISD::DUPLANE32; 6909 if (EltType == MVT::i64 || EltType == MVT::f64) 6910 return AArch64ISD::DUPLANE64; 6911 6912 llvm_unreachable("Invalid vector element type?"); 6913 } 6914 6915 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 6916 SelectionDAG &DAG) const { 6917 SDLoc dl(Op); 6918 EVT VT = Op.getValueType(); 6919 6920 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6921 6922 // Convert shuffles that are directly supported on NEON to target-specific 6923 // DAG nodes, instead of keeping them as shuffles and matching them again 6924 // during code selection. This is more efficient and avoids the possibility 6925 // of inconsistencies between legalization and selection. 6926 ArrayRef<int> ShuffleMask = SVN->getMask(); 6927 6928 SDValue V1 = Op.getOperand(0); 6929 SDValue V2 = Op.getOperand(1); 6930 6931 if (SVN->isSplat()) { 6932 int Lane = SVN->getSplatIndex(); 6933 // If this is undef splat, generate it via "just" vdup, if possible. 6934 if (Lane == -1) 6935 Lane = 0; 6936 6937 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 6938 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 6939 V1.getOperand(0)); 6940 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 6941 // constant. If so, we can just reference the lane's definition directly. 6942 if (V1.getOpcode() == ISD::BUILD_VECTOR && 6943 !isa<ConstantSDNode>(V1.getOperand(Lane))) 6944 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 6945 6946 // Otherwise, duplicate from the lane of the input vector. 6947 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 6948 6949 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 6950 // to make a vector of the same size as this SHUFFLE. We can ignore the 6951 // extract entirely, and canonicalise the concat using WidenVector. 6952 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 6953 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 6954 V1 = V1.getOperand(0); 6955 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 6956 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 6957 Lane -= Idx * VT.getVectorNumElements() / 2; 6958 V1 = WidenVector(V1.getOperand(Idx), DAG); 6959 } else if (VT.getSizeInBits() == 64) 6960 V1 = WidenVector(V1, DAG); 6961 6962 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 6963 } 6964 6965 if (isREVMask(ShuffleMask, VT, 64)) 6966 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 6967 if (isREVMask(ShuffleMask, VT, 32)) 6968 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 6969 if (isREVMask(ShuffleMask, VT, 16)) 6970 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 6971 6972 bool ReverseEXT = false; 6973 unsigned Imm; 6974 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 6975 if (ReverseEXT) 6976 std::swap(V1, V2); 6977 Imm *= getExtFactor(V1); 6978 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 6979 DAG.getConstant(Imm, dl, MVT::i32)); 6980 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 6981 Imm *= getExtFactor(V1); 6982 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 6983 DAG.getConstant(Imm, dl, MVT::i32)); 6984 } 6985 6986 unsigned WhichResult; 6987 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 6988 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6989 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6990 } 6991 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 6992 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6993 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6994 } 6995 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 6996 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6997 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6998 } 6999 7000 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7001 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7002 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7003 } 7004 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7005 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7006 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7007 } 7008 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7009 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7010 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7011 } 7012 7013 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 7014 return Concat; 7015 7016 bool DstIsLeft; 7017 int Anomaly; 7018 int NumInputElements = V1.getValueType().getVectorNumElements(); 7019 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 7020 SDValue DstVec = DstIsLeft ? V1 : V2; 7021 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 7022 7023 SDValue SrcVec = V1; 7024 int SrcLane = ShuffleMask[Anomaly]; 7025 if (SrcLane >= NumInputElements) { 7026 SrcVec = V2; 7027 SrcLane -= VT.getVectorNumElements(); 7028 } 7029 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 7030 7031 EVT ScalarVT = VT.getVectorElementType(); 7032 7033 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 7034 ScalarVT = MVT::i32; 7035 7036 return DAG.getNode( 7037 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 7038 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 7039 DstLaneV); 7040 } 7041 7042 // If the shuffle is not directly supported and it has 4 elements, use 7043 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7044 unsigned NumElts = VT.getVectorNumElements(); 7045 if (NumElts == 4) { 7046 unsigned PFIndexes[4]; 7047 for (unsigned i = 0; i != 4; ++i) { 7048 if (ShuffleMask[i] < 0) 7049 PFIndexes[i] = 8; 7050 else 7051 PFIndexes[i] = ShuffleMask[i]; 7052 } 7053 7054 // Compute the index in the perfect shuffle table. 7055 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7056 PFIndexes[2] * 9 + PFIndexes[3]; 7057 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7058 unsigned Cost = (PFEntry >> 30); 7059 7060 if (Cost <= 4) 7061 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7062 } 7063 7064 return GenerateTBL(Op, ShuffleMask, DAG); 7065 } 7066 7067 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 7068 SelectionDAG &DAG) const { 7069 SDLoc dl(Op); 7070 EVT VT = Op.getValueType(); 7071 EVT ElemVT = VT.getScalarType(); 7072 7073 SDValue SplatVal = Op.getOperand(0); 7074 7075 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 7076 // FPRs don't have this restriction. 7077 switch (ElemVT.getSimpleVT().SimpleTy) { 7078 case MVT::i8: 7079 case MVT::i16: 7080 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 7081 break; 7082 case MVT::i64: 7083 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7084 break; 7085 case MVT::i32: 7086 // Fine as is 7087 break; 7088 // TODO: we can support splats of i1s and float types, but haven't added 7089 // patterns yet. 7090 case MVT::i1: 7091 case MVT::f16: 7092 case MVT::f32: 7093 case MVT::f64: 7094 default: 7095 llvm_unreachable("Unsupported SPLAT_VECTOR input operand type"); 7096 break; 7097 } 7098 7099 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 7100 } 7101 7102 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 7103 APInt &UndefBits) { 7104 EVT VT = BVN->getValueType(0); 7105 APInt SplatBits, SplatUndef; 7106 unsigned SplatBitSize; 7107 bool HasAnyUndefs; 7108 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7109 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 7110 7111 for (unsigned i = 0; i < NumSplats; ++i) { 7112 CnstBits <<= SplatBitSize; 7113 UndefBits <<= SplatBitSize; 7114 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 7115 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 7116 } 7117 7118 return true; 7119 } 7120 7121 return false; 7122 } 7123 7124 // Try 64-bit splatted SIMD immediate. 7125 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7126 const APInt &Bits) { 7127 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7128 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7129 EVT VT = Op.getValueType(); 7130 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 7131 7132 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 7133 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 7134 7135 SDLoc dl(Op); 7136 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7137 DAG.getConstant(Value, dl, MVT::i32)); 7138 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7139 } 7140 } 7141 7142 return SDValue(); 7143 } 7144 7145 // Try 32-bit splatted SIMD immediate. 7146 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7147 const APInt &Bits, 7148 const SDValue *LHS = nullptr) { 7149 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7150 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7151 EVT VT = Op.getValueType(); 7152 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7153 bool isAdvSIMDModImm = false; 7154 uint64_t Shift; 7155 7156 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 7157 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 7158 Shift = 0; 7159 } 7160 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 7161 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 7162 Shift = 8; 7163 } 7164 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 7165 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 7166 Shift = 16; 7167 } 7168 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 7169 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 7170 Shift = 24; 7171 } 7172 7173 if (isAdvSIMDModImm) { 7174 SDLoc dl(Op); 7175 SDValue Mov; 7176 7177 if (LHS) 7178 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7179 DAG.getConstant(Value, dl, MVT::i32), 7180 DAG.getConstant(Shift, dl, MVT::i32)); 7181 else 7182 Mov = DAG.getNode(NewOp, dl, MovTy, 7183 DAG.getConstant(Value, dl, MVT::i32), 7184 DAG.getConstant(Shift, dl, MVT::i32)); 7185 7186 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7187 } 7188 } 7189 7190 return SDValue(); 7191 } 7192 7193 // Try 16-bit splatted SIMD immediate. 7194 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7195 const APInt &Bits, 7196 const SDValue *LHS = nullptr) { 7197 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7198 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7199 EVT VT = Op.getValueType(); 7200 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 7201 bool isAdvSIMDModImm = false; 7202 uint64_t Shift; 7203 7204 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 7205 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 7206 Shift = 0; 7207 } 7208 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 7209 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 7210 Shift = 8; 7211 } 7212 7213 if (isAdvSIMDModImm) { 7214 SDLoc dl(Op); 7215 SDValue Mov; 7216 7217 if (LHS) 7218 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7219 DAG.getConstant(Value, dl, MVT::i32), 7220 DAG.getConstant(Shift, dl, MVT::i32)); 7221 else 7222 Mov = DAG.getNode(NewOp, dl, MovTy, 7223 DAG.getConstant(Value, dl, MVT::i32), 7224 DAG.getConstant(Shift, dl, MVT::i32)); 7225 7226 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7227 } 7228 } 7229 7230 return SDValue(); 7231 } 7232 7233 // Try 32-bit splatted SIMD immediate with shifted ones. 7234 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 7235 SelectionDAG &DAG, const APInt &Bits) { 7236 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7237 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7238 EVT VT = Op.getValueType(); 7239 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7240 bool isAdvSIMDModImm = false; 7241 uint64_t Shift; 7242 7243 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 7244 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 7245 Shift = 264; 7246 } 7247 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 7248 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 7249 Shift = 272; 7250 } 7251 7252 if (isAdvSIMDModImm) { 7253 SDLoc dl(Op); 7254 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7255 DAG.getConstant(Value, dl, MVT::i32), 7256 DAG.getConstant(Shift, dl, MVT::i32)); 7257 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7258 } 7259 } 7260 7261 return SDValue(); 7262 } 7263 7264 // Try 8-bit splatted SIMD immediate. 7265 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7266 const APInt &Bits) { 7267 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7268 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7269 EVT VT = Op.getValueType(); 7270 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 7271 7272 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 7273 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 7274 7275 SDLoc dl(Op); 7276 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7277 DAG.getConstant(Value, dl, MVT::i32)); 7278 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7279 } 7280 } 7281 7282 return SDValue(); 7283 } 7284 7285 // Try FP splatted SIMD immediate. 7286 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7287 const APInt &Bits) { 7288 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7289 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7290 EVT VT = Op.getValueType(); 7291 bool isWide = (VT.getSizeInBits() == 128); 7292 MVT MovTy; 7293 bool isAdvSIMDModImm = false; 7294 7295 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 7296 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 7297 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 7298 } 7299 else if (isWide && 7300 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 7301 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 7302 MovTy = MVT::v2f64; 7303 } 7304 7305 if (isAdvSIMDModImm) { 7306 SDLoc dl(Op); 7307 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7308 DAG.getConstant(Value, dl, MVT::i32)); 7309 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7310 } 7311 } 7312 7313 return SDValue(); 7314 } 7315 7316 // Specialized code to quickly find if PotentialBVec is a BuildVector that 7317 // consists of only the same constant int value, returned in reference arg 7318 // ConstVal 7319 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 7320 uint64_t &ConstVal) { 7321 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 7322 if (!Bvec) 7323 return false; 7324 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 7325 if (!FirstElt) 7326 return false; 7327 EVT VT = Bvec->getValueType(0); 7328 unsigned NumElts = VT.getVectorNumElements(); 7329 for (unsigned i = 1; i < NumElts; ++i) 7330 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 7331 return false; 7332 ConstVal = FirstElt->getZExtValue(); 7333 return true; 7334 } 7335 7336 static unsigned getIntrinsicID(const SDNode *N) { 7337 unsigned Opcode = N->getOpcode(); 7338 switch (Opcode) { 7339 default: 7340 return Intrinsic::not_intrinsic; 7341 case ISD::INTRINSIC_WO_CHAIN: { 7342 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7343 if (IID < Intrinsic::num_intrinsics) 7344 return IID; 7345 return Intrinsic::not_intrinsic; 7346 } 7347 } 7348 } 7349 7350 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 7351 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 7352 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 7353 // Also, logical shift right -> sri, with the same structure. 7354 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 7355 EVT VT = N->getValueType(0); 7356 7357 if (!VT.isVector()) 7358 return SDValue(); 7359 7360 SDLoc DL(N); 7361 7362 // Is the first op an AND? 7363 const SDValue And = N->getOperand(0); 7364 if (And.getOpcode() != ISD::AND) 7365 return SDValue(); 7366 7367 // Is the second op an shl or lshr? 7368 SDValue Shift = N->getOperand(1); 7369 // This will have been turned into: AArch64ISD::VSHL vector, #shift 7370 // or AArch64ISD::VLSHR vector, #shift 7371 unsigned ShiftOpc = Shift.getOpcode(); 7372 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 7373 return SDValue(); 7374 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 7375 7376 // Is the shift amount constant? 7377 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7378 if (!C2node) 7379 return SDValue(); 7380 7381 // Is the and mask vector all constant? 7382 uint64_t C1; 7383 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 7384 return SDValue(); 7385 7386 // Is C1 == ~C2, taking into account how much one can shift elements of a 7387 // particular size? 7388 uint64_t C2 = C2node->getZExtValue(); 7389 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 7390 if (C2 > ElemSizeInBits) 7391 return SDValue(); 7392 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 7393 if ((C1 & ElemMask) != (~C2 & ElemMask)) 7394 return SDValue(); 7395 7396 SDValue X = And.getOperand(0); 7397 SDValue Y = Shift.getOperand(0); 7398 7399 unsigned Intrin = 7400 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 7401 SDValue ResultSLI = 7402 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7403 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 7404 Shift.getOperand(1)); 7405 7406 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 7407 LLVM_DEBUG(N->dump(&DAG)); 7408 LLVM_DEBUG(dbgs() << "into: \n"); 7409 LLVM_DEBUG(ResultSLI->dump(&DAG)); 7410 7411 ++NumShiftInserts; 7412 return ResultSLI; 7413 } 7414 7415 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 7416 SelectionDAG &DAG) const { 7417 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 7418 if (EnableAArch64SlrGeneration) { 7419 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 7420 return Res; 7421 } 7422 7423 EVT VT = Op.getValueType(); 7424 7425 SDValue LHS = Op.getOperand(0); 7426 BuildVectorSDNode *BVN = 7427 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 7428 if (!BVN) { 7429 // OR commutes, so try swapping the operands. 7430 LHS = Op.getOperand(1); 7431 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 7432 } 7433 if (!BVN) 7434 return Op; 7435 7436 APInt DefBits(VT.getSizeInBits(), 0); 7437 APInt UndefBits(VT.getSizeInBits(), 0); 7438 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7439 SDValue NewOp; 7440 7441 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7442 DefBits, &LHS)) || 7443 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7444 DefBits, &LHS))) 7445 return NewOp; 7446 7447 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7448 UndefBits, &LHS)) || 7449 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7450 UndefBits, &LHS))) 7451 return NewOp; 7452 } 7453 7454 // We can always fall back to a non-immediate OR. 7455 return Op; 7456 } 7457 7458 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 7459 // be truncated to fit element width. 7460 static SDValue NormalizeBuildVector(SDValue Op, 7461 SelectionDAG &DAG) { 7462 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7463 SDLoc dl(Op); 7464 EVT VT = Op.getValueType(); 7465 EVT EltTy= VT.getVectorElementType(); 7466 7467 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 7468 return Op; 7469 7470 SmallVector<SDValue, 16> Ops; 7471 for (SDValue Lane : Op->ops()) { 7472 // For integer vectors, type legalization would have promoted the 7473 // operands already. Otherwise, if Op is a floating-point splat 7474 // (with operands cast to integers), then the only possibilities 7475 // are constants and UNDEFs. 7476 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 7477 APInt LowBits(EltTy.getSizeInBits(), 7478 CstLane->getZExtValue()); 7479 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 7480 } else if (Lane.getNode()->isUndef()) { 7481 Lane = DAG.getUNDEF(MVT::i32); 7482 } else { 7483 assert(Lane.getValueType() == MVT::i32 && 7484 "Unexpected BUILD_VECTOR operand type"); 7485 } 7486 Ops.push_back(Lane); 7487 } 7488 return DAG.getBuildVector(VT, dl, Ops); 7489 } 7490 7491 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 7492 EVT VT = Op.getValueType(); 7493 7494 APInt DefBits(VT.getSizeInBits(), 0); 7495 APInt UndefBits(VT.getSizeInBits(), 0); 7496 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7497 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7498 SDValue NewOp; 7499 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 7500 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7501 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 7502 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7503 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 7504 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 7505 return NewOp; 7506 7507 DefBits = ~DefBits; 7508 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 7509 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 7510 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 7511 return NewOp; 7512 7513 DefBits = UndefBits; 7514 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 7515 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7516 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 7517 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7518 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 7519 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 7520 return NewOp; 7521 7522 DefBits = ~UndefBits; 7523 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 7524 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 7525 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 7526 return NewOp; 7527 } 7528 7529 return SDValue(); 7530 } 7531 7532 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 7533 SelectionDAG &DAG) const { 7534 EVT VT = Op.getValueType(); 7535 7536 // Try to build a simple constant vector. 7537 Op = NormalizeBuildVector(Op, DAG); 7538 if (VT.isInteger()) { 7539 // Certain vector constants, used to express things like logical NOT and 7540 // arithmetic NEG, are passed through unmodified. This allows special 7541 // patterns for these operations to match, which will lower these constants 7542 // to whatever is proven necessary. 7543 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7544 if (BVN->isConstant()) 7545 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 7546 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 7547 APInt Val(BitSize, 7548 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 7549 if (Val.isNullValue() || Val.isAllOnesValue()) 7550 return Op; 7551 } 7552 } 7553 7554 if (SDValue V = ConstantBuildVector(Op, DAG)) 7555 return V; 7556 7557 // Scan through the operands to find some interesting properties we can 7558 // exploit: 7559 // 1) If only one value is used, we can use a DUP, or 7560 // 2) if only the low element is not undef, we can just insert that, or 7561 // 3) if only one constant value is used (w/ some non-constant lanes), 7562 // we can splat the constant value into the whole vector then fill 7563 // in the non-constant lanes. 7564 // 4) FIXME: If different constant values are used, but we can intelligently 7565 // select the values we'll be overwriting for the non-constant 7566 // lanes such that we can directly materialize the vector 7567 // some other way (MOVI, e.g.), we can be sneaky. 7568 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 7569 SDLoc dl(Op); 7570 unsigned NumElts = VT.getVectorNumElements(); 7571 bool isOnlyLowElement = true; 7572 bool usesOnlyOneValue = true; 7573 bool usesOnlyOneConstantValue = true; 7574 bool isConstant = true; 7575 bool AllLanesExtractElt = true; 7576 unsigned NumConstantLanes = 0; 7577 SDValue Value; 7578 SDValue ConstantValue; 7579 for (unsigned i = 0; i < NumElts; ++i) { 7580 SDValue V = Op.getOperand(i); 7581 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7582 AllLanesExtractElt = false; 7583 if (V.isUndef()) 7584 continue; 7585 if (i > 0) 7586 isOnlyLowElement = false; 7587 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7588 isConstant = false; 7589 7590 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 7591 ++NumConstantLanes; 7592 if (!ConstantValue.getNode()) 7593 ConstantValue = V; 7594 else if (ConstantValue != V) 7595 usesOnlyOneConstantValue = false; 7596 } 7597 7598 if (!Value.getNode()) 7599 Value = V; 7600 else if (V != Value) 7601 usesOnlyOneValue = false; 7602 } 7603 7604 if (!Value.getNode()) { 7605 LLVM_DEBUG( 7606 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 7607 return DAG.getUNDEF(VT); 7608 } 7609 7610 // Convert BUILD_VECTOR where all elements but the lowest are undef into 7611 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 7612 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 7613 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 7614 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 7615 "SCALAR_TO_VECTOR node\n"); 7616 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7617 } 7618 7619 if (AllLanesExtractElt) { 7620 SDNode *Vector = nullptr; 7621 bool Even = false; 7622 bool Odd = false; 7623 // Check whether the extract elements match the Even pattern <0,2,4,...> or 7624 // the Odd pattern <1,3,5,...>. 7625 for (unsigned i = 0; i < NumElts; ++i) { 7626 SDValue V = Op.getOperand(i); 7627 const SDNode *N = V.getNode(); 7628 if (!isa<ConstantSDNode>(N->getOperand(1))) 7629 break; 7630 SDValue N0 = N->getOperand(0); 7631 7632 // All elements are extracted from the same vector. 7633 if (!Vector) { 7634 Vector = N0.getNode(); 7635 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 7636 // BUILD_VECTOR. 7637 if (VT.getVectorElementType() != 7638 N0.getValueType().getVectorElementType()) 7639 break; 7640 } else if (Vector != N0.getNode()) { 7641 Odd = false; 7642 Even = false; 7643 break; 7644 } 7645 7646 // Extracted values are either at Even indices <0,2,4,...> or at Odd 7647 // indices <1,3,5,...>. 7648 uint64_t Val = N->getConstantOperandVal(1); 7649 if (Val == 2 * i) { 7650 Even = true; 7651 continue; 7652 } 7653 if (Val - 1 == 2 * i) { 7654 Odd = true; 7655 continue; 7656 } 7657 7658 // Something does not match: abort. 7659 Odd = false; 7660 Even = false; 7661 break; 7662 } 7663 if (Even || Odd) { 7664 SDValue LHS = 7665 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 7666 DAG.getConstant(0, dl, MVT::i64)); 7667 SDValue RHS = 7668 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 7669 DAG.getConstant(NumElts, dl, MVT::i64)); 7670 7671 if (Even && !Odd) 7672 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 7673 RHS); 7674 if (Odd && !Even) 7675 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 7676 RHS); 7677 } 7678 } 7679 7680 // Use DUP for non-constant splats. For f32 constant splats, reduce to 7681 // i32 and try again. 7682 if (usesOnlyOneValue) { 7683 if (!isConstant) { 7684 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7685 Value.getValueType() != VT) { 7686 LLVM_DEBUG( 7687 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 7688 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 7689 } 7690 7691 // This is actually a DUPLANExx operation, which keeps everything vectory. 7692 7693 SDValue Lane = Value.getOperand(1); 7694 Value = Value.getOperand(0); 7695 if (Value.getValueSizeInBits() == 64) { 7696 LLVM_DEBUG( 7697 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 7698 "widening it\n"); 7699 Value = WidenVector(Value, DAG); 7700 } 7701 7702 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 7703 return DAG.getNode(Opcode, dl, VT, Value, Lane); 7704 } 7705 7706 if (VT.getVectorElementType().isFloatingPoint()) { 7707 SmallVector<SDValue, 8> Ops; 7708 EVT EltTy = VT.getVectorElementType(); 7709 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 7710 "Unsupported floating-point vector type"); 7711 LLVM_DEBUG( 7712 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 7713 "BITCASTS, and try again\n"); 7714 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 7715 for (unsigned i = 0; i < NumElts; ++i) 7716 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 7717 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 7718 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7719 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 7720 Val.dump();); 7721 Val = LowerBUILD_VECTOR(Val, DAG); 7722 if (Val.getNode()) 7723 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7724 } 7725 } 7726 7727 // If there was only one constant value used and for more than one lane, 7728 // start by splatting that value, then replace the non-constant lanes. This 7729 // is better than the default, which will perform a separate initialization 7730 // for each lane. 7731 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 7732 // Firstly, try to materialize the splat constant. 7733 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 7734 Val = ConstantBuildVector(Vec, DAG); 7735 if (!Val) { 7736 // Otherwise, materialize the constant and splat it. 7737 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 7738 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 7739 } 7740 7741 // Now insert the non-constant lanes. 7742 for (unsigned i = 0; i < NumElts; ++i) { 7743 SDValue V = Op.getOperand(i); 7744 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 7745 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 7746 // Note that type legalization likely mucked about with the VT of the 7747 // source operand, so we may have to convert it here before inserting. 7748 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 7749 } 7750 return Val; 7751 } 7752 7753 // This will generate a load from the constant pool. 7754 if (isConstant) { 7755 LLVM_DEBUG( 7756 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 7757 "expansion\n"); 7758 return SDValue(); 7759 } 7760 7761 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7762 if (NumElts >= 4) { 7763 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7764 return shuffle; 7765 } 7766 7767 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7768 // know the default expansion would otherwise fall back on something even 7769 // worse. For a vector with one or two non-undef values, that's 7770 // scalar_to_vector for the elements followed by a shuffle (provided the 7771 // shuffle is valid for the target) and materialization element by element 7772 // on the stack followed by a load for everything else. 7773 if (!isConstant && !usesOnlyOneValue) { 7774 LLVM_DEBUG( 7775 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 7776 "of INSERT_VECTOR_ELT\n"); 7777 7778 SDValue Vec = DAG.getUNDEF(VT); 7779 SDValue Op0 = Op.getOperand(0); 7780 unsigned i = 0; 7781 7782 // Use SCALAR_TO_VECTOR for lane zero to 7783 // a) Avoid a RMW dependency on the full vector register, and 7784 // b) Allow the register coalescer to fold away the copy if the 7785 // value is already in an S or D register, and we're forced to emit an 7786 // INSERT_SUBREG that we can't fold anywhere. 7787 // 7788 // We also allow types like i8 and i16 which are illegal scalar but legal 7789 // vector element types. After type-legalization the inserted value is 7790 // extended (i32) and it is safe to cast them to the vector type by ignoring 7791 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 7792 if (!Op0.isUndef()) { 7793 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 7794 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 7795 ++i; 7796 } 7797 LLVM_DEBUG(if (i < NumElts) dbgs() 7798 << "Creating nodes for the other vector elements:\n";); 7799 for (; i < NumElts; ++i) { 7800 SDValue V = Op.getOperand(i); 7801 if (V.isUndef()) 7802 continue; 7803 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 7804 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7805 } 7806 return Vec; 7807 } 7808 7809 LLVM_DEBUG( 7810 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 7811 "better alternative\n"); 7812 return SDValue(); 7813 } 7814 7815 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 7816 SelectionDAG &DAG) const { 7817 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 7818 7819 // Check for non-constant or out of range lane. 7820 EVT VT = Op.getOperand(0).getValueType(); 7821 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 7822 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 7823 return SDValue(); 7824 7825 7826 // Insertion/extraction are legal for V128 types. 7827 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 7828 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 7829 VT == MVT::v8f16) 7830 return Op; 7831 7832 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 7833 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 7834 return SDValue(); 7835 7836 // For V64 types, we perform insertion by expanding the value 7837 // to a V128 type and perform the insertion on that. 7838 SDLoc DL(Op); 7839 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 7840 EVT WideTy = WideVec.getValueType(); 7841 7842 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 7843 Op.getOperand(1), Op.getOperand(2)); 7844 // Re-narrow the resultant vector. 7845 return NarrowVector(Node, DAG); 7846 } 7847 7848 SDValue 7849 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7850 SelectionDAG &DAG) const { 7851 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 7852 7853 // Check for non-constant or out of range lane. 7854 EVT VT = Op.getOperand(0).getValueType(); 7855 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7856 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 7857 return SDValue(); 7858 7859 7860 // Insertion/extraction are legal for V128 types. 7861 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 7862 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 7863 VT == MVT::v8f16) 7864 return Op; 7865 7866 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 7867 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 7868 return SDValue(); 7869 7870 // For V64 types, we perform extraction by expanding the value 7871 // to a V128 type and perform the extraction on that. 7872 SDLoc DL(Op); 7873 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 7874 EVT WideTy = WideVec.getValueType(); 7875 7876 EVT ExtrTy = WideTy.getVectorElementType(); 7877 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 7878 ExtrTy = MVT::i32; 7879 7880 // For extractions, we just return the result directly. 7881 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 7882 Op.getOperand(1)); 7883 } 7884 7885 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 7886 SelectionDAG &DAG) const { 7887 EVT VT = Op.getOperand(0).getValueType(); 7888 SDLoc dl(Op); 7889 // Just in case... 7890 if (!VT.isVector()) 7891 return SDValue(); 7892 7893 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7894 if (!Cst) 7895 return SDValue(); 7896 unsigned Val = Cst->getZExtValue(); 7897 7898 unsigned Size = Op.getValueSizeInBits(); 7899 7900 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 7901 if (Val == 0) 7902 return Op; 7903 7904 // If this is extracting the upper 64-bits of a 128-bit vector, we match 7905 // that directly. 7906 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 7907 return Op; 7908 7909 return SDValue(); 7910 } 7911 7912 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7913 if (VT.getVectorNumElements() == 4 && 7914 (VT.is128BitVector() || VT.is64BitVector())) { 7915 unsigned PFIndexes[4]; 7916 for (unsigned i = 0; i != 4; ++i) { 7917 if (M[i] < 0) 7918 PFIndexes[i] = 8; 7919 else 7920 PFIndexes[i] = M[i]; 7921 } 7922 7923 // Compute the index in the perfect shuffle table. 7924 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7925 PFIndexes[2] * 9 + PFIndexes[3]; 7926 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7927 unsigned Cost = (PFEntry >> 30); 7928 7929 if (Cost <= 4) 7930 return true; 7931 } 7932 7933 bool DummyBool; 7934 int DummyInt; 7935 unsigned DummyUnsigned; 7936 7937 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 7938 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 7939 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 7940 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 7941 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 7942 isZIPMask(M, VT, DummyUnsigned) || 7943 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 7944 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 7945 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 7946 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 7947 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 7948 } 7949 7950 /// getVShiftImm - Check if this is a valid build_vector for the immediate 7951 /// operand of a vector shift operation, where all the elements of the 7952 /// build_vector must have the same constant integer value. 7953 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 7954 // Ignore bit_converts. 7955 while (Op.getOpcode() == ISD::BITCAST) 7956 Op = Op.getOperand(0); 7957 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7958 APInt SplatBits, SplatUndef; 7959 unsigned SplatBitSize; 7960 bool HasAnyUndefs; 7961 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 7962 HasAnyUndefs, ElementBits) || 7963 SplatBitSize > ElementBits) 7964 return false; 7965 Cnt = SplatBits.getSExtValue(); 7966 return true; 7967 } 7968 7969 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 7970 /// operand of a vector shift left operation. That value must be in the range: 7971 /// 0 <= Value < ElementBits for a left shift; or 7972 /// 0 <= Value <= ElementBits for a long left shift. 7973 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 7974 assert(VT.isVector() && "vector shift count is not a vector type"); 7975 int64_t ElementBits = VT.getScalarSizeInBits(); 7976 if (!getVShiftImm(Op, ElementBits, Cnt)) 7977 return false; 7978 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 7979 } 7980 7981 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 7982 /// operand of a vector shift right operation. The value must be in the range: 7983 /// 1 <= Value <= ElementBits for a right shift; or 7984 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 7985 assert(VT.isVector() && "vector shift count is not a vector type"); 7986 int64_t ElementBits = VT.getScalarSizeInBits(); 7987 if (!getVShiftImm(Op, ElementBits, Cnt)) 7988 return false; 7989 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 7990 } 7991 7992 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 7993 SelectionDAG &DAG) const { 7994 EVT VT = Op.getValueType(); 7995 SDLoc DL(Op); 7996 int64_t Cnt; 7997 7998 if (!Op.getOperand(1).getValueType().isVector()) 7999 return Op; 8000 unsigned EltSize = VT.getScalarSizeInBits(); 8001 8002 switch (Op.getOpcode()) { 8003 default: 8004 llvm_unreachable("unexpected shift opcode"); 8005 8006 case ISD::SHL: 8007 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 8008 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 8009 DAG.getConstant(Cnt, DL, MVT::i32)); 8010 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8011 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 8012 MVT::i32), 8013 Op.getOperand(0), Op.getOperand(1)); 8014 case ISD::SRA: 8015 case ISD::SRL: 8016 // Right shift immediate 8017 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 8018 unsigned Opc = 8019 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 8020 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 8021 DAG.getConstant(Cnt, DL, MVT::i32)); 8022 } 8023 8024 // Right shift register. Note, there is not a shift right register 8025 // instruction, but the shift left register instruction takes a signed 8026 // value, where negative numbers specify a right shift. 8027 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 8028 : Intrinsic::aarch64_neon_ushl; 8029 // negate the shift amount 8030 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 8031 SDValue NegShiftLeft = 8032 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8033 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 8034 NegShift); 8035 return NegShiftLeft; 8036 } 8037 8038 return SDValue(); 8039 } 8040 8041 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 8042 AArch64CC::CondCode CC, bool NoNans, EVT VT, 8043 const SDLoc &dl, SelectionDAG &DAG) { 8044 EVT SrcVT = LHS.getValueType(); 8045 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 8046 "function only supposed to emit natural comparisons"); 8047 8048 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 8049 APInt CnstBits(VT.getSizeInBits(), 0); 8050 APInt UndefBits(VT.getSizeInBits(), 0); 8051 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 8052 bool IsZero = IsCnst && (CnstBits == 0); 8053 8054 if (SrcVT.getVectorElementType().isFloatingPoint()) { 8055 switch (CC) { 8056 default: 8057 return SDValue(); 8058 case AArch64CC::NE: { 8059 SDValue Fcmeq; 8060 if (IsZero) 8061 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8062 else 8063 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8064 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 8065 } 8066 case AArch64CC::EQ: 8067 if (IsZero) 8068 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8069 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8070 case AArch64CC::GE: 8071 if (IsZero) 8072 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 8073 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 8074 case AArch64CC::GT: 8075 if (IsZero) 8076 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 8077 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 8078 case AArch64CC::LS: 8079 if (IsZero) 8080 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 8081 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 8082 case AArch64CC::LT: 8083 if (!NoNans) 8084 return SDValue(); 8085 // If we ignore NaNs then we can use to the MI implementation. 8086 LLVM_FALLTHROUGH; 8087 case AArch64CC::MI: 8088 if (IsZero) 8089 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 8090 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 8091 } 8092 } 8093 8094 switch (CC) { 8095 default: 8096 return SDValue(); 8097 case AArch64CC::NE: { 8098 SDValue Cmeq; 8099 if (IsZero) 8100 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8101 else 8102 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8103 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 8104 } 8105 case AArch64CC::EQ: 8106 if (IsZero) 8107 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8108 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8109 case AArch64CC::GE: 8110 if (IsZero) 8111 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 8112 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 8113 case AArch64CC::GT: 8114 if (IsZero) 8115 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 8116 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 8117 case AArch64CC::LE: 8118 if (IsZero) 8119 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 8120 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 8121 case AArch64CC::LS: 8122 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 8123 case AArch64CC::LO: 8124 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 8125 case AArch64CC::LT: 8126 if (IsZero) 8127 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 8128 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 8129 case AArch64CC::HI: 8130 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 8131 case AArch64CC::HS: 8132 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 8133 } 8134 } 8135 8136 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 8137 SelectionDAG &DAG) const { 8138 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8139 SDValue LHS = Op.getOperand(0); 8140 SDValue RHS = Op.getOperand(1); 8141 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 8142 SDLoc dl(Op); 8143 8144 if (LHS.getValueType().getVectorElementType().isInteger()) { 8145 assert(LHS.getValueType() == RHS.getValueType()); 8146 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 8147 SDValue Cmp = 8148 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 8149 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8150 } 8151 8152 const bool FullFP16 = 8153 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 8154 8155 // Make v4f16 (only) fcmp operations utilise vector instructions 8156 // v8f16 support will be a litle more complicated 8157 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 8158 if (LHS.getValueType().getVectorNumElements() == 4) { 8159 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 8160 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 8161 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 8162 DAG.ReplaceAllUsesWith(Op, NewSetcc); 8163 CmpVT = MVT::v4i32; 8164 } else 8165 return SDValue(); 8166 } 8167 8168 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 8169 LHS.getValueType().getVectorElementType() != MVT::f128); 8170 8171 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 8172 // clean. Some of them require two branches to implement. 8173 AArch64CC::CondCode CC1, CC2; 8174 bool ShouldInvert; 8175 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 8176 8177 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 8178 SDValue Cmp = 8179 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 8180 if (!Cmp.getNode()) 8181 return SDValue(); 8182 8183 if (CC2 != AArch64CC::AL) { 8184 SDValue Cmp2 = 8185 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 8186 if (!Cmp2.getNode()) 8187 return SDValue(); 8188 8189 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 8190 } 8191 8192 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8193 8194 if (ShouldInvert) 8195 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 8196 8197 return Cmp; 8198 } 8199 8200 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 8201 SelectionDAG &DAG) { 8202 SDValue VecOp = ScalarOp.getOperand(0); 8203 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 8204 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 8205 DAG.getConstant(0, DL, MVT::i64)); 8206 } 8207 8208 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 8209 SelectionDAG &DAG) const { 8210 SDLoc dl(Op); 8211 switch (Op.getOpcode()) { 8212 case ISD::VECREDUCE_ADD: 8213 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 8214 case ISD::VECREDUCE_SMAX: 8215 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 8216 case ISD::VECREDUCE_SMIN: 8217 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 8218 case ISD::VECREDUCE_UMAX: 8219 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 8220 case ISD::VECREDUCE_UMIN: 8221 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 8222 case ISD::VECREDUCE_FMAX: { 8223 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 8224 return DAG.getNode( 8225 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8226 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 8227 Op.getOperand(0)); 8228 } 8229 case ISD::VECREDUCE_FMIN: { 8230 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 8231 return DAG.getNode( 8232 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8233 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 8234 Op.getOperand(0)); 8235 } 8236 default: 8237 llvm_unreachable("Unhandled reduction"); 8238 } 8239 } 8240 8241 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 8242 SelectionDAG &DAG) const { 8243 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8244 if (!Subtarget.hasLSE()) 8245 return SDValue(); 8246 8247 // LSE has an atomic load-add instruction, but not a load-sub. 8248 SDLoc dl(Op); 8249 MVT VT = Op.getSimpleValueType(); 8250 SDValue RHS = Op.getOperand(2); 8251 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8252 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 8253 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 8254 Op.getOperand(0), Op.getOperand(1), RHS, 8255 AN->getMemOperand()); 8256 } 8257 8258 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 8259 SelectionDAG &DAG) const { 8260 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8261 if (!Subtarget.hasLSE()) 8262 return SDValue(); 8263 8264 // LSE has an atomic load-clear instruction, but not a load-and. 8265 SDLoc dl(Op); 8266 MVT VT = Op.getSimpleValueType(); 8267 SDValue RHS = Op.getOperand(2); 8268 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8269 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 8270 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 8271 Op.getOperand(0), Op.getOperand(1), RHS, 8272 AN->getMemOperand()); 8273 } 8274 8275 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 8276 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 8277 SDLoc dl(Op); 8278 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8279 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 8280 8281 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 8282 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 8283 if (Subtarget->hasCustomCallingConv()) 8284 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 8285 8286 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 8287 DAG.getConstant(4, dl, MVT::i64)); 8288 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 8289 Chain = 8290 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 8291 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 8292 DAG.getRegisterMask(Mask), Chain.getValue(1)); 8293 // To match the actual intent better, we should read the output from X15 here 8294 // again (instead of potentially spilling it to the stack), but rereading Size 8295 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 8296 // here. 8297 8298 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 8299 DAG.getConstant(4, dl, MVT::i64)); 8300 return Chain; 8301 } 8302 8303 SDValue 8304 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 8305 SelectionDAG &DAG) const { 8306 assert(Subtarget->isTargetWindows() && 8307 "Only Windows alloca probing supported"); 8308 SDLoc dl(Op); 8309 // Get the inputs. 8310 SDNode *Node = Op.getNode(); 8311 SDValue Chain = Op.getOperand(0); 8312 SDValue Size = Op.getOperand(1); 8313 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8314 EVT VT = Node->getValueType(0); 8315 8316 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 8317 "no-stack-arg-probe")) { 8318 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8319 Chain = SP.getValue(1); 8320 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8321 if (Align) 8322 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8323 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8324 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8325 SDValue Ops[2] = {SP, Chain}; 8326 return DAG.getMergeValues(Ops, dl); 8327 } 8328 8329 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 8330 8331 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 8332 8333 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8334 Chain = SP.getValue(1); 8335 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8336 if (Align) 8337 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8338 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8339 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8340 8341 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 8342 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 8343 8344 SDValue Ops[2] = {SP, Chain}; 8345 return DAG.getMergeValues(Ops, dl); 8346 } 8347 8348 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 8349 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 8350 /// specified in the intrinsic calls. 8351 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 8352 const CallInst &I, 8353 MachineFunction &MF, 8354 unsigned Intrinsic) const { 8355 auto &DL = I.getModule()->getDataLayout(); 8356 switch (Intrinsic) { 8357 case Intrinsic::aarch64_neon_ld2: 8358 case Intrinsic::aarch64_neon_ld3: 8359 case Intrinsic::aarch64_neon_ld4: 8360 case Intrinsic::aarch64_neon_ld1x2: 8361 case Intrinsic::aarch64_neon_ld1x3: 8362 case Intrinsic::aarch64_neon_ld1x4: 8363 case Intrinsic::aarch64_neon_ld2lane: 8364 case Intrinsic::aarch64_neon_ld3lane: 8365 case Intrinsic::aarch64_neon_ld4lane: 8366 case Intrinsic::aarch64_neon_ld2r: 8367 case Intrinsic::aarch64_neon_ld3r: 8368 case Intrinsic::aarch64_neon_ld4r: { 8369 Info.opc = ISD::INTRINSIC_W_CHAIN; 8370 // Conservatively set memVT to the entire set of vectors loaded. 8371 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 8372 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8373 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8374 Info.offset = 0; 8375 Info.align.reset(); 8376 // volatile loads with NEON intrinsics not supported 8377 Info.flags = MachineMemOperand::MOLoad; 8378 return true; 8379 } 8380 case Intrinsic::aarch64_neon_st2: 8381 case Intrinsic::aarch64_neon_st3: 8382 case Intrinsic::aarch64_neon_st4: 8383 case Intrinsic::aarch64_neon_st1x2: 8384 case Intrinsic::aarch64_neon_st1x3: 8385 case Intrinsic::aarch64_neon_st1x4: 8386 case Intrinsic::aarch64_neon_st2lane: 8387 case Intrinsic::aarch64_neon_st3lane: 8388 case Intrinsic::aarch64_neon_st4lane: { 8389 Info.opc = ISD::INTRINSIC_VOID; 8390 // Conservatively set memVT to the entire set of vectors stored. 8391 unsigned NumElts = 0; 8392 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 8393 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 8394 if (!ArgTy->isVectorTy()) 8395 break; 8396 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 8397 } 8398 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8399 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8400 Info.offset = 0; 8401 Info.align.reset(); 8402 // volatile stores with NEON intrinsics not supported 8403 Info.flags = MachineMemOperand::MOStore; 8404 return true; 8405 } 8406 case Intrinsic::aarch64_ldaxr: 8407 case Intrinsic::aarch64_ldxr: { 8408 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 8409 Info.opc = ISD::INTRINSIC_W_CHAIN; 8410 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8411 Info.ptrVal = I.getArgOperand(0); 8412 Info.offset = 0; 8413 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8414 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8415 return true; 8416 } 8417 case Intrinsic::aarch64_stlxr: 8418 case Intrinsic::aarch64_stxr: { 8419 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 8420 Info.opc = ISD::INTRINSIC_W_CHAIN; 8421 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8422 Info.ptrVal = I.getArgOperand(1); 8423 Info.offset = 0; 8424 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8425 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8426 return true; 8427 } 8428 case Intrinsic::aarch64_ldaxp: 8429 case Intrinsic::aarch64_ldxp: 8430 Info.opc = ISD::INTRINSIC_W_CHAIN; 8431 Info.memVT = MVT::i128; 8432 Info.ptrVal = I.getArgOperand(0); 8433 Info.offset = 0; 8434 Info.align = Align(16); 8435 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8436 return true; 8437 case Intrinsic::aarch64_stlxp: 8438 case Intrinsic::aarch64_stxp: 8439 Info.opc = ISD::INTRINSIC_W_CHAIN; 8440 Info.memVT = MVT::i128; 8441 Info.ptrVal = I.getArgOperand(2); 8442 Info.offset = 0; 8443 Info.align = Align(16); 8444 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8445 return true; 8446 default: 8447 break; 8448 } 8449 8450 return false; 8451 } 8452 8453 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 8454 ISD::LoadExtType ExtTy, 8455 EVT NewVT) const { 8456 // TODO: This may be worth removing. Check regression tests for diffs. 8457 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 8458 return false; 8459 8460 // If we're reducing the load width in order to avoid having to use an extra 8461 // instruction to do extension then it's probably a good idea. 8462 if (ExtTy != ISD::NON_EXTLOAD) 8463 return true; 8464 // Don't reduce load width if it would prevent us from combining a shift into 8465 // the offset. 8466 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 8467 assert(Mem); 8468 const SDValue &Base = Mem->getBasePtr(); 8469 if (Base.getOpcode() == ISD::ADD && 8470 Base.getOperand(1).getOpcode() == ISD::SHL && 8471 Base.getOperand(1).hasOneUse() && 8472 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 8473 // The shift can be combined if it matches the size of the value being 8474 // loaded (and so reducing the width would make it not match). 8475 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 8476 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 8477 if (ShiftAmount == Log2_32(LoadBytes)) 8478 return false; 8479 } 8480 // We have no reason to disallow reducing the load width, so allow it. 8481 return true; 8482 } 8483 8484 // Truncations from 64-bit GPR to 32-bit GPR is free. 8485 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 8486 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 8487 return false; 8488 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 8489 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 8490 return NumBits1 > NumBits2; 8491 } 8492 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 8493 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 8494 return false; 8495 unsigned NumBits1 = VT1.getSizeInBits(); 8496 unsigned NumBits2 = VT2.getSizeInBits(); 8497 return NumBits1 > NumBits2; 8498 } 8499 8500 /// Check if it is profitable to hoist instruction in then/else to if. 8501 /// Not profitable if I and it's user can form a FMA instruction 8502 /// because we prefer FMSUB/FMADD. 8503 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 8504 if (I->getOpcode() != Instruction::FMul) 8505 return true; 8506 8507 if (!I->hasOneUse()) 8508 return true; 8509 8510 Instruction *User = I->user_back(); 8511 8512 if (User && 8513 !(User->getOpcode() == Instruction::FSub || 8514 User->getOpcode() == Instruction::FAdd)) 8515 return true; 8516 8517 const TargetOptions &Options = getTargetMachine().Options; 8518 const DataLayout &DL = I->getModule()->getDataLayout(); 8519 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 8520 8521 return !(isFMAFasterThanFMulAndFAdd(VT) && 8522 isOperationLegalOrCustom(ISD::FMA, VT) && 8523 (Options.AllowFPOpFusion == FPOpFusion::Fast || 8524 Options.UnsafeFPMath)); 8525 } 8526 8527 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 8528 // 64-bit GPR. 8529 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 8530 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 8531 return false; 8532 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 8533 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 8534 return NumBits1 == 32 && NumBits2 == 64; 8535 } 8536 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 8537 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 8538 return false; 8539 unsigned NumBits1 = VT1.getSizeInBits(); 8540 unsigned NumBits2 = VT2.getSizeInBits(); 8541 return NumBits1 == 32 && NumBits2 == 64; 8542 } 8543 8544 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 8545 EVT VT1 = Val.getValueType(); 8546 if (isZExtFree(VT1, VT2)) { 8547 return true; 8548 } 8549 8550 if (Val.getOpcode() != ISD::LOAD) 8551 return false; 8552 8553 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 8554 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 8555 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 8556 VT1.getSizeInBits() <= 32); 8557 } 8558 8559 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 8560 if (isa<FPExtInst>(Ext)) 8561 return false; 8562 8563 // Vector types are not free. 8564 if (Ext->getType()->isVectorTy()) 8565 return false; 8566 8567 for (const Use &U : Ext->uses()) { 8568 // The extension is free if we can fold it with a left shift in an 8569 // addressing mode or an arithmetic operation: add, sub, and cmp. 8570 8571 // Is there a shift? 8572 const Instruction *Instr = cast<Instruction>(U.getUser()); 8573 8574 // Is this a constant shift? 8575 switch (Instr->getOpcode()) { 8576 case Instruction::Shl: 8577 if (!isa<ConstantInt>(Instr->getOperand(1))) 8578 return false; 8579 break; 8580 case Instruction::GetElementPtr: { 8581 gep_type_iterator GTI = gep_type_begin(Instr); 8582 auto &DL = Ext->getModule()->getDataLayout(); 8583 std::advance(GTI, U.getOperandNo()-1); 8584 Type *IdxTy = GTI.getIndexedType(); 8585 // This extension will end up with a shift because of the scaling factor. 8586 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 8587 // Get the shift amount based on the scaling factor: 8588 // log2(sizeof(IdxTy)) - log2(8). 8589 uint64_t ShiftAmt = 8590 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 8591 // Is the constant foldable in the shift of the addressing mode? 8592 // I.e., shift amount is between 1 and 4 inclusive. 8593 if (ShiftAmt == 0 || ShiftAmt > 4) 8594 return false; 8595 break; 8596 } 8597 case Instruction::Trunc: 8598 // Check if this is a noop. 8599 // trunc(sext ty1 to ty2) to ty1. 8600 if (Instr->getType() == Ext->getOperand(0)->getType()) 8601 continue; 8602 LLVM_FALLTHROUGH; 8603 default: 8604 return false; 8605 } 8606 8607 // At this point we can use the bfm family, so this extension is free 8608 // for that use. 8609 } 8610 return true; 8611 } 8612 8613 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 8614 /// or upper half of the vector elements. 8615 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 8616 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 8617 auto *FullVT = cast<VectorType>(FullV->getType()); 8618 auto *HalfVT = cast<VectorType>(HalfV->getType()); 8619 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth(); 8620 }; 8621 8622 auto extractHalf = [](Value *FullV, Value *HalfV) { 8623 auto *FullVT = cast<VectorType>(FullV->getType()); 8624 auto *HalfVT = cast<VectorType>(HalfV->getType()); 8625 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 8626 }; 8627 8628 Constant *M1, *M2; 8629 Value *S1Op1, *S2Op1; 8630 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) || 8631 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2)))) 8632 return false; 8633 8634 // Check that the operands are half as wide as the result and we extract 8635 // half of the elements of the input vectors. 8636 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 8637 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 8638 return false; 8639 8640 // Check the mask extracts either the lower or upper half of vector 8641 // elements. 8642 int M1Start = -1; 8643 int M2Start = -1; 8644 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2; 8645 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 8646 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 8647 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 8648 return false; 8649 8650 return true; 8651 } 8652 8653 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 8654 /// of the vector elements. 8655 static bool areExtractExts(Value *Ext1, Value *Ext2) { 8656 auto areExtDoubled = [](Instruction *Ext) { 8657 return Ext->getType()->getScalarSizeInBits() == 8658 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 8659 }; 8660 8661 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 8662 !match(Ext2, m_ZExtOrSExt(m_Value())) || 8663 !areExtDoubled(cast<Instruction>(Ext1)) || 8664 !areExtDoubled(cast<Instruction>(Ext2))) 8665 return false; 8666 8667 return true; 8668 } 8669 8670 /// Check if sinking \p I's operands to I's basic block is profitable, because 8671 /// the operands can be folded into a target instruction, e.g. 8672 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 8673 bool AArch64TargetLowering::shouldSinkOperands( 8674 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 8675 if (!I->getType()->isVectorTy()) 8676 return false; 8677 8678 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 8679 switch (II->getIntrinsicID()) { 8680 case Intrinsic::aarch64_neon_umull: 8681 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 8682 return false; 8683 Ops.push_back(&II->getOperandUse(0)); 8684 Ops.push_back(&II->getOperandUse(1)); 8685 return true; 8686 default: 8687 return false; 8688 } 8689 } 8690 8691 switch (I->getOpcode()) { 8692 case Instruction::Sub: 8693 case Instruction::Add: { 8694 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 8695 return false; 8696 8697 // If the exts' operands extract either the lower or upper elements, we 8698 // can sink them too. 8699 auto Ext1 = cast<Instruction>(I->getOperand(0)); 8700 auto Ext2 = cast<Instruction>(I->getOperand(1)); 8701 if (areExtractShuffleVectors(Ext1, Ext2)) { 8702 Ops.push_back(&Ext1->getOperandUse(0)); 8703 Ops.push_back(&Ext2->getOperandUse(0)); 8704 } 8705 8706 Ops.push_back(&I->getOperandUse(0)); 8707 Ops.push_back(&I->getOperandUse(1)); 8708 8709 return true; 8710 } 8711 default: 8712 return false; 8713 } 8714 return false; 8715 } 8716 8717 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 8718 unsigned &RequiredAligment) const { 8719 if (!LoadedType.isSimple() || 8720 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 8721 return false; 8722 // Cyclone supports unaligned accesses. 8723 RequiredAligment = 0; 8724 unsigned NumBits = LoadedType.getSizeInBits(); 8725 return NumBits == 32 || NumBits == 64; 8726 } 8727 8728 /// A helper function for determining the number of interleaved accesses we 8729 /// will generate when lowering accesses of the given type. 8730 unsigned 8731 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 8732 const DataLayout &DL) const { 8733 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 8734 } 8735 8736 MachineMemOperand::Flags 8737 AArch64TargetLowering::getMMOFlags(const Instruction &I) const { 8738 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 8739 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 8740 return MOStridedAccess; 8741 return MachineMemOperand::MONone; 8742 } 8743 8744 bool AArch64TargetLowering::isLegalInterleavedAccessType( 8745 VectorType *VecTy, const DataLayout &DL) const { 8746 8747 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 8748 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 8749 8750 // Ensure the number of vector elements is greater than 1. 8751 if (VecTy->getNumElements() < 2) 8752 return false; 8753 8754 // Ensure the element type is legal. 8755 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 8756 return false; 8757 8758 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 8759 // 128 will be split into multiple interleaved accesses. 8760 return VecSize == 64 || VecSize % 128 == 0; 8761 } 8762 8763 /// Lower an interleaved load into a ldN intrinsic. 8764 /// 8765 /// E.g. Lower an interleaved load (Factor = 2): 8766 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 8767 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 8768 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 8769 /// 8770 /// Into: 8771 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 8772 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 8773 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 8774 bool AArch64TargetLowering::lowerInterleavedLoad( 8775 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 8776 ArrayRef<unsigned> Indices, unsigned Factor) const { 8777 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 8778 "Invalid interleave factor"); 8779 assert(!Shuffles.empty() && "Empty shufflevector input"); 8780 assert(Shuffles.size() == Indices.size() && 8781 "Unmatched number of shufflevectors and indices"); 8782 8783 const DataLayout &DL = LI->getModule()->getDataLayout(); 8784 8785 VectorType *VecTy = Shuffles[0]->getType(); 8786 8787 // Skip if we do not have NEON and skip illegal vector types. We can 8788 // "legalize" wide vector types into multiple interleaved accesses as long as 8789 // the vector types are divisible by 128. 8790 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 8791 return false; 8792 8793 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 8794 8795 // A pointer vector can not be the return type of the ldN intrinsics. Need to 8796 // load integer vectors first and then convert to pointer vectors. 8797 Type *EltTy = VecTy->getVectorElementType(); 8798 if (EltTy->isPointerTy()) 8799 VecTy = 8800 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 8801 8802 IRBuilder<> Builder(LI); 8803 8804 // The base address of the load. 8805 Value *BaseAddr = LI->getPointerOperand(); 8806 8807 if (NumLoads > 1) { 8808 // If we're going to generate more than one load, reset the sub-vector type 8809 // to something legal. 8810 VecTy = VectorType::get(VecTy->getVectorElementType(), 8811 VecTy->getVectorNumElements() / NumLoads); 8812 8813 // We will compute the pointer operand of each load from the original base 8814 // address using GEPs. Cast the base address to a pointer to the scalar 8815 // element type. 8816 BaseAddr = Builder.CreateBitCast( 8817 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 8818 LI->getPointerAddressSpace())); 8819 } 8820 8821 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 8822 Type *Tys[2] = {VecTy, PtrTy}; 8823 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 8824 Intrinsic::aarch64_neon_ld3, 8825 Intrinsic::aarch64_neon_ld4}; 8826 Function *LdNFunc = 8827 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 8828 8829 // Holds sub-vectors extracted from the load intrinsic return values. The 8830 // sub-vectors are associated with the shufflevector instructions they will 8831 // replace. 8832 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 8833 8834 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 8835 8836 // If we're generating more than one load, compute the base address of 8837 // subsequent loads as an offset from the previous. 8838 if (LoadCount > 0) 8839 BaseAddr = 8840 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 8841 VecTy->getVectorNumElements() * Factor); 8842 8843 CallInst *LdN = Builder.CreateCall( 8844 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 8845 8846 // Extract and store the sub-vectors returned by the load intrinsic. 8847 for (unsigned i = 0; i < Shuffles.size(); i++) { 8848 ShuffleVectorInst *SVI = Shuffles[i]; 8849 unsigned Index = Indices[i]; 8850 8851 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 8852 8853 // Convert the integer vector to pointer vector if the element is pointer. 8854 if (EltTy->isPointerTy()) 8855 SubVec = Builder.CreateIntToPtr( 8856 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 8857 VecTy->getVectorNumElements())); 8858 SubVecs[SVI].push_back(SubVec); 8859 } 8860 } 8861 8862 // Replace uses of the shufflevector instructions with the sub-vectors 8863 // returned by the load intrinsic. If a shufflevector instruction is 8864 // associated with more than one sub-vector, those sub-vectors will be 8865 // concatenated into a single wide vector. 8866 for (ShuffleVectorInst *SVI : Shuffles) { 8867 auto &SubVec = SubVecs[SVI]; 8868 auto *WideVec = 8869 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 8870 SVI->replaceAllUsesWith(WideVec); 8871 } 8872 8873 return true; 8874 } 8875 8876 /// Lower an interleaved store into a stN intrinsic. 8877 /// 8878 /// E.g. Lower an interleaved store (Factor = 3): 8879 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 8880 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 8881 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 8882 /// 8883 /// Into: 8884 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 8885 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 8886 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 8887 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 8888 /// 8889 /// Note that the new shufflevectors will be removed and we'll only generate one 8890 /// st3 instruction in CodeGen. 8891 /// 8892 /// Example for a more general valid mask (Factor 3). Lower: 8893 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 8894 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 8895 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 8896 /// 8897 /// Into: 8898 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 8899 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 8900 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 8901 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 8902 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 8903 ShuffleVectorInst *SVI, 8904 unsigned Factor) const { 8905 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 8906 "Invalid interleave factor"); 8907 8908 VectorType *VecTy = SVI->getType(); 8909 assert(VecTy->getVectorNumElements() % Factor == 0 && 8910 "Invalid interleaved store"); 8911 8912 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 8913 Type *EltTy = VecTy->getVectorElementType(); 8914 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 8915 8916 const DataLayout &DL = SI->getModule()->getDataLayout(); 8917 8918 // Skip if we do not have NEON and skip illegal vector types. We can 8919 // "legalize" wide vector types into multiple interleaved accesses as long as 8920 // the vector types are divisible by 128. 8921 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 8922 return false; 8923 8924 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 8925 8926 Value *Op0 = SVI->getOperand(0); 8927 Value *Op1 = SVI->getOperand(1); 8928 IRBuilder<> Builder(SI); 8929 8930 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 8931 // vectors to integer vectors. 8932 if (EltTy->isPointerTy()) { 8933 Type *IntTy = DL.getIntPtrType(EltTy); 8934 unsigned NumOpElts = Op0->getType()->getVectorNumElements(); 8935 8936 // Convert to the corresponding integer vector. 8937 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 8938 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 8939 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 8940 8941 SubVecTy = VectorType::get(IntTy, LaneLen); 8942 } 8943 8944 // The base address of the store. 8945 Value *BaseAddr = SI->getPointerOperand(); 8946 8947 if (NumStores > 1) { 8948 // If we're going to generate more than one store, reset the lane length 8949 // and sub-vector type to something legal. 8950 LaneLen /= NumStores; 8951 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 8952 8953 // We will compute the pointer operand of each store from the original base 8954 // address using GEPs. Cast the base address to a pointer to the scalar 8955 // element type. 8956 BaseAddr = Builder.CreateBitCast( 8957 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 8958 SI->getPointerAddressSpace())); 8959 } 8960 8961 auto Mask = SVI->getShuffleMask(); 8962 8963 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 8964 Type *Tys[2] = {SubVecTy, PtrTy}; 8965 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 8966 Intrinsic::aarch64_neon_st3, 8967 Intrinsic::aarch64_neon_st4}; 8968 Function *StNFunc = 8969 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 8970 8971 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 8972 8973 SmallVector<Value *, 5> Ops; 8974 8975 // Split the shufflevector operands into sub vectors for the new stN call. 8976 for (unsigned i = 0; i < Factor; i++) { 8977 unsigned IdxI = StoreCount * LaneLen * Factor + i; 8978 if (Mask[IdxI] >= 0) { 8979 Ops.push_back(Builder.CreateShuffleVector( 8980 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 8981 } else { 8982 unsigned StartMask = 0; 8983 for (unsigned j = 1; j < LaneLen; j++) { 8984 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 8985 if (Mask[IdxJ * Factor + IdxI] >= 0) { 8986 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 8987 break; 8988 } 8989 } 8990 // Note: Filling undef gaps with random elements is ok, since 8991 // those elements were being written anyway (with undefs). 8992 // In the case of all undefs we're defaulting to using elems from 0 8993 // Note: StartMask cannot be negative, it's checked in 8994 // isReInterleaveMask 8995 Ops.push_back(Builder.CreateShuffleVector( 8996 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 8997 } 8998 } 8999 9000 // If we generating more than one store, we compute the base address of 9001 // subsequent stores as an offset from the previous. 9002 if (StoreCount > 0) 9003 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 9004 BaseAddr, LaneLen * Factor); 9005 9006 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 9007 Builder.CreateCall(StNFunc, Ops); 9008 } 9009 return true; 9010 } 9011 9012 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 9013 unsigned AlignCheck) { 9014 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 9015 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 9016 } 9017 9018 EVT AArch64TargetLowering::getOptimalMemOpType( 9019 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 9020 bool ZeroMemset, bool MemcpyStrSrc, 9021 const AttributeList &FuncAttributes) const { 9022 bool CanImplicitFloat = 9023 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9024 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9025 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9026 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9027 // taken one instruction to materialize the v2i64 zero and one store (with 9028 // restrictive addressing mode). Just do i64 stores. 9029 bool IsSmallMemset = IsMemset && Size < 32; 9030 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) { 9031 if (memOpAlign(SrcAlign, DstAlign, AlignCheck)) 9032 return true; 9033 bool Fast; 9034 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9035 &Fast) && 9036 Fast; 9037 }; 9038 9039 if (CanUseNEON && IsMemset && !IsSmallMemset && 9040 AlignmentIsAcceptable(MVT::v2i64, 16)) 9041 return MVT::v2i64; 9042 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16)) 9043 return MVT::f128; 9044 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8)) 9045 return MVT::i64; 9046 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4)) 9047 return MVT::i32; 9048 return MVT::Other; 9049 } 9050 9051 LLT AArch64TargetLowering::getOptimalMemOpLLT( 9052 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 9053 bool ZeroMemset, bool MemcpyStrSrc, 9054 const AttributeList &FuncAttributes) const { 9055 bool CanImplicitFloat = 9056 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9057 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9058 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9059 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9060 // taken one instruction to materialize the v2i64 zero and one store (with 9061 // restrictive addressing mode). Just do i64 stores. 9062 bool IsSmallMemset = IsMemset && Size < 32; 9063 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) { 9064 if (memOpAlign(SrcAlign, DstAlign, AlignCheck)) 9065 return true; 9066 bool Fast; 9067 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9068 &Fast) && 9069 Fast; 9070 }; 9071 9072 if (CanUseNEON && IsMemset && !IsSmallMemset && 9073 AlignmentIsAcceptable(MVT::v2i64, 16)) 9074 return LLT::vector(2, 64); 9075 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16)) 9076 return LLT::scalar(128); 9077 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8)) 9078 return LLT::scalar(64); 9079 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4)) 9080 return LLT::scalar(32); 9081 return LLT(); 9082 } 9083 9084 // 12-bit optionally shifted immediates are legal for adds. 9085 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 9086 if (Immed == std::numeric_limits<int64_t>::min()) { 9087 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 9088 << ": avoid UB for INT64_MIN\n"); 9089 return false; 9090 } 9091 // Same encoding for add/sub, just flip the sign. 9092 Immed = std::abs(Immed); 9093 bool IsLegal = ((Immed >> 12) == 0 || 9094 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 9095 LLVM_DEBUG(dbgs() << "Is " << Immed 9096 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 9097 return IsLegal; 9098 } 9099 9100 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 9101 // immediates is the same as for an add or a sub. 9102 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 9103 return isLegalAddImmediate(Immed); 9104 } 9105 9106 /// isLegalAddressingMode - Return true if the addressing mode represented 9107 /// by AM is legal for this target, for a load/store of the specified type. 9108 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 9109 const AddrMode &AM, Type *Ty, 9110 unsigned AS, Instruction *I) const { 9111 // AArch64 has five basic addressing modes: 9112 // reg 9113 // reg + 9-bit signed offset 9114 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 9115 // reg1 + reg2 9116 // reg + SIZE_IN_BYTES * reg 9117 9118 // No global is ever allowed as a base. 9119 if (AM.BaseGV) 9120 return false; 9121 9122 // No reg+reg+imm addressing. 9123 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 9124 return false; 9125 9126 // check reg + imm case: 9127 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 9128 uint64_t NumBytes = 0; 9129 if (Ty->isSized()) { 9130 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 9131 NumBytes = NumBits / 8; 9132 if (!isPowerOf2_64(NumBits)) 9133 NumBytes = 0; 9134 } 9135 9136 if (!AM.Scale) { 9137 int64_t Offset = AM.BaseOffs; 9138 9139 // 9-bit signed offset 9140 if (isInt<9>(Offset)) 9141 return true; 9142 9143 // 12-bit unsigned offset 9144 unsigned shift = Log2_64(NumBytes); 9145 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 9146 // Must be a multiple of NumBytes (NumBytes is a power of 2) 9147 (Offset >> shift) << shift == Offset) 9148 return true; 9149 return false; 9150 } 9151 9152 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 9153 9154 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 9155 } 9156 9157 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 9158 // Consider splitting large offset of struct or array. 9159 return true; 9160 } 9161 9162 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 9163 const AddrMode &AM, Type *Ty, 9164 unsigned AS) const { 9165 // Scaling factors are not free at all. 9166 // Operands | Rt Latency 9167 // ------------------------------------------- 9168 // Rt, [Xn, Xm] | 4 9169 // ------------------------------------------- 9170 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 9171 // Rt, [Xn, Wm, <extend> #imm] | 9172 if (isLegalAddressingMode(DL, AM, Ty, AS)) 9173 // Scale represents reg2 * scale, thus account for 1 if 9174 // it is not equal to 0 or 1. 9175 return AM.Scale != 0 && AM.Scale != 1; 9176 return -1; 9177 } 9178 9179 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 9180 VT = VT.getScalarType(); 9181 9182 if (!VT.isSimple()) 9183 return false; 9184 9185 switch (VT.getSimpleVT().SimpleTy) { 9186 case MVT::f32: 9187 case MVT::f64: 9188 return true; 9189 default: 9190 break; 9191 } 9192 9193 return false; 9194 } 9195 9196 const MCPhysReg * 9197 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 9198 // LR is a callee-save register, but we must treat it as clobbered by any call 9199 // site. Hence we include LR in the scratch registers, which are in turn added 9200 // as implicit-defs for stackmaps and patchpoints. 9201 static const MCPhysReg ScratchRegs[] = { 9202 AArch64::X16, AArch64::X17, AArch64::LR, 0 9203 }; 9204 return ScratchRegs; 9205 } 9206 9207 bool 9208 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 9209 CombineLevel Level) const { 9210 N = N->getOperand(0).getNode(); 9211 EVT VT = N->getValueType(0); 9212 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 9213 // it with shift to let it be lowered to UBFX. 9214 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 9215 isa<ConstantSDNode>(N->getOperand(1))) { 9216 uint64_t TruncMask = N->getConstantOperandVal(1); 9217 if (isMask_64(TruncMask) && 9218 N->getOperand(0).getOpcode() == ISD::SRL && 9219 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 9220 return false; 9221 } 9222 return true; 9223 } 9224 9225 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 9226 Type *Ty) const { 9227 assert(Ty->isIntegerTy()); 9228 9229 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 9230 if (BitSize == 0) 9231 return false; 9232 9233 int64_t Val = Imm.getSExtValue(); 9234 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 9235 return true; 9236 9237 if ((int64_t)Val < 0) 9238 Val = ~Val; 9239 if (BitSize == 32) 9240 Val &= (1LL << 32) - 1; 9241 9242 unsigned LZ = countLeadingZeros((uint64_t)Val); 9243 unsigned Shift = (63 - LZ) / 16; 9244 // MOVZ is free so return true for one or fewer MOVK. 9245 return Shift < 3; 9246 } 9247 9248 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 9249 unsigned Index) const { 9250 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 9251 return false; 9252 9253 return (Index == 0 || Index == ResVT.getVectorNumElements()); 9254 } 9255 9256 /// Turn vector tests of the signbit in the form of: 9257 /// xor (sra X, elt_size(X)-1), -1 9258 /// into: 9259 /// cmge X, X, #0 9260 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 9261 const AArch64Subtarget *Subtarget) { 9262 EVT VT = N->getValueType(0); 9263 if (!Subtarget->hasNEON() || !VT.isVector()) 9264 return SDValue(); 9265 9266 // There must be a shift right algebraic before the xor, and the xor must be a 9267 // 'not' operation. 9268 SDValue Shift = N->getOperand(0); 9269 SDValue Ones = N->getOperand(1); 9270 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 9271 !ISD::isBuildVectorAllOnes(Ones.getNode())) 9272 return SDValue(); 9273 9274 // The shift should be smearing the sign bit across each vector element. 9275 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 9276 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 9277 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 9278 return SDValue(); 9279 9280 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 9281 } 9282 9283 // Generate SUBS and CSEL for integer abs. 9284 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 9285 EVT VT = N->getValueType(0); 9286 9287 SDValue N0 = N->getOperand(0); 9288 SDValue N1 = N->getOperand(1); 9289 SDLoc DL(N); 9290 9291 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 9292 // and change it to SUB and CSEL. 9293 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 9294 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 9295 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 9296 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 9297 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 9298 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 9299 N0.getOperand(0)); 9300 // Generate SUBS & CSEL. 9301 SDValue Cmp = 9302 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 9303 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 9304 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 9305 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 9306 SDValue(Cmp.getNode(), 1)); 9307 } 9308 return SDValue(); 9309 } 9310 9311 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 9312 TargetLowering::DAGCombinerInfo &DCI, 9313 const AArch64Subtarget *Subtarget) { 9314 if (DCI.isBeforeLegalizeOps()) 9315 return SDValue(); 9316 9317 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 9318 return Cmp; 9319 9320 return performIntegerAbsCombine(N, DAG); 9321 } 9322 9323 SDValue 9324 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9325 SelectionDAG &DAG, 9326 SmallVectorImpl<SDNode *> &Created) const { 9327 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 9328 if (isIntDivCheap(N->getValueType(0), Attr)) 9329 return SDValue(N,0); // Lower SDIV as SDIV 9330 9331 // fold (sdiv X, pow2) 9332 EVT VT = N->getValueType(0); 9333 if ((VT != MVT::i32 && VT != MVT::i64) || 9334 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 9335 return SDValue(); 9336 9337 SDLoc DL(N); 9338 SDValue N0 = N->getOperand(0); 9339 unsigned Lg2 = Divisor.countTrailingZeros(); 9340 SDValue Zero = DAG.getConstant(0, DL, VT); 9341 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 9342 9343 // Add (N0 < 0) ? Pow2 - 1 : 0; 9344 SDValue CCVal; 9345 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 9346 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 9347 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 9348 9349 Created.push_back(Cmp.getNode()); 9350 Created.push_back(Add.getNode()); 9351 Created.push_back(CSel.getNode()); 9352 9353 // Divide by pow2. 9354 SDValue SRA = 9355 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 9356 9357 // If we're dividing by a positive value, we're done. Otherwise, we must 9358 // negate the result. 9359 if (Divisor.isNonNegative()) 9360 return SRA; 9361 9362 Created.push_back(SRA.getNode()); 9363 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 9364 } 9365 9366 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 9367 TargetLowering::DAGCombinerInfo &DCI, 9368 const AArch64Subtarget *Subtarget) { 9369 if (DCI.isBeforeLegalizeOps()) 9370 return SDValue(); 9371 9372 // The below optimizations require a constant RHS. 9373 if (!isa<ConstantSDNode>(N->getOperand(1))) 9374 return SDValue(); 9375 9376 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 9377 const APInt &ConstValue = C->getAPIntValue(); 9378 9379 // Multiplication of a power of two plus/minus one can be done more 9380 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 9381 // future CPUs have a cheaper MADD instruction, this may need to be 9382 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 9383 // 64-bit is 5 cycles, so this is always a win. 9384 // More aggressively, some multiplications N0 * C can be lowered to 9385 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 9386 // e.g. 6=3*2=(2+1)*2. 9387 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 9388 // which equals to (1+2)*16-(1+2). 9389 SDValue N0 = N->getOperand(0); 9390 // TrailingZeroes is used to test if the mul can be lowered to 9391 // shift+add+shift. 9392 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 9393 if (TrailingZeroes) { 9394 // Conservatively do not lower to shift+add+shift if the mul might be 9395 // folded into smul or umul. 9396 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 9397 isZeroExtended(N0.getNode(), DAG))) 9398 return SDValue(); 9399 // Conservatively do not lower to shift+add+shift if the mul might be 9400 // folded into madd or msub. 9401 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 9402 N->use_begin()->getOpcode() == ISD::SUB)) 9403 return SDValue(); 9404 } 9405 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 9406 // and shift+add+shift. 9407 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 9408 9409 unsigned ShiftAmt, AddSubOpc; 9410 // Is the shifted value the LHS operand of the add/sub? 9411 bool ShiftValUseIsN0 = true; 9412 // Do we need to negate the result? 9413 bool NegateResult = false; 9414 9415 if (ConstValue.isNonNegative()) { 9416 // (mul x, 2^N + 1) => (add (shl x, N), x) 9417 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9418 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 9419 APInt SCVMinus1 = ShiftedConstValue - 1; 9420 APInt CVPlus1 = ConstValue + 1; 9421 if (SCVMinus1.isPowerOf2()) { 9422 ShiftAmt = SCVMinus1.logBase2(); 9423 AddSubOpc = ISD::ADD; 9424 } else if (CVPlus1.isPowerOf2()) { 9425 ShiftAmt = CVPlus1.logBase2(); 9426 AddSubOpc = ISD::SUB; 9427 } else 9428 return SDValue(); 9429 } else { 9430 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9431 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9432 APInt CVNegPlus1 = -ConstValue + 1; 9433 APInt CVNegMinus1 = -ConstValue - 1; 9434 if (CVNegPlus1.isPowerOf2()) { 9435 ShiftAmt = CVNegPlus1.logBase2(); 9436 AddSubOpc = ISD::SUB; 9437 ShiftValUseIsN0 = false; 9438 } else if (CVNegMinus1.isPowerOf2()) { 9439 ShiftAmt = CVNegMinus1.logBase2(); 9440 AddSubOpc = ISD::ADD; 9441 NegateResult = true; 9442 } else 9443 return SDValue(); 9444 } 9445 9446 SDLoc DL(N); 9447 EVT VT = N->getValueType(0); 9448 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 9449 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 9450 9451 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 9452 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 9453 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 9454 assert(!(NegateResult && TrailingZeroes) && 9455 "NegateResult and TrailingZeroes cannot both be true for now."); 9456 // Negate the result. 9457 if (NegateResult) 9458 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 9459 // Shift the result. 9460 if (TrailingZeroes) 9461 return DAG.getNode(ISD::SHL, DL, VT, Res, 9462 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 9463 return Res; 9464 } 9465 9466 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 9467 SelectionDAG &DAG) { 9468 // Take advantage of vector comparisons producing 0 or -1 in each lane to 9469 // optimize away operation when it's from a constant. 9470 // 9471 // The general transformation is: 9472 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 9473 // AND(VECTOR_CMP(x,y), constant2) 9474 // constant2 = UNARYOP(constant) 9475 9476 // Early exit if this isn't a vector operation, the operand of the 9477 // unary operation isn't a bitwise AND, or if the sizes of the operations 9478 // aren't the same. 9479 EVT VT = N->getValueType(0); 9480 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 9481 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 9482 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 9483 return SDValue(); 9484 9485 // Now check that the other operand of the AND is a constant. We could 9486 // make the transformation for non-constant splats as well, but it's unclear 9487 // that would be a benefit as it would not eliminate any operations, just 9488 // perform one more step in scalar code before moving to the vector unit. 9489 if (BuildVectorSDNode *BV = 9490 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 9491 // Bail out if the vector isn't a constant. 9492 if (!BV->isConstant()) 9493 return SDValue(); 9494 9495 // Everything checks out. Build up the new and improved node. 9496 SDLoc DL(N); 9497 EVT IntVT = BV->getValueType(0); 9498 // Create a new constant of the appropriate type for the transformed 9499 // DAG. 9500 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 9501 // The AND node needs bitcasts to/from an integer vector type around it. 9502 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 9503 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 9504 N->getOperand(0)->getOperand(0), MaskConst); 9505 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 9506 return Res; 9507 } 9508 9509 return SDValue(); 9510 } 9511 9512 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 9513 const AArch64Subtarget *Subtarget) { 9514 // First try to optimize away the conversion when it's conditionally from 9515 // a constant. Vectors only. 9516 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 9517 return Res; 9518 9519 EVT VT = N->getValueType(0); 9520 if (VT != MVT::f32 && VT != MVT::f64) 9521 return SDValue(); 9522 9523 // Only optimize when the source and destination types have the same width. 9524 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 9525 return SDValue(); 9526 9527 // If the result of an integer load is only used by an integer-to-float 9528 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 9529 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 9530 SDValue N0 = N->getOperand(0); 9531 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9532 // Do not change the width of a volatile load. 9533 !cast<LoadSDNode>(N0)->isVolatile()) { 9534 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9535 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 9536 LN0->getPointerInfo(), LN0->getAlignment(), 9537 LN0->getMemOperand()->getFlags()); 9538 9539 // Make sure successors of the original load stay after it by updating them 9540 // to use the new Chain. 9541 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 9542 9543 unsigned Opcode = 9544 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 9545 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 9546 } 9547 9548 return SDValue(); 9549 } 9550 9551 /// Fold a floating-point multiply by power of two into floating-point to 9552 /// fixed-point conversion. 9553 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 9554 TargetLowering::DAGCombinerInfo &DCI, 9555 const AArch64Subtarget *Subtarget) { 9556 if (!Subtarget->hasNEON()) 9557 return SDValue(); 9558 9559 if (!N->getValueType(0).isSimple()) 9560 return SDValue(); 9561 9562 SDValue Op = N->getOperand(0); 9563 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 9564 Op.getOpcode() != ISD::FMUL) 9565 return SDValue(); 9566 9567 SDValue ConstVec = Op->getOperand(1); 9568 if (!isa<BuildVectorSDNode>(ConstVec)) 9569 return SDValue(); 9570 9571 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 9572 uint32_t FloatBits = FloatTy.getSizeInBits(); 9573 if (FloatBits != 32 && FloatBits != 64) 9574 return SDValue(); 9575 9576 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 9577 uint32_t IntBits = IntTy.getSizeInBits(); 9578 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 9579 return SDValue(); 9580 9581 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 9582 if (IntBits > FloatBits) 9583 return SDValue(); 9584 9585 BitVector UndefElements; 9586 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 9587 int32_t Bits = IntBits == 64 ? 64 : 32; 9588 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 9589 if (C == -1 || C == 0 || C > Bits) 9590 return SDValue(); 9591 9592 MVT ResTy; 9593 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9594 switch (NumLanes) { 9595 default: 9596 return SDValue(); 9597 case 2: 9598 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 9599 break; 9600 case 4: 9601 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 9602 break; 9603 } 9604 9605 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 9606 return SDValue(); 9607 9608 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 9609 "Illegal vector type after legalization"); 9610 9611 SDLoc DL(N); 9612 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 9613 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 9614 : Intrinsic::aarch64_neon_vcvtfp2fxu; 9615 SDValue FixConv = 9616 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 9617 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 9618 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 9619 // We can handle smaller integers by generating an extra trunc. 9620 if (IntBits < FloatBits) 9621 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 9622 9623 return FixConv; 9624 } 9625 9626 /// Fold a floating-point divide by power of two into fixed-point to 9627 /// floating-point conversion. 9628 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 9629 TargetLowering::DAGCombinerInfo &DCI, 9630 const AArch64Subtarget *Subtarget) { 9631 if (!Subtarget->hasNEON()) 9632 return SDValue(); 9633 9634 SDValue Op = N->getOperand(0); 9635 unsigned Opc = Op->getOpcode(); 9636 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 9637 !Op.getOperand(0).getValueType().isSimple() || 9638 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 9639 return SDValue(); 9640 9641 SDValue ConstVec = N->getOperand(1); 9642 if (!isa<BuildVectorSDNode>(ConstVec)) 9643 return SDValue(); 9644 9645 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 9646 int32_t IntBits = IntTy.getSizeInBits(); 9647 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 9648 return SDValue(); 9649 9650 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 9651 int32_t FloatBits = FloatTy.getSizeInBits(); 9652 if (FloatBits != 32 && FloatBits != 64) 9653 return SDValue(); 9654 9655 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 9656 if (IntBits > FloatBits) 9657 return SDValue(); 9658 9659 BitVector UndefElements; 9660 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 9661 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 9662 if (C == -1 || C == 0 || C > FloatBits) 9663 return SDValue(); 9664 9665 MVT ResTy; 9666 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9667 switch (NumLanes) { 9668 default: 9669 return SDValue(); 9670 case 2: 9671 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 9672 break; 9673 case 4: 9674 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 9675 break; 9676 } 9677 9678 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 9679 return SDValue(); 9680 9681 SDLoc DL(N); 9682 SDValue ConvInput = Op.getOperand(0); 9683 bool IsSigned = Opc == ISD::SINT_TO_FP; 9684 if (IntBits < FloatBits) 9685 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 9686 ResTy, ConvInput); 9687 9688 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 9689 : Intrinsic::aarch64_neon_vcvtfxu2fp; 9690 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 9691 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 9692 DAG.getConstant(C, DL, MVT::i32)); 9693 } 9694 9695 /// An EXTR instruction is made up of two shifts, ORed together. This helper 9696 /// searches for and classifies those shifts. 9697 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 9698 bool &FromHi) { 9699 if (N.getOpcode() == ISD::SHL) 9700 FromHi = false; 9701 else if (N.getOpcode() == ISD::SRL) 9702 FromHi = true; 9703 else 9704 return false; 9705 9706 if (!isa<ConstantSDNode>(N.getOperand(1))) 9707 return false; 9708 9709 ShiftAmount = N->getConstantOperandVal(1); 9710 Src = N->getOperand(0); 9711 return true; 9712 } 9713 9714 /// EXTR instruction extracts a contiguous chunk of bits from two existing 9715 /// registers viewed as a high/low pair. This function looks for the pattern: 9716 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 9717 /// with an EXTR. Can't quite be done in TableGen because the two immediates 9718 /// aren't independent. 9719 static SDValue tryCombineToEXTR(SDNode *N, 9720 TargetLowering::DAGCombinerInfo &DCI) { 9721 SelectionDAG &DAG = DCI.DAG; 9722 SDLoc DL(N); 9723 EVT VT = N->getValueType(0); 9724 9725 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 9726 9727 if (VT != MVT::i32 && VT != MVT::i64) 9728 return SDValue(); 9729 9730 SDValue LHS; 9731 uint32_t ShiftLHS = 0; 9732 bool LHSFromHi = false; 9733 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 9734 return SDValue(); 9735 9736 SDValue RHS; 9737 uint32_t ShiftRHS = 0; 9738 bool RHSFromHi = false; 9739 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 9740 return SDValue(); 9741 9742 // If they're both trying to come from the high part of the register, they're 9743 // not really an EXTR. 9744 if (LHSFromHi == RHSFromHi) 9745 return SDValue(); 9746 9747 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 9748 return SDValue(); 9749 9750 if (LHSFromHi) { 9751 std::swap(LHS, RHS); 9752 std::swap(ShiftLHS, ShiftRHS); 9753 } 9754 9755 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 9756 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 9757 } 9758 9759 static SDValue tryCombineToBSL(SDNode *N, 9760 TargetLowering::DAGCombinerInfo &DCI) { 9761 EVT VT = N->getValueType(0); 9762 SelectionDAG &DAG = DCI.DAG; 9763 SDLoc DL(N); 9764 9765 if (!VT.isVector()) 9766 return SDValue(); 9767 9768 SDValue N0 = N->getOperand(0); 9769 if (N0.getOpcode() != ISD::AND) 9770 return SDValue(); 9771 9772 SDValue N1 = N->getOperand(1); 9773 if (N1.getOpcode() != ISD::AND) 9774 return SDValue(); 9775 9776 // We only have to look for constant vectors here since the general, variable 9777 // case can be handled in TableGen. 9778 unsigned Bits = VT.getScalarSizeInBits(); 9779 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 9780 for (int i = 1; i >= 0; --i) 9781 for (int j = 1; j >= 0; --j) { 9782 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 9783 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 9784 if (!BVN0 || !BVN1) 9785 continue; 9786 9787 bool FoundMatch = true; 9788 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 9789 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 9790 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 9791 if (!CN0 || !CN1 || 9792 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 9793 FoundMatch = false; 9794 break; 9795 } 9796 } 9797 9798 if (FoundMatch) 9799 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 9800 N0->getOperand(1 - i), N1->getOperand(1 - j)); 9801 } 9802 9803 return SDValue(); 9804 } 9805 9806 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 9807 const AArch64Subtarget *Subtarget) { 9808 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 9809 SelectionDAG &DAG = DCI.DAG; 9810 EVT VT = N->getValueType(0); 9811 9812 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9813 return SDValue(); 9814 9815 if (SDValue Res = tryCombineToEXTR(N, DCI)) 9816 return Res; 9817 9818 if (SDValue Res = tryCombineToBSL(N, DCI)) 9819 return Res; 9820 9821 return SDValue(); 9822 } 9823 9824 static SDValue performANDCombine(SDNode *N, 9825 TargetLowering::DAGCombinerInfo &DCI) { 9826 SelectionDAG &DAG = DCI.DAG; 9827 SDValue LHS = N->getOperand(0); 9828 EVT VT = N->getValueType(0); 9829 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9830 return SDValue(); 9831 9832 BuildVectorSDNode *BVN = 9833 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 9834 if (!BVN) 9835 return SDValue(); 9836 9837 // AND does not accept an immediate, so check if we can use a BIC immediate 9838 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 9839 // pattern in isel, because some immediates may be lowered to the preferred 9840 // (and x, (movi imm)) form, even though an mvni representation also exists. 9841 APInt DefBits(VT.getSizeInBits(), 0); 9842 APInt UndefBits(VT.getSizeInBits(), 0); 9843 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9844 SDValue NewOp; 9845 9846 DefBits = ~DefBits; 9847 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 9848 DefBits, &LHS)) || 9849 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 9850 DefBits, &LHS))) 9851 return NewOp; 9852 9853 UndefBits = ~UndefBits; 9854 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 9855 UndefBits, &LHS)) || 9856 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 9857 UndefBits, &LHS))) 9858 return NewOp; 9859 } 9860 9861 return SDValue(); 9862 } 9863 9864 static SDValue performSRLCombine(SDNode *N, 9865 TargetLowering::DAGCombinerInfo &DCI) { 9866 SelectionDAG &DAG = DCI.DAG; 9867 EVT VT = N->getValueType(0); 9868 if (VT != MVT::i32 && VT != MVT::i64) 9869 return SDValue(); 9870 9871 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 9872 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 9873 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 9874 SDValue N0 = N->getOperand(0); 9875 if (N0.getOpcode() == ISD::BSWAP) { 9876 SDLoc DL(N); 9877 SDValue N1 = N->getOperand(1); 9878 SDValue N00 = N0.getOperand(0); 9879 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 9880 uint64_t ShiftAmt = C->getZExtValue(); 9881 if (VT == MVT::i32 && ShiftAmt == 16 && 9882 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 9883 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 9884 if (VT == MVT::i64 && ShiftAmt == 32 && 9885 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 9886 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 9887 } 9888 } 9889 return SDValue(); 9890 } 9891 9892 static SDValue performBitcastCombine(SDNode *N, 9893 TargetLowering::DAGCombinerInfo &DCI, 9894 SelectionDAG &DAG) { 9895 // Wait 'til after everything is legalized to try this. That way we have 9896 // legal vector types and such. 9897 if (DCI.isBeforeLegalizeOps()) 9898 return SDValue(); 9899 9900 // Remove extraneous bitcasts around an extract_subvector. 9901 // For example, 9902 // (v4i16 (bitconvert 9903 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 9904 // becomes 9905 // (extract_subvector ((v8i16 ...), (i64 4))) 9906 9907 // Only interested in 64-bit vectors as the ultimate result. 9908 EVT VT = N->getValueType(0); 9909 if (!VT.isVector()) 9910 return SDValue(); 9911 if (VT.getSimpleVT().getSizeInBits() != 64) 9912 return SDValue(); 9913 // Is the operand an extract_subvector starting at the beginning or halfway 9914 // point of the vector? A low half may also come through as an 9915 // EXTRACT_SUBREG, so look for that, too. 9916 SDValue Op0 = N->getOperand(0); 9917 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 9918 !(Op0->isMachineOpcode() && 9919 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 9920 return SDValue(); 9921 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 9922 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 9923 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 9924 return SDValue(); 9925 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 9926 if (idx != AArch64::dsub) 9927 return SDValue(); 9928 // The dsub reference is equivalent to a lane zero subvector reference. 9929 idx = 0; 9930 } 9931 // Look through the bitcast of the input to the extract. 9932 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 9933 return SDValue(); 9934 SDValue Source = Op0->getOperand(0)->getOperand(0); 9935 // If the source type has twice the number of elements as our destination 9936 // type, we know this is an extract of the high or low half of the vector. 9937 EVT SVT = Source->getValueType(0); 9938 if (!SVT.isVector() || 9939 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 9940 return SDValue(); 9941 9942 LLVM_DEBUG( 9943 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 9944 9945 // Create the simplified form to just extract the low or high half of the 9946 // vector directly rather than bothering with the bitcasts. 9947 SDLoc dl(N); 9948 unsigned NumElements = VT.getVectorNumElements(); 9949 if (idx) { 9950 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 9951 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 9952 } else { 9953 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 9954 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 9955 Source, SubReg), 9956 0); 9957 } 9958 } 9959 9960 static SDValue performConcatVectorsCombine(SDNode *N, 9961 TargetLowering::DAGCombinerInfo &DCI, 9962 SelectionDAG &DAG) { 9963 SDLoc dl(N); 9964 EVT VT = N->getValueType(0); 9965 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 9966 9967 // Optimize concat_vectors of truncated vectors, where the intermediate 9968 // type is illegal, to avoid said illegality, e.g., 9969 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 9970 // (v2i16 (truncate (v2i64))))) 9971 // -> 9972 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 9973 // (v4i32 (bitcast (v2i64))), 9974 // <0, 2, 4, 6>))) 9975 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 9976 // on both input and result type, so we might generate worse code. 9977 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 9978 if (N->getNumOperands() == 2 && 9979 N0->getOpcode() == ISD::TRUNCATE && 9980 N1->getOpcode() == ISD::TRUNCATE) { 9981 SDValue N00 = N0->getOperand(0); 9982 SDValue N10 = N1->getOperand(0); 9983 EVT N00VT = N00.getValueType(); 9984 9985 if (N00VT == N10.getValueType() && 9986 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 9987 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 9988 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 9989 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 9990 for (size_t i = 0; i < Mask.size(); ++i) 9991 Mask[i] = i * 2; 9992 return DAG.getNode(ISD::TRUNCATE, dl, VT, 9993 DAG.getVectorShuffle( 9994 MidVT, dl, 9995 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 9996 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 9997 } 9998 } 9999 10000 // Wait 'til after everything is legalized to try this. That way we have 10001 // legal vector types and such. 10002 if (DCI.isBeforeLegalizeOps()) 10003 return SDValue(); 10004 10005 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 10006 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 10007 // canonicalise to that. 10008 if (N0 == N1 && VT.getVectorNumElements() == 2) { 10009 assert(VT.getScalarSizeInBits() == 64); 10010 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 10011 DAG.getConstant(0, dl, MVT::i64)); 10012 } 10013 10014 // Canonicalise concat_vectors so that the right-hand vector has as few 10015 // bit-casts as possible before its real operation. The primary matching 10016 // destination for these operations will be the narrowing "2" instructions, 10017 // which depend on the operation being performed on this right-hand vector. 10018 // For example, 10019 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 10020 // becomes 10021 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 10022 10023 if (N1->getOpcode() != ISD::BITCAST) 10024 return SDValue(); 10025 SDValue RHS = N1->getOperand(0); 10026 MVT RHSTy = RHS.getValueType().getSimpleVT(); 10027 // If the RHS is not a vector, this is not the pattern we're looking for. 10028 if (!RHSTy.isVector()) 10029 return SDValue(); 10030 10031 LLVM_DEBUG( 10032 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 10033 10034 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 10035 RHSTy.getVectorNumElements() * 2); 10036 return DAG.getNode(ISD::BITCAST, dl, VT, 10037 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 10038 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 10039 RHS)); 10040 } 10041 10042 static SDValue tryCombineFixedPointConvert(SDNode *N, 10043 TargetLowering::DAGCombinerInfo &DCI, 10044 SelectionDAG &DAG) { 10045 // Wait until after everything is legalized to try this. That way we have 10046 // legal vector types and such. 10047 if (DCI.isBeforeLegalizeOps()) 10048 return SDValue(); 10049 // Transform a scalar conversion of a value from a lane extract into a 10050 // lane extract of a vector conversion. E.g., from foo1 to foo2: 10051 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 10052 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 10053 // 10054 // The second form interacts better with instruction selection and the 10055 // register allocator to avoid cross-class register copies that aren't 10056 // coalescable due to a lane reference. 10057 10058 // Check the operand and see if it originates from a lane extract. 10059 SDValue Op1 = N->getOperand(1); 10060 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10061 // Yep, no additional predication needed. Perform the transform. 10062 SDValue IID = N->getOperand(0); 10063 SDValue Shift = N->getOperand(2); 10064 SDValue Vec = Op1.getOperand(0); 10065 SDValue Lane = Op1.getOperand(1); 10066 EVT ResTy = N->getValueType(0); 10067 EVT VecResTy; 10068 SDLoc DL(N); 10069 10070 // The vector width should be 128 bits by the time we get here, even 10071 // if it started as 64 bits (the extract_vector handling will have 10072 // done so). 10073 assert(Vec.getValueSizeInBits() == 128 && 10074 "unexpected vector size on extract_vector_elt!"); 10075 if (Vec.getValueType() == MVT::v4i32) 10076 VecResTy = MVT::v4f32; 10077 else if (Vec.getValueType() == MVT::v2i64) 10078 VecResTy = MVT::v2f64; 10079 else 10080 llvm_unreachable("unexpected vector type!"); 10081 10082 SDValue Convert = 10083 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 10084 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 10085 } 10086 return SDValue(); 10087 } 10088 10089 // AArch64 high-vector "long" operations are formed by performing the non-high 10090 // version on an extract_subvector of each operand which gets the high half: 10091 // 10092 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 10093 // 10094 // However, there are cases which don't have an extract_high explicitly, but 10095 // have another operation that can be made compatible with one for free. For 10096 // example: 10097 // 10098 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 10099 // 10100 // This routine does the actual conversion of such DUPs, once outer routines 10101 // have determined that everything else is in order. 10102 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 10103 // similarly here. 10104 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 10105 switch (N.getOpcode()) { 10106 case AArch64ISD::DUP: 10107 case AArch64ISD::DUPLANE8: 10108 case AArch64ISD::DUPLANE16: 10109 case AArch64ISD::DUPLANE32: 10110 case AArch64ISD::DUPLANE64: 10111 case AArch64ISD::MOVI: 10112 case AArch64ISD::MOVIshift: 10113 case AArch64ISD::MOVIedit: 10114 case AArch64ISD::MOVImsl: 10115 case AArch64ISD::MVNIshift: 10116 case AArch64ISD::MVNImsl: 10117 break; 10118 default: 10119 // FMOV could be supported, but isn't very useful, as it would only occur 10120 // if you passed a bitcast' floating point immediate to an eligible long 10121 // integer op (addl, smull, ...). 10122 return SDValue(); 10123 } 10124 10125 MVT NarrowTy = N.getSimpleValueType(); 10126 if (!NarrowTy.is64BitVector()) 10127 return SDValue(); 10128 10129 MVT ElementTy = NarrowTy.getVectorElementType(); 10130 unsigned NumElems = NarrowTy.getVectorNumElements(); 10131 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 10132 10133 SDLoc dl(N); 10134 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 10135 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 10136 DAG.getConstant(NumElems, dl, MVT::i64)); 10137 } 10138 10139 static bool isEssentiallyExtractHighSubvector(SDValue N) { 10140 if (N.getOpcode() == ISD::BITCAST) 10141 N = N.getOperand(0); 10142 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10143 return false; 10144 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 10145 N.getOperand(0).getValueType().getVectorNumElements() / 2; 10146 } 10147 10148 /// Helper structure to keep track of ISD::SET_CC operands. 10149 struct GenericSetCCInfo { 10150 const SDValue *Opnd0; 10151 const SDValue *Opnd1; 10152 ISD::CondCode CC; 10153 }; 10154 10155 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 10156 struct AArch64SetCCInfo { 10157 const SDValue *Cmp; 10158 AArch64CC::CondCode CC; 10159 }; 10160 10161 /// Helper structure to keep track of SetCC information. 10162 union SetCCInfo { 10163 GenericSetCCInfo Generic; 10164 AArch64SetCCInfo AArch64; 10165 }; 10166 10167 /// Helper structure to be able to read SetCC information. If set to 10168 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 10169 /// GenericSetCCInfo. 10170 struct SetCCInfoAndKind { 10171 SetCCInfo Info; 10172 bool IsAArch64; 10173 }; 10174 10175 /// Check whether or not \p Op is a SET_CC operation, either a generic or 10176 /// an 10177 /// AArch64 lowered one. 10178 /// \p SetCCInfo is filled accordingly. 10179 /// \post SetCCInfo is meanginfull only when this function returns true. 10180 /// \return True when Op is a kind of SET_CC operation. 10181 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 10182 // If this is a setcc, this is straight forward. 10183 if (Op.getOpcode() == ISD::SETCC) { 10184 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 10185 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 10186 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10187 SetCCInfo.IsAArch64 = false; 10188 return true; 10189 } 10190 // Otherwise, check if this is a matching csel instruction. 10191 // In other words: 10192 // - csel 1, 0, cc 10193 // - csel 0, 1, !cc 10194 if (Op.getOpcode() != AArch64ISD::CSEL) 10195 return false; 10196 // Set the information about the operands. 10197 // TODO: we want the operands of the Cmp not the csel 10198 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 10199 SetCCInfo.IsAArch64 = true; 10200 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 10201 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10202 10203 // Check that the operands matches the constraints: 10204 // (1) Both operands must be constants. 10205 // (2) One must be 1 and the other must be 0. 10206 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 10207 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10208 10209 // Check (1). 10210 if (!TValue || !FValue) 10211 return false; 10212 10213 // Check (2). 10214 if (!TValue->isOne()) { 10215 // Update the comparison when we are interested in !cc. 10216 std::swap(TValue, FValue); 10217 SetCCInfo.Info.AArch64.CC = 10218 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 10219 } 10220 return TValue->isOne() && FValue->isNullValue(); 10221 } 10222 10223 // Returns true if Op is setcc or zext of setcc. 10224 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 10225 if (isSetCC(Op, Info)) 10226 return true; 10227 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 10228 isSetCC(Op->getOperand(0), Info)); 10229 } 10230 10231 // The folding we want to perform is: 10232 // (add x, [zext] (setcc cc ...) ) 10233 // --> 10234 // (csel x, (add x, 1), !cc ...) 10235 // 10236 // The latter will get matched to a CSINC instruction. 10237 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 10238 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 10239 SDValue LHS = Op->getOperand(0); 10240 SDValue RHS = Op->getOperand(1); 10241 SetCCInfoAndKind InfoAndKind; 10242 10243 // If neither operand is a SET_CC, give up. 10244 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 10245 std::swap(LHS, RHS); 10246 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 10247 return SDValue(); 10248 } 10249 10250 // FIXME: This could be generatized to work for FP comparisons. 10251 EVT CmpVT = InfoAndKind.IsAArch64 10252 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 10253 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 10254 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 10255 return SDValue(); 10256 10257 SDValue CCVal; 10258 SDValue Cmp; 10259 SDLoc dl(Op); 10260 if (InfoAndKind.IsAArch64) { 10261 CCVal = DAG.getConstant( 10262 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 10263 MVT::i32); 10264 Cmp = *InfoAndKind.Info.AArch64.Cmp; 10265 } else 10266 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 10267 *InfoAndKind.Info.Generic.Opnd1, 10268 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 10269 CCVal, DAG, dl); 10270 10271 EVT VT = Op->getValueType(0); 10272 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 10273 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 10274 } 10275 10276 // The basic add/sub long vector instructions have variants with "2" on the end 10277 // which act on the high-half of their inputs. They are normally matched by 10278 // patterns like: 10279 // 10280 // (add (zeroext (extract_high LHS)), 10281 // (zeroext (extract_high RHS))) 10282 // -> uaddl2 vD, vN, vM 10283 // 10284 // However, if one of the extracts is something like a duplicate, this 10285 // instruction can still be used profitably. This function puts the DAG into a 10286 // more appropriate form for those patterns to trigger. 10287 static SDValue performAddSubLongCombine(SDNode *N, 10288 TargetLowering::DAGCombinerInfo &DCI, 10289 SelectionDAG &DAG) { 10290 if (DCI.isBeforeLegalizeOps()) 10291 return SDValue(); 10292 10293 MVT VT = N->getSimpleValueType(0); 10294 if (!VT.is128BitVector()) { 10295 if (N->getOpcode() == ISD::ADD) 10296 return performSetccAddFolding(N, DAG); 10297 return SDValue(); 10298 } 10299 10300 // Make sure both branches are extended in the same way. 10301 SDValue LHS = N->getOperand(0); 10302 SDValue RHS = N->getOperand(1); 10303 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 10304 LHS.getOpcode() != ISD::SIGN_EXTEND) || 10305 LHS.getOpcode() != RHS.getOpcode()) 10306 return SDValue(); 10307 10308 unsigned ExtType = LHS.getOpcode(); 10309 10310 // It's not worth doing if at least one of the inputs isn't already an 10311 // extract, but we don't know which it'll be so we have to try both. 10312 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 10313 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 10314 if (!RHS.getNode()) 10315 return SDValue(); 10316 10317 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 10318 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 10319 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 10320 if (!LHS.getNode()) 10321 return SDValue(); 10322 10323 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 10324 } 10325 10326 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 10327 } 10328 10329 // Massage DAGs which we can use the high-half "long" operations on into 10330 // something isel will recognize better. E.g. 10331 // 10332 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 10333 // (aarch64_neon_umull (extract_high (v2i64 vec))) 10334 // (extract_high (v2i64 (dup128 scalar))))) 10335 // 10336 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 10337 TargetLowering::DAGCombinerInfo &DCI, 10338 SelectionDAG &DAG) { 10339 if (DCI.isBeforeLegalizeOps()) 10340 return SDValue(); 10341 10342 SDValue LHS = N->getOperand(1); 10343 SDValue RHS = N->getOperand(2); 10344 assert(LHS.getValueType().is64BitVector() && 10345 RHS.getValueType().is64BitVector() && 10346 "unexpected shape for long operation"); 10347 10348 // Either node could be a DUP, but it's not worth doing both of them (you'd 10349 // just as well use the non-high version) so look for a corresponding extract 10350 // operation on the other "wing". 10351 if (isEssentiallyExtractHighSubvector(LHS)) { 10352 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 10353 if (!RHS.getNode()) 10354 return SDValue(); 10355 } else if (isEssentiallyExtractHighSubvector(RHS)) { 10356 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 10357 if (!LHS.getNode()) 10358 return SDValue(); 10359 } 10360 10361 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 10362 N->getOperand(0), LHS, RHS); 10363 } 10364 10365 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 10366 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 10367 unsigned ElemBits = ElemTy.getSizeInBits(); 10368 10369 int64_t ShiftAmount; 10370 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 10371 APInt SplatValue, SplatUndef; 10372 unsigned SplatBitSize; 10373 bool HasAnyUndefs; 10374 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 10375 HasAnyUndefs, ElemBits) || 10376 SplatBitSize != ElemBits) 10377 return SDValue(); 10378 10379 ShiftAmount = SplatValue.getSExtValue(); 10380 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 10381 ShiftAmount = CVN->getSExtValue(); 10382 } else 10383 return SDValue(); 10384 10385 unsigned Opcode; 10386 bool IsRightShift; 10387 switch (IID) { 10388 default: 10389 llvm_unreachable("Unknown shift intrinsic"); 10390 case Intrinsic::aarch64_neon_sqshl: 10391 Opcode = AArch64ISD::SQSHL_I; 10392 IsRightShift = false; 10393 break; 10394 case Intrinsic::aarch64_neon_uqshl: 10395 Opcode = AArch64ISD::UQSHL_I; 10396 IsRightShift = false; 10397 break; 10398 case Intrinsic::aarch64_neon_srshl: 10399 Opcode = AArch64ISD::SRSHR_I; 10400 IsRightShift = true; 10401 break; 10402 case Intrinsic::aarch64_neon_urshl: 10403 Opcode = AArch64ISD::URSHR_I; 10404 IsRightShift = true; 10405 break; 10406 case Intrinsic::aarch64_neon_sqshlu: 10407 Opcode = AArch64ISD::SQSHLU_I; 10408 IsRightShift = false; 10409 break; 10410 case Intrinsic::aarch64_neon_sshl: 10411 case Intrinsic::aarch64_neon_ushl: 10412 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 10413 // left shift for positive shift amounts. Below, we only replace the current 10414 // node with VSHL, if this condition is met. 10415 Opcode = AArch64ISD::VSHL; 10416 IsRightShift = false; 10417 break; 10418 } 10419 10420 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 10421 SDLoc dl(N); 10422 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 10423 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 10424 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 10425 SDLoc dl(N); 10426 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 10427 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 10428 } 10429 10430 return SDValue(); 10431 } 10432 10433 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 10434 // the intrinsics must be legal and take an i32, this means there's almost 10435 // certainly going to be a zext in the DAG which we can eliminate. 10436 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 10437 SDValue AndN = N->getOperand(2); 10438 if (AndN.getOpcode() != ISD::AND) 10439 return SDValue(); 10440 10441 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 10442 if (!CMask || CMask->getZExtValue() != Mask) 10443 return SDValue(); 10444 10445 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 10446 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 10447 } 10448 10449 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 10450 SelectionDAG &DAG) { 10451 SDLoc dl(N); 10452 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 10453 DAG.getNode(Opc, dl, 10454 N->getOperand(1).getSimpleValueType(), 10455 N->getOperand(1)), 10456 DAG.getConstant(0, dl, MVT::i64)); 10457 } 10458 10459 static SDValue performIntrinsicCombine(SDNode *N, 10460 TargetLowering::DAGCombinerInfo &DCI, 10461 const AArch64Subtarget *Subtarget) { 10462 SelectionDAG &DAG = DCI.DAG; 10463 unsigned IID = getIntrinsicID(N); 10464 switch (IID) { 10465 default: 10466 break; 10467 case Intrinsic::aarch64_neon_vcvtfxs2fp: 10468 case Intrinsic::aarch64_neon_vcvtfxu2fp: 10469 return tryCombineFixedPointConvert(N, DCI, DAG); 10470 case Intrinsic::aarch64_neon_saddv: 10471 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 10472 case Intrinsic::aarch64_neon_uaddv: 10473 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 10474 case Intrinsic::aarch64_neon_sminv: 10475 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 10476 case Intrinsic::aarch64_neon_uminv: 10477 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 10478 case Intrinsic::aarch64_neon_smaxv: 10479 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 10480 case Intrinsic::aarch64_neon_umaxv: 10481 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 10482 case Intrinsic::aarch64_neon_fmax: 10483 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 10484 N->getOperand(1), N->getOperand(2)); 10485 case Intrinsic::aarch64_neon_fmin: 10486 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 10487 N->getOperand(1), N->getOperand(2)); 10488 case Intrinsic::aarch64_neon_fmaxnm: 10489 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 10490 N->getOperand(1), N->getOperand(2)); 10491 case Intrinsic::aarch64_neon_fminnm: 10492 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 10493 N->getOperand(1), N->getOperand(2)); 10494 case Intrinsic::aarch64_neon_smull: 10495 case Intrinsic::aarch64_neon_umull: 10496 case Intrinsic::aarch64_neon_pmull: 10497 case Intrinsic::aarch64_neon_sqdmull: 10498 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 10499 case Intrinsic::aarch64_neon_sqshl: 10500 case Intrinsic::aarch64_neon_uqshl: 10501 case Intrinsic::aarch64_neon_sqshlu: 10502 case Intrinsic::aarch64_neon_srshl: 10503 case Intrinsic::aarch64_neon_urshl: 10504 case Intrinsic::aarch64_neon_sshl: 10505 case Intrinsic::aarch64_neon_ushl: 10506 return tryCombineShiftImm(IID, N, DAG); 10507 case Intrinsic::aarch64_crc32b: 10508 case Intrinsic::aarch64_crc32cb: 10509 return tryCombineCRC32(0xff, N, DAG); 10510 case Intrinsic::aarch64_crc32h: 10511 case Intrinsic::aarch64_crc32ch: 10512 return tryCombineCRC32(0xffff, N, DAG); 10513 } 10514 return SDValue(); 10515 } 10516 10517 static SDValue performExtendCombine(SDNode *N, 10518 TargetLowering::DAGCombinerInfo &DCI, 10519 SelectionDAG &DAG) { 10520 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 10521 // we can convert that DUP into another extract_high (of a bigger DUP), which 10522 // helps the backend to decide that an sabdl2 would be useful, saving a real 10523 // extract_high operation. 10524 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 10525 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 10526 SDNode *ABDNode = N->getOperand(0).getNode(); 10527 unsigned IID = getIntrinsicID(ABDNode); 10528 if (IID == Intrinsic::aarch64_neon_sabd || 10529 IID == Intrinsic::aarch64_neon_uabd) { 10530 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 10531 if (!NewABD.getNode()) 10532 return SDValue(); 10533 10534 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 10535 NewABD); 10536 } 10537 } 10538 10539 // This is effectively a custom type legalization for AArch64. 10540 // 10541 // Type legalization will split an extend of a small, legal, type to a larger 10542 // illegal type by first splitting the destination type, often creating 10543 // illegal source types, which then get legalized in isel-confusing ways, 10544 // leading to really terrible codegen. E.g., 10545 // %result = v8i32 sext v8i8 %value 10546 // becomes 10547 // %losrc = extract_subreg %value, ... 10548 // %hisrc = extract_subreg %value, ... 10549 // %lo = v4i32 sext v4i8 %losrc 10550 // %hi = v4i32 sext v4i8 %hisrc 10551 // Things go rapidly downhill from there. 10552 // 10553 // For AArch64, the [sz]ext vector instructions can only go up one element 10554 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 10555 // take two instructions. 10556 // 10557 // This implies that the most efficient way to do the extend from v8i8 10558 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 10559 // the normal splitting to happen for the v8i16->v8i32. 10560 10561 // This is pre-legalization to catch some cases where the default 10562 // type legalization will create ill-tempered code. 10563 if (!DCI.isBeforeLegalizeOps()) 10564 return SDValue(); 10565 10566 // We're only interested in cleaning things up for non-legal vector types 10567 // here. If both the source and destination are legal, things will just 10568 // work naturally without any fiddling. 10569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10570 EVT ResVT = N->getValueType(0); 10571 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 10572 return SDValue(); 10573 // If the vector type isn't a simple VT, it's beyond the scope of what 10574 // we're worried about here. Let legalization do its thing and hope for 10575 // the best. 10576 SDValue Src = N->getOperand(0); 10577 EVT SrcVT = Src->getValueType(0); 10578 if (!ResVT.isSimple() || !SrcVT.isSimple()) 10579 return SDValue(); 10580 10581 // If the source VT is a 64-bit vector, we can play games and get the 10582 // better results we want. 10583 if (SrcVT.getSizeInBits() != 64) 10584 return SDValue(); 10585 10586 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 10587 unsigned ElementCount = SrcVT.getVectorNumElements(); 10588 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 10589 SDLoc DL(N); 10590 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 10591 10592 // Now split the rest of the operation into two halves, each with a 64 10593 // bit source. 10594 EVT LoVT, HiVT; 10595 SDValue Lo, Hi; 10596 unsigned NumElements = ResVT.getVectorNumElements(); 10597 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 10598 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 10599 ResVT.getVectorElementType(), NumElements / 2); 10600 10601 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 10602 LoVT.getVectorNumElements()); 10603 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 10604 DAG.getConstant(0, DL, MVT::i64)); 10605 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 10606 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 10607 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 10608 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 10609 10610 // Now combine the parts back together so we still have a single result 10611 // like the combiner expects. 10612 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 10613 } 10614 10615 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 10616 SDValue SplatVal, unsigned NumVecElts) { 10617 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 10618 unsigned OrigAlignment = St.getAlignment(); 10619 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 10620 10621 // Create scalar stores. This is at least as good as the code sequence for a 10622 // split unaligned store which is a dup.s, ext.b, and two stores. 10623 // Most of the time the three stores should be replaced by store pair 10624 // instructions (stp). 10625 SDLoc DL(&St); 10626 SDValue BasePtr = St.getBasePtr(); 10627 uint64_t BaseOffset = 0; 10628 10629 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 10630 SDValue NewST1 = 10631 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 10632 OrigAlignment, St.getMemOperand()->getFlags()); 10633 10634 // As this in ISel, we will not merge this add which may degrade results. 10635 if (BasePtr->getOpcode() == ISD::ADD && 10636 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 10637 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 10638 BasePtr = BasePtr->getOperand(0); 10639 } 10640 10641 unsigned Offset = EltOffset; 10642 while (--NumVecElts) { 10643 unsigned Alignment = MinAlign(OrigAlignment, Offset); 10644 SDValue OffsetPtr = 10645 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 10646 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 10647 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 10648 PtrInfo.getWithOffset(Offset), Alignment, 10649 St.getMemOperand()->getFlags()); 10650 Offset += EltOffset; 10651 } 10652 return NewST1; 10653 } 10654 10655 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 10656 /// load store optimizer pass will merge them to store pair stores. This should 10657 /// be better than a movi to create the vector zero followed by a vector store 10658 /// if the zero constant is not re-used, since one instructions and one register 10659 /// live range will be removed. 10660 /// 10661 /// For example, the final generated code should be: 10662 /// 10663 /// stp xzr, xzr, [x0] 10664 /// 10665 /// instead of: 10666 /// 10667 /// movi v0.2d, #0 10668 /// str q0, [x0] 10669 /// 10670 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 10671 SDValue StVal = St.getValue(); 10672 EVT VT = StVal.getValueType(); 10673 10674 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 10675 // 2, 3 or 4 i32 elements. 10676 int NumVecElts = VT.getVectorNumElements(); 10677 if (!(((NumVecElts == 2 || NumVecElts == 3) && 10678 VT.getVectorElementType().getSizeInBits() == 64) || 10679 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 10680 VT.getVectorElementType().getSizeInBits() == 32))) 10681 return SDValue(); 10682 10683 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 10684 return SDValue(); 10685 10686 // If the zero constant has more than one use then the vector store could be 10687 // better since the constant mov will be amortized and stp q instructions 10688 // should be able to be formed. 10689 if (!StVal.hasOneUse()) 10690 return SDValue(); 10691 10692 // If the store is truncating then it's going down to i16 or smaller, which 10693 // means it can be implemented in a single store anyway. 10694 if (St.isTruncatingStore()) 10695 return SDValue(); 10696 10697 // If the immediate offset of the address operand is too large for the stp 10698 // instruction, then bail out. 10699 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 10700 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 10701 if (Offset < -512 || Offset > 504) 10702 return SDValue(); 10703 } 10704 10705 for (int I = 0; I < NumVecElts; ++I) { 10706 SDValue EltVal = StVal.getOperand(I); 10707 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 10708 return SDValue(); 10709 } 10710 10711 // Use a CopyFromReg WZR/XZR here to prevent 10712 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 10713 SDLoc DL(&St); 10714 unsigned ZeroReg; 10715 EVT ZeroVT; 10716 if (VT.getVectorElementType().getSizeInBits() == 32) { 10717 ZeroReg = AArch64::WZR; 10718 ZeroVT = MVT::i32; 10719 } else { 10720 ZeroReg = AArch64::XZR; 10721 ZeroVT = MVT::i64; 10722 } 10723 SDValue SplatVal = 10724 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 10725 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 10726 } 10727 10728 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 10729 /// value. The load store optimizer pass will merge them to store pair stores. 10730 /// This has better performance than a splat of the scalar followed by a split 10731 /// vector store. Even if the stores are not merged it is four stores vs a dup, 10732 /// followed by an ext.b and two stores. 10733 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 10734 SDValue StVal = St.getValue(); 10735 EVT VT = StVal.getValueType(); 10736 10737 // Don't replace floating point stores, they possibly won't be transformed to 10738 // stp because of the store pair suppress pass. 10739 if (VT.isFloatingPoint()) 10740 return SDValue(); 10741 10742 // We can express a splat as store pair(s) for 2 or 4 elements. 10743 unsigned NumVecElts = VT.getVectorNumElements(); 10744 if (NumVecElts != 4 && NumVecElts != 2) 10745 return SDValue(); 10746 10747 // If the store is truncating then it's going down to i16 or smaller, which 10748 // means it can be implemented in a single store anyway. 10749 if (St.isTruncatingStore()) 10750 return SDValue(); 10751 10752 // Check that this is a splat. 10753 // Make sure that each of the relevant vector element locations are inserted 10754 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 10755 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 10756 SDValue SplatVal; 10757 for (unsigned I = 0; I < NumVecElts; ++I) { 10758 // Check for insert vector elements. 10759 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 10760 return SDValue(); 10761 10762 // Check that same value is inserted at each vector element. 10763 if (I == 0) 10764 SplatVal = StVal.getOperand(1); 10765 else if (StVal.getOperand(1) != SplatVal) 10766 return SDValue(); 10767 10768 // Check insert element index. 10769 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 10770 if (!CIndex) 10771 return SDValue(); 10772 uint64_t IndexVal = CIndex->getZExtValue(); 10773 if (IndexVal >= NumVecElts) 10774 return SDValue(); 10775 IndexNotInserted.reset(IndexVal); 10776 10777 StVal = StVal.getOperand(0); 10778 } 10779 // Check that all vector element locations were inserted to. 10780 if (IndexNotInserted.any()) 10781 return SDValue(); 10782 10783 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 10784 } 10785 10786 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 10787 SelectionDAG &DAG, 10788 const AArch64Subtarget *Subtarget) { 10789 10790 StoreSDNode *S = cast<StoreSDNode>(N); 10791 if (S->isVolatile() || S->isIndexed()) 10792 return SDValue(); 10793 10794 SDValue StVal = S->getValue(); 10795 EVT VT = StVal.getValueType(); 10796 if (!VT.isVector()) 10797 return SDValue(); 10798 10799 // If we get a splat of zeros, convert this vector store to a store of 10800 // scalars. They will be merged into store pairs of xzr thereby removing one 10801 // instruction and one register. 10802 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 10803 return ReplacedZeroSplat; 10804 10805 // FIXME: The logic for deciding if an unaligned store should be split should 10806 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 10807 // a call to that function here. 10808 10809 if (!Subtarget->isMisaligned128StoreSlow()) 10810 return SDValue(); 10811 10812 // Don't split at -Oz. 10813 if (DAG.getMachineFunction().getFunction().hasMinSize()) 10814 return SDValue(); 10815 10816 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 10817 // those up regresses performance on micro-benchmarks and olden/bh. 10818 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 10819 return SDValue(); 10820 10821 // Split unaligned 16B stores. They are terrible for performance. 10822 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 10823 // extensions can use this to mark that it does not want splitting to happen 10824 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 10825 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 10826 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 10827 S->getAlignment() <= 2) 10828 return SDValue(); 10829 10830 // If we get a splat of a scalar convert this vector store to a store of 10831 // scalars. They will be merged into store pairs thereby removing two 10832 // instructions. 10833 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 10834 return ReplacedSplat; 10835 10836 SDLoc DL(S); 10837 10838 // Split VT into two. 10839 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 10840 unsigned NumElts = HalfVT.getVectorNumElements(); 10841 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 10842 DAG.getConstant(0, DL, MVT::i64)); 10843 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 10844 DAG.getConstant(NumElts, DL, MVT::i64)); 10845 SDValue BasePtr = S->getBasePtr(); 10846 SDValue NewST1 = 10847 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 10848 S->getAlignment(), S->getMemOperand()->getFlags()); 10849 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 10850 DAG.getConstant(8, DL, MVT::i64)); 10851 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 10852 S->getPointerInfo(), S->getAlignment(), 10853 S->getMemOperand()->getFlags()); 10854 } 10855 10856 /// Target-specific DAG combine function for post-increment LD1 (lane) and 10857 /// post-increment LD1R. 10858 static SDValue performPostLD1Combine(SDNode *N, 10859 TargetLowering::DAGCombinerInfo &DCI, 10860 bool IsLaneOp) { 10861 if (DCI.isBeforeLegalizeOps()) 10862 return SDValue(); 10863 10864 SelectionDAG &DAG = DCI.DAG; 10865 EVT VT = N->getValueType(0); 10866 10867 unsigned LoadIdx = IsLaneOp ? 1 : 0; 10868 SDNode *LD = N->getOperand(LoadIdx).getNode(); 10869 // If it is not LOAD, can not do such combine. 10870 if (LD->getOpcode() != ISD::LOAD) 10871 return SDValue(); 10872 10873 // The vector lane must be a constant in the LD1LANE opcode. 10874 SDValue Lane; 10875 if (IsLaneOp) { 10876 Lane = N->getOperand(2); 10877 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 10878 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 10879 return SDValue(); 10880 } 10881 10882 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 10883 EVT MemVT = LoadSDN->getMemoryVT(); 10884 // Check if memory operand is the same type as the vector element. 10885 if (MemVT != VT.getVectorElementType()) 10886 return SDValue(); 10887 10888 // Check if there are other uses. If so, do not combine as it will introduce 10889 // an extra load. 10890 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 10891 ++UI) { 10892 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 10893 continue; 10894 if (*UI != N) 10895 return SDValue(); 10896 } 10897 10898 SDValue Addr = LD->getOperand(1); 10899 SDValue Vector = N->getOperand(0); 10900 // Search for a use of the address operand that is an increment. 10901 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 10902 Addr.getNode()->use_end(); UI != UE; ++UI) { 10903 SDNode *User = *UI; 10904 if (User->getOpcode() != ISD::ADD 10905 || UI.getUse().getResNo() != Addr.getResNo()) 10906 continue; 10907 10908 // If the increment is a constant, it must match the memory ref size. 10909 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10910 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10911 uint32_t IncVal = CInc->getZExtValue(); 10912 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 10913 if (IncVal != NumBytes) 10914 continue; 10915 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 10916 } 10917 10918 // To avoid cycle construction make sure that neither the load nor the add 10919 // are predecessors to each other or the Vector. 10920 SmallPtrSet<const SDNode *, 32> Visited; 10921 SmallVector<const SDNode *, 16> Worklist; 10922 Visited.insert(Addr.getNode()); 10923 Worklist.push_back(User); 10924 Worklist.push_back(LD); 10925 Worklist.push_back(Vector.getNode()); 10926 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 10927 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 10928 continue; 10929 10930 SmallVector<SDValue, 8> Ops; 10931 Ops.push_back(LD->getOperand(0)); // Chain 10932 if (IsLaneOp) { 10933 Ops.push_back(Vector); // The vector to be inserted 10934 Ops.push_back(Lane); // The lane to be inserted in the vector 10935 } 10936 Ops.push_back(Addr); 10937 Ops.push_back(Inc); 10938 10939 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 10940 SDVTList SDTys = DAG.getVTList(Tys); 10941 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 10942 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 10943 MemVT, 10944 LoadSDN->getMemOperand()); 10945 10946 // Update the uses. 10947 SDValue NewResults[] = { 10948 SDValue(LD, 0), // The result of load 10949 SDValue(UpdN.getNode(), 2) // Chain 10950 }; 10951 DCI.CombineTo(LD, NewResults); 10952 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 10953 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 10954 10955 break; 10956 } 10957 return SDValue(); 10958 } 10959 10960 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 10961 /// address translation. 10962 static bool performTBISimplification(SDValue Addr, 10963 TargetLowering::DAGCombinerInfo &DCI, 10964 SelectionDAG &DAG) { 10965 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 10966 KnownBits Known; 10967 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 10968 !DCI.isBeforeLegalizeOps()); 10969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10970 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 10971 DCI.CommitTargetLoweringOpt(TLO); 10972 return true; 10973 } 10974 return false; 10975 } 10976 10977 static SDValue performSTORECombine(SDNode *N, 10978 TargetLowering::DAGCombinerInfo &DCI, 10979 SelectionDAG &DAG, 10980 const AArch64Subtarget *Subtarget) { 10981 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 10982 return Split; 10983 10984 if (Subtarget->supportsAddressTopByteIgnored() && 10985 performTBISimplification(N->getOperand(2), DCI, DAG)) 10986 return SDValue(N, 0); 10987 10988 return SDValue(); 10989 } 10990 10991 10992 /// Target-specific DAG combine function for NEON load/store intrinsics 10993 /// to merge base address updates. 10994 static SDValue performNEONPostLDSTCombine(SDNode *N, 10995 TargetLowering::DAGCombinerInfo &DCI, 10996 SelectionDAG &DAG) { 10997 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10998 return SDValue(); 10999 11000 unsigned AddrOpIdx = N->getNumOperands() - 1; 11001 SDValue Addr = N->getOperand(AddrOpIdx); 11002 11003 // Search for a use of the address operand that is an increment. 11004 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11005 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11006 SDNode *User = *UI; 11007 if (User->getOpcode() != ISD::ADD || 11008 UI.getUse().getResNo() != Addr.getResNo()) 11009 continue; 11010 11011 // Check that the add is independent of the load/store. Otherwise, folding 11012 // it would create a cycle. 11013 SmallPtrSet<const SDNode *, 32> Visited; 11014 SmallVector<const SDNode *, 16> Worklist; 11015 Visited.insert(Addr.getNode()); 11016 Worklist.push_back(N); 11017 Worklist.push_back(User); 11018 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11019 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11020 continue; 11021 11022 // Find the new opcode for the updating load/store. 11023 bool IsStore = false; 11024 bool IsLaneOp = false; 11025 bool IsDupOp = false; 11026 unsigned NewOpc = 0; 11027 unsigned NumVecs = 0; 11028 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11029 switch (IntNo) { 11030 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11031 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 11032 NumVecs = 2; break; 11033 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 11034 NumVecs = 3; break; 11035 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 11036 NumVecs = 4; break; 11037 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 11038 NumVecs = 2; IsStore = true; break; 11039 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 11040 NumVecs = 3; IsStore = true; break; 11041 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 11042 NumVecs = 4; IsStore = true; break; 11043 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 11044 NumVecs = 2; break; 11045 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 11046 NumVecs = 3; break; 11047 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 11048 NumVecs = 4; break; 11049 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 11050 NumVecs = 2; IsStore = true; break; 11051 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 11052 NumVecs = 3; IsStore = true; break; 11053 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 11054 NumVecs = 4; IsStore = true; break; 11055 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 11056 NumVecs = 2; IsDupOp = true; break; 11057 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 11058 NumVecs = 3; IsDupOp = true; break; 11059 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 11060 NumVecs = 4; IsDupOp = true; break; 11061 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 11062 NumVecs = 2; IsLaneOp = true; break; 11063 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 11064 NumVecs = 3; IsLaneOp = true; break; 11065 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 11066 NumVecs = 4; IsLaneOp = true; break; 11067 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 11068 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 11069 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 11070 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 11071 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 11072 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 11073 } 11074 11075 EVT VecTy; 11076 if (IsStore) 11077 VecTy = N->getOperand(2).getValueType(); 11078 else 11079 VecTy = N->getValueType(0); 11080 11081 // If the increment is a constant, it must match the memory ref size. 11082 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11083 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 11084 uint32_t IncVal = CInc->getZExtValue(); 11085 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11086 if (IsLaneOp || IsDupOp) 11087 NumBytes /= VecTy.getVectorNumElements(); 11088 if (IncVal != NumBytes) 11089 continue; 11090 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 11091 } 11092 SmallVector<SDValue, 8> Ops; 11093 Ops.push_back(N->getOperand(0)); // Incoming chain 11094 // Load lane and store have vector list as input. 11095 if (IsLaneOp || IsStore) 11096 for (unsigned i = 2; i < AddrOpIdx; ++i) 11097 Ops.push_back(N->getOperand(i)); 11098 Ops.push_back(Addr); // Base register 11099 Ops.push_back(Inc); 11100 11101 // Return Types. 11102 EVT Tys[6]; 11103 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 11104 unsigned n; 11105 for (n = 0; n < NumResultVecs; ++n) 11106 Tys[n] = VecTy; 11107 Tys[n++] = MVT::i64; // Type of write back register 11108 Tys[n] = MVT::Other; // Type of the chain 11109 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 11110 11111 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 11112 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 11113 MemInt->getMemoryVT(), 11114 MemInt->getMemOperand()); 11115 11116 // Update the uses. 11117 std::vector<SDValue> NewResults; 11118 for (unsigned i = 0; i < NumResultVecs; ++i) { 11119 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11120 } 11121 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 11122 DCI.CombineTo(N, NewResults); 11123 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11124 11125 break; 11126 } 11127 return SDValue(); 11128 } 11129 11130 // Checks to see if the value is the prescribed width and returns information 11131 // about its extension mode. 11132 static 11133 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 11134 ExtType = ISD::NON_EXTLOAD; 11135 switch(V.getNode()->getOpcode()) { 11136 default: 11137 return false; 11138 case ISD::LOAD: { 11139 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 11140 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 11141 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 11142 ExtType = LoadNode->getExtensionType(); 11143 return true; 11144 } 11145 return false; 11146 } 11147 case ISD::AssertSext: { 11148 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 11149 if ((TypeNode->getVT() == MVT::i8 && width == 8) 11150 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 11151 ExtType = ISD::SEXTLOAD; 11152 return true; 11153 } 11154 return false; 11155 } 11156 case ISD::AssertZext: { 11157 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 11158 if ((TypeNode->getVT() == MVT::i8 && width == 8) 11159 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 11160 ExtType = ISD::ZEXTLOAD; 11161 return true; 11162 } 11163 return false; 11164 } 11165 case ISD::Constant: 11166 case ISD::TargetConstant: { 11167 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 11168 1LL << (width - 1); 11169 } 11170 } 11171 11172 return true; 11173 } 11174 11175 // This function does a whole lot of voodoo to determine if the tests are 11176 // equivalent without and with a mask. Essentially what happens is that given a 11177 // DAG resembling: 11178 // 11179 // +-------------+ +-------------+ +-------------+ +-------------+ 11180 // | Input | | AddConstant | | CompConstant| | CC | 11181 // +-------------+ +-------------+ +-------------+ +-------------+ 11182 // | | | | 11183 // V V | +----------+ 11184 // +-------------+ +----+ | | 11185 // | ADD | |0xff| | | 11186 // +-------------+ +----+ | | 11187 // | | | | 11188 // V V | | 11189 // +-------------+ | | 11190 // | AND | | | 11191 // +-------------+ | | 11192 // | | | 11193 // +-----+ | | 11194 // | | | 11195 // V V V 11196 // +-------------+ 11197 // | CMP | 11198 // +-------------+ 11199 // 11200 // The AND node may be safely removed for some combinations of inputs. In 11201 // particular we need to take into account the extension type of the Input, 11202 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 11203 // width of the input (this can work for any width inputs, the above graph is 11204 // specific to 8 bits. 11205 // 11206 // The specific equations were worked out by generating output tables for each 11207 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 11208 // problem was simplified by working with 4 bit inputs, which means we only 11209 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 11210 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 11211 // patterns present in both extensions (0,7). For every distinct set of 11212 // AddConstant and CompConstants bit patterns we can consider the masked and 11213 // unmasked versions to be equivalent if the result of this function is true for 11214 // all 16 distinct bit patterns of for the current extension type of Input (w0). 11215 // 11216 // sub w8, w0, w1 11217 // and w10, w8, #0x0f 11218 // cmp w8, w2 11219 // cset w9, AArch64CC 11220 // cmp w10, w2 11221 // cset w11, AArch64CC 11222 // cmp w9, w11 11223 // cset w0, eq 11224 // ret 11225 // 11226 // Since the above function shows when the outputs are equivalent it defines 11227 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 11228 // would be expensive to run during compiles. The equations below were written 11229 // in a test harness that confirmed they gave equivalent outputs to the above 11230 // for all inputs function, so they can be used determine if the removal is 11231 // legal instead. 11232 // 11233 // isEquivalentMaskless() is the code for testing if the AND can be removed 11234 // factored out of the DAG recognition as the DAG can take several forms. 11235 11236 static bool isEquivalentMaskless(unsigned CC, unsigned width, 11237 ISD::LoadExtType ExtType, int AddConstant, 11238 int CompConstant) { 11239 // By being careful about our equations and only writing the in term 11240 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 11241 // make them generally applicable to all bit widths. 11242 int MaxUInt = (1 << width); 11243 11244 // For the purposes of these comparisons sign extending the type is 11245 // equivalent to zero extending the add and displacing it by half the integer 11246 // width. Provided we are careful and make sure our equations are valid over 11247 // the whole range we can just adjust the input and avoid writing equations 11248 // for sign extended inputs. 11249 if (ExtType == ISD::SEXTLOAD) 11250 AddConstant -= (1 << (width-1)); 11251 11252 switch(CC) { 11253 case AArch64CC::LE: 11254 case AArch64CC::GT: 11255 if ((AddConstant == 0) || 11256 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 11257 (AddConstant >= 0 && CompConstant < 0) || 11258 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 11259 return true; 11260 break; 11261 case AArch64CC::LT: 11262 case AArch64CC::GE: 11263 if ((AddConstant == 0) || 11264 (AddConstant >= 0 && CompConstant <= 0) || 11265 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 11266 return true; 11267 break; 11268 case AArch64CC::HI: 11269 case AArch64CC::LS: 11270 if ((AddConstant >= 0 && CompConstant < 0) || 11271 (AddConstant <= 0 && CompConstant >= -1 && 11272 CompConstant < AddConstant + MaxUInt)) 11273 return true; 11274 break; 11275 case AArch64CC::PL: 11276 case AArch64CC::MI: 11277 if ((AddConstant == 0) || 11278 (AddConstant > 0 && CompConstant <= 0) || 11279 (AddConstant < 0 && CompConstant <= AddConstant)) 11280 return true; 11281 break; 11282 case AArch64CC::LO: 11283 case AArch64CC::HS: 11284 if ((AddConstant >= 0 && CompConstant <= 0) || 11285 (AddConstant <= 0 && CompConstant >= 0 && 11286 CompConstant <= AddConstant + MaxUInt)) 11287 return true; 11288 break; 11289 case AArch64CC::EQ: 11290 case AArch64CC::NE: 11291 if ((AddConstant > 0 && CompConstant < 0) || 11292 (AddConstant < 0 && CompConstant >= 0 && 11293 CompConstant < AddConstant + MaxUInt) || 11294 (AddConstant >= 0 && CompConstant >= 0 && 11295 CompConstant >= AddConstant) || 11296 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 11297 return true; 11298 break; 11299 case AArch64CC::VS: 11300 case AArch64CC::VC: 11301 case AArch64CC::AL: 11302 case AArch64CC::NV: 11303 return true; 11304 case AArch64CC::Invalid: 11305 break; 11306 } 11307 11308 return false; 11309 } 11310 11311 static 11312 SDValue performCONDCombine(SDNode *N, 11313 TargetLowering::DAGCombinerInfo &DCI, 11314 SelectionDAG &DAG, unsigned CCIndex, 11315 unsigned CmpIndex) { 11316 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 11317 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 11318 unsigned CondOpcode = SubsNode->getOpcode(); 11319 11320 if (CondOpcode != AArch64ISD::SUBS) 11321 return SDValue(); 11322 11323 // There is a SUBS feeding this condition. Is it fed by a mask we can 11324 // use? 11325 11326 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 11327 unsigned MaskBits = 0; 11328 11329 if (AndNode->getOpcode() != ISD::AND) 11330 return SDValue(); 11331 11332 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 11333 uint32_t CNV = CN->getZExtValue(); 11334 if (CNV == 255) 11335 MaskBits = 8; 11336 else if (CNV == 65535) 11337 MaskBits = 16; 11338 } 11339 11340 if (!MaskBits) 11341 return SDValue(); 11342 11343 SDValue AddValue = AndNode->getOperand(0); 11344 11345 if (AddValue.getOpcode() != ISD::ADD) 11346 return SDValue(); 11347 11348 // The basic dag structure is correct, grab the inputs and validate them. 11349 11350 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 11351 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 11352 SDValue SubsInputValue = SubsNode->getOperand(1); 11353 11354 // The mask is present and the provenance of all the values is a smaller type, 11355 // lets see if the mask is superfluous. 11356 11357 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 11358 !isa<ConstantSDNode>(SubsInputValue.getNode())) 11359 return SDValue(); 11360 11361 ISD::LoadExtType ExtType; 11362 11363 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 11364 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 11365 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 11366 return SDValue(); 11367 11368 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 11369 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 11370 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 11371 return SDValue(); 11372 11373 // The AND is not necessary, remove it. 11374 11375 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 11376 SubsNode->getValueType(1)); 11377 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 11378 11379 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 11380 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 11381 11382 return SDValue(N, 0); 11383 } 11384 11385 // Optimize compare with zero and branch. 11386 static SDValue performBRCONDCombine(SDNode *N, 11387 TargetLowering::DAGCombinerInfo &DCI, 11388 SelectionDAG &DAG) { 11389 MachineFunction &MF = DAG.getMachineFunction(); 11390 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 11391 // will not be produced, as they are conditional branch instructions that do 11392 // not set flags. 11393 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 11394 return SDValue(); 11395 11396 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 11397 N = NV.getNode(); 11398 SDValue Chain = N->getOperand(0); 11399 SDValue Dest = N->getOperand(1); 11400 SDValue CCVal = N->getOperand(2); 11401 SDValue Cmp = N->getOperand(3); 11402 11403 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 11404 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 11405 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 11406 return SDValue(); 11407 11408 unsigned CmpOpc = Cmp.getOpcode(); 11409 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 11410 return SDValue(); 11411 11412 // Only attempt folding if there is only one use of the flag and no use of the 11413 // value. 11414 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 11415 return SDValue(); 11416 11417 SDValue LHS = Cmp.getOperand(0); 11418 SDValue RHS = Cmp.getOperand(1); 11419 11420 assert(LHS.getValueType() == RHS.getValueType() && 11421 "Expected the value type to be the same for both operands!"); 11422 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 11423 return SDValue(); 11424 11425 if (isNullConstant(LHS)) 11426 std::swap(LHS, RHS); 11427 11428 if (!isNullConstant(RHS)) 11429 return SDValue(); 11430 11431 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 11432 LHS.getOpcode() == ISD::SRL) 11433 return SDValue(); 11434 11435 // Fold the compare into the branch instruction. 11436 SDValue BR; 11437 if (CC == AArch64CC::EQ) 11438 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 11439 else 11440 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 11441 11442 // Do not add new nodes to DAG combiner worklist. 11443 DCI.CombineTo(N, BR, false); 11444 11445 return SDValue(); 11446 } 11447 11448 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 11449 // as well as whether the test should be inverted. This code is required to 11450 // catch these cases (as opposed to standard dag combines) because 11451 // AArch64ISD::TBZ is matched during legalization. 11452 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 11453 SelectionDAG &DAG) { 11454 11455 if (!Op->hasOneUse()) 11456 return Op; 11457 11458 // We don't handle undef/constant-fold cases below, as they should have 11459 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 11460 // etc.) 11461 11462 // (tbz (trunc x), b) -> (tbz x, b) 11463 // This case is just here to enable more of the below cases to be caught. 11464 if (Op->getOpcode() == ISD::TRUNCATE && 11465 Bit < Op->getValueType(0).getSizeInBits()) { 11466 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11467 } 11468 11469 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 11470 if (Op->getOpcode() == ISD::ANY_EXTEND && 11471 Bit < Op->getOperand(0).getValueSizeInBits()) { 11472 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11473 } 11474 11475 if (Op->getNumOperands() != 2) 11476 return Op; 11477 11478 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 11479 if (!C) 11480 return Op; 11481 11482 switch (Op->getOpcode()) { 11483 default: 11484 return Op; 11485 11486 // (tbz (and x, m), b) -> (tbz x, b) 11487 case ISD::AND: 11488 if ((C->getZExtValue() >> Bit) & 1) 11489 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11490 return Op; 11491 11492 // (tbz (shl x, c), b) -> (tbz x, b-c) 11493 case ISD::SHL: 11494 if (C->getZExtValue() <= Bit && 11495 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 11496 Bit = Bit - C->getZExtValue(); 11497 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11498 } 11499 return Op; 11500 11501 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 11502 case ISD::SRA: 11503 Bit = Bit + C->getZExtValue(); 11504 if (Bit >= Op->getValueType(0).getSizeInBits()) 11505 Bit = Op->getValueType(0).getSizeInBits() - 1; 11506 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11507 11508 // (tbz (srl x, c), b) -> (tbz x, b+c) 11509 case ISD::SRL: 11510 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 11511 Bit = Bit + C->getZExtValue(); 11512 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11513 } 11514 return Op; 11515 11516 // (tbz (xor x, -1), b) -> (tbnz x, b) 11517 case ISD::XOR: 11518 if ((C->getZExtValue() >> Bit) & 1) 11519 Invert = !Invert; 11520 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11521 } 11522 } 11523 11524 // Optimize test single bit zero/non-zero and branch. 11525 static SDValue performTBZCombine(SDNode *N, 11526 TargetLowering::DAGCombinerInfo &DCI, 11527 SelectionDAG &DAG) { 11528 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11529 bool Invert = false; 11530 SDValue TestSrc = N->getOperand(1); 11531 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 11532 11533 if (TestSrc == NewTestSrc) 11534 return SDValue(); 11535 11536 unsigned NewOpc = N->getOpcode(); 11537 if (Invert) { 11538 if (NewOpc == AArch64ISD::TBZ) 11539 NewOpc = AArch64ISD::TBNZ; 11540 else { 11541 assert(NewOpc == AArch64ISD::TBNZ); 11542 NewOpc = AArch64ISD::TBZ; 11543 } 11544 } 11545 11546 SDLoc DL(N); 11547 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 11548 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 11549 } 11550 11551 // vselect (v1i1 setcc) -> 11552 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 11553 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 11554 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 11555 // such VSELECT. 11556 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 11557 SDValue N0 = N->getOperand(0); 11558 EVT CCVT = N0.getValueType(); 11559 11560 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 11561 CCVT.getVectorElementType() != MVT::i1) 11562 return SDValue(); 11563 11564 EVT ResVT = N->getValueType(0); 11565 EVT CmpVT = N0.getOperand(0).getValueType(); 11566 // Only combine when the result type is of the same size as the compared 11567 // operands. 11568 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 11569 return SDValue(); 11570 11571 SDValue IfTrue = N->getOperand(1); 11572 SDValue IfFalse = N->getOperand(2); 11573 SDValue SetCC = 11574 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 11575 N0.getOperand(0), N0.getOperand(1), 11576 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11577 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 11578 IfTrue, IfFalse); 11579 } 11580 11581 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 11582 /// the compare-mask instructions rather than going via NZCV, even if LHS and 11583 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 11584 /// with a vector one followed by a DUP shuffle on the result. 11585 static SDValue performSelectCombine(SDNode *N, 11586 TargetLowering::DAGCombinerInfo &DCI) { 11587 SelectionDAG &DAG = DCI.DAG; 11588 SDValue N0 = N->getOperand(0); 11589 EVT ResVT = N->getValueType(0); 11590 11591 if (N0.getOpcode() != ISD::SETCC) 11592 return SDValue(); 11593 11594 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 11595 // scalar SetCCResultType. We also don't expect vectors, because we assume 11596 // that selects fed by vector SETCCs are canonicalized to VSELECT. 11597 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 11598 "Scalar-SETCC feeding SELECT has unexpected result type!"); 11599 11600 // If NumMaskElts == 0, the comparison is larger than select result. The 11601 // largest real NEON comparison is 64-bits per lane, which means the result is 11602 // at most 32-bits and an illegal vector. Just bail out for now. 11603 EVT SrcVT = N0.getOperand(0).getValueType(); 11604 11605 // Don't try to do this optimization when the setcc itself has i1 operands. 11606 // There are no legal vectors of i1, so this would be pointless. 11607 if (SrcVT == MVT::i1) 11608 return SDValue(); 11609 11610 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 11611 if (!ResVT.isVector() || NumMaskElts == 0) 11612 return SDValue(); 11613 11614 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 11615 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 11616 11617 // Also bail out if the vector CCVT isn't the same size as ResVT. 11618 // This can happen if the SETCC operand size doesn't divide the ResVT size 11619 // (e.g., f64 vs v3f32). 11620 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 11621 return SDValue(); 11622 11623 // Make sure we didn't create illegal types, if we're not supposed to. 11624 assert(DCI.isBeforeLegalize() || 11625 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 11626 11627 // First perform a vector comparison, where lane 0 is the one we're interested 11628 // in. 11629 SDLoc DL(N0); 11630 SDValue LHS = 11631 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 11632 SDValue RHS = 11633 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 11634 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 11635 11636 // Now duplicate the comparison mask we want across all other lanes. 11637 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 11638 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 11639 Mask = DAG.getNode(ISD::BITCAST, DL, 11640 ResVT.changeVectorElementTypeToInteger(), Mask); 11641 11642 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 11643 } 11644 11645 /// Get rid of unnecessary NVCASTs (that don't change the type). 11646 static SDValue performNVCASTCombine(SDNode *N) { 11647 if (N->getValueType(0) == N->getOperand(0).getValueType()) 11648 return N->getOperand(0); 11649 11650 return SDValue(); 11651 } 11652 11653 // If all users of the globaladdr are of the form (globaladdr + constant), find 11654 // the smallest constant, fold it into the globaladdr's offset and rewrite the 11655 // globaladdr as (globaladdr + constant) - constant. 11656 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 11657 const AArch64Subtarget *Subtarget, 11658 const TargetMachine &TM) { 11659 auto *GN = cast<GlobalAddressSDNode>(N); 11660 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 11661 AArch64II::MO_NO_FLAG) 11662 return SDValue(); 11663 11664 uint64_t MinOffset = -1ull; 11665 for (SDNode *N : GN->uses()) { 11666 if (N->getOpcode() != ISD::ADD) 11667 return SDValue(); 11668 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 11669 if (!C) 11670 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11671 if (!C) 11672 return SDValue(); 11673 MinOffset = std::min(MinOffset, C->getZExtValue()); 11674 } 11675 uint64_t Offset = MinOffset + GN->getOffset(); 11676 11677 // Require that the new offset is larger than the existing one. Otherwise, we 11678 // can end up oscillating between two possible DAGs, for example, 11679 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 11680 if (Offset <= uint64_t(GN->getOffset())) 11681 return SDValue(); 11682 11683 // Check whether folding this offset is legal. It must not go out of bounds of 11684 // the referenced object to avoid violating the code model, and must be 11685 // smaller than 2^21 because this is the largest offset expressible in all 11686 // object formats. 11687 // 11688 // This check also prevents us from folding negative offsets, which will end 11689 // up being treated in the same way as large positive ones. They could also 11690 // cause code model violations, and aren't really common enough to matter. 11691 if (Offset >= (1 << 21)) 11692 return SDValue(); 11693 11694 const GlobalValue *GV = GN->getGlobal(); 11695 Type *T = GV->getValueType(); 11696 if (!T->isSized() || 11697 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 11698 return SDValue(); 11699 11700 SDLoc DL(GN); 11701 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 11702 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 11703 DAG.getConstant(MinOffset, DL, MVT::i64)); 11704 } 11705 11706 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 11707 DAGCombinerInfo &DCI) const { 11708 SelectionDAG &DAG = DCI.DAG; 11709 switch (N->getOpcode()) { 11710 default: 11711 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 11712 break; 11713 case ISD::ADD: 11714 case ISD::SUB: 11715 return performAddSubLongCombine(N, DCI, DAG); 11716 case ISD::XOR: 11717 return performXorCombine(N, DAG, DCI, Subtarget); 11718 case ISD::MUL: 11719 return performMulCombine(N, DAG, DCI, Subtarget); 11720 case ISD::SINT_TO_FP: 11721 case ISD::UINT_TO_FP: 11722 return performIntToFpCombine(N, DAG, Subtarget); 11723 case ISD::FP_TO_SINT: 11724 case ISD::FP_TO_UINT: 11725 return performFpToIntCombine(N, DAG, DCI, Subtarget); 11726 case ISD::FDIV: 11727 return performFDivCombine(N, DAG, DCI, Subtarget); 11728 case ISD::OR: 11729 return performORCombine(N, DCI, Subtarget); 11730 case ISD::AND: 11731 return performANDCombine(N, DCI); 11732 case ISD::SRL: 11733 return performSRLCombine(N, DCI); 11734 case ISD::INTRINSIC_WO_CHAIN: 11735 return performIntrinsicCombine(N, DCI, Subtarget); 11736 case ISD::ANY_EXTEND: 11737 case ISD::ZERO_EXTEND: 11738 case ISD::SIGN_EXTEND: 11739 return performExtendCombine(N, DCI, DAG); 11740 case ISD::BITCAST: 11741 return performBitcastCombine(N, DCI, DAG); 11742 case ISD::CONCAT_VECTORS: 11743 return performConcatVectorsCombine(N, DCI, DAG); 11744 case ISD::SELECT: 11745 return performSelectCombine(N, DCI); 11746 case ISD::VSELECT: 11747 return performVSelectCombine(N, DCI.DAG); 11748 case ISD::LOAD: 11749 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 11750 return SDValue(N, 0); 11751 break; 11752 case ISD::STORE: 11753 return performSTORECombine(N, DCI, DAG, Subtarget); 11754 case AArch64ISD::BRCOND: 11755 return performBRCONDCombine(N, DCI, DAG); 11756 case AArch64ISD::TBNZ: 11757 case AArch64ISD::TBZ: 11758 return performTBZCombine(N, DCI, DAG); 11759 case AArch64ISD::CSEL: 11760 return performCONDCombine(N, DCI, DAG, 2, 3); 11761 case AArch64ISD::DUP: 11762 return performPostLD1Combine(N, DCI, false); 11763 case AArch64ISD::NVCAST: 11764 return performNVCASTCombine(N); 11765 case ISD::INSERT_VECTOR_ELT: 11766 return performPostLD1Combine(N, DCI, true); 11767 case ISD::INTRINSIC_VOID: 11768 case ISD::INTRINSIC_W_CHAIN: 11769 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11770 case Intrinsic::aarch64_neon_ld2: 11771 case Intrinsic::aarch64_neon_ld3: 11772 case Intrinsic::aarch64_neon_ld4: 11773 case Intrinsic::aarch64_neon_ld1x2: 11774 case Intrinsic::aarch64_neon_ld1x3: 11775 case Intrinsic::aarch64_neon_ld1x4: 11776 case Intrinsic::aarch64_neon_ld2lane: 11777 case Intrinsic::aarch64_neon_ld3lane: 11778 case Intrinsic::aarch64_neon_ld4lane: 11779 case Intrinsic::aarch64_neon_ld2r: 11780 case Intrinsic::aarch64_neon_ld3r: 11781 case Intrinsic::aarch64_neon_ld4r: 11782 case Intrinsic::aarch64_neon_st2: 11783 case Intrinsic::aarch64_neon_st3: 11784 case Intrinsic::aarch64_neon_st4: 11785 case Intrinsic::aarch64_neon_st1x2: 11786 case Intrinsic::aarch64_neon_st1x3: 11787 case Intrinsic::aarch64_neon_st1x4: 11788 case Intrinsic::aarch64_neon_st2lane: 11789 case Intrinsic::aarch64_neon_st3lane: 11790 case Intrinsic::aarch64_neon_st4lane: 11791 return performNEONPostLDSTCombine(N, DCI, DAG); 11792 default: 11793 break; 11794 } 11795 break; 11796 case ISD::GlobalAddress: 11797 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 11798 } 11799 return SDValue(); 11800 } 11801 11802 // Check if the return value is used as only a return value, as otherwise 11803 // we can't perform a tail-call. In particular, we need to check for 11804 // target ISD nodes that are returns and any other "odd" constructs 11805 // that the generic analysis code won't necessarily catch. 11806 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 11807 SDValue &Chain) const { 11808 if (N->getNumValues() != 1) 11809 return false; 11810 if (!N->hasNUsesOfValue(1, 0)) 11811 return false; 11812 11813 SDValue TCChain = Chain; 11814 SDNode *Copy = *N->use_begin(); 11815 if (Copy->getOpcode() == ISD::CopyToReg) { 11816 // If the copy has a glue operand, we conservatively assume it isn't safe to 11817 // perform a tail call. 11818 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 11819 MVT::Glue) 11820 return false; 11821 TCChain = Copy->getOperand(0); 11822 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 11823 return false; 11824 11825 bool HasRet = false; 11826 for (SDNode *Node : Copy->uses()) { 11827 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 11828 return false; 11829 HasRet = true; 11830 } 11831 11832 if (!HasRet) 11833 return false; 11834 11835 Chain = TCChain; 11836 return true; 11837 } 11838 11839 // Return whether the an instruction can potentially be optimized to a tail 11840 // call. This will cause the optimizers to attempt to move, or duplicate, 11841 // return instructions to help enable tail call optimizations for this 11842 // instruction. 11843 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11844 return CI->isTailCall(); 11845 } 11846 11847 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 11848 SDValue &Offset, 11849 ISD::MemIndexedMode &AM, 11850 bool &IsInc, 11851 SelectionDAG &DAG) const { 11852 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 11853 return false; 11854 11855 Base = Op->getOperand(0); 11856 // All of the indexed addressing mode instructions take a signed 11857 // 9 bit immediate offset. 11858 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 11859 int64_t RHSC = RHS->getSExtValue(); 11860 if (Op->getOpcode() == ISD::SUB) 11861 RHSC = -(uint64_t)RHSC; 11862 if (!isInt<9>(RHSC)) 11863 return false; 11864 IsInc = (Op->getOpcode() == ISD::ADD); 11865 Offset = Op->getOperand(1); 11866 return true; 11867 } 11868 return false; 11869 } 11870 11871 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11872 SDValue &Offset, 11873 ISD::MemIndexedMode &AM, 11874 SelectionDAG &DAG) const { 11875 EVT VT; 11876 SDValue Ptr; 11877 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11878 VT = LD->getMemoryVT(); 11879 Ptr = LD->getBasePtr(); 11880 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11881 VT = ST->getMemoryVT(); 11882 Ptr = ST->getBasePtr(); 11883 } else 11884 return false; 11885 11886 bool IsInc; 11887 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 11888 return false; 11889 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 11890 return true; 11891 } 11892 11893 bool AArch64TargetLowering::getPostIndexedAddressParts( 11894 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 11895 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 11896 EVT VT; 11897 SDValue Ptr; 11898 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11899 VT = LD->getMemoryVT(); 11900 Ptr = LD->getBasePtr(); 11901 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11902 VT = ST->getMemoryVT(); 11903 Ptr = ST->getBasePtr(); 11904 } else 11905 return false; 11906 11907 bool IsInc; 11908 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 11909 return false; 11910 // Post-indexing updates the base, so it's not a valid transform 11911 // if that's not the same as the load's pointer. 11912 if (Ptr != Base) 11913 return false; 11914 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 11915 return true; 11916 } 11917 11918 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 11919 SelectionDAG &DAG) { 11920 SDLoc DL(N); 11921 SDValue Op = N->getOperand(0); 11922 11923 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 11924 return; 11925 11926 Op = SDValue( 11927 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 11928 DAG.getUNDEF(MVT::i32), Op, 11929 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 11930 0); 11931 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 11932 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 11933 } 11934 11935 static void ReplaceReductionResults(SDNode *N, 11936 SmallVectorImpl<SDValue> &Results, 11937 SelectionDAG &DAG, unsigned InterOp, 11938 unsigned AcrossOp) { 11939 EVT LoVT, HiVT; 11940 SDValue Lo, Hi; 11941 SDLoc dl(N); 11942 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 11943 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 11944 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 11945 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 11946 Results.push_back(SplitVal); 11947 } 11948 11949 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 11950 SDLoc DL(N); 11951 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 11952 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 11953 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 11954 DAG.getConstant(64, DL, MVT::i64))); 11955 return std::make_pair(Lo, Hi); 11956 } 11957 11958 // Create an even/odd pair of X registers holding integer value V. 11959 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 11960 SDLoc dl(V.getNode()); 11961 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 11962 SDValue VHi = DAG.getAnyExtOrTrunc( 11963 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 11964 dl, MVT::i64); 11965 if (DAG.getDataLayout().isBigEndian()) 11966 std::swap (VLo, VHi); 11967 SDValue RegClass = 11968 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 11969 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 11970 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 11971 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 11972 return SDValue( 11973 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 11974 } 11975 11976 static void ReplaceCMP_SWAP_128Results(SDNode *N, 11977 SmallVectorImpl<SDValue> &Results, 11978 SelectionDAG &DAG, 11979 const AArch64Subtarget *Subtarget) { 11980 assert(N->getValueType(0) == MVT::i128 && 11981 "AtomicCmpSwap on types less than 128 should be legal"); 11982 11983 if (Subtarget->hasLSE()) { 11984 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 11985 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 11986 SDValue Ops[] = { 11987 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 11988 createGPRPairNode(DAG, N->getOperand(3)), // Store value 11989 N->getOperand(1), // Ptr 11990 N->getOperand(0), // Chain in 11991 }; 11992 11993 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 11994 11995 unsigned Opcode; 11996 switch (MemOp->getOrdering()) { 11997 case AtomicOrdering::Monotonic: 11998 Opcode = AArch64::CASPX; 11999 break; 12000 case AtomicOrdering::Acquire: 12001 Opcode = AArch64::CASPAX; 12002 break; 12003 case AtomicOrdering::Release: 12004 Opcode = AArch64::CASPLX; 12005 break; 12006 case AtomicOrdering::AcquireRelease: 12007 case AtomicOrdering::SequentiallyConsistent: 12008 Opcode = AArch64::CASPALX; 12009 break; 12010 default: 12011 llvm_unreachable("Unexpected ordering!"); 12012 } 12013 12014 MachineSDNode *CmpSwap = DAG.getMachineNode( 12015 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 12016 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 12017 12018 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 12019 if (DAG.getDataLayout().isBigEndian()) 12020 std::swap(SubReg1, SubReg2); 12021 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 12022 SDValue(CmpSwap, 0))); 12023 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 12024 SDValue(CmpSwap, 0))); 12025 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 12026 return; 12027 } 12028 12029 auto Desired = splitInt128(N->getOperand(2), DAG); 12030 auto New = splitInt128(N->getOperand(3), DAG); 12031 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 12032 New.first, New.second, N->getOperand(0)}; 12033 SDNode *CmpSwap = DAG.getMachineNode( 12034 AArch64::CMP_SWAP_128, SDLoc(N), 12035 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 12036 12037 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 12038 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 12039 12040 Results.push_back(SDValue(CmpSwap, 0)); 12041 Results.push_back(SDValue(CmpSwap, 1)); 12042 Results.push_back(SDValue(CmpSwap, 3)); 12043 } 12044 12045 void AArch64TargetLowering::ReplaceNodeResults( 12046 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 12047 switch (N->getOpcode()) { 12048 default: 12049 llvm_unreachable("Don't know how to custom expand this"); 12050 case ISD::BITCAST: 12051 ReplaceBITCASTResults(N, Results, DAG); 12052 return; 12053 case ISD::VECREDUCE_ADD: 12054 case ISD::VECREDUCE_SMAX: 12055 case ISD::VECREDUCE_SMIN: 12056 case ISD::VECREDUCE_UMAX: 12057 case ISD::VECREDUCE_UMIN: 12058 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 12059 return; 12060 12061 case AArch64ISD::SADDV: 12062 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 12063 return; 12064 case AArch64ISD::UADDV: 12065 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 12066 return; 12067 case AArch64ISD::SMINV: 12068 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 12069 return; 12070 case AArch64ISD::UMINV: 12071 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 12072 return; 12073 case AArch64ISD::SMAXV: 12074 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 12075 return; 12076 case AArch64ISD::UMAXV: 12077 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 12078 return; 12079 case ISD::FP_TO_UINT: 12080 case ISD::FP_TO_SINT: 12081 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 12082 // Let normal code take care of it by not adding anything to Results. 12083 return; 12084 case ISD::ATOMIC_CMP_SWAP: 12085 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 12086 return; 12087 } 12088 } 12089 12090 bool AArch64TargetLowering::useLoadStackGuardNode() const { 12091 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 12092 return TargetLowering::useLoadStackGuardNode(); 12093 return true; 12094 } 12095 12096 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 12097 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12098 // reciprocal if there are three or more FDIVs. 12099 return 3; 12100 } 12101 12102 TargetLoweringBase::LegalizeTypeAction 12103 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 12104 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 12105 // v4i16, v2i32 instead of to promote. 12106 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 12107 VT == MVT::v1f32) 12108 return TypeWidenVector; 12109 12110 return TargetLoweringBase::getPreferredVectorAction(VT); 12111 } 12112 12113 // Loads and stores less than 128-bits are already atomic; ones above that 12114 // are doomed anyway, so defer to the default libcall and blame the OS when 12115 // things go wrong. 12116 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12117 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 12118 return Size == 128; 12119 } 12120 12121 // Loads and stores less than 128-bits are already atomic; ones above that 12122 // are doomed anyway, so defer to the default libcall and blame the OS when 12123 // things go wrong. 12124 TargetLowering::AtomicExpansionKind 12125 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12126 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 12127 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 12128 } 12129 12130 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 12131 TargetLowering::AtomicExpansionKind 12132 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12133 if (AI->isFloatingPointOperation()) 12134 return AtomicExpansionKind::CmpXChg; 12135 12136 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12137 if (Size > 128) return AtomicExpansionKind::None; 12138 // Nand not supported in LSE. 12139 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 12140 // Leave 128 bits to LLSC. 12141 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 12142 } 12143 12144 TargetLowering::AtomicExpansionKind 12145 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 12146 AtomicCmpXchgInst *AI) const { 12147 // If subtarget has LSE, leave cmpxchg intact for codegen. 12148 if (Subtarget->hasLSE()) 12149 return AtomicExpansionKind::None; 12150 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 12151 // implement cmpxchg without spilling. If the address being exchanged is also 12152 // on the stack and close enough to the spill slot, this can lead to a 12153 // situation where the monitor always gets cleared and the atomic operation 12154 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 12155 if (getTargetMachine().getOptLevel() == 0) 12156 return AtomicExpansionKind::None; 12157 return AtomicExpansionKind::LLSC; 12158 } 12159 12160 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 12161 AtomicOrdering Ord) const { 12162 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12163 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 12164 bool IsAcquire = isAcquireOrStronger(Ord); 12165 12166 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 12167 // intrinsic must return {i64, i64} and we have to recombine them into a 12168 // single i128 here. 12169 if (ValTy->getPrimitiveSizeInBits() == 128) { 12170 Intrinsic::ID Int = 12171 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 12172 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 12173 12174 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12175 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 12176 12177 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 12178 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 12179 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 12180 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 12181 return Builder.CreateOr( 12182 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 12183 } 12184 12185 Type *Tys[] = { Addr->getType() }; 12186 Intrinsic::ID Int = 12187 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 12188 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 12189 12190 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 12191 12192 const DataLayout &DL = M->getDataLayout(); 12193 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 12194 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 12195 12196 return Builder.CreateBitCast(Trunc, EltTy); 12197 } 12198 12199 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 12200 IRBuilder<> &Builder) const { 12201 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12202 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 12203 } 12204 12205 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 12206 Value *Val, Value *Addr, 12207 AtomicOrdering Ord) const { 12208 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 12209 bool IsRelease = isReleaseOrStronger(Ord); 12210 12211 // Since the intrinsics must have legal type, the i128 intrinsics take two 12212 // parameters: "i64, i64". We must marshal Val into the appropriate form 12213 // before the call. 12214 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 12215 Intrinsic::ID Int = 12216 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 12217 Function *Stxr = Intrinsic::getDeclaration(M, Int); 12218 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 12219 12220 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 12221 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 12222 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 12223 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 12224 } 12225 12226 Intrinsic::ID Int = 12227 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 12228 Type *Tys[] = { Addr->getType() }; 12229 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 12230 12231 const DataLayout &DL = M->getDataLayout(); 12232 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 12233 Val = Builder.CreateBitCast(Val, IntValTy); 12234 12235 return Builder.CreateCall(Stxr, 12236 {Builder.CreateZExtOrBitCast( 12237 Val, Stxr->getFunctionType()->getParamType(0)), 12238 Addr}); 12239 } 12240 12241 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 12242 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 12243 return Ty->isArrayTy(); 12244 } 12245 12246 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 12247 EVT) const { 12248 return false; 12249 } 12250 12251 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 12252 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 12253 Function *ThreadPointerFunc = 12254 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 12255 return IRB.CreatePointerCast( 12256 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 12257 Offset), 12258 IRB.getInt8PtrTy()->getPointerTo(0)); 12259 } 12260 12261 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 12262 // Android provides a fixed TLS slot for the stack cookie. See the definition 12263 // of TLS_SLOT_STACK_GUARD in 12264 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 12265 if (Subtarget->isTargetAndroid()) 12266 return UseTlsOffset(IRB, 0x28); 12267 12268 // Fuchsia is similar. 12269 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 12270 if (Subtarget->isTargetFuchsia()) 12271 return UseTlsOffset(IRB, -0x10); 12272 12273 return TargetLowering::getIRStackGuard(IRB); 12274 } 12275 12276 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 12277 // MSVC CRT provides functionalities for stack protection. 12278 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 12279 // MSVC CRT has a global variable holding security cookie. 12280 M.getOrInsertGlobal("__security_cookie", 12281 Type::getInt8PtrTy(M.getContext())); 12282 12283 // MSVC CRT has a function to validate security cookie. 12284 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 12285 "__security_check_cookie", Type::getVoidTy(M.getContext()), 12286 Type::getInt8PtrTy(M.getContext())); 12287 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 12288 F->setCallingConv(CallingConv::Win64); 12289 F->addAttribute(1, Attribute::AttrKind::InReg); 12290 } 12291 return; 12292 } 12293 TargetLowering::insertSSPDeclarations(M); 12294 } 12295 12296 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 12297 // MSVC CRT has a global variable holding security cookie. 12298 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 12299 return M.getGlobalVariable("__security_cookie"); 12300 return TargetLowering::getSDagStackGuard(M); 12301 } 12302 12303 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 12304 // MSVC CRT has a function to validate security cookie. 12305 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 12306 return M.getFunction("__security_check_cookie"); 12307 return TargetLowering::getSSPStackGuardCheck(M); 12308 } 12309 12310 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 12311 // Android provides a fixed TLS slot for the SafeStack pointer. See the 12312 // definition of TLS_SLOT_SAFESTACK in 12313 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 12314 if (Subtarget->isTargetAndroid()) 12315 return UseTlsOffset(IRB, 0x48); 12316 12317 // Fuchsia is similar. 12318 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 12319 if (Subtarget->isTargetFuchsia()) 12320 return UseTlsOffset(IRB, -0x8); 12321 12322 return TargetLowering::getSafeStackPointerLocation(IRB); 12323 } 12324 12325 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 12326 const Instruction &AndI) const { 12327 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 12328 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 12329 // may be beneficial to sink in other cases, but we would have to check that 12330 // the cmp would not get folded into the br to form a cbz for these to be 12331 // beneficial. 12332 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 12333 if (!Mask) 12334 return false; 12335 return Mask->getValue().isPowerOf2(); 12336 } 12337 12338 bool AArch64TargetLowering:: 12339 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 12340 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 12341 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 12342 SelectionDAG &DAG) const { 12343 // Does baseline recommend not to perform the fold by default? 12344 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 12345 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 12346 return false; 12347 // Else, if this is a vector shift, prefer 'shl'. 12348 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 12349 } 12350 12351 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 12352 SDNode *N) const { 12353 if (DAG.getMachineFunction().getFunction().hasMinSize() && 12354 !Subtarget->isTargetWindows()) 12355 return false; 12356 return true; 12357 } 12358 12359 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 12360 // Update IsSplitCSR in AArch64unctionInfo. 12361 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 12362 AFI->setIsSplitCSR(true); 12363 } 12364 12365 void AArch64TargetLowering::insertCopiesSplitCSR( 12366 MachineBasicBlock *Entry, 12367 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 12368 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 12369 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 12370 if (!IStart) 12371 return; 12372 12373 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 12374 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 12375 MachineBasicBlock::iterator MBBI = Entry->begin(); 12376 for (const MCPhysReg *I = IStart; *I; ++I) { 12377 const TargetRegisterClass *RC = nullptr; 12378 if (AArch64::GPR64RegClass.contains(*I)) 12379 RC = &AArch64::GPR64RegClass; 12380 else if (AArch64::FPR64RegClass.contains(*I)) 12381 RC = &AArch64::FPR64RegClass; 12382 else 12383 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12384 12385 Register NewVR = MRI->createVirtualRegister(RC); 12386 // Create copy from CSR to a virtual register. 12387 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12388 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12389 // nounwind. If we want to generalize this later, we may need to emit 12390 // CFI pseudo-instructions. 12391 assert(Entry->getParent()->getFunction().hasFnAttribute( 12392 Attribute::NoUnwind) && 12393 "Function should be nounwind in insertCopiesSplitCSR!"); 12394 Entry->addLiveIn(*I); 12395 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12396 .addReg(*I); 12397 12398 // Insert the copy-back instructions right before the terminator. 12399 for (auto *Exit : Exits) 12400 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12401 TII->get(TargetOpcode::COPY), *I) 12402 .addReg(NewVR); 12403 } 12404 } 12405 12406 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 12407 // Integer division on AArch64 is expensive. However, when aggressively 12408 // optimizing for code size, we prefer to use a div instruction, as it is 12409 // usually smaller than the alternative sequence. 12410 // The exception to this is vector division. Since AArch64 doesn't have vector 12411 // integer division, leaving the division as-is is a loss even in terms of 12412 // size, because it will have to be scalarized, while the alternative code 12413 // sequence can be performed in vector form. 12414 bool OptSize = 12415 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 12416 return OptSize && !VT.isVector(); 12417 } 12418 12419 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 12420 // We want inc-of-add for scalars and sub-of-not for vectors. 12421 return VT.isScalarInteger(); 12422 } 12423 12424 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 12425 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 12426 } 12427 12428 unsigned 12429 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 12430 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 12431 return getPointerTy(DL).getSizeInBits(); 12432 12433 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 12434 } 12435 12436 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 12437 MF.getFrameInfo().computeMaxCallFrameSize(MF); 12438 TargetLoweringBase::finalizeLowering(MF); 12439 } 12440 12441 // Unlike X86, we let frame lowering assign offsets to all catch objects. 12442 bool AArch64TargetLowering::needsFixedCatchObjects() const { 12443 return false; 12444 } 12445