1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the AArch64TargetLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AArch64ISelLowering.h" 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/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/Analysis/VectorUtils.h" 33 #include "llvm/CodeGen/CallingConvLower.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineMemOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/MachineValueType.h" 42 #include "llvm/CodeGen/RuntimeLibcalls.h" 43 #include "llvm/CodeGen/SelectionDAG.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Attributes.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugLoc.h" 50 #include "llvm/IR/DerivedTypes.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/GetElementPtrTypeIterator.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/IRBuilder.h" 55 #include "llvm/IR/Instruction.h" 56 #include "llvm/IR/Instructions.h" 57 #include "llvm/IR/Intrinsics.h" 58 #include "llvm/IR/Module.h" 59 #include "llvm/IR/OperandTraits.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/Use.h" 62 #include "llvm/IR/Value.h" 63 #include "llvm/MC/MCRegisterInfo.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CodeGen.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Compiler.h" 68 #include "llvm/Support/Debug.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/KnownBits.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/Target/TargetCallingConv.h" 74 #include "llvm/Target/TargetInstrInfo.h" 75 #include "llvm/Target/TargetMachine.h" 76 #include "llvm/Target/TargetOptions.h" 77 #include <algorithm> 78 #include <bitset> 79 #include <cassert> 80 #include <cctype> 81 #include <cstdint> 82 #include <cstdlib> 83 #include <iterator> 84 #include <limits> 85 #include <tuple> 86 #include <utility> 87 #include <vector> 88 89 using namespace llvm; 90 91 #define DEBUG_TYPE "aarch64-lower" 92 93 STATISTIC(NumTailCalls, "Number of tail calls"); 94 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 96 97 static cl::opt<bool> 98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 99 cl::desc("Allow AArch64 SLI/SRI formation"), 100 cl::init(false)); 101 102 // FIXME: The necessary dtprel relocations don't seem to be supported 103 // well in the GNU bfd and gold linkers at the moment. Therefore, by 104 // default, for now, fall back to GeneralDynamic code generation. 105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 106 "aarch64-elf-ldtls-generation", cl::Hidden, 107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 112 cl::desc("Enable AArch64 logical imm instruction " 113 "optimization"), 114 cl::init(true)); 115 116 /// Value type used for condition codes. 117 static const MVT MVT_CC = MVT::i32; 118 119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 120 const AArch64Subtarget &STI) 121 : TargetLowering(TM), Subtarget(&STI) { 122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 123 // we have to make something up. Arbitrarily, choose ZeroOrOne. 124 setBooleanContents(ZeroOrOneBooleanContent); 125 // When comparing vectors the result sets the different elements in the 126 // vector to all-one or all-zero. 127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 128 129 // Set up the register classes. 130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 132 133 if (Subtarget->hasFPARMv8()) { 134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 138 } 139 140 if (Subtarget->hasNEON()) { 141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 143 // Someone set us up the NEON. 144 addDRTypeForNEON(MVT::v2f32); 145 addDRTypeForNEON(MVT::v8i8); 146 addDRTypeForNEON(MVT::v4i16); 147 addDRTypeForNEON(MVT::v2i32); 148 addDRTypeForNEON(MVT::v1i64); 149 addDRTypeForNEON(MVT::v1f64); 150 addDRTypeForNEON(MVT::v4f16); 151 152 addQRTypeForNEON(MVT::v4f32); 153 addQRTypeForNEON(MVT::v2f64); 154 addQRTypeForNEON(MVT::v16i8); 155 addQRTypeForNEON(MVT::v8i16); 156 addQRTypeForNEON(MVT::v4i32); 157 addQRTypeForNEON(MVT::v2i64); 158 addQRTypeForNEON(MVT::v8f16); 159 } 160 161 // Compute derived properties from the register classes 162 computeRegisterProperties(Subtarget->getRegisterInfo()); 163 164 // Provide all sorts of operation actions 165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 167 setOperationAction(ISD::SETCC, MVT::i32, Custom); 168 setOperationAction(ISD::SETCC, MVT::i64, Custom); 169 setOperationAction(ISD::SETCC, MVT::f32, Custom); 170 setOperationAction(ISD::SETCC, MVT::f64, Custom); 171 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 172 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 173 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 174 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 175 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 176 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 177 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 178 setOperationAction(ISD::SELECT, MVT::i32, Custom); 179 setOperationAction(ISD::SELECT, MVT::i64, Custom); 180 setOperationAction(ISD::SELECT, MVT::f32, Custom); 181 setOperationAction(ISD::SELECT, MVT::f64, Custom); 182 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 183 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 184 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 185 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 186 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 187 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 188 189 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 190 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 191 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 192 193 setOperationAction(ISD::FREM, MVT::f32, Expand); 194 setOperationAction(ISD::FREM, MVT::f64, Expand); 195 setOperationAction(ISD::FREM, MVT::f80, Expand); 196 197 // Custom lowering hooks are needed for XOR 198 // to fold it into CSINC/CSINV. 199 setOperationAction(ISD::XOR, MVT::i32, Custom); 200 setOperationAction(ISD::XOR, MVT::i64, Custom); 201 202 // Virtually no operation on f128 is legal, but LLVM can't expand them when 203 // there's a valid register class, so we need custom operations in most cases. 204 setOperationAction(ISD::FABS, MVT::f128, Expand); 205 setOperationAction(ISD::FADD, MVT::f128, Custom); 206 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 207 setOperationAction(ISD::FCOS, MVT::f128, Expand); 208 setOperationAction(ISD::FDIV, MVT::f128, Custom); 209 setOperationAction(ISD::FMA, MVT::f128, Expand); 210 setOperationAction(ISD::FMUL, MVT::f128, Custom); 211 setOperationAction(ISD::FNEG, MVT::f128, Expand); 212 setOperationAction(ISD::FPOW, MVT::f128, Expand); 213 setOperationAction(ISD::FREM, MVT::f128, Expand); 214 setOperationAction(ISD::FRINT, MVT::f128, Expand); 215 setOperationAction(ISD::FSIN, MVT::f128, Expand); 216 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 217 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 218 setOperationAction(ISD::FSUB, MVT::f128, Custom); 219 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 220 setOperationAction(ISD::SETCC, MVT::f128, Custom); 221 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 222 setOperationAction(ISD::SELECT, MVT::f128, Custom); 223 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 224 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 225 226 // Lowering for many of the conversions is actually specified by the non-f128 227 // type. The LowerXXX function will be trivial when f128 isn't involved. 228 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 229 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 230 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 231 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 232 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 233 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 234 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 235 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 236 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 237 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 238 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 239 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 240 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 241 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 242 243 // Variable arguments. 244 setOperationAction(ISD::VASTART, MVT::Other, Custom); 245 setOperationAction(ISD::VAARG, MVT::Other, Custom); 246 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 247 setOperationAction(ISD::VAEND, MVT::Other, Expand); 248 249 // Variable-sized objects. 250 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 251 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 252 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 253 254 // Constant pool entries 255 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 256 257 // BlockAddress 258 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 259 260 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 261 setOperationAction(ISD::ADDC, MVT::i32, Custom); 262 setOperationAction(ISD::ADDE, MVT::i32, Custom); 263 setOperationAction(ISD::SUBC, MVT::i32, Custom); 264 setOperationAction(ISD::SUBE, MVT::i32, Custom); 265 setOperationAction(ISD::ADDC, MVT::i64, Custom); 266 setOperationAction(ISD::ADDE, MVT::i64, Custom); 267 setOperationAction(ISD::SUBC, MVT::i64, Custom); 268 setOperationAction(ISD::SUBE, MVT::i64, Custom); 269 270 // AArch64 lacks both left-rotate and popcount instructions. 271 setOperationAction(ISD::ROTL, MVT::i32, Expand); 272 setOperationAction(ISD::ROTL, MVT::i64, Expand); 273 for (MVT VT : MVT::vector_valuetypes()) { 274 setOperationAction(ISD::ROTL, VT, Expand); 275 setOperationAction(ISD::ROTR, VT, Expand); 276 } 277 278 // AArch64 doesn't have {U|S}MUL_LOHI. 279 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 280 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 281 282 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 283 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 284 285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 287 for (MVT VT : MVT::vector_valuetypes()) { 288 setOperationAction(ISD::SDIVREM, VT, Expand); 289 setOperationAction(ISD::UDIVREM, VT, Expand); 290 } 291 setOperationAction(ISD::SREM, MVT::i32, Expand); 292 setOperationAction(ISD::SREM, MVT::i64, Expand); 293 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 294 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 295 setOperationAction(ISD::UREM, MVT::i32, Expand); 296 setOperationAction(ISD::UREM, MVT::i64, Expand); 297 298 // Custom lower Add/Sub/Mul with overflow. 299 setOperationAction(ISD::SADDO, MVT::i32, Custom); 300 setOperationAction(ISD::SADDO, MVT::i64, Custom); 301 setOperationAction(ISD::UADDO, MVT::i32, Custom); 302 setOperationAction(ISD::UADDO, MVT::i64, Custom); 303 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 304 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 305 setOperationAction(ISD::USUBO, MVT::i32, Custom); 306 setOperationAction(ISD::USUBO, MVT::i64, Custom); 307 setOperationAction(ISD::SMULO, MVT::i32, Custom); 308 setOperationAction(ISD::SMULO, MVT::i64, Custom); 309 setOperationAction(ISD::UMULO, MVT::i32, Custom); 310 setOperationAction(ISD::UMULO, MVT::i64, Custom); 311 312 setOperationAction(ISD::FSIN, MVT::f32, Expand); 313 setOperationAction(ISD::FSIN, MVT::f64, Expand); 314 setOperationAction(ISD::FCOS, MVT::f32, Expand); 315 setOperationAction(ISD::FCOS, MVT::f64, Expand); 316 setOperationAction(ISD::FPOW, MVT::f32, Expand); 317 setOperationAction(ISD::FPOW, MVT::f64, Expand); 318 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 319 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 320 321 // f16 is a storage-only type, always promote it to f32. 322 setOperationAction(ISD::SETCC, MVT::f16, Promote); 323 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 324 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 325 setOperationAction(ISD::SELECT, MVT::f16, Promote); 326 setOperationAction(ISD::FADD, MVT::f16, Promote); 327 setOperationAction(ISD::FSUB, MVT::f16, Promote); 328 setOperationAction(ISD::FMUL, MVT::f16, Promote); 329 setOperationAction(ISD::FDIV, MVT::f16, Promote); 330 setOperationAction(ISD::FREM, MVT::f16, Promote); 331 setOperationAction(ISD::FMA, MVT::f16, Promote); 332 setOperationAction(ISD::FNEG, MVT::f16, Promote); 333 setOperationAction(ISD::FABS, MVT::f16, Promote); 334 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 335 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 336 setOperationAction(ISD::FCOS, MVT::f16, Promote); 337 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 338 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 339 setOperationAction(ISD::FPOW, MVT::f16, Promote); 340 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 341 setOperationAction(ISD::FRINT, MVT::f16, Promote); 342 setOperationAction(ISD::FSIN, MVT::f16, Promote); 343 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 344 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 345 setOperationAction(ISD::FEXP, MVT::f16, Promote); 346 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 347 setOperationAction(ISD::FLOG, MVT::f16, Promote); 348 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 349 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 350 setOperationAction(ISD::FROUND, MVT::f16, Promote); 351 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 352 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 353 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 354 setOperationAction(ISD::FMINNAN, MVT::f16, Promote); 355 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote); 356 357 // v4f16 is also a storage-only type, so promote it to v4f32 when that is 358 // known to be safe. 359 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 360 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 361 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 362 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 363 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 364 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 365 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 366 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 367 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 368 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 369 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 370 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 371 372 // Expand all other v4f16 operations. 373 // FIXME: We could generate better code by promoting some operations to 374 // a pair of v4f32s 375 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 376 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 377 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 378 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 379 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 380 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 381 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 382 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 383 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 384 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 385 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 386 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 387 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 388 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 389 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 390 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 391 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 392 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 393 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 394 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 395 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 396 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 397 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 398 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 399 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 400 401 402 // v8f16 is also a storage-only type, so expand it. 403 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 404 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 405 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 406 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 407 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 408 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 409 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 410 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 411 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 412 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 413 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 414 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 415 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 416 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 417 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 418 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 419 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 420 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 421 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 422 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 423 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 424 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 425 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 426 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 427 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 428 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 429 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 430 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 431 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 432 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 433 434 // AArch64 has implementations of a lot of rounding-like FP operations. 435 for (MVT Ty : {MVT::f32, MVT::f64}) { 436 setOperationAction(ISD::FFLOOR, Ty, Legal); 437 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 438 setOperationAction(ISD::FCEIL, Ty, Legal); 439 setOperationAction(ISD::FRINT, Ty, Legal); 440 setOperationAction(ISD::FTRUNC, Ty, Legal); 441 setOperationAction(ISD::FROUND, Ty, Legal); 442 setOperationAction(ISD::FMINNUM, Ty, Legal); 443 setOperationAction(ISD::FMAXNUM, Ty, Legal); 444 setOperationAction(ISD::FMINNAN, Ty, Legal); 445 setOperationAction(ISD::FMAXNAN, Ty, Legal); 446 } 447 448 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 449 450 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 451 452 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 453 // This requires the Performance Monitors extension. 454 if (Subtarget->hasPerfMon()) 455 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 456 457 if (Subtarget->isTargetMachO()) { 458 // For iOS, we don't want to the normal expansion of a libcall to 459 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 460 // traffic. 461 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 462 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 463 } else { 464 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 465 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 466 } 467 468 // Make floating-point constants legal for the large code model, so they don't 469 // become loads from the constant pool. 470 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 471 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 472 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 473 } 474 475 // AArch64 does not have floating-point extending loads, i1 sign-extending 476 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 477 for (MVT VT : MVT::fp_valuetypes()) { 478 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 479 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 480 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 481 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 482 } 483 for (MVT VT : MVT::integer_valuetypes()) 484 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 485 486 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 487 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 488 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 489 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 490 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 491 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 492 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 493 494 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 495 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 496 497 // Indexed loads and stores are supported. 498 for (unsigned im = (unsigned)ISD::PRE_INC; 499 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 500 setIndexedLoadAction(im, MVT::i8, Legal); 501 setIndexedLoadAction(im, MVT::i16, Legal); 502 setIndexedLoadAction(im, MVT::i32, Legal); 503 setIndexedLoadAction(im, MVT::i64, Legal); 504 setIndexedLoadAction(im, MVT::f64, Legal); 505 setIndexedLoadAction(im, MVT::f32, Legal); 506 setIndexedLoadAction(im, MVT::f16, Legal); 507 setIndexedStoreAction(im, MVT::i8, Legal); 508 setIndexedStoreAction(im, MVT::i16, Legal); 509 setIndexedStoreAction(im, MVT::i32, Legal); 510 setIndexedStoreAction(im, MVT::i64, Legal); 511 setIndexedStoreAction(im, MVT::f64, Legal); 512 setIndexedStoreAction(im, MVT::f32, Legal); 513 setIndexedStoreAction(im, MVT::f16, Legal); 514 } 515 516 // Trap. 517 setOperationAction(ISD::TRAP, MVT::Other, Legal); 518 519 // We combine OR nodes for bitfield operations. 520 setTargetDAGCombine(ISD::OR); 521 522 // Vector add and sub nodes may conceal a high-half opportunity. 523 // Also, try to fold ADD into CSINC/CSINV.. 524 setTargetDAGCombine(ISD::ADD); 525 setTargetDAGCombine(ISD::SUB); 526 setTargetDAGCombine(ISD::SRL); 527 setTargetDAGCombine(ISD::XOR); 528 setTargetDAGCombine(ISD::SINT_TO_FP); 529 setTargetDAGCombine(ISD::UINT_TO_FP); 530 531 setTargetDAGCombine(ISD::FP_TO_SINT); 532 setTargetDAGCombine(ISD::FP_TO_UINT); 533 setTargetDAGCombine(ISD::FDIV); 534 535 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 536 537 setTargetDAGCombine(ISD::ANY_EXTEND); 538 setTargetDAGCombine(ISD::ZERO_EXTEND); 539 setTargetDAGCombine(ISD::SIGN_EXTEND); 540 setTargetDAGCombine(ISD::BITCAST); 541 setTargetDAGCombine(ISD::CONCAT_VECTORS); 542 setTargetDAGCombine(ISD::STORE); 543 if (Subtarget->supportsAddressTopByteIgnored()) 544 setTargetDAGCombine(ISD::LOAD); 545 546 setTargetDAGCombine(ISD::MUL); 547 548 setTargetDAGCombine(ISD::SELECT); 549 setTargetDAGCombine(ISD::VSELECT); 550 551 setTargetDAGCombine(ISD::INTRINSIC_VOID); 552 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 553 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 554 555 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8; 556 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4; 557 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4; 558 559 setStackPointerRegisterToSaveRestore(AArch64::SP); 560 561 setSchedulingPreference(Sched::Hybrid); 562 563 EnableExtLdPromotion = true; 564 565 // Set required alignment. 566 setMinFunctionAlignment(2); 567 // Set preferred alignments. 568 setPrefFunctionAlignment(STI.getPrefFunctionAlignment()); 569 setPrefLoopAlignment(STI.getPrefLoopAlignment()); 570 571 // Only change the limit for entries in a jump table if specified by 572 // the subtarget, but not at the command line. 573 unsigned MaxJT = STI.getMaximumJumpTableSize(); 574 if (MaxJT && getMaximumJumpTableSize() == 0) 575 setMaximumJumpTableSize(MaxJT); 576 577 setHasExtractBitsInsn(true); 578 579 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 580 581 if (Subtarget->hasNEON()) { 582 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 583 // silliness like this: 584 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 585 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 586 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 587 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 588 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 589 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 590 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 591 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 592 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 593 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 594 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 595 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 596 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 597 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 598 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 599 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 600 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 601 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 602 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 603 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 604 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 605 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 606 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 607 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 608 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 609 610 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 611 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 612 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 613 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 614 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 615 616 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 617 618 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 619 // elements smaller than i32, so promote the input to i32 first. 620 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote); 621 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote); 622 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote); 623 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote); 624 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16 625 // -> v8f16 conversions. 626 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote); 627 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote); 628 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 629 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote); 630 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 631 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 632 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 633 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 634 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 635 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 636 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 637 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 638 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 639 640 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 641 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 642 643 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand); 644 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand); 645 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand); 646 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand); 647 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand); 648 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand); 649 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand); 650 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand); 651 652 // AArch64 doesn't have MUL.2d: 653 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 654 // Custom handling for some quad-vector types to detect MULL. 655 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 656 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 657 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 658 659 // Vector reductions 660 for (MVT VT : MVT::integer_valuetypes()) { 661 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 662 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 663 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 664 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 665 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 666 } 667 for (MVT VT : MVT::fp_valuetypes()) { 668 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 669 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 670 } 671 672 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 673 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 674 // Likewise, narrowing and extending vector loads/stores aren't handled 675 // directly. 676 for (MVT VT : MVT::vector_valuetypes()) { 677 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 678 679 setOperationAction(ISD::MULHS, VT, Expand); 680 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 681 setOperationAction(ISD::MULHU, VT, Expand); 682 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 683 684 setOperationAction(ISD::BSWAP, VT, Expand); 685 686 for (MVT InnerVT : MVT::vector_valuetypes()) { 687 setTruncStoreAction(VT, InnerVT, Expand); 688 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 689 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 690 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 691 } 692 } 693 694 // AArch64 has implementations of a lot of rounding-like FP operations. 695 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 696 setOperationAction(ISD::FFLOOR, Ty, Legal); 697 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 698 setOperationAction(ISD::FCEIL, Ty, Legal); 699 setOperationAction(ISD::FRINT, Ty, Legal); 700 setOperationAction(ISD::FTRUNC, Ty, Legal); 701 setOperationAction(ISD::FROUND, Ty, Legal); 702 } 703 } 704 705 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 706 } 707 708 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 709 if (VT == MVT::v2f32 || VT == MVT::v4f16) { 710 setOperationAction(ISD::LOAD, VT, Promote); 711 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32); 712 713 setOperationAction(ISD::STORE, VT, Promote); 714 AddPromotedToType(ISD::STORE, VT, MVT::v2i32); 715 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) { 716 setOperationAction(ISD::LOAD, VT, Promote); 717 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64); 718 719 setOperationAction(ISD::STORE, VT, Promote); 720 AddPromotedToType(ISD::STORE, VT, MVT::v2i64); 721 } 722 723 // Mark vector float intrinsics as expand. 724 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 725 setOperationAction(ISD::FSIN, VT, Expand); 726 setOperationAction(ISD::FCOS, VT, Expand); 727 setOperationAction(ISD::FPOW, VT, Expand); 728 setOperationAction(ISD::FLOG, VT, Expand); 729 setOperationAction(ISD::FLOG2, VT, Expand); 730 setOperationAction(ISD::FLOG10, VT, Expand); 731 setOperationAction(ISD::FEXP, VT, Expand); 732 setOperationAction(ISD::FEXP2, VT, Expand); 733 734 // But we do support custom-lowering for FCOPYSIGN. 735 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 736 } 737 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 739 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 740 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 741 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 742 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 743 setOperationAction(ISD::SRA, VT, Custom); 744 setOperationAction(ISD::SRL, VT, Custom); 745 setOperationAction(ISD::SHL, VT, Custom); 746 setOperationAction(ISD::AND, VT, Custom); 747 setOperationAction(ISD::OR, VT, Custom); 748 setOperationAction(ISD::SETCC, VT, Custom); 749 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 750 751 setOperationAction(ISD::SELECT, VT, Expand); 752 setOperationAction(ISD::SELECT_CC, VT, Expand); 753 setOperationAction(ISD::VSELECT, VT, Expand); 754 for (MVT InnerVT : MVT::all_valuetypes()) 755 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 756 757 // CNT supports only B element sizes. 758 if (VT != MVT::v8i8 && VT != MVT::v16i8) 759 setOperationAction(ISD::CTPOP, VT, Expand); 760 761 setOperationAction(ISD::UDIV, VT, Expand); 762 setOperationAction(ISD::SDIV, VT, Expand); 763 setOperationAction(ISD::UREM, VT, Expand); 764 setOperationAction(ISD::SREM, VT, Expand); 765 setOperationAction(ISD::FREM, VT, Expand); 766 767 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 768 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 769 770 if (!VT.isFloatingPoint()) 771 setOperationAction(ISD::ABS, VT, Legal); 772 773 // [SU][MIN|MAX] are available for all NEON types apart from i64. 774 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 775 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 776 setOperationAction(Opcode, VT, Legal); 777 778 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!). 779 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16) 780 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN, 781 ISD::FMINNUM, ISD::FMAXNUM}) 782 setOperationAction(Opcode, VT, Legal); 783 784 if (Subtarget->isLittleEndian()) { 785 for (unsigned im = (unsigned)ISD::PRE_INC; 786 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 787 setIndexedLoadAction(im, VT, Legal); 788 setIndexedStoreAction(im, VT, Legal); 789 } 790 } 791 } 792 793 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 794 addRegisterClass(VT, &AArch64::FPR64RegClass); 795 addTypeForNEON(VT, MVT::v2i32); 796 } 797 798 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 799 addRegisterClass(VT, &AArch64::FPR128RegClass); 800 addTypeForNEON(VT, MVT::v4i32); 801 } 802 803 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 804 EVT VT) const { 805 if (!VT.isVector()) 806 return MVT::i32; 807 return VT.changeVectorElementTypeToInteger(); 808 } 809 810 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 811 const APInt &Demanded, 812 TargetLowering::TargetLoweringOpt &TLO, 813 unsigned NewOpc) { 814 uint64_t OldImm = Imm, NewImm, Enc; 815 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 816 817 // Return if the immediate is already all zeros, all ones, a bimm32 or a 818 // bimm64. 819 if (Imm == 0 || Imm == Mask || 820 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 821 return false; 822 823 unsigned EltSize = Size; 824 uint64_t DemandedBits = Demanded.getZExtValue(); 825 826 // Clear bits that are not demanded. 827 Imm &= DemandedBits; 828 829 while (true) { 830 // The goal here is to set the non-demanded bits in a way that minimizes 831 // the number of switching between 0 and 1. In order to achieve this goal, 832 // we set the non-demanded bits to the value of the preceding demanded bits. 833 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 834 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 835 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 836 // The final result is 0b11000011. 837 uint64_t NonDemandedBits = ~DemandedBits; 838 uint64_t InvertedImm = ~Imm & DemandedBits; 839 uint64_t RotatedImm = 840 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 841 NonDemandedBits; 842 uint64_t Sum = RotatedImm + NonDemandedBits; 843 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 844 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 845 NewImm = (Imm | Ones) & Mask; 846 847 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 848 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 849 // we halve the element size and continue the search. 850 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 851 break; 852 853 // We cannot shrink the element size any further if it is 2-bits. 854 if (EltSize == 2) 855 return false; 856 857 EltSize /= 2; 858 Mask >>= EltSize; 859 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 860 861 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 862 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 863 return false; 864 865 // Merge the upper and lower halves of Imm and DemandedBits. 866 Imm |= Hi; 867 DemandedBits |= DemandedBitsHi; 868 } 869 870 ++NumOptimizedImms; 871 872 // Replicate the element across the register width. 873 while (EltSize < Size) { 874 NewImm |= NewImm << EltSize; 875 EltSize *= 2; 876 } 877 878 (void)OldImm; 879 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 880 "demanded bits should never be altered"); 881 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 882 883 // Create the new constant immediate node. 884 EVT VT = Op.getValueType(); 885 SDLoc DL(Op); 886 SDValue New; 887 888 // If the new constant immediate is all-zeros or all-ones, let the target 889 // independent DAG combine optimize this node. 890 if (NewImm == 0 || NewImm == OrigMask) { 891 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 892 TLO.DAG.getConstant(NewImm, DL, VT)); 893 // Otherwise, create a machine node so that target independent DAG combine 894 // doesn't undo this optimization. 895 } else { 896 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 897 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 898 New = SDValue( 899 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 900 } 901 902 return TLO.CombineTo(Op, New); 903 } 904 905 bool AArch64TargetLowering::targetShrinkDemandedConstant( 906 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 907 // Delay this optimization to as late as possible. 908 if (!TLO.LegalOps) 909 return false; 910 911 if (!EnableOptimizeLogicalImm) 912 return false; 913 914 EVT VT = Op.getValueType(); 915 if (VT.isVector()) 916 return false; 917 918 unsigned Size = VT.getSizeInBits(); 919 assert((Size == 32 || Size == 64) && 920 "i32 or i64 is expected after legalization."); 921 922 // Exit early if we demand all bits. 923 if (Demanded.countPopulation() == Size) 924 return false; 925 926 unsigned NewOpc; 927 switch (Op.getOpcode()) { 928 default: 929 return false; 930 case ISD::AND: 931 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 932 break; 933 case ISD::OR: 934 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 935 break; 936 case ISD::XOR: 937 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 938 break; 939 } 940 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 941 if (!C) 942 return false; 943 uint64_t Imm = C->getZExtValue(); 944 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 945 } 946 947 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 948 /// Mask are known to be either zero or one and return them Known. 949 void AArch64TargetLowering::computeKnownBitsForTargetNode( 950 const SDValue Op, KnownBits &Known, 951 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 952 switch (Op.getOpcode()) { 953 default: 954 break; 955 case AArch64ISD::CSEL: { 956 KnownBits Known2; 957 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1); 958 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1); 959 Known.Zero &= Known2.Zero; 960 Known.One &= Known2.One; 961 break; 962 } 963 case ISD::INTRINSIC_W_CHAIN: { 964 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 965 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 966 switch (IntID) { 967 default: return; 968 case Intrinsic::aarch64_ldaxr: 969 case Intrinsic::aarch64_ldxr: { 970 unsigned BitWidth = Known.getBitWidth(); 971 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 972 unsigned MemBits = VT.getScalarSizeInBits(); 973 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 974 return; 975 } 976 } 977 break; 978 } 979 case ISD::INTRINSIC_WO_CHAIN: 980 case ISD::INTRINSIC_VOID: { 981 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 982 switch (IntNo) { 983 default: 984 break; 985 case Intrinsic::aarch64_neon_umaxv: 986 case Intrinsic::aarch64_neon_uminv: { 987 // Figure out the datatype of the vector operand. The UMINV instruction 988 // will zero extend the result, so we can mark as known zero all the 989 // bits larger than the element datatype. 32-bit or larget doesn't need 990 // this as those are legal types and will be handled by isel directly. 991 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 992 unsigned BitWidth = Known.getBitWidth(); 993 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 994 assert(BitWidth >= 8 && "Unexpected width!"); 995 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 996 Known.Zero |= Mask; 997 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 998 assert(BitWidth >= 16 && "Unexpected width!"); 999 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1000 Known.Zero |= Mask; 1001 } 1002 break; 1003 } break; 1004 } 1005 } 1006 } 1007 } 1008 1009 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1010 EVT) const { 1011 return MVT::i64; 1012 } 1013 1014 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 1015 unsigned AddrSpace, 1016 unsigned Align, 1017 bool *Fast) const { 1018 if (Subtarget->requiresStrictAlign()) 1019 return false; 1020 1021 if (Fast) { 1022 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1023 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1024 // See comments in performSTORECombine() for more details about 1025 // these conditions. 1026 1027 // Code that uses clang vector extensions can mark that it 1028 // wants unaligned accesses to be treated as fast by 1029 // underspecifying alignment to be 1 or 2. 1030 Align <= 2 || 1031 1032 // Disregard v2i64. Memcpy lowering produces those and splitting 1033 // them regresses performance on micro-benchmarks and olden/bh. 1034 VT == MVT::v2i64; 1035 } 1036 return true; 1037 } 1038 1039 FastISel * 1040 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1041 const TargetLibraryInfo *libInfo) const { 1042 return AArch64::createFastISel(funcInfo, libInfo); 1043 } 1044 1045 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1046 switch ((AArch64ISD::NodeType)Opcode) { 1047 case AArch64ISD::FIRST_NUMBER: break; 1048 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1049 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1050 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1051 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1052 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1053 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1054 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1055 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1056 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1057 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1058 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1059 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1060 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1061 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1062 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1063 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1064 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1065 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1066 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1067 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1068 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1069 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1070 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1071 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1072 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1073 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1074 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1075 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1076 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1077 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1078 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1079 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1080 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1081 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1082 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1083 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1084 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1085 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1086 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 1087 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1088 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1089 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1090 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1091 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1092 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1093 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1094 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1095 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1096 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1097 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1098 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1099 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1100 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1101 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1102 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1103 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1104 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1105 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1106 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1107 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1108 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1109 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1110 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1111 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1112 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1113 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1114 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1115 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1116 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1117 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1118 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1119 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1120 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1121 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1122 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1123 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1124 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1125 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1126 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1127 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1128 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1129 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1130 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1131 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1132 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1133 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1134 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1135 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1136 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1137 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1138 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1139 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1140 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1141 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1142 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1143 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1144 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1145 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1146 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1147 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1148 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1149 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1150 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1151 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1152 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1153 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1154 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1155 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1156 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1157 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1158 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1159 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1160 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1161 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1162 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1163 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1164 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1165 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1166 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1167 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1168 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1169 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1170 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1171 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1172 } 1173 return nullptr; 1174 } 1175 1176 MachineBasicBlock * 1177 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1178 MachineBasicBlock *MBB) const { 1179 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1180 // phi node: 1181 1182 // OrigBB: 1183 // [... previous instrs leading to comparison ...] 1184 // b.ne TrueBB 1185 // b EndBB 1186 // TrueBB: 1187 // ; Fallthrough 1188 // EndBB: 1189 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1190 1191 MachineFunction *MF = MBB->getParent(); 1192 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1193 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1194 DebugLoc DL = MI.getDebugLoc(); 1195 MachineFunction::iterator It = ++MBB->getIterator(); 1196 1197 unsigned DestReg = MI.getOperand(0).getReg(); 1198 unsigned IfTrueReg = MI.getOperand(1).getReg(); 1199 unsigned IfFalseReg = MI.getOperand(2).getReg(); 1200 unsigned CondCode = MI.getOperand(3).getImm(); 1201 bool NZCVKilled = MI.getOperand(4).isKill(); 1202 1203 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1204 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1205 MF->insert(It, TrueBB); 1206 MF->insert(It, EndBB); 1207 1208 // Transfer rest of current basic-block to EndBB 1209 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1210 MBB->end()); 1211 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1212 1213 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1214 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1215 MBB->addSuccessor(TrueBB); 1216 MBB->addSuccessor(EndBB); 1217 1218 // TrueBB falls through to the end. 1219 TrueBB->addSuccessor(EndBB); 1220 1221 if (!NZCVKilled) { 1222 TrueBB->addLiveIn(AArch64::NZCV); 1223 EndBB->addLiveIn(AArch64::NZCV); 1224 } 1225 1226 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1227 .addReg(IfTrueReg) 1228 .addMBB(TrueBB) 1229 .addReg(IfFalseReg) 1230 .addMBB(MBB); 1231 1232 MI.eraseFromParent(); 1233 return EndBB; 1234 } 1235 1236 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1237 MachineInstr &MI, MachineBasicBlock *BB) const { 1238 switch (MI.getOpcode()) { 1239 default: 1240 #ifndef NDEBUG 1241 MI.dump(); 1242 #endif 1243 llvm_unreachable("Unexpected instruction for custom inserter!"); 1244 1245 case AArch64::F128CSEL: 1246 return EmitF128CSEL(MI, BB); 1247 1248 case TargetOpcode::STACKMAP: 1249 case TargetOpcode::PATCHPOINT: 1250 return emitPatchPoint(MI, BB); 1251 } 1252 } 1253 1254 //===----------------------------------------------------------------------===// 1255 // AArch64 Lowering private implementation. 1256 //===----------------------------------------------------------------------===// 1257 1258 //===----------------------------------------------------------------------===// 1259 // Lowering Code 1260 //===----------------------------------------------------------------------===// 1261 1262 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1263 /// CC 1264 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1265 switch (CC) { 1266 default: 1267 llvm_unreachable("Unknown condition code!"); 1268 case ISD::SETNE: 1269 return AArch64CC::NE; 1270 case ISD::SETEQ: 1271 return AArch64CC::EQ; 1272 case ISD::SETGT: 1273 return AArch64CC::GT; 1274 case ISD::SETGE: 1275 return AArch64CC::GE; 1276 case ISD::SETLT: 1277 return AArch64CC::LT; 1278 case ISD::SETLE: 1279 return AArch64CC::LE; 1280 case ISD::SETUGT: 1281 return AArch64CC::HI; 1282 case ISD::SETUGE: 1283 return AArch64CC::HS; 1284 case ISD::SETULT: 1285 return AArch64CC::LO; 1286 case ISD::SETULE: 1287 return AArch64CC::LS; 1288 } 1289 } 1290 1291 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1292 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1293 AArch64CC::CondCode &CondCode, 1294 AArch64CC::CondCode &CondCode2) { 1295 CondCode2 = AArch64CC::AL; 1296 switch (CC) { 1297 default: 1298 llvm_unreachable("Unknown FP condition!"); 1299 case ISD::SETEQ: 1300 case ISD::SETOEQ: 1301 CondCode = AArch64CC::EQ; 1302 break; 1303 case ISD::SETGT: 1304 case ISD::SETOGT: 1305 CondCode = AArch64CC::GT; 1306 break; 1307 case ISD::SETGE: 1308 case ISD::SETOGE: 1309 CondCode = AArch64CC::GE; 1310 break; 1311 case ISD::SETOLT: 1312 CondCode = AArch64CC::MI; 1313 break; 1314 case ISD::SETOLE: 1315 CondCode = AArch64CC::LS; 1316 break; 1317 case ISD::SETONE: 1318 CondCode = AArch64CC::MI; 1319 CondCode2 = AArch64CC::GT; 1320 break; 1321 case ISD::SETO: 1322 CondCode = AArch64CC::VC; 1323 break; 1324 case ISD::SETUO: 1325 CondCode = AArch64CC::VS; 1326 break; 1327 case ISD::SETUEQ: 1328 CondCode = AArch64CC::EQ; 1329 CondCode2 = AArch64CC::VS; 1330 break; 1331 case ISD::SETUGT: 1332 CondCode = AArch64CC::HI; 1333 break; 1334 case ISD::SETUGE: 1335 CondCode = AArch64CC::PL; 1336 break; 1337 case ISD::SETLT: 1338 case ISD::SETULT: 1339 CondCode = AArch64CC::LT; 1340 break; 1341 case ISD::SETLE: 1342 case ISD::SETULE: 1343 CondCode = AArch64CC::LE; 1344 break; 1345 case ISD::SETNE: 1346 case ISD::SETUNE: 1347 CondCode = AArch64CC::NE; 1348 break; 1349 } 1350 } 1351 1352 /// Convert a DAG fp condition code to an AArch64 CC. 1353 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1354 /// should be AND'ed instead of OR'ed. 1355 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1356 AArch64CC::CondCode &CondCode, 1357 AArch64CC::CondCode &CondCode2) { 1358 CondCode2 = AArch64CC::AL; 1359 switch (CC) { 1360 default: 1361 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1362 assert(CondCode2 == AArch64CC::AL); 1363 break; 1364 case ISD::SETONE: 1365 // (a one b) 1366 // == ((a olt b) || (a ogt b)) 1367 // == ((a ord b) && (a une b)) 1368 CondCode = AArch64CC::VC; 1369 CondCode2 = AArch64CC::NE; 1370 break; 1371 case ISD::SETUEQ: 1372 // (a ueq b) 1373 // == ((a uno b) || (a oeq b)) 1374 // == ((a ule b) && (a uge b)) 1375 CondCode = AArch64CC::PL; 1376 CondCode2 = AArch64CC::LE; 1377 break; 1378 } 1379 } 1380 1381 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1382 /// CC usable with the vector instructions. Fewer operations are available 1383 /// without a real NZCV register, so we have to use less efficient combinations 1384 /// to get the same effect. 1385 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1386 AArch64CC::CondCode &CondCode, 1387 AArch64CC::CondCode &CondCode2, 1388 bool &Invert) { 1389 Invert = false; 1390 switch (CC) { 1391 default: 1392 // Mostly the scalar mappings work fine. 1393 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1394 break; 1395 case ISD::SETUO: 1396 Invert = true; 1397 LLVM_FALLTHROUGH; 1398 case ISD::SETO: 1399 CondCode = AArch64CC::MI; 1400 CondCode2 = AArch64CC::GE; 1401 break; 1402 case ISD::SETUEQ: 1403 case ISD::SETULT: 1404 case ISD::SETULE: 1405 case ISD::SETUGT: 1406 case ISD::SETUGE: 1407 // All of the compare-mask comparisons are ordered, but we can switch 1408 // between the two by a double inversion. E.g. ULE == !OGT. 1409 Invert = true; 1410 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1411 break; 1412 } 1413 } 1414 1415 static bool isLegalArithImmed(uint64_t C) { 1416 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1417 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1418 } 1419 1420 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1421 const SDLoc &dl, SelectionDAG &DAG) { 1422 EVT VT = LHS.getValueType(); 1423 1424 if (VT.isFloatingPoint()) { 1425 assert(VT != MVT::f128); 1426 if (VT == MVT::f16) { 1427 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1428 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1429 VT = MVT::f32; 1430 } 1431 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1432 } 1433 1434 // The CMP instruction is just an alias for SUBS, and representing it as 1435 // SUBS means that it's possible to get CSE with subtract operations. 1436 // A later phase can perform the optimization of setting the destination 1437 // register to WZR/XZR if it ends up being unused. 1438 unsigned Opcode = AArch64ISD::SUBS; 1439 1440 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 1441 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1442 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on 1443 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags 1444 // can be set differently by this operation. It comes down to whether 1445 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1446 // everything is fine. If not then the optimization is wrong. Thus general 1447 // comparisons are only valid if op2 != 0. 1448 1449 // So, finally, the only LLVM-native comparisons that don't mention C and V 1450 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1451 // the absence of information about op2. 1452 Opcode = AArch64ISD::ADDS; 1453 RHS = RHS.getOperand(1); 1454 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1455 !isUnsignedIntSetCC(CC)) { 1456 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1457 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1458 // of the signed comparisons. 1459 Opcode = AArch64ISD::ANDS; 1460 RHS = LHS.getOperand(1); 1461 LHS = LHS.getOperand(0); 1462 } 1463 1464 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1465 .getValue(1); 1466 } 1467 1468 /// \defgroup AArch64CCMP CMP;CCMP matching 1469 /// 1470 /// These functions deal with the formation of CMP;CCMP;... sequences. 1471 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1472 /// a comparison. They set the NZCV flags to a predefined value if their 1473 /// predicate is false. This allows to express arbitrary conjunctions, for 1474 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))" 1475 /// expressed as: 1476 /// cmp A 1477 /// ccmp B, inv(CB), CA 1478 /// check for CB flags 1479 /// 1480 /// In general we can create code for arbitrary "... (and (and A B) C)" 1481 /// sequences. We can also implement some "or" expressions, because "(or A B)" 1482 /// is equivalent to "not (and (not A) (not B))" and we can implement some 1483 /// negation operations: 1484 /// We can negate the results of a single comparison by inverting the flags 1485 /// used when the predicate fails and inverting the flags tested in the next 1486 /// instruction; We can also negate the results of the whole previous 1487 /// conditional compare sequence by inverting the flags tested in the next 1488 /// instruction. However there is no way to negate the result of a partial 1489 /// sequence. 1490 /// 1491 /// Therefore on encountering an "or" expression we can negate the subtree on 1492 /// one side and have to be able to push the negate to the leafs of the subtree 1493 /// on the other side (see also the comments in code). As complete example: 1494 /// "or (or (setCA (cmp A)) (setCB (cmp B))) 1495 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1496 /// is transformed to 1497 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D)))) 1498 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1499 /// and implemented as: 1500 /// cmp C 1501 /// ccmp D, inv(CD), CC 1502 /// ccmp A, CA, inv(CD) 1503 /// ccmp B, CB, inv(CA) 1504 /// check for CB flags 1505 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented 1506 /// by conditional compare sequences. 1507 /// @{ 1508 1509 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1510 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1511 ISD::CondCode CC, SDValue CCOp, 1512 AArch64CC::CondCode Predicate, 1513 AArch64CC::CondCode OutCC, 1514 const SDLoc &DL, SelectionDAG &DAG) { 1515 unsigned Opcode = 0; 1516 if (LHS.getValueType().isFloatingPoint()) { 1517 assert(LHS.getValueType() != MVT::f128); 1518 if (LHS.getValueType() == MVT::f16) { 1519 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1520 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1521 } 1522 Opcode = AArch64ISD::FCCMP; 1523 } else if (RHS.getOpcode() == ISD::SUB) { 1524 SDValue SubOp0 = RHS.getOperand(0); 1525 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1526 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1527 Opcode = AArch64ISD::CCMN; 1528 RHS = RHS.getOperand(1); 1529 } 1530 } 1531 if (Opcode == 0) 1532 Opcode = AArch64ISD::CCMP; 1533 1534 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1535 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1536 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1537 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1538 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1539 } 1540 1541 /// Returns true if @p Val is a tree of AND/OR/SETCC operations. 1542 /// CanPushNegate is set to true if we can push a negate operation through 1543 /// the tree in a was that we are left with AND operations and negate operations 1544 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to 1545 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be 1546 /// brought into such a form. 1547 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate, 1548 unsigned Depth = 0) { 1549 if (!Val.hasOneUse()) 1550 return false; 1551 unsigned Opcode = Val->getOpcode(); 1552 if (Opcode == ISD::SETCC) { 1553 if (Val->getOperand(0).getValueType() == MVT::f128) 1554 return false; 1555 CanNegate = true; 1556 return true; 1557 } 1558 // Protect against exponential runtime and stack overflow. 1559 if (Depth > 6) 1560 return false; 1561 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1562 SDValue O0 = Val->getOperand(0); 1563 SDValue O1 = Val->getOperand(1); 1564 bool CanNegateL; 1565 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1)) 1566 return false; 1567 bool CanNegateR; 1568 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1)) 1569 return false; 1570 1571 if (Opcode == ISD::OR) { 1572 // For an OR expression we need to be able to negate at least one side or 1573 // we cannot do the transformation at all. 1574 if (!CanNegateL && !CanNegateR) 1575 return false; 1576 // We can however change a (not (or x y)) to (and (not x) (not y)) if we 1577 // can negate the x and y subtrees. 1578 CanNegate = CanNegateL && CanNegateR; 1579 } else { 1580 // If the operands are OR expressions then we finally need to negate their 1581 // outputs, we can only do that for the operand with emitted last by 1582 // negating OutCC, not for both operands. 1583 bool NeedsNegOutL = O0->getOpcode() == ISD::OR; 1584 bool NeedsNegOutR = O1->getOpcode() == ISD::OR; 1585 if (NeedsNegOutL && NeedsNegOutR) 1586 return false; 1587 // We cannot negate an AND operation (it would become an OR), 1588 CanNegate = false; 1589 } 1590 return true; 1591 } 1592 return false; 1593 } 1594 1595 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1596 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1597 /// Tries to transform the given i1 producing node @p Val to a series compare 1598 /// and conditional compare operations. @returns an NZCV flags producing node 1599 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1600 /// transformation was not possible. 1601 /// On recursive invocations @p PushNegate may be set to true to have negation 1602 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate 1603 /// for the comparisons in the current subtree; @p Depth limits the search 1604 /// depth to avoid stack overflow. 1605 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val, 1606 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1607 AArch64CC::CondCode Predicate) { 1608 // We're at a tree leaf, produce a conditional comparison operation. 1609 unsigned Opcode = Val->getOpcode(); 1610 if (Opcode == ISD::SETCC) { 1611 SDValue LHS = Val->getOperand(0); 1612 SDValue RHS = Val->getOperand(1); 1613 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1614 bool isInteger = LHS.getValueType().isInteger(); 1615 if (Negate) 1616 CC = getSetCCInverse(CC, isInteger); 1617 SDLoc DL(Val); 1618 // Determine OutCC and handle FP special case. 1619 if (isInteger) { 1620 OutCC = changeIntCCToAArch64CC(CC); 1621 } else { 1622 assert(LHS.getValueType().isFloatingPoint()); 1623 AArch64CC::CondCode ExtraCC; 1624 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1625 // Some floating point conditions can't be tested with a single condition 1626 // code. Construct an additional comparison in this case. 1627 if (ExtraCC != AArch64CC::AL) { 1628 SDValue ExtraCmp; 1629 if (!CCOp.getNode()) 1630 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1631 else 1632 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1633 ExtraCC, DL, DAG); 1634 CCOp = ExtraCmp; 1635 Predicate = ExtraCC; 1636 } 1637 } 1638 1639 // Produce a normal comparison if we are first in the chain 1640 if (!CCOp) 1641 return emitComparison(LHS, RHS, CC, DL, DAG); 1642 // Otherwise produce a ccmp. 1643 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1644 DAG); 1645 } 1646 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) && 1647 "Valid conjunction/disjunction tree"); 1648 1649 // Check if both sides can be transformed. 1650 SDValue LHS = Val->getOperand(0); 1651 SDValue RHS = Val->getOperand(1); 1652 1653 // In case of an OR we need to negate our operands and the result. 1654 // (A v B) <=> not(not(A) ^ not(B)) 1655 bool NegateOpsAndResult = Opcode == ISD::OR; 1656 // We can negate the results of all previous operations by inverting the 1657 // predicate flags giving us a free negation for one side. The other side 1658 // must be negatable by itself. 1659 if (NegateOpsAndResult) { 1660 // See which side we can negate. 1661 bool CanNegateL; 1662 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL); 1663 assert(isValidL && "Valid conjunction/disjunction tree"); 1664 (void)isValidL; 1665 1666 #ifndef NDEBUG 1667 bool CanNegateR; 1668 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR); 1669 assert(isValidR && "Valid conjunction/disjunction tree"); 1670 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree"); 1671 #endif 1672 1673 // Order the side which we cannot negate to RHS so we can emit it first. 1674 if (!CanNegateL) 1675 std::swap(LHS, RHS); 1676 } else { 1677 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR; 1678 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) && 1679 "Valid conjunction/disjunction tree"); 1680 // Order the side where we need to negate the output flags to RHS so it 1681 // gets emitted first. 1682 if (NeedsNegOutL) 1683 std::swap(LHS, RHS); 1684 } 1685 1686 // Emit RHS. If we want to negate the tree we only need to push a negate 1687 // through if we are already in a PushNegate case, otherwise we can negate 1688 // the "flags to test" afterwards. 1689 AArch64CC::CondCode RHSCC; 1690 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate, 1691 CCOp, Predicate); 1692 if (NegateOpsAndResult && !Negate) 1693 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1694 // Emit LHS. We may need to negate it. 1695 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC, 1696 NegateOpsAndResult, CmpR, 1697 RHSCC); 1698 // If we transformed an OR to and AND then we have to negate the result 1699 // (or absorb the Negate parameter). 1700 if (NegateOpsAndResult && !Negate) 1701 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1702 return CmpL; 1703 } 1704 1705 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1706 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1707 /// \see emitConjunctionDisjunctionTreeRec(). 1708 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val, 1709 AArch64CC::CondCode &OutCC) { 1710 bool CanNegate; 1711 if (!isConjunctionDisjunctionTree(Val, CanNegate)) 1712 return SDValue(); 1713 1714 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(), 1715 AArch64CC::AL); 1716 } 1717 1718 /// @} 1719 1720 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1721 SDValue &AArch64cc, SelectionDAG &DAG, 1722 const SDLoc &dl) { 1723 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1724 EVT VT = RHS.getValueType(); 1725 uint64_t C = RHSC->getZExtValue(); 1726 if (!isLegalArithImmed(C)) { 1727 // Constant does not fit, try adjusting it by one? 1728 switch (CC) { 1729 default: 1730 break; 1731 case ISD::SETLT: 1732 case ISD::SETGE: 1733 if ((VT == MVT::i32 && C != 0x80000000 && 1734 isLegalArithImmed((uint32_t)(C - 1))) || 1735 (VT == MVT::i64 && C != 0x80000000ULL && 1736 isLegalArithImmed(C - 1ULL))) { 1737 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1738 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1739 RHS = DAG.getConstant(C, dl, VT); 1740 } 1741 break; 1742 case ISD::SETULT: 1743 case ISD::SETUGE: 1744 if ((VT == MVT::i32 && C != 0 && 1745 isLegalArithImmed((uint32_t)(C - 1))) || 1746 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1747 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1748 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1749 RHS = DAG.getConstant(C, dl, VT); 1750 } 1751 break; 1752 case ISD::SETLE: 1753 case ISD::SETGT: 1754 if ((VT == MVT::i32 && C != INT32_MAX && 1755 isLegalArithImmed((uint32_t)(C + 1))) || 1756 (VT == MVT::i64 && C != INT64_MAX && 1757 isLegalArithImmed(C + 1ULL))) { 1758 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1759 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1760 RHS = DAG.getConstant(C, dl, VT); 1761 } 1762 break; 1763 case ISD::SETULE: 1764 case ISD::SETUGT: 1765 if ((VT == MVT::i32 && C != UINT32_MAX && 1766 isLegalArithImmed((uint32_t)(C + 1))) || 1767 (VT == MVT::i64 && C != UINT64_MAX && 1768 isLegalArithImmed(C + 1ULL))) { 1769 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1770 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1771 RHS = DAG.getConstant(C, dl, VT); 1772 } 1773 break; 1774 } 1775 } 1776 } 1777 SDValue Cmp; 1778 AArch64CC::CondCode AArch64CC; 1779 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1780 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1781 1782 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1783 // For the i8 operand, the largest immediate is 255, so this can be easily 1784 // encoded in the compare instruction. For the i16 operand, however, the 1785 // largest immediate cannot be encoded in the compare. 1786 // Therefore, use a sign extending load and cmn to avoid materializing the 1787 // -1 constant. For example, 1788 // movz w1, #65535 1789 // ldrh w0, [x0, #0] 1790 // cmp w0, w1 1791 // > 1792 // ldrsh w0, [x0, #0] 1793 // cmn w0, #1 1794 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1795 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1796 // ensure both the LHS and RHS are truly zero extended and to make sure the 1797 // transformation is profitable. 1798 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1799 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1800 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1801 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1802 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1803 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1804 SDValue SExt = 1805 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1806 DAG.getValueType(MVT::i16)); 1807 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1808 RHS.getValueType()), 1809 CC, dl, DAG); 1810 AArch64CC = changeIntCCToAArch64CC(CC); 1811 } 1812 } 1813 1814 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 1815 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) { 1816 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 1817 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 1818 } 1819 } 1820 } 1821 1822 if (!Cmp) { 1823 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 1824 AArch64CC = changeIntCCToAArch64CC(CC); 1825 } 1826 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 1827 return Cmp; 1828 } 1829 1830 static std::pair<SDValue, SDValue> 1831 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 1832 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 1833 "Unsupported value type"); 1834 SDValue Value, Overflow; 1835 SDLoc DL(Op); 1836 SDValue LHS = Op.getOperand(0); 1837 SDValue RHS = Op.getOperand(1); 1838 unsigned Opc = 0; 1839 switch (Op.getOpcode()) { 1840 default: 1841 llvm_unreachable("Unknown overflow instruction!"); 1842 case ISD::SADDO: 1843 Opc = AArch64ISD::ADDS; 1844 CC = AArch64CC::VS; 1845 break; 1846 case ISD::UADDO: 1847 Opc = AArch64ISD::ADDS; 1848 CC = AArch64CC::HS; 1849 break; 1850 case ISD::SSUBO: 1851 Opc = AArch64ISD::SUBS; 1852 CC = AArch64CC::VS; 1853 break; 1854 case ISD::USUBO: 1855 Opc = AArch64ISD::SUBS; 1856 CC = AArch64CC::LO; 1857 break; 1858 // Multiply needs a little bit extra work. 1859 case ISD::SMULO: 1860 case ISD::UMULO: { 1861 CC = AArch64CC::NE; 1862 bool IsSigned = Op.getOpcode() == ISD::SMULO; 1863 if (Op.getValueType() == MVT::i32) { 1864 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1865 // For a 32 bit multiply with overflow check we want the instruction 1866 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 1867 // need to generate the following pattern: 1868 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 1869 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 1870 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 1871 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1872 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 1873 DAG.getConstant(0, DL, MVT::i64)); 1874 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 1875 // operation. We need to clear out the upper 32 bits, because we used a 1876 // widening multiply that wrote all 64 bits. In the end this should be a 1877 // noop. 1878 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 1879 if (IsSigned) { 1880 // The signed overflow check requires more than just a simple check for 1881 // any bit set in the upper 32 bits of the result. These bits could be 1882 // just the sign bits of a negative number. To perform the overflow 1883 // check we have to arithmetic shift right the 32nd bit of the result by 1884 // 31 bits. Then we compare the result to the upper 32 bits. 1885 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 1886 DAG.getConstant(32, DL, MVT::i64)); 1887 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 1888 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 1889 DAG.getConstant(31, DL, MVT::i64)); 1890 // It is important that LowerBits is last, otherwise the arithmetic 1891 // shift will not be folded into the compare (SUBS). 1892 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 1893 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1894 .getValue(1); 1895 } else { 1896 // The overflow check for unsigned multiply is easy. We only need to 1897 // check if any of the upper 32 bits are set. This can be done with a 1898 // CMP (shifted register). For that we need to generate the following 1899 // pattern: 1900 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 1901 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 1902 DAG.getConstant(32, DL, MVT::i64)); 1903 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1904 Overflow = 1905 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1906 DAG.getConstant(0, DL, MVT::i64), 1907 UpperBits).getValue(1); 1908 } 1909 break; 1910 } 1911 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 1912 // For the 64 bit multiply 1913 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1914 if (IsSigned) { 1915 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 1916 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 1917 DAG.getConstant(63, DL, MVT::i64)); 1918 // It is important that LowerBits is last, otherwise the arithmetic 1919 // shift will not be folded into the compare (SUBS). 1920 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1921 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1922 .getValue(1); 1923 } else { 1924 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 1925 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1926 Overflow = 1927 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1928 DAG.getConstant(0, DL, MVT::i64), 1929 UpperBits).getValue(1); 1930 } 1931 break; 1932 } 1933 } // switch (...) 1934 1935 if (Opc) { 1936 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 1937 1938 // Emit the AArch64 operation with overflow check. 1939 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 1940 Overflow = Value.getValue(1); 1941 } 1942 return std::make_pair(Value, Overflow); 1943 } 1944 1945 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 1946 RTLIB::Libcall Call) const { 1947 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1948 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 1949 } 1950 1951 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1952 SDValue Sel = Op.getOperand(0); 1953 SDValue Other = Op.getOperand(1); 1954 1955 // If neither operand is a SELECT_CC, give up. 1956 if (Sel.getOpcode() != ISD::SELECT_CC) 1957 std::swap(Sel, Other); 1958 if (Sel.getOpcode() != ISD::SELECT_CC) 1959 return Op; 1960 1961 // The folding we want to perform is: 1962 // (xor x, (select_cc a, b, cc, 0, -1) ) 1963 // --> 1964 // (csel x, (xor x, -1), cc ...) 1965 // 1966 // The latter will get matched to a CSINV instruction. 1967 1968 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 1969 SDValue LHS = Sel.getOperand(0); 1970 SDValue RHS = Sel.getOperand(1); 1971 SDValue TVal = Sel.getOperand(2); 1972 SDValue FVal = Sel.getOperand(3); 1973 SDLoc dl(Sel); 1974 1975 // FIXME: This could be generalized to non-integer comparisons. 1976 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 1977 return Op; 1978 1979 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 1980 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 1981 1982 // The values aren't constants, this isn't the pattern we're looking for. 1983 if (!CFVal || !CTVal) 1984 return Op; 1985 1986 // We can commute the SELECT_CC by inverting the condition. This 1987 // might be needed to make this fit into a CSINV pattern. 1988 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 1989 std::swap(TVal, FVal); 1990 std::swap(CTVal, CFVal); 1991 CC = ISD::getSetCCInverse(CC, true); 1992 } 1993 1994 // If the constants line up, perform the transform! 1995 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 1996 SDValue CCVal; 1997 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 1998 1999 FVal = Other; 2000 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2001 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2002 2003 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2004 CCVal, Cmp); 2005 } 2006 2007 return Op; 2008 } 2009 2010 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2011 EVT VT = Op.getValueType(); 2012 2013 // Let legalize expand this if it isn't a legal type yet. 2014 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2015 return SDValue(); 2016 2017 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2018 2019 unsigned Opc; 2020 bool ExtraOp = false; 2021 switch (Op.getOpcode()) { 2022 default: 2023 llvm_unreachable("Invalid code"); 2024 case ISD::ADDC: 2025 Opc = AArch64ISD::ADDS; 2026 break; 2027 case ISD::SUBC: 2028 Opc = AArch64ISD::SUBS; 2029 break; 2030 case ISD::ADDE: 2031 Opc = AArch64ISD::ADCS; 2032 ExtraOp = true; 2033 break; 2034 case ISD::SUBE: 2035 Opc = AArch64ISD::SBCS; 2036 ExtraOp = true; 2037 break; 2038 } 2039 2040 if (!ExtraOp) 2041 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2042 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2043 Op.getOperand(2)); 2044 } 2045 2046 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2047 // Let legalize expand this if it isn't a legal type yet. 2048 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2049 return SDValue(); 2050 2051 SDLoc dl(Op); 2052 AArch64CC::CondCode CC; 2053 // The actual operation that sets the overflow or carry flag. 2054 SDValue Value, Overflow; 2055 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2056 2057 // We use 0 and 1 as false and true values. 2058 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2059 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2060 2061 // We use an inverted condition, because the conditional select is inverted 2062 // too. This will allow it to be selected to a single instruction: 2063 // CSINC Wd, WZR, WZR, invert(cond). 2064 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2065 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2066 CCVal, Overflow); 2067 2068 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2069 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2070 } 2071 2072 // Prefetch operands are: 2073 // 1: Address to prefetch 2074 // 2: bool isWrite 2075 // 3: int locality (0 = no locality ... 3 = extreme locality) 2076 // 4: bool isDataCache 2077 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2078 SDLoc DL(Op); 2079 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2080 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2081 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2082 2083 bool IsStream = !Locality; 2084 // When the locality number is set 2085 if (Locality) { 2086 // The front-end should have filtered out the out-of-range values 2087 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2088 // The locality degree is the opposite of the cache speed. 2089 // Put the number the other way around. 2090 // The encoding starts at 0 for level 1 2091 Locality = 3 - Locality; 2092 } 2093 2094 // built the mask value encoding the expected behavior. 2095 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2096 (!IsData << 3) | // IsDataCache bit 2097 (Locality << 1) | // Cache level bits 2098 (unsigned)IsStream; // Stream bit 2099 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2100 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2101 } 2102 2103 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2104 SelectionDAG &DAG) const { 2105 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2106 2107 RTLIB::Libcall LC; 2108 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2109 2110 return LowerF128Call(Op, DAG, LC); 2111 } 2112 2113 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2114 SelectionDAG &DAG) const { 2115 if (Op.getOperand(0).getValueType() != MVT::f128) { 2116 // It's legal except when f128 is involved 2117 return Op; 2118 } 2119 2120 RTLIB::Libcall LC; 2121 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 2122 2123 // FP_ROUND node has a second operand indicating whether it is known to be 2124 // precise. That doesn't take part in the LibCall so we can't directly use 2125 // LowerF128Call. 2126 SDValue SrcVal = Op.getOperand(0); 2127 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 2128 SDLoc(Op)).first; 2129 } 2130 2131 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 2132 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2133 // Any additional optimization in this function should be recorded 2134 // in the cost tables. 2135 EVT InVT = Op.getOperand(0).getValueType(); 2136 EVT VT = Op.getValueType(); 2137 unsigned NumElts = InVT.getVectorNumElements(); 2138 2139 // f16 vectors are promoted to f32 before a conversion. 2140 if (InVT.getVectorElementType() == MVT::f16) { 2141 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2142 SDLoc dl(Op); 2143 return DAG.getNode( 2144 Op.getOpcode(), dl, Op.getValueType(), 2145 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2146 } 2147 2148 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2149 SDLoc dl(Op); 2150 SDValue Cv = 2151 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2152 Op.getOperand(0)); 2153 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2154 } 2155 2156 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2157 SDLoc dl(Op); 2158 MVT ExtVT = 2159 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2160 VT.getVectorNumElements()); 2161 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2162 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2163 } 2164 2165 // Type changing conversions are illegal. 2166 return Op; 2167 } 2168 2169 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2170 SelectionDAG &DAG) const { 2171 if (Op.getOperand(0).getValueType().isVector()) 2172 return LowerVectorFP_TO_INT(Op, DAG); 2173 2174 // f16 conversions are promoted to f32. 2175 if (Op.getOperand(0).getValueType() == MVT::f16) { 2176 SDLoc dl(Op); 2177 return DAG.getNode( 2178 Op.getOpcode(), dl, Op.getValueType(), 2179 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2180 } 2181 2182 if (Op.getOperand(0).getValueType() != MVT::f128) { 2183 // It's legal except when f128 is involved 2184 return Op; 2185 } 2186 2187 RTLIB::Libcall LC; 2188 if (Op.getOpcode() == ISD::FP_TO_SINT) 2189 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2190 else 2191 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2192 2193 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2194 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2195 } 2196 2197 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2198 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2199 // Any additional optimization in this function should be recorded 2200 // in the cost tables. 2201 EVT VT = Op.getValueType(); 2202 SDLoc dl(Op); 2203 SDValue In = Op.getOperand(0); 2204 EVT InVT = In.getValueType(); 2205 2206 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2207 MVT CastVT = 2208 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2209 InVT.getVectorNumElements()); 2210 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2211 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2212 } 2213 2214 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2215 unsigned CastOpc = 2216 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2217 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2218 In = DAG.getNode(CastOpc, dl, CastVT, In); 2219 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2220 } 2221 2222 return Op; 2223 } 2224 2225 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2226 SelectionDAG &DAG) const { 2227 if (Op.getValueType().isVector()) 2228 return LowerVectorINT_TO_FP(Op, DAG); 2229 2230 // f16 conversions are promoted to f32. 2231 if (Op.getValueType() == MVT::f16) { 2232 SDLoc dl(Op); 2233 return DAG.getNode( 2234 ISD::FP_ROUND, dl, MVT::f16, 2235 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2236 DAG.getIntPtrConstant(0, dl)); 2237 } 2238 2239 // i128 conversions are libcalls. 2240 if (Op.getOperand(0).getValueType() == MVT::i128) 2241 return SDValue(); 2242 2243 // Other conversions are legal, unless it's to the completely software-based 2244 // fp128. 2245 if (Op.getValueType() != MVT::f128) 2246 return Op; 2247 2248 RTLIB::Libcall LC; 2249 if (Op.getOpcode() == ISD::SINT_TO_FP) 2250 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2251 else 2252 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2253 2254 return LowerF128Call(Op, DAG, LC); 2255 } 2256 2257 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2258 SelectionDAG &DAG) const { 2259 // For iOS, we want to call an alternative entry point: __sincos_stret, 2260 // which returns the values in two S / D registers. 2261 SDLoc dl(Op); 2262 SDValue Arg = Op.getOperand(0); 2263 EVT ArgVT = Arg.getValueType(); 2264 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2265 2266 ArgListTy Args; 2267 ArgListEntry Entry; 2268 2269 Entry.Node = Arg; 2270 Entry.Ty = ArgTy; 2271 Entry.IsSExt = false; 2272 Entry.IsZExt = false; 2273 Args.push_back(Entry); 2274 2275 const char *LibcallName = 2276 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2277 SDValue Callee = 2278 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2279 2280 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2281 TargetLowering::CallLoweringInfo CLI(DAG); 2282 CLI.setDebugLoc(dl) 2283 .setChain(DAG.getEntryNode()) 2284 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2285 2286 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2287 return CallResult.first; 2288 } 2289 2290 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2291 if (Op.getValueType() != MVT::f16) 2292 return SDValue(); 2293 2294 assert(Op.getOperand(0).getValueType() == MVT::i16); 2295 SDLoc DL(Op); 2296 2297 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2298 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2299 return SDValue( 2300 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2301 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2302 0); 2303 } 2304 2305 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2306 if (OrigVT.getSizeInBits() >= 64) 2307 return OrigVT; 2308 2309 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2310 2311 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2312 switch (OrigSimpleTy) { 2313 default: llvm_unreachable("Unexpected Vector Type"); 2314 case MVT::v2i8: 2315 case MVT::v2i16: 2316 return MVT::v2i32; 2317 case MVT::v4i8: 2318 return MVT::v4i16; 2319 } 2320 } 2321 2322 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2323 const EVT &OrigTy, 2324 const EVT &ExtTy, 2325 unsigned ExtOpcode) { 2326 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2327 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2328 // 64-bits we need to insert a new extension so that it will be 64-bits. 2329 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2330 if (OrigTy.getSizeInBits() >= 64) 2331 return N; 2332 2333 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2334 EVT NewVT = getExtensionTo64Bits(OrigTy); 2335 2336 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2337 } 2338 2339 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2340 bool isSigned) { 2341 EVT VT = N->getValueType(0); 2342 2343 if (N->getOpcode() != ISD::BUILD_VECTOR) 2344 return false; 2345 2346 for (const SDValue &Elt : N->op_values()) { 2347 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2348 unsigned EltSize = VT.getScalarSizeInBits(); 2349 unsigned HalfSize = EltSize / 2; 2350 if (isSigned) { 2351 if (!isIntN(HalfSize, C->getSExtValue())) 2352 return false; 2353 } else { 2354 if (!isUIntN(HalfSize, C->getZExtValue())) 2355 return false; 2356 } 2357 continue; 2358 } 2359 return false; 2360 } 2361 2362 return true; 2363 } 2364 2365 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2366 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2367 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2368 N->getOperand(0)->getValueType(0), 2369 N->getValueType(0), 2370 N->getOpcode()); 2371 2372 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2373 EVT VT = N->getValueType(0); 2374 SDLoc dl(N); 2375 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2376 unsigned NumElts = VT.getVectorNumElements(); 2377 MVT TruncVT = MVT::getIntegerVT(EltSize); 2378 SmallVector<SDValue, 8> Ops; 2379 for (unsigned i = 0; i != NumElts; ++i) { 2380 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2381 const APInt &CInt = C->getAPIntValue(); 2382 // Element types smaller than 32 bits are not legal, so use i32 elements. 2383 // The values are implicitly truncated so sext vs. zext doesn't matter. 2384 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2385 } 2386 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2387 } 2388 2389 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2390 return N->getOpcode() == ISD::SIGN_EXTEND || 2391 isExtendedBUILD_VECTOR(N, DAG, true); 2392 } 2393 2394 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2395 return N->getOpcode() == ISD::ZERO_EXTEND || 2396 isExtendedBUILD_VECTOR(N, DAG, false); 2397 } 2398 2399 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2400 unsigned Opcode = N->getOpcode(); 2401 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2402 SDNode *N0 = N->getOperand(0).getNode(); 2403 SDNode *N1 = N->getOperand(1).getNode(); 2404 return N0->hasOneUse() && N1->hasOneUse() && 2405 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2406 } 2407 return false; 2408 } 2409 2410 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2411 unsigned Opcode = N->getOpcode(); 2412 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2413 SDNode *N0 = N->getOperand(0).getNode(); 2414 SDNode *N1 = N->getOperand(1).getNode(); 2415 return N0->hasOneUse() && N1->hasOneUse() && 2416 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2417 } 2418 return false; 2419 } 2420 2421 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2422 // Multiplications are only custom-lowered for 128-bit vectors so that 2423 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2424 EVT VT = Op.getValueType(); 2425 assert(VT.is128BitVector() && VT.isInteger() && 2426 "unexpected type for custom-lowering ISD::MUL"); 2427 SDNode *N0 = Op.getOperand(0).getNode(); 2428 SDNode *N1 = Op.getOperand(1).getNode(); 2429 unsigned NewOpc = 0; 2430 bool isMLA = false; 2431 bool isN0SExt = isSignExtended(N0, DAG); 2432 bool isN1SExt = isSignExtended(N1, DAG); 2433 if (isN0SExt && isN1SExt) 2434 NewOpc = AArch64ISD::SMULL; 2435 else { 2436 bool isN0ZExt = isZeroExtended(N0, DAG); 2437 bool isN1ZExt = isZeroExtended(N1, DAG); 2438 if (isN0ZExt && isN1ZExt) 2439 NewOpc = AArch64ISD::UMULL; 2440 else if (isN1SExt || isN1ZExt) { 2441 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2442 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2443 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2444 NewOpc = AArch64ISD::SMULL; 2445 isMLA = true; 2446 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2447 NewOpc = AArch64ISD::UMULL; 2448 isMLA = true; 2449 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2450 std::swap(N0, N1); 2451 NewOpc = AArch64ISD::UMULL; 2452 isMLA = true; 2453 } 2454 } 2455 2456 if (!NewOpc) { 2457 if (VT == MVT::v2i64) 2458 // Fall through to expand this. It is not legal. 2459 return SDValue(); 2460 else 2461 // Other vector multiplications are legal. 2462 return Op; 2463 } 2464 } 2465 2466 // Legalize to a S/UMULL instruction 2467 SDLoc DL(Op); 2468 SDValue Op0; 2469 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2470 if (!isMLA) { 2471 Op0 = skipExtensionForVectorMULL(N0, DAG); 2472 assert(Op0.getValueType().is64BitVector() && 2473 Op1.getValueType().is64BitVector() && 2474 "unexpected types for extended operands to VMULL"); 2475 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2476 } 2477 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2478 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2479 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2480 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2481 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2482 EVT Op1VT = Op1.getValueType(); 2483 return DAG.getNode(N0->getOpcode(), DL, VT, 2484 DAG.getNode(NewOpc, DL, VT, 2485 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2486 DAG.getNode(NewOpc, DL, VT, 2487 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2488 } 2489 2490 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2491 SelectionDAG &DAG) const { 2492 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2493 SDLoc dl(Op); 2494 switch (IntNo) { 2495 default: return SDValue(); // Don't custom lower most intrinsics. 2496 case Intrinsic::thread_pointer: { 2497 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2498 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2499 } 2500 case Intrinsic::aarch64_neon_abs: 2501 return DAG.getNode(ISD::ABS, dl, Op.getValueType(), 2502 Op.getOperand(1)); 2503 case Intrinsic::aarch64_neon_smax: 2504 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2505 Op.getOperand(1), Op.getOperand(2)); 2506 case Intrinsic::aarch64_neon_umax: 2507 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2508 Op.getOperand(1), Op.getOperand(2)); 2509 case Intrinsic::aarch64_neon_smin: 2510 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2511 Op.getOperand(1), Op.getOperand(2)); 2512 case Intrinsic::aarch64_neon_umin: 2513 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2514 Op.getOperand(1), Op.getOperand(2)); 2515 } 2516 } 2517 2518 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2519 SelectionDAG &DAG) const { 2520 switch (Op.getOpcode()) { 2521 default: 2522 llvm_unreachable("unimplemented operand"); 2523 return SDValue(); 2524 case ISD::BITCAST: 2525 return LowerBITCAST(Op, DAG); 2526 case ISD::GlobalAddress: 2527 return LowerGlobalAddress(Op, DAG); 2528 case ISD::GlobalTLSAddress: 2529 return LowerGlobalTLSAddress(Op, DAG); 2530 case ISD::SETCC: 2531 return LowerSETCC(Op, DAG); 2532 case ISD::BR_CC: 2533 return LowerBR_CC(Op, DAG); 2534 case ISD::SELECT: 2535 return LowerSELECT(Op, DAG); 2536 case ISD::SELECT_CC: 2537 return LowerSELECT_CC(Op, DAG); 2538 case ISD::JumpTable: 2539 return LowerJumpTable(Op, DAG); 2540 case ISD::ConstantPool: 2541 return LowerConstantPool(Op, DAG); 2542 case ISD::BlockAddress: 2543 return LowerBlockAddress(Op, DAG); 2544 case ISD::VASTART: 2545 return LowerVASTART(Op, DAG); 2546 case ISD::VACOPY: 2547 return LowerVACOPY(Op, DAG); 2548 case ISD::VAARG: 2549 return LowerVAARG(Op, DAG); 2550 case ISD::ADDC: 2551 case ISD::ADDE: 2552 case ISD::SUBC: 2553 case ISD::SUBE: 2554 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2555 case ISD::SADDO: 2556 case ISD::UADDO: 2557 case ISD::SSUBO: 2558 case ISD::USUBO: 2559 case ISD::SMULO: 2560 case ISD::UMULO: 2561 return LowerXALUO(Op, DAG); 2562 case ISD::FADD: 2563 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2564 case ISD::FSUB: 2565 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2566 case ISD::FMUL: 2567 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2568 case ISD::FDIV: 2569 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2570 case ISD::FP_ROUND: 2571 return LowerFP_ROUND(Op, DAG); 2572 case ISD::FP_EXTEND: 2573 return LowerFP_EXTEND(Op, DAG); 2574 case ISD::FRAMEADDR: 2575 return LowerFRAMEADDR(Op, DAG); 2576 case ISD::RETURNADDR: 2577 return LowerRETURNADDR(Op, DAG); 2578 case ISD::INSERT_VECTOR_ELT: 2579 return LowerINSERT_VECTOR_ELT(Op, DAG); 2580 case ISD::EXTRACT_VECTOR_ELT: 2581 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2582 case ISD::BUILD_VECTOR: 2583 return LowerBUILD_VECTOR(Op, DAG); 2584 case ISD::VECTOR_SHUFFLE: 2585 return LowerVECTOR_SHUFFLE(Op, DAG); 2586 case ISD::EXTRACT_SUBVECTOR: 2587 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2588 case ISD::SRA: 2589 case ISD::SRL: 2590 case ISD::SHL: 2591 return LowerVectorSRA_SRL_SHL(Op, DAG); 2592 case ISD::SHL_PARTS: 2593 return LowerShiftLeftParts(Op, DAG); 2594 case ISD::SRL_PARTS: 2595 case ISD::SRA_PARTS: 2596 return LowerShiftRightParts(Op, DAG); 2597 case ISD::CTPOP: 2598 return LowerCTPOP(Op, DAG); 2599 case ISD::FCOPYSIGN: 2600 return LowerFCOPYSIGN(Op, DAG); 2601 case ISD::AND: 2602 return LowerVectorAND(Op, DAG); 2603 case ISD::OR: 2604 return LowerVectorOR(Op, DAG); 2605 case ISD::XOR: 2606 return LowerXOR(Op, DAG); 2607 case ISD::PREFETCH: 2608 return LowerPREFETCH(Op, DAG); 2609 case ISD::SINT_TO_FP: 2610 case ISD::UINT_TO_FP: 2611 return LowerINT_TO_FP(Op, DAG); 2612 case ISD::FP_TO_SINT: 2613 case ISD::FP_TO_UINT: 2614 return LowerFP_TO_INT(Op, DAG); 2615 case ISD::FSINCOS: 2616 return LowerFSINCOS(Op, DAG); 2617 case ISD::MUL: 2618 return LowerMUL(Op, DAG); 2619 case ISD::INTRINSIC_WO_CHAIN: 2620 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2621 case ISD::VECREDUCE_ADD: 2622 case ISD::VECREDUCE_SMAX: 2623 case ISD::VECREDUCE_SMIN: 2624 case ISD::VECREDUCE_UMAX: 2625 case ISD::VECREDUCE_UMIN: 2626 case ISD::VECREDUCE_FMAX: 2627 case ISD::VECREDUCE_FMIN: 2628 return LowerVECREDUCE(Op, DAG); 2629 } 2630 } 2631 2632 //===----------------------------------------------------------------------===// 2633 // Calling Convention Implementation 2634 //===----------------------------------------------------------------------===// 2635 2636 #include "AArch64GenCallingConv.inc" 2637 2638 /// Selects the correct CCAssignFn for a given CallingConvention value. 2639 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2640 bool IsVarArg) const { 2641 switch (CC) { 2642 default: 2643 llvm_unreachable("Unsupported calling convention."); 2644 case CallingConv::WebKit_JS: 2645 return CC_AArch64_WebKit_JS; 2646 case CallingConv::GHC: 2647 return CC_AArch64_GHC; 2648 case CallingConv::C: 2649 case CallingConv::Fast: 2650 case CallingConv::PreserveMost: 2651 case CallingConv::CXX_FAST_TLS: 2652 case CallingConv::Swift: 2653 if (Subtarget->isTargetWindows() && IsVarArg) 2654 return CC_AArch64_Win64_VarArg; 2655 if (!Subtarget->isTargetDarwin()) 2656 return CC_AArch64_AAPCS; 2657 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2658 case CallingConv::Win64: 2659 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 2660 } 2661 } 2662 2663 CCAssignFn * 2664 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 2665 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 2666 : RetCC_AArch64_AAPCS; 2667 } 2668 2669 SDValue AArch64TargetLowering::LowerFormalArguments( 2670 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2671 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2672 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2673 MachineFunction &MF = DAG.getMachineFunction(); 2674 MachineFrameInfo &MFI = MF.getFrameInfo(); 2675 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()); 2676 2677 // Assign locations to all of the incoming arguments. 2678 SmallVector<CCValAssign, 16> ArgLocs; 2679 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2680 *DAG.getContext()); 2681 2682 // At this point, Ins[].VT may already be promoted to i32. To correctly 2683 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2684 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2685 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2686 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2687 // LocVT. 2688 unsigned NumArgs = Ins.size(); 2689 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2690 unsigned CurArgIdx = 0; 2691 for (unsigned i = 0; i != NumArgs; ++i) { 2692 MVT ValVT = Ins[i].VT; 2693 if (Ins[i].isOrigArg()) { 2694 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2695 CurArgIdx = Ins[i].getOrigArgIndex(); 2696 2697 // Get type of the original argument. 2698 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2699 /*AllowUnknown*/ true); 2700 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2701 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2702 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2703 ValVT = MVT::i8; 2704 else if (ActualMVT == MVT::i16) 2705 ValVT = MVT::i16; 2706 } 2707 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2708 bool Res = 2709 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2710 assert(!Res && "Call operand has unhandled type"); 2711 (void)Res; 2712 } 2713 assert(ArgLocs.size() == Ins.size()); 2714 SmallVector<SDValue, 16> ArgValues; 2715 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2716 CCValAssign &VA = ArgLocs[i]; 2717 2718 if (Ins[i].Flags.isByVal()) { 2719 // Byval is used for HFAs in the PCS, but the system should work in a 2720 // non-compliant manner for larger structs. 2721 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2722 int Size = Ins[i].Flags.getByValSize(); 2723 unsigned NumRegs = (Size + 7) / 8; 2724 2725 // FIXME: This works on big-endian for composite byvals, which are the common 2726 // case. It should also work for fundamental types too. 2727 unsigned FrameIdx = 2728 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2729 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2730 InVals.push_back(FrameIdxN); 2731 2732 continue; 2733 } 2734 2735 if (VA.isRegLoc()) { 2736 // Arguments stored in registers. 2737 EVT RegVT = VA.getLocVT(); 2738 2739 SDValue ArgValue; 2740 const TargetRegisterClass *RC; 2741 2742 if (RegVT == MVT::i32) 2743 RC = &AArch64::GPR32RegClass; 2744 else if (RegVT == MVT::i64) 2745 RC = &AArch64::GPR64RegClass; 2746 else if (RegVT == MVT::f16) 2747 RC = &AArch64::FPR16RegClass; 2748 else if (RegVT == MVT::f32) 2749 RC = &AArch64::FPR32RegClass; 2750 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2751 RC = &AArch64::FPR64RegClass; 2752 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2753 RC = &AArch64::FPR128RegClass; 2754 else 2755 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2756 2757 // Transform the arguments in physical registers into virtual ones. 2758 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2759 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2760 2761 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2762 // to 64 bits. Insert an assert[sz]ext to capture this, then 2763 // truncate to the right size. 2764 switch (VA.getLocInfo()) { 2765 default: 2766 llvm_unreachable("Unknown loc info!"); 2767 case CCValAssign::Full: 2768 break; 2769 case CCValAssign::BCvt: 2770 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2771 break; 2772 case CCValAssign::AExt: 2773 case CCValAssign::SExt: 2774 case CCValAssign::ZExt: 2775 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2776 // nodes after our lowering. 2777 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2778 break; 2779 } 2780 2781 InVals.push_back(ArgValue); 2782 2783 } else { // VA.isRegLoc() 2784 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2785 unsigned ArgOffset = VA.getLocMemOffset(); 2786 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2787 2788 uint32_t BEAlign = 0; 2789 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2790 !Ins[i].Flags.isInConsecutiveRegs()) 2791 BEAlign = 8 - ArgSize; 2792 2793 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2794 2795 // Create load nodes to retrieve arguments from the stack. 2796 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2797 SDValue ArgValue; 2798 2799 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2800 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2801 MVT MemVT = VA.getValVT(); 2802 2803 switch (VA.getLocInfo()) { 2804 default: 2805 break; 2806 case CCValAssign::BCvt: 2807 MemVT = VA.getLocVT(); 2808 break; 2809 case CCValAssign::SExt: 2810 ExtType = ISD::SEXTLOAD; 2811 break; 2812 case CCValAssign::ZExt: 2813 ExtType = ISD::ZEXTLOAD; 2814 break; 2815 case CCValAssign::AExt: 2816 ExtType = ISD::EXTLOAD; 2817 break; 2818 } 2819 2820 ArgValue = DAG.getExtLoad( 2821 ExtType, DL, VA.getLocVT(), Chain, FIN, 2822 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2823 MemVT); 2824 2825 InVals.push_back(ArgValue); 2826 } 2827 } 2828 2829 // varargs 2830 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2831 if (isVarArg) { 2832 if (!Subtarget->isTargetDarwin() || IsWin64) { 2833 // The AAPCS variadic function ABI is identical to the non-variadic 2834 // one. As a result there may be more arguments in registers and we should 2835 // save them for future reference. 2836 // Win64 variadic functions also pass arguments in registers, but all float 2837 // arguments are passed in integer registers. 2838 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2839 } 2840 2841 // This will point to the next argument passed via stack. 2842 unsigned StackOffset = CCInfo.getNextStackOffset(); 2843 // We currently pass all varargs at 8-byte alignment. 2844 StackOffset = ((StackOffset + 7) & ~7); 2845 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 2846 } 2847 2848 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2849 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2850 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2851 // This is a non-standard ABI so by fiat I say we're allowed to make full 2852 // use of the stack area to be popped, which must be aligned to 16 bytes in 2853 // any case: 2854 StackArgSize = alignTo(StackArgSize, 16); 2855 2856 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2857 // a multiple of 16. 2858 FuncInfo->setArgumentStackToRestore(StackArgSize); 2859 2860 // This realignment carries over to the available bytes below. Our own 2861 // callers will guarantee the space is free by giving an aligned value to 2862 // CALLSEQ_START. 2863 } 2864 // Even if we're not expected to free up the space, it's useful to know how 2865 // much is there while considering tail calls (because we can reuse it). 2866 FuncInfo->setBytesInStackArgArea(StackArgSize); 2867 2868 return Chain; 2869 } 2870 2871 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2872 SelectionDAG &DAG, 2873 const SDLoc &DL, 2874 SDValue &Chain) const { 2875 MachineFunction &MF = DAG.getMachineFunction(); 2876 MachineFrameInfo &MFI = MF.getFrameInfo(); 2877 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2878 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2879 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()); 2880 2881 SmallVector<SDValue, 8> MemOps; 2882 2883 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2884 AArch64::X3, AArch64::X4, AArch64::X5, 2885 AArch64::X6, AArch64::X7 }; 2886 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2887 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2888 2889 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2890 int GPRIdx = 0; 2891 if (GPRSaveSize != 0) { 2892 if (IsWin64) { 2893 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 2894 if (GPRSaveSize & 15) 2895 // The extra size here, if triggered, will always be 8. 2896 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 2897 } else 2898 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 2899 2900 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2901 2902 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2903 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2904 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2905 SDValue Store = DAG.getStore( 2906 Val.getValue(1), DL, Val, FIN, 2907 IsWin64 2908 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 2909 GPRIdx, 2910 (i - FirstVariadicGPR) * 8) 2911 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 2912 MemOps.push_back(Store); 2913 FIN = 2914 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2915 } 2916 } 2917 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2918 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2919 2920 if (Subtarget->hasFPARMv8() && !IsWin64) { 2921 static const MCPhysReg FPRArgRegs[] = { 2922 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2923 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2924 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2925 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2926 2927 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2928 int FPRIdx = 0; 2929 if (FPRSaveSize != 0) { 2930 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 2931 2932 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2933 2934 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2935 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2936 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2937 2938 SDValue Store = DAG.getStore( 2939 Val.getValue(1), DL, Val, FIN, 2940 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 2941 MemOps.push_back(Store); 2942 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 2943 DAG.getConstant(16, DL, PtrVT)); 2944 } 2945 } 2946 FuncInfo->setVarArgsFPRIndex(FPRIdx); 2947 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 2948 } 2949 2950 if (!MemOps.empty()) { 2951 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2952 } 2953 } 2954 2955 /// LowerCallResult - Lower the result values of a call into the 2956 /// appropriate copies out of appropriate physical registers. 2957 SDValue AArch64TargetLowering::LowerCallResult( 2958 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2959 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2960 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2961 SDValue ThisVal) const { 2962 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 2963 ? RetCC_AArch64_WebKit_JS 2964 : RetCC_AArch64_AAPCS; 2965 // Assign locations to each value returned by this call. 2966 SmallVector<CCValAssign, 16> RVLocs; 2967 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2968 *DAG.getContext()); 2969 CCInfo.AnalyzeCallResult(Ins, RetCC); 2970 2971 // Copy all of the result registers out of their specified physreg. 2972 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2973 CCValAssign VA = RVLocs[i]; 2974 2975 // Pass 'this' value directly from the argument to return value, to avoid 2976 // reg unit interference 2977 if (i == 0 && isThisReturn) { 2978 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 2979 "unexpected return calling convention register assignment"); 2980 InVals.push_back(ThisVal); 2981 continue; 2982 } 2983 2984 SDValue Val = 2985 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2986 Chain = Val.getValue(1); 2987 InFlag = Val.getValue(2); 2988 2989 switch (VA.getLocInfo()) { 2990 default: 2991 llvm_unreachable("Unknown loc info!"); 2992 case CCValAssign::Full: 2993 break; 2994 case CCValAssign::BCvt: 2995 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2996 break; 2997 } 2998 2999 InVals.push_back(Val); 3000 } 3001 3002 return Chain; 3003 } 3004 3005 /// Return true if the calling convention is one that we can guarantee TCO for. 3006 static bool canGuaranteeTCO(CallingConv::ID CC) { 3007 return CC == CallingConv::Fast; 3008 } 3009 3010 /// Return true if we might ever do TCO for calls with this calling convention. 3011 static bool mayTailCallThisCC(CallingConv::ID CC) { 3012 switch (CC) { 3013 case CallingConv::C: 3014 case CallingConv::PreserveMost: 3015 case CallingConv::Swift: 3016 return true; 3017 default: 3018 return canGuaranteeTCO(CC); 3019 } 3020 } 3021 3022 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3023 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3024 const SmallVectorImpl<ISD::OutputArg> &Outs, 3025 const SmallVectorImpl<SDValue> &OutVals, 3026 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3027 if (!mayTailCallThisCC(CalleeCC)) 3028 return false; 3029 3030 MachineFunction &MF = DAG.getMachineFunction(); 3031 const Function *CallerF = MF.getFunction(); 3032 CallingConv::ID CallerCC = CallerF->getCallingConv(); 3033 bool CCMatch = CallerCC == CalleeCC; 3034 3035 // Byval parameters hand the function a pointer directly into the stack area 3036 // we want to reuse during a tail call. Working around this *is* possible (see 3037 // X86) but less efficient and uglier in LowerCall. 3038 for (Function::const_arg_iterator i = CallerF->arg_begin(), 3039 e = CallerF->arg_end(); 3040 i != e; ++i) 3041 if (i->hasByValAttr()) 3042 return false; 3043 3044 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3045 return canGuaranteeTCO(CalleeCC) && CCMatch; 3046 3047 // Externally-defined functions with weak linkage should not be 3048 // tail-called on AArch64 when the OS does not support dynamic 3049 // pre-emption of symbols, as the AAELF spec requires normal calls 3050 // to undefined weak functions to be replaced with a NOP or jump to the 3051 // next instruction. The behaviour of branch instructions in this 3052 // situation (as used for tail calls) is implementation-defined, so we 3053 // cannot rely on the linker replacing the tail call with a return. 3054 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3055 const GlobalValue *GV = G->getGlobal(); 3056 const Triple &TT = getTargetMachine().getTargetTriple(); 3057 if (GV->hasExternalWeakLinkage() && 3058 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3059 return false; 3060 } 3061 3062 // Now we search for cases where we can use a tail call without changing the 3063 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3064 // concept. 3065 3066 // I want anyone implementing a new calling convention to think long and hard 3067 // about this assert. 3068 assert((!isVarArg || CalleeCC == CallingConv::C) && 3069 "Unexpected variadic calling convention"); 3070 3071 LLVMContext &C = *DAG.getContext(); 3072 if (isVarArg && !Outs.empty()) { 3073 // At least two cases here: if caller is fastcc then we can't have any 3074 // memory arguments (we'd be expected to clean up the stack afterwards). If 3075 // caller is C then we could potentially use its argument area. 3076 3077 // FIXME: for now we take the most conservative of these in both cases: 3078 // disallow all variadic memory operands. 3079 SmallVector<CCValAssign, 16> ArgLocs; 3080 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3081 3082 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3083 for (const CCValAssign &ArgLoc : ArgLocs) 3084 if (!ArgLoc.isRegLoc()) 3085 return false; 3086 } 3087 3088 // Check that the call results are passed in the same way. 3089 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3090 CCAssignFnForCall(CalleeCC, isVarArg), 3091 CCAssignFnForCall(CallerCC, isVarArg))) 3092 return false; 3093 // The callee has to preserve all registers the caller needs to preserve. 3094 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3095 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3096 if (!CCMatch) { 3097 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3098 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3099 return false; 3100 } 3101 3102 // Nothing more to check if the callee is taking no arguments 3103 if (Outs.empty()) 3104 return true; 3105 3106 SmallVector<CCValAssign, 16> ArgLocs; 3107 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3108 3109 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3110 3111 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3112 3113 // If the stack arguments for this call do not fit into our own save area then 3114 // the call cannot be made tail. 3115 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3116 return false; 3117 3118 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3119 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3120 return false; 3121 3122 return true; 3123 } 3124 3125 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3126 SelectionDAG &DAG, 3127 MachineFrameInfo &MFI, 3128 int ClobberedFI) const { 3129 SmallVector<SDValue, 8> ArgChains; 3130 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3131 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3132 3133 // Include the original chain at the beginning of the list. When this is 3134 // used by target LowerCall hooks, this helps legalize find the 3135 // CALLSEQ_BEGIN node. 3136 ArgChains.push_back(Chain); 3137 3138 // Add a chain value for each stack argument corresponding 3139 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 3140 UE = DAG.getEntryNode().getNode()->use_end(); 3141 U != UE; ++U) 3142 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3143 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3144 if (FI->getIndex() < 0) { 3145 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 3146 int64_t InLastByte = InFirstByte; 3147 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 3148 3149 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 3150 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 3151 ArgChains.push_back(SDValue(L, 1)); 3152 } 3153 3154 // Build a tokenfactor for all the chains. 3155 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3156 } 3157 3158 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 3159 bool TailCallOpt) const { 3160 return CallCC == CallingConv::Fast && TailCallOpt; 3161 } 3162 3163 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 3164 /// and add input and output parameter nodes. 3165 SDValue 3166 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 3167 SmallVectorImpl<SDValue> &InVals) const { 3168 SelectionDAG &DAG = CLI.DAG; 3169 SDLoc &DL = CLI.DL; 3170 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3171 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3172 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3173 SDValue Chain = CLI.Chain; 3174 SDValue Callee = CLI.Callee; 3175 bool &IsTailCall = CLI.IsTailCall; 3176 CallingConv::ID CallConv = CLI.CallConv; 3177 bool IsVarArg = CLI.IsVarArg; 3178 3179 MachineFunction &MF = DAG.getMachineFunction(); 3180 bool IsThisReturn = false; 3181 3182 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3183 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3184 bool IsSibCall = false; 3185 3186 if (IsTailCall) { 3187 // Check if it's really possible to do a tail call. 3188 IsTailCall = isEligibleForTailCallOptimization( 3189 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3190 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall()) 3191 report_fatal_error("failed to perform tail call elimination on a call " 3192 "site marked musttail"); 3193 3194 // A sibling call is one where we're under the usual C ABI and not planning 3195 // to change that but can still do a tail call: 3196 if (!TailCallOpt && IsTailCall) 3197 IsSibCall = true; 3198 3199 if (IsTailCall) 3200 ++NumTailCalls; 3201 } 3202 3203 // Analyze operands of the call, assigning locations to each operand. 3204 SmallVector<CCValAssign, 16> ArgLocs; 3205 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3206 *DAG.getContext()); 3207 3208 if (IsVarArg) { 3209 // Handle fixed and variable vector arguments differently. 3210 // Variable vector arguments always go into memory. 3211 unsigned NumArgs = Outs.size(); 3212 3213 for (unsigned i = 0; i != NumArgs; ++i) { 3214 MVT ArgVT = Outs[i].VT; 3215 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3216 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3217 /*IsVarArg=*/ !Outs[i].IsFixed); 3218 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3219 assert(!Res && "Call operand has unhandled type"); 3220 (void)Res; 3221 } 3222 } else { 3223 // At this point, Outs[].VT may already be promoted to i32. To correctly 3224 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3225 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3226 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3227 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3228 // LocVT. 3229 unsigned NumArgs = Outs.size(); 3230 for (unsigned i = 0; i != NumArgs; ++i) { 3231 MVT ValVT = Outs[i].VT; 3232 // Get type of the original argument. 3233 EVT ActualVT = getValueType(DAG.getDataLayout(), 3234 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3235 /*AllowUnknown*/ true); 3236 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3237 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3238 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3239 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3240 ValVT = MVT::i8; 3241 else if (ActualMVT == MVT::i16) 3242 ValVT = MVT::i16; 3243 3244 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3245 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3246 assert(!Res && "Call operand has unhandled type"); 3247 (void)Res; 3248 } 3249 } 3250 3251 // Get a count of how many bytes are to be pushed on the stack. 3252 unsigned NumBytes = CCInfo.getNextStackOffset(); 3253 3254 if (IsSibCall) { 3255 // Since we're not changing the ABI to make this a tail call, the memory 3256 // operands are already available in the caller's incoming argument space. 3257 NumBytes = 0; 3258 } 3259 3260 // FPDiff is the byte offset of the call's argument area from the callee's. 3261 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3262 // by this amount for a tail call. In a sibling call it must be 0 because the 3263 // caller will deallocate the entire stack and the callee still expects its 3264 // arguments to begin at SP+0. Completely unused for non-tail calls. 3265 int FPDiff = 0; 3266 3267 if (IsTailCall && !IsSibCall) { 3268 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3269 3270 // Since callee will pop argument stack as a tail call, we must keep the 3271 // popped size 16-byte aligned. 3272 NumBytes = alignTo(NumBytes, 16); 3273 3274 // FPDiff will be negative if this tail call requires more space than we 3275 // would automatically have in our incoming argument space. Positive if we 3276 // can actually shrink the stack. 3277 FPDiff = NumReusableBytes - NumBytes; 3278 3279 // The stack pointer must be 16-byte aligned at all times it's used for a 3280 // memory operation, which in practice means at *all* times and in 3281 // particular across call boundaries. Therefore our own arguments started at 3282 // a 16-byte aligned SP and the delta applied for the tail call should 3283 // satisfy the same constraint. 3284 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3285 } 3286 3287 // Adjust the stack pointer for the new arguments... 3288 // These operations are automatically eliminated by the prolog/epilog pass 3289 if (!IsSibCall) 3290 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 3291 3292 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3293 getPointerTy(DAG.getDataLayout())); 3294 3295 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3296 SmallVector<SDValue, 8> MemOpChains; 3297 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3298 3299 // Walk the register/memloc assignments, inserting copies/loads. 3300 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3301 ++i, ++realArgIdx) { 3302 CCValAssign &VA = ArgLocs[i]; 3303 SDValue Arg = OutVals[realArgIdx]; 3304 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3305 3306 // Promote the value if needed. 3307 switch (VA.getLocInfo()) { 3308 default: 3309 llvm_unreachable("Unknown loc info!"); 3310 case CCValAssign::Full: 3311 break; 3312 case CCValAssign::SExt: 3313 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3314 break; 3315 case CCValAssign::ZExt: 3316 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3317 break; 3318 case CCValAssign::AExt: 3319 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3320 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3321 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3322 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3323 } 3324 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3325 break; 3326 case CCValAssign::BCvt: 3327 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3328 break; 3329 case CCValAssign::FPExt: 3330 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3331 break; 3332 } 3333 3334 if (VA.isRegLoc()) { 3335 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 3336 Outs[0].VT == MVT::i64) { 3337 assert(VA.getLocVT() == MVT::i64 && 3338 "unexpected calling convention register assignment"); 3339 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3340 "unexpected use of 'returned'"); 3341 IsThisReturn = true; 3342 } 3343 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3344 } else { 3345 assert(VA.isMemLoc()); 3346 3347 SDValue DstAddr; 3348 MachinePointerInfo DstInfo; 3349 3350 // FIXME: This works on big-endian for composite byvals, which are the 3351 // common case. It should also work for fundamental types too. 3352 uint32_t BEAlign = 0; 3353 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3354 : VA.getValVT().getSizeInBits(); 3355 OpSize = (OpSize + 7) / 8; 3356 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3357 !Flags.isInConsecutiveRegs()) { 3358 if (OpSize < 8) 3359 BEAlign = 8 - OpSize; 3360 } 3361 unsigned LocMemOffset = VA.getLocMemOffset(); 3362 int32_t Offset = LocMemOffset + BEAlign; 3363 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3364 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3365 3366 if (IsTailCall) { 3367 Offset = Offset + FPDiff; 3368 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 3369 3370 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3371 DstInfo = 3372 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3373 3374 // Make sure any stack arguments overlapping with where we're storing 3375 // are loaded before this eventual operation. Otherwise they'll be 3376 // clobbered. 3377 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3378 } else { 3379 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3380 3381 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3382 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3383 LocMemOffset); 3384 } 3385 3386 if (Outs[i].Flags.isByVal()) { 3387 SDValue SizeNode = 3388 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3389 SDValue Cpy = DAG.getMemcpy( 3390 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3391 /*isVol = */ false, /*AlwaysInline = */ false, 3392 /*isTailCall = */ false, 3393 DstInfo, MachinePointerInfo()); 3394 3395 MemOpChains.push_back(Cpy); 3396 } else { 3397 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3398 // promoted to a legal register type i32, we should truncate Arg back to 3399 // i1/i8/i16. 3400 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3401 VA.getValVT() == MVT::i16) 3402 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3403 3404 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 3405 MemOpChains.push_back(Store); 3406 } 3407 } 3408 } 3409 3410 if (!MemOpChains.empty()) 3411 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3412 3413 // Build a sequence of copy-to-reg nodes chained together with token chain 3414 // and flag operands which copy the outgoing args into the appropriate regs. 3415 SDValue InFlag; 3416 for (auto &RegToPass : RegsToPass) { 3417 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3418 RegToPass.second, InFlag); 3419 InFlag = Chain.getValue(1); 3420 } 3421 3422 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3423 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3424 // node so that legalize doesn't hack it. 3425 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3426 auto GV = G->getGlobal(); 3427 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) == 3428 AArch64II::MO_GOT) { 3429 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3430 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3431 } else { 3432 const GlobalValue *GV = G->getGlobal(); 3433 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3434 } 3435 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3436 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3437 Subtarget->isTargetMachO()) { 3438 const char *Sym = S->getSymbol(); 3439 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3440 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3441 } else { 3442 const char *Sym = S->getSymbol(); 3443 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3444 } 3445 } 3446 3447 // We don't usually want to end the call-sequence here because we would tidy 3448 // the frame up *after* the call, however in the ABI-changing tail-call case 3449 // we've carefully laid out the parameters so that when sp is reset they'll be 3450 // in the correct location. 3451 if (IsTailCall && !IsSibCall) { 3452 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3453 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3454 InFlag = Chain.getValue(1); 3455 } 3456 3457 std::vector<SDValue> Ops; 3458 Ops.push_back(Chain); 3459 Ops.push_back(Callee); 3460 3461 if (IsTailCall) { 3462 // Each tail call may have to adjust the stack by a different amount, so 3463 // this information must travel along with the operation for eventual 3464 // consumption by emitEpilogue. 3465 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3466 } 3467 3468 // Add argument registers to the end of the list so that they are known live 3469 // into the call. 3470 for (auto &RegToPass : RegsToPass) 3471 Ops.push_back(DAG.getRegister(RegToPass.first, 3472 RegToPass.second.getValueType())); 3473 3474 // Add a register mask operand representing the call-preserved registers. 3475 const uint32_t *Mask; 3476 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3477 if (IsThisReturn) { 3478 // For 'this' returns, use the X0-preserving mask if applicable 3479 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3480 if (!Mask) { 3481 IsThisReturn = false; 3482 Mask = TRI->getCallPreservedMask(MF, CallConv); 3483 } 3484 } else 3485 Mask = TRI->getCallPreservedMask(MF, CallConv); 3486 3487 assert(Mask && "Missing call preserved mask for calling convention"); 3488 Ops.push_back(DAG.getRegisterMask(Mask)); 3489 3490 if (InFlag.getNode()) 3491 Ops.push_back(InFlag); 3492 3493 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3494 3495 // If we're doing a tall call, use a TC_RETURN here rather than an 3496 // actual call instruction. 3497 if (IsTailCall) { 3498 MF.getFrameInfo().setHasTailCall(); 3499 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3500 } 3501 3502 // Returns a chain and a flag for retval copy to use. 3503 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3504 InFlag = Chain.getValue(1); 3505 3506 uint64_t CalleePopBytes = 3507 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3508 3509 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3510 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3511 InFlag, DL); 3512 if (!Ins.empty()) 3513 InFlag = Chain.getValue(1); 3514 3515 // Handle result values, copying them out of physregs into vregs that we 3516 // return. 3517 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3518 InVals, IsThisReturn, 3519 IsThisReturn ? OutVals[0] : SDValue()); 3520 } 3521 3522 bool AArch64TargetLowering::CanLowerReturn( 3523 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3524 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3525 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3526 ? RetCC_AArch64_WebKit_JS 3527 : RetCC_AArch64_AAPCS; 3528 SmallVector<CCValAssign, 16> RVLocs; 3529 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3530 return CCInfo.CheckReturn(Outs, RetCC); 3531 } 3532 3533 SDValue 3534 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3535 bool isVarArg, 3536 const SmallVectorImpl<ISD::OutputArg> &Outs, 3537 const SmallVectorImpl<SDValue> &OutVals, 3538 const SDLoc &DL, SelectionDAG &DAG) const { 3539 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3540 ? RetCC_AArch64_WebKit_JS 3541 : RetCC_AArch64_AAPCS; 3542 SmallVector<CCValAssign, 16> RVLocs; 3543 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3544 *DAG.getContext()); 3545 CCInfo.AnalyzeReturn(Outs, RetCC); 3546 3547 // Copy the result values into the output registers. 3548 SDValue Flag; 3549 SmallVector<SDValue, 4> RetOps(1, Chain); 3550 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3551 ++i, ++realRVLocIdx) { 3552 CCValAssign &VA = RVLocs[i]; 3553 assert(VA.isRegLoc() && "Can only return in registers!"); 3554 SDValue Arg = OutVals[realRVLocIdx]; 3555 3556 switch (VA.getLocInfo()) { 3557 default: 3558 llvm_unreachable("Unknown loc info!"); 3559 case CCValAssign::Full: 3560 if (Outs[i].ArgVT == MVT::i1) { 3561 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3562 // value. This is strictly redundant on Darwin (which uses "zeroext 3563 // i1"), but will be optimised out before ISel. 3564 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3565 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3566 } 3567 break; 3568 case CCValAssign::BCvt: 3569 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3570 break; 3571 } 3572 3573 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3574 Flag = Chain.getValue(1); 3575 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3576 } 3577 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3578 const MCPhysReg *I = 3579 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3580 if (I) { 3581 for (; *I; ++I) { 3582 if (AArch64::GPR64RegClass.contains(*I)) 3583 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3584 else if (AArch64::FPR64RegClass.contains(*I)) 3585 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3586 else 3587 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3588 } 3589 } 3590 3591 RetOps[0] = Chain; // Update chain. 3592 3593 // Add the flag if we have it. 3594 if (Flag.getNode()) 3595 RetOps.push_back(Flag); 3596 3597 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3598 } 3599 3600 //===----------------------------------------------------------------------===// 3601 // Other Lowering Code 3602 //===----------------------------------------------------------------------===// 3603 3604 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 3605 SelectionDAG &DAG, 3606 unsigned Flag) const { 3607 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag); 3608 } 3609 3610 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 3611 SelectionDAG &DAG, 3612 unsigned Flag) const { 3613 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 3614 } 3615 3616 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 3617 SelectionDAG &DAG, 3618 unsigned Flag) const { 3619 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 3620 N->getOffset(), Flag); 3621 } 3622 3623 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 3624 SelectionDAG &DAG, 3625 unsigned Flag) const { 3626 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 3627 } 3628 3629 // (loadGOT sym) 3630 template <class NodeTy> 3631 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const { 3632 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 3633 SDLoc DL(N); 3634 EVT Ty = getPointerTy(DAG.getDataLayout()); 3635 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT); 3636 // FIXME: Once remat is capable of dealing with instructions with register 3637 // operands, expand this into two nodes instead of using a wrapper node. 3638 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 3639 } 3640 3641 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 3642 template <class NodeTy> 3643 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG) 3644 const { 3645 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 3646 SDLoc DL(N); 3647 EVT Ty = getPointerTy(DAG.getDataLayout()); 3648 const unsigned char MO_NC = AArch64II::MO_NC; 3649 return DAG.getNode( 3650 AArch64ISD::WrapperLarge, DL, Ty, 3651 getTargetNode(N, Ty, DAG, AArch64II::MO_G3), 3652 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC), 3653 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC), 3654 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC)); 3655 } 3656 3657 // (addlow (adrp %hi(sym)) %lo(sym)) 3658 template <class NodeTy> 3659 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const { 3660 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 3661 SDLoc DL(N); 3662 EVT Ty = getPointerTy(DAG.getDataLayout()); 3663 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE); 3664 SDValue Lo = getTargetNode(N, Ty, DAG, 3665 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3666 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 3667 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 3668 } 3669 3670 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3671 SelectionDAG &DAG) const { 3672 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3673 const GlobalValue *GV = GN->getGlobal(); 3674 unsigned char OpFlags = 3675 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3676 3677 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3678 "unexpected offset in global node"); 3679 3680 // This also catches the large code model case for Darwin. 3681 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3682 return getGOT(GN, DAG); 3683 } 3684 3685 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3686 return getAddrLarge(GN, DAG); 3687 } else { 3688 return getAddr(GN, DAG); 3689 } 3690 } 3691 3692 /// \brief Convert a TLS address reference into the correct sequence of loads 3693 /// and calls to compute the variable's address (for Darwin, currently) and 3694 /// return an SDValue containing the final node. 3695 3696 /// Darwin only has one TLS scheme which must be capable of dealing with the 3697 /// fully general situation, in the worst case. This means: 3698 /// + "extern __thread" declaration. 3699 /// + Defined in a possibly unknown dynamic library. 3700 /// 3701 /// The general system is that each __thread variable has a [3 x i64] descriptor 3702 /// which contains information used by the runtime to calculate the address. The 3703 /// only part of this the compiler needs to know about is the first xword, which 3704 /// contains a function pointer that must be called with the address of the 3705 /// entire descriptor in "x0". 3706 /// 3707 /// Since this descriptor may be in a different unit, in general even the 3708 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3709 /// is: 3710 /// adrp x0, _var@TLVPPAGE 3711 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3712 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3713 /// ; the function pointer 3714 /// blr x1 ; Uses descriptor address in x0 3715 /// ; Address of _var is now in x0. 3716 /// 3717 /// If the address of _var's descriptor *is* known to the linker, then it can 3718 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3719 /// a slight efficiency gain. 3720 SDValue 3721 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3722 SelectionDAG &DAG) const { 3723 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3724 3725 SDLoc DL(Op); 3726 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3727 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3728 3729 SDValue TLVPAddr = 3730 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3731 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3732 3733 // The first entry in the descriptor is a function pointer that we must call 3734 // to obtain the address of the variable. 3735 SDValue Chain = DAG.getEntryNode(); 3736 SDValue FuncTLVGet = DAG.getLoad( 3737 MVT::i64, DL, Chain, DescAddr, 3738 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3739 /* Alignment = */ 8, 3740 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant | 3741 MachineMemOperand::MODereferenceable); 3742 Chain = FuncTLVGet.getValue(1); 3743 3744 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3745 MFI.setAdjustsStack(true); 3746 3747 // TLS calls preserve all registers except those that absolutely must be 3748 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3749 // silly). 3750 const uint32_t *Mask = 3751 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3752 3753 // Finally, we can make the call. This is just a degenerate version of a 3754 // normal AArch64 call node: x0 takes the address of the descriptor, and 3755 // returns the address of the variable in this thread. 3756 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3757 Chain = 3758 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3759 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3760 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3761 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3762 } 3763 3764 /// When accessing thread-local variables under either the general-dynamic or 3765 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3766 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3767 /// is a function pointer to carry out the resolution. 3768 /// 3769 /// The sequence is: 3770 /// adrp x0, :tlsdesc:var 3771 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3772 /// add x0, x0, #:tlsdesc_lo12:var 3773 /// .tlsdesccall var 3774 /// blr x1 3775 /// (TPIDR_EL0 offset now in x0) 3776 /// 3777 /// The above sequence must be produced unscheduled, to enable the linker to 3778 /// optimize/relax this sequence. 3779 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3780 /// above sequence, and expanded really late in the compilation flow, to ensure 3781 /// the sequence is produced as per above. 3782 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 3783 const SDLoc &DL, 3784 SelectionDAG &DAG) const { 3785 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3786 3787 SDValue Chain = DAG.getEntryNode(); 3788 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3789 3790 Chain = 3791 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 3792 SDValue Glue = Chain.getValue(1); 3793 3794 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3795 } 3796 3797 SDValue 3798 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3799 SelectionDAG &DAG) const { 3800 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3801 assert(Subtarget->useSmallAddressing() && 3802 "ELF TLS only supported in small memory model"); 3803 // Different choices can be made for the maximum size of the TLS area for a 3804 // module. For the small address model, the default TLS size is 16MiB and the 3805 // maximum TLS size is 4GiB. 3806 // FIXME: add -mtls-size command line option and make it control the 16MiB 3807 // vs. 4GiB code sequence generation. 3808 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3809 3810 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3811 3812 if (DAG.getTarget().Options.EmulatedTLS) 3813 return LowerToTLSEmulatedModel(GA, DAG); 3814 3815 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3816 if (Model == TLSModel::LocalDynamic) 3817 Model = TLSModel::GeneralDynamic; 3818 } 3819 3820 SDValue TPOff; 3821 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3822 SDLoc DL(Op); 3823 const GlobalValue *GV = GA->getGlobal(); 3824 3825 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3826 3827 if (Model == TLSModel::LocalExec) { 3828 SDValue HiVar = DAG.getTargetGlobalAddress( 3829 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3830 SDValue LoVar = DAG.getTargetGlobalAddress( 3831 GV, DL, PtrVT, 0, 3832 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3833 3834 SDValue TPWithOff_lo = 3835 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3836 HiVar, 3837 DAG.getTargetConstant(0, DL, MVT::i32)), 3838 0); 3839 SDValue TPWithOff = 3840 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3841 LoVar, 3842 DAG.getTargetConstant(0, DL, MVT::i32)), 3843 0); 3844 return TPWithOff; 3845 } else if (Model == TLSModel::InitialExec) { 3846 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3847 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3848 } else if (Model == TLSModel::LocalDynamic) { 3849 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3850 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3851 // the beginning of the module's TLS region, followed by a DTPREL offset 3852 // calculation. 3853 3854 // These accesses will need deduplicating if there's more than one. 3855 AArch64FunctionInfo *MFI = 3856 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3857 MFI->incNumLocalDynamicTLSAccesses(); 3858 3859 // The call needs a relocation too for linker relaxation. It doesn't make 3860 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3861 // the address. 3862 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3863 AArch64II::MO_TLS); 3864 3865 // Now we can calculate the offset from TPIDR_EL0 to this module's 3866 // thread-local area. 3867 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3868 3869 // Now use :dtprel_whatever: operations to calculate this variable's offset 3870 // in its thread-storage area. 3871 SDValue HiVar = DAG.getTargetGlobalAddress( 3872 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3873 SDValue LoVar = DAG.getTargetGlobalAddress( 3874 GV, DL, MVT::i64, 0, 3875 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3876 3877 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3878 DAG.getTargetConstant(0, DL, MVT::i32)), 3879 0); 3880 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3881 DAG.getTargetConstant(0, DL, MVT::i32)), 3882 0); 3883 } else if (Model == TLSModel::GeneralDynamic) { 3884 // The call needs a relocation too for linker relaxation. It doesn't make 3885 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3886 // the address. 3887 SDValue SymAddr = 3888 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3889 3890 // Finally we can make a call to calculate the offset from tpidr_el0. 3891 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3892 } else 3893 llvm_unreachable("Unsupported ELF TLS access model"); 3894 3895 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3896 } 3897 3898 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3899 SelectionDAG &DAG) const { 3900 if (Subtarget->isTargetDarwin()) 3901 return LowerDarwinGlobalTLSAddress(Op, DAG); 3902 if (Subtarget->isTargetELF()) 3903 return LowerELFGlobalTLSAddress(Op, DAG); 3904 3905 llvm_unreachable("Unexpected platform trying to use TLS"); 3906 } 3907 3908 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3909 SDValue Chain = Op.getOperand(0); 3910 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3911 SDValue LHS = Op.getOperand(2); 3912 SDValue RHS = Op.getOperand(3); 3913 SDValue Dest = Op.getOperand(4); 3914 SDLoc dl(Op); 3915 3916 // Handle f128 first, since lowering it will result in comparing the return 3917 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3918 // is expecting to deal with. 3919 if (LHS.getValueType() == MVT::f128) { 3920 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3921 3922 // If softenSetCCOperands returned a scalar, we need to compare the result 3923 // against zero to select between true and false values. 3924 if (!RHS.getNode()) { 3925 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3926 CC = ISD::SETNE; 3927 } 3928 } 3929 3930 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 3931 // instruction. 3932 unsigned Opc = LHS.getOpcode(); 3933 if (LHS.getResNo() == 1 && isOneConstant(RHS) && 3934 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3935 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 3936 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 3937 "Unexpected condition code."); 3938 // Only lower legal XALUO ops. 3939 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 3940 return SDValue(); 3941 3942 // The actual operation with overflow check. 3943 AArch64CC::CondCode OFCC; 3944 SDValue Value, Overflow; 3945 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 3946 3947 if (CC == ISD::SETNE) 3948 OFCC = getInvertedCondCode(OFCC); 3949 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 3950 3951 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3952 Overflow); 3953 } 3954 3955 if (LHS.getValueType().isInteger()) { 3956 assert((LHS.getValueType() == RHS.getValueType()) && 3957 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3958 3959 // If the RHS of the comparison is zero, we can potentially fold this 3960 // to a specialized branch. 3961 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 3962 if (RHSC && RHSC->getZExtValue() == 0) { 3963 if (CC == ISD::SETEQ) { 3964 // See if we can use a TBZ to fold in an AND as well. 3965 // TBZ has a smaller branch displacement than CBZ. If the offset is 3966 // out of bounds, a late MI-layer pass rewrites branches. 3967 // 403.gcc is an example that hits this case. 3968 if (LHS.getOpcode() == ISD::AND && 3969 isa<ConstantSDNode>(LHS.getOperand(1)) && 3970 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3971 SDValue Test = LHS.getOperand(0); 3972 uint64_t Mask = LHS.getConstantOperandVal(1); 3973 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 3974 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3975 Dest); 3976 } 3977 3978 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 3979 } else if (CC == ISD::SETNE) { 3980 // See if we can use a TBZ to fold in an AND as well. 3981 // TBZ has a smaller branch displacement than CBZ. If the offset is 3982 // out of bounds, a late MI-layer pass rewrites branches. 3983 // 403.gcc is an example that hits this case. 3984 if (LHS.getOpcode() == ISD::AND && 3985 isa<ConstantSDNode>(LHS.getOperand(1)) && 3986 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3987 SDValue Test = LHS.getOperand(0); 3988 uint64_t Mask = LHS.getConstantOperandVal(1); 3989 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 3990 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3991 Dest); 3992 } 3993 3994 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 3995 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 3996 // Don't combine AND since emitComparison converts the AND to an ANDS 3997 // (a.k.a. TST) and the test in the test bit and branch instruction 3998 // becomes redundant. This would also increase register pressure. 3999 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4000 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 4001 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4002 } 4003 } 4004 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 4005 LHS.getOpcode() != ISD::AND) { 4006 // Don't combine AND since emitComparison converts the AND to an ANDS 4007 // (a.k.a. TST) and the test in the test bit and branch instruction 4008 // becomes redundant. This would also increase register pressure. 4009 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4010 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 4011 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4012 } 4013 4014 SDValue CCVal; 4015 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4016 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4017 Cmp); 4018 } 4019 4020 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4021 4022 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4023 // clean. Some of them require two branches to implement. 4024 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4025 AArch64CC::CondCode CC1, CC2; 4026 changeFPCCToAArch64CC(CC, CC1, CC2); 4027 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4028 SDValue BR1 = 4029 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 4030 if (CC2 != AArch64CC::AL) { 4031 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4032 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 4033 Cmp); 4034 } 4035 4036 return BR1; 4037 } 4038 4039 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 4040 SelectionDAG &DAG) const { 4041 EVT VT = Op.getValueType(); 4042 SDLoc DL(Op); 4043 4044 SDValue In1 = Op.getOperand(0); 4045 SDValue In2 = Op.getOperand(1); 4046 EVT SrcVT = In2.getValueType(); 4047 4048 if (SrcVT.bitsLT(VT)) 4049 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 4050 else if (SrcVT.bitsGT(VT)) 4051 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 4052 4053 EVT VecVT; 4054 EVT EltVT; 4055 uint64_t EltMask; 4056 SDValue VecVal1, VecVal2; 4057 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 4058 EltVT = MVT::i32; 4059 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 4060 EltMask = 0x80000000ULL; 4061 4062 if (!VT.isVector()) { 4063 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 4064 DAG.getUNDEF(VecVT), In1); 4065 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 4066 DAG.getUNDEF(VecVT), In2); 4067 } else { 4068 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 4069 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 4070 } 4071 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 4072 EltVT = MVT::i64; 4073 VecVT = MVT::v2i64; 4074 4075 // We want to materialize a mask with the high bit set, but the AdvSIMD 4076 // immediate moves cannot materialize that in a single instruction for 4077 // 64-bit elements. Instead, materialize zero and then negate it. 4078 EltMask = 0; 4079 4080 if (!VT.isVector()) { 4081 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 4082 DAG.getUNDEF(VecVT), In1); 4083 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 4084 DAG.getUNDEF(VecVT), In2); 4085 } else { 4086 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 4087 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 4088 } 4089 } else { 4090 llvm_unreachable("Invalid type for copysign!"); 4091 } 4092 4093 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 4094 4095 // If we couldn't materialize the mask above, then the mask vector will be 4096 // the zero vector, and we need to negate it here. 4097 if (VT == MVT::f64 || VT == MVT::v2f64) { 4098 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 4099 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 4100 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 4101 } 4102 4103 SDValue Sel = 4104 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 4105 4106 if (VT == MVT::f32) 4107 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 4108 else if (VT == MVT::f64) 4109 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 4110 else 4111 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 4112 } 4113 4114 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 4115 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 4116 Attribute::NoImplicitFloat)) 4117 return SDValue(); 4118 4119 if (!Subtarget->hasNEON()) 4120 return SDValue(); 4121 4122 // While there is no integer popcount instruction, it can 4123 // be more efficiently lowered to the following sequence that uses 4124 // AdvSIMD registers/instructions as long as the copies to/from 4125 // the AdvSIMD registers are cheap. 4126 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 4127 // CNT V0.8B, V0.8B // 8xbyte pop-counts 4128 // ADDV B0, V0.8B // sum 8xbyte pop-counts 4129 // UMOV X0, V0.B[0] // copy byte result back to integer reg 4130 SDValue Val = Op.getOperand(0); 4131 SDLoc DL(Op); 4132 EVT VT = Op.getValueType(); 4133 4134 if (VT == MVT::i32) 4135 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 4136 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 4137 4138 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 4139 SDValue UaddLV = DAG.getNode( 4140 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 4141 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 4142 4143 if (VT == MVT::i64) 4144 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 4145 return UaddLV; 4146 } 4147 4148 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 4149 4150 if (Op.getValueType().isVector()) 4151 return LowerVSETCC(Op, DAG); 4152 4153 SDValue LHS = Op.getOperand(0); 4154 SDValue RHS = Op.getOperand(1); 4155 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 4156 SDLoc dl(Op); 4157 4158 // We chose ZeroOrOneBooleanContents, so use zero and one. 4159 EVT VT = Op.getValueType(); 4160 SDValue TVal = DAG.getConstant(1, dl, VT); 4161 SDValue FVal = DAG.getConstant(0, dl, VT); 4162 4163 // Handle f128 first, since one possible outcome is a normal integer 4164 // comparison which gets picked up by the next if statement. 4165 if (LHS.getValueType() == MVT::f128) { 4166 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4167 4168 // If softenSetCCOperands returned a scalar, use it. 4169 if (!RHS.getNode()) { 4170 assert(LHS.getValueType() == Op.getValueType() && 4171 "Unexpected setcc expansion!"); 4172 return LHS; 4173 } 4174 } 4175 4176 if (LHS.getValueType().isInteger()) { 4177 SDValue CCVal; 4178 SDValue Cmp = 4179 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 4180 4181 // Note that we inverted the condition above, so we reverse the order of 4182 // the true and false operands here. This will allow the setcc to be 4183 // matched to a single CSINC instruction. 4184 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 4185 } 4186 4187 // Now we know we're dealing with FP values. 4188 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4189 4190 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 4191 // and do the comparison. 4192 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4193 4194 AArch64CC::CondCode CC1, CC2; 4195 changeFPCCToAArch64CC(CC, CC1, CC2); 4196 if (CC2 == AArch64CC::AL) { 4197 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 4198 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4199 4200 // Note that we inverted the condition above, so we reverse the order of 4201 // the true and false operands here. This will allow the setcc to be 4202 // matched to a single CSINC instruction. 4203 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 4204 } else { 4205 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 4206 // totally clean. Some of them require two CSELs to implement. As is in 4207 // this case, we emit the first CSEL and then emit a second using the output 4208 // of the first as the RHS. We're effectively OR'ing the two CC's together. 4209 4210 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 4211 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4212 SDValue CS1 = 4213 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4214 4215 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4216 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4217 } 4218 } 4219 4220 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 4221 SDValue RHS, SDValue TVal, 4222 SDValue FVal, const SDLoc &dl, 4223 SelectionDAG &DAG) const { 4224 // Handle f128 first, because it will result in a comparison of some RTLIB 4225 // call result against zero. 4226 if (LHS.getValueType() == MVT::f128) { 4227 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4228 4229 // If softenSetCCOperands returned a scalar, we need to compare the result 4230 // against zero to select between true and false values. 4231 if (!RHS.getNode()) { 4232 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4233 CC = ISD::SETNE; 4234 } 4235 } 4236 4237 // Also handle f16, for which we need to do a f32 comparison. 4238 if (LHS.getValueType() == MVT::f16) { 4239 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 4240 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 4241 } 4242 4243 // Next, handle integers. 4244 if (LHS.getValueType().isInteger()) { 4245 assert((LHS.getValueType() == RHS.getValueType()) && 4246 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4247 4248 unsigned Opcode = AArch64ISD::CSEL; 4249 4250 // If both the TVal and the FVal are constants, see if we can swap them in 4251 // order to for a CSINV or CSINC out of them. 4252 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4253 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4254 4255 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4256 std::swap(TVal, FVal); 4257 std::swap(CTVal, CFVal); 4258 CC = ISD::getSetCCInverse(CC, true); 4259 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4260 std::swap(TVal, FVal); 4261 std::swap(CTVal, CFVal); 4262 CC = ISD::getSetCCInverse(CC, true); 4263 } else if (TVal.getOpcode() == ISD::XOR) { 4264 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4265 // with a CSINV rather than a CSEL. 4266 if (isAllOnesConstant(TVal.getOperand(1))) { 4267 std::swap(TVal, FVal); 4268 std::swap(CTVal, CFVal); 4269 CC = ISD::getSetCCInverse(CC, true); 4270 } 4271 } else if (TVal.getOpcode() == ISD::SUB) { 4272 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4273 // that we can match with a CSNEG rather than a CSEL. 4274 if (isNullConstant(TVal.getOperand(0))) { 4275 std::swap(TVal, FVal); 4276 std::swap(CTVal, CFVal); 4277 CC = ISD::getSetCCInverse(CC, true); 4278 } 4279 } else if (CTVal && CFVal) { 4280 const int64_t TrueVal = CTVal->getSExtValue(); 4281 const int64_t FalseVal = CFVal->getSExtValue(); 4282 bool Swap = false; 4283 4284 // If both TVal and FVal are constants, see if FVal is the 4285 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4286 // instead of a CSEL in that case. 4287 if (TrueVal == ~FalseVal) { 4288 Opcode = AArch64ISD::CSINV; 4289 } else if (TrueVal == -FalseVal) { 4290 Opcode = AArch64ISD::CSNEG; 4291 } else if (TVal.getValueType() == MVT::i32) { 4292 // If our operands are only 32-bit wide, make sure we use 32-bit 4293 // arithmetic for the check whether we can use CSINC. This ensures that 4294 // the addition in the check will wrap around properly in case there is 4295 // an overflow (which would not be the case if we do the check with 4296 // 64-bit arithmetic). 4297 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4298 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4299 4300 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4301 Opcode = AArch64ISD::CSINC; 4302 4303 if (TrueVal32 > FalseVal32) { 4304 Swap = true; 4305 } 4306 } 4307 // 64-bit check whether we can use CSINC. 4308 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4309 Opcode = AArch64ISD::CSINC; 4310 4311 if (TrueVal > FalseVal) { 4312 Swap = true; 4313 } 4314 } 4315 4316 // Swap TVal and FVal if necessary. 4317 if (Swap) { 4318 std::swap(TVal, FVal); 4319 std::swap(CTVal, CFVal); 4320 CC = ISD::getSetCCInverse(CC, true); 4321 } 4322 4323 if (Opcode != AArch64ISD::CSEL) { 4324 // Drop FVal since we can get its value by simply inverting/negating 4325 // TVal. 4326 FVal = TVal; 4327 } 4328 } 4329 4330 // Avoid materializing a constant when possible by reusing a known value in 4331 // a register. However, don't perform this optimization if the known value 4332 // is one, zero or negative one in the case of a CSEL. We can always 4333 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 4334 // FVal, respectively. 4335 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 4336 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 4337 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 4338 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4339 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 4340 // "a != C ? x : a" to avoid materializing C. 4341 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 4342 TVal = LHS; 4343 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 4344 FVal = LHS; 4345 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 4346 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 4347 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 4348 // avoid materializing C. 4349 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4350 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 4351 Opcode = AArch64ISD::CSINV; 4352 TVal = LHS; 4353 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 4354 } 4355 } 4356 4357 SDValue CCVal; 4358 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4359 4360 EVT VT = TVal.getValueType(); 4361 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4362 } 4363 4364 // Now we know we're dealing with FP values. 4365 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4366 assert(LHS.getValueType() == RHS.getValueType()); 4367 EVT VT = TVal.getValueType(); 4368 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4369 4370 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4371 // clean. Some of them require two CSELs to implement. 4372 AArch64CC::CondCode CC1, CC2; 4373 changeFPCCToAArch64CC(CC, CC1, CC2); 4374 4375 if (DAG.getTarget().Options.UnsafeFPMath) { 4376 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 4377 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 4378 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 4379 if (RHSVal && RHSVal->isZero()) { 4380 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 4381 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 4382 4383 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 4384 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 4385 TVal = LHS; 4386 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 4387 CFVal && CFVal->isZero() && 4388 FVal.getValueType() == LHS.getValueType()) 4389 FVal = LHS; 4390 } 4391 } 4392 4393 // Emit first, and possibly only, CSEL. 4394 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4395 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4396 4397 // If we need a second CSEL, emit it, using the output of the first as the 4398 // RHS. We're effectively OR'ing the two CC's together. 4399 if (CC2 != AArch64CC::AL) { 4400 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4401 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4402 } 4403 4404 // Otherwise, return the output of the first CSEL. 4405 return CS1; 4406 } 4407 4408 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4409 SelectionDAG &DAG) const { 4410 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4411 SDValue LHS = Op.getOperand(0); 4412 SDValue RHS = Op.getOperand(1); 4413 SDValue TVal = Op.getOperand(2); 4414 SDValue FVal = Op.getOperand(3); 4415 SDLoc DL(Op); 4416 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4417 } 4418 4419 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4420 SelectionDAG &DAG) const { 4421 SDValue CCVal = Op->getOperand(0); 4422 SDValue TVal = Op->getOperand(1); 4423 SDValue FVal = Op->getOperand(2); 4424 SDLoc DL(Op); 4425 4426 unsigned Opc = CCVal.getOpcode(); 4427 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4428 // instruction. 4429 if (CCVal.getResNo() == 1 && 4430 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4431 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4432 // Only lower legal XALUO ops. 4433 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4434 return SDValue(); 4435 4436 AArch64CC::CondCode OFCC; 4437 SDValue Value, Overflow; 4438 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4439 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4440 4441 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4442 CCVal, Overflow); 4443 } 4444 4445 // Lower it the same way as we would lower a SELECT_CC node. 4446 ISD::CondCode CC; 4447 SDValue LHS, RHS; 4448 if (CCVal.getOpcode() == ISD::SETCC) { 4449 LHS = CCVal.getOperand(0); 4450 RHS = CCVal.getOperand(1); 4451 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4452 } else { 4453 LHS = CCVal; 4454 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4455 CC = ISD::SETNE; 4456 } 4457 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4458 } 4459 4460 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4461 SelectionDAG &DAG) const { 4462 // Jump table entries as PC relative offsets. No additional tweaking 4463 // is necessary here. Just get the address of the jump table. 4464 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4465 4466 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4467 !Subtarget->isTargetMachO()) { 4468 return getAddrLarge(JT, DAG); 4469 } 4470 return getAddr(JT, DAG); 4471 } 4472 4473 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4474 SelectionDAG &DAG) const { 4475 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4476 4477 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4478 // Use the GOT for the large code model on iOS. 4479 if (Subtarget->isTargetMachO()) { 4480 return getGOT(CP, DAG); 4481 } 4482 return getAddrLarge(CP, DAG); 4483 } else { 4484 return getAddr(CP, DAG); 4485 } 4486 } 4487 4488 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4489 SelectionDAG &DAG) const { 4490 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 4491 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4492 !Subtarget->isTargetMachO()) { 4493 return getAddrLarge(BA, DAG); 4494 } else { 4495 return getAddr(BA, DAG); 4496 } 4497 } 4498 4499 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4500 SelectionDAG &DAG) const { 4501 AArch64FunctionInfo *FuncInfo = 4502 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4503 4504 SDLoc DL(Op); 4505 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4506 getPointerTy(DAG.getDataLayout())); 4507 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4508 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4509 MachinePointerInfo(SV)); 4510 } 4511 4512 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 4513 SelectionDAG &DAG) const { 4514 AArch64FunctionInfo *FuncInfo = 4515 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4516 4517 SDLoc DL(Op); 4518 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 4519 ? FuncInfo->getVarArgsGPRIndex() 4520 : FuncInfo->getVarArgsStackIndex(), 4521 getPointerTy(DAG.getDataLayout())); 4522 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4523 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4524 MachinePointerInfo(SV)); 4525 } 4526 4527 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4528 SelectionDAG &DAG) const { 4529 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4530 // Standard, section B.3. 4531 MachineFunction &MF = DAG.getMachineFunction(); 4532 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4533 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4534 SDLoc DL(Op); 4535 4536 SDValue Chain = Op.getOperand(0); 4537 SDValue VAList = Op.getOperand(1); 4538 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4539 SmallVector<SDValue, 4> MemOps; 4540 4541 // void *__stack at offset 0 4542 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4543 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4544 MachinePointerInfo(SV), /* Alignment = */ 8)); 4545 4546 // void *__gr_top at offset 8 4547 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4548 if (GPRSize > 0) { 4549 SDValue GRTop, GRTopAddr; 4550 4551 GRTopAddr = 4552 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4553 4554 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4555 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4556 DAG.getConstant(GPRSize, DL, PtrVT)); 4557 4558 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4559 MachinePointerInfo(SV, 8), 4560 /* Alignment = */ 8)); 4561 } 4562 4563 // void *__vr_top at offset 16 4564 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4565 if (FPRSize > 0) { 4566 SDValue VRTop, VRTopAddr; 4567 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4568 DAG.getConstant(16, DL, PtrVT)); 4569 4570 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4571 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4572 DAG.getConstant(FPRSize, DL, PtrVT)); 4573 4574 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4575 MachinePointerInfo(SV, 16), 4576 /* Alignment = */ 8)); 4577 } 4578 4579 // int __gr_offs at offset 24 4580 SDValue GROffsAddr = 4581 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4582 MemOps.push_back(DAG.getStore( 4583 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 4584 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 4585 4586 // int __vr_offs at offset 28 4587 SDValue VROffsAddr = 4588 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4589 MemOps.push_back(DAG.getStore( 4590 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 4591 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 4592 4593 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4594 } 4595 4596 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4597 SelectionDAG &DAG) const { 4598 MachineFunction &MF = DAG.getMachineFunction(); 4599 4600 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) 4601 return LowerWin64_VASTART(Op, DAG); 4602 else if (Subtarget->isTargetDarwin()) 4603 return LowerDarwin_VASTART(Op, DAG); 4604 else 4605 return LowerAAPCS_VASTART(Op, DAG); 4606 } 4607 4608 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4609 SelectionDAG &DAG) const { 4610 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4611 // pointer. 4612 SDLoc DL(Op); 4613 unsigned VaListSize = 4614 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32; 4615 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4616 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4617 4618 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4619 Op.getOperand(2), 4620 DAG.getConstant(VaListSize, DL, MVT::i32), 4621 8, false, false, false, MachinePointerInfo(DestSV), 4622 MachinePointerInfo(SrcSV)); 4623 } 4624 4625 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4626 assert(Subtarget->isTargetDarwin() && 4627 "automatic va_arg instruction only works on Darwin"); 4628 4629 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4630 EVT VT = Op.getValueType(); 4631 SDLoc DL(Op); 4632 SDValue Chain = Op.getOperand(0); 4633 SDValue Addr = Op.getOperand(1); 4634 unsigned Align = Op.getConstantOperandVal(3); 4635 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4636 4637 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V)); 4638 Chain = VAList.getValue(1); 4639 4640 if (Align > 8) { 4641 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4642 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4643 DAG.getConstant(Align - 1, DL, PtrVT)); 4644 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4645 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4646 } 4647 4648 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4649 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4650 4651 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4652 // up to 64 bits. At the very least, we have to increase the striding of the 4653 // vaargs list to match this, and for FP values we need to introduce 4654 // FP_ROUND nodes as well. 4655 if (VT.isInteger() && !VT.isVector()) 4656 ArgSize = 8; 4657 bool NeedFPTrunc = false; 4658 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4659 ArgSize = 8; 4660 NeedFPTrunc = true; 4661 } 4662 4663 // Increment the pointer, VAList, to the next vaarg 4664 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4665 DAG.getConstant(ArgSize, DL, PtrVT)); 4666 // Store the incremented VAList to the legalized pointer 4667 SDValue APStore = 4668 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 4669 4670 // Load the actual argument out of the pointer VAList 4671 if (NeedFPTrunc) { 4672 // Load the value as an f64. 4673 SDValue WideFP = 4674 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 4675 // Round the value down to an f32. 4676 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4677 DAG.getIntPtrConstant(1, DL)); 4678 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4679 // Merge the rounded value with the chain output of the load. 4680 return DAG.getMergeValues(Ops, DL); 4681 } 4682 4683 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 4684 } 4685 4686 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4687 SelectionDAG &DAG) const { 4688 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4689 MFI.setFrameAddressIsTaken(true); 4690 4691 EVT VT = Op.getValueType(); 4692 SDLoc DL(Op); 4693 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4694 SDValue FrameAddr = 4695 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4696 while (Depth--) 4697 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4698 MachinePointerInfo()); 4699 return FrameAddr; 4700 } 4701 4702 // FIXME? Maybe this could be a TableGen attribute on some registers and 4703 // this table could be generated automatically from RegInfo. 4704 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4705 SelectionDAG &DAG) const { 4706 unsigned Reg = StringSwitch<unsigned>(RegName) 4707 .Case("sp", AArch64::SP) 4708 .Case("x18", AArch64::X18) 4709 .Case("w18", AArch64::W18) 4710 .Default(0); 4711 if ((Reg == AArch64::X18 || Reg == AArch64::W18) && 4712 !Subtarget->isX18Reserved()) 4713 Reg = 0; 4714 if (Reg) 4715 return Reg; 4716 report_fatal_error(Twine("Invalid register name \"" 4717 + StringRef(RegName) + "\".")); 4718 } 4719 4720 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4721 SelectionDAG &DAG) const { 4722 MachineFunction &MF = DAG.getMachineFunction(); 4723 MachineFrameInfo &MFI = MF.getFrameInfo(); 4724 MFI.setReturnAddressIsTaken(true); 4725 4726 EVT VT = Op.getValueType(); 4727 SDLoc DL(Op); 4728 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4729 if (Depth) { 4730 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4731 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4732 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4733 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4734 MachinePointerInfo()); 4735 } 4736 4737 // Return LR, which contains the return address. Mark it an implicit live-in. 4738 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4739 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4740 } 4741 4742 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4743 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4744 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4745 SelectionDAG &DAG) const { 4746 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4747 EVT VT = Op.getValueType(); 4748 unsigned VTBits = VT.getSizeInBits(); 4749 SDLoc dl(Op); 4750 SDValue ShOpLo = Op.getOperand(0); 4751 SDValue ShOpHi = Op.getOperand(1); 4752 SDValue ShAmt = Op.getOperand(2); 4753 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4754 4755 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4756 4757 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4758 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4759 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4760 4761 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4762 // is "undef". We wanted 0, so CSEL it directly. 4763 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4764 ISD::SETEQ, dl, DAG); 4765 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4766 HiBitsForLo = 4767 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4768 HiBitsForLo, CCVal, Cmp); 4769 4770 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4771 DAG.getConstant(VTBits, dl, MVT::i64)); 4772 4773 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4774 SDValue LoForNormalShift = 4775 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4776 4777 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4778 dl, DAG); 4779 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4780 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4781 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4782 LoForNormalShift, CCVal, Cmp); 4783 4784 // AArch64 shifts larger than the register width are wrapped rather than 4785 // clamped, so we can't just emit "hi >> x". 4786 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4787 SDValue HiForBigShift = 4788 Opc == ISD::SRA 4789 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4790 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4791 : DAG.getConstant(0, dl, VT); 4792 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4793 HiForNormalShift, CCVal, Cmp); 4794 4795 SDValue Ops[2] = { Lo, Hi }; 4796 return DAG.getMergeValues(Ops, dl); 4797 } 4798 4799 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4800 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4801 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4802 SelectionDAG &DAG) const { 4803 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4804 EVT VT = Op.getValueType(); 4805 unsigned VTBits = VT.getSizeInBits(); 4806 SDLoc dl(Op); 4807 SDValue ShOpLo = Op.getOperand(0); 4808 SDValue ShOpHi = Op.getOperand(1); 4809 SDValue ShAmt = Op.getOperand(2); 4810 4811 assert(Op.getOpcode() == ISD::SHL_PARTS); 4812 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4813 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4814 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4815 4816 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4817 // is "undef". We wanted 0, so CSEL it directly. 4818 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4819 ISD::SETEQ, dl, DAG); 4820 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4821 LoBitsForHi = 4822 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4823 LoBitsForHi, CCVal, Cmp); 4824 4825 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4826 DAG.getConstant(VTBits, dl, MVT::i64)); 4827 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4828 SDValue HiForNormalShift = 4829 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4830 4831 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4832 4833 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4834 dl, DAG); 4835 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4836 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4837 HiForNormalShift, CCVal, Cmp); 4838 4839 // AArch64 shifts of larger than register sizes are wrapped rather than 4840 // clamped, so we can't just emit "lo << a" if a is too big. 4841 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4842 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4843 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4844 LoForNormalShift, CCVal, Cmp); 4845 4846 SDValue Ops[2] = { Lo, Hi }; 4847 return DAG.getMergeValues(Ops, dl); 4848 } 4849 4850 bool AArch64TargetLowering::isOffsetFoldingLegal( 4851 const GlobalAddressSDNode *GA) const { 4852 // The AArch64 target doesn't support folding offsets into global addresses. 4853 return false; 4854 } 4855 4856 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4857 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4858 // FIXME: We should be able to handle f128 as well with a clever lowering. 4859 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32)) 4860 return true; 4861 4862 if (VT == MVT::f64) 4863 return AArch64_AM::getFP64Imm(Imm) != -1; 4864 else if (VT == MVT::f32) 4865 return AArch64_AM::getFP32Imm(Imm) != -1; 4866 return false; 4867 } 4868 4869 //===----------------------------------------------------------------------===// 4870 // AArch64 Optimization Hooks 4871 //===----------------------------------------------------------------------===// 4872 4873 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 4874 SDValue Operand, SelectionDAG &DAG, 4875 int &ExtraSteps) { 4876 EVT VT = Operand.getValueType(); 4877 if (ST->hasNEON() && 4878 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 4879 VT == MVT::f32 || VT == MVT::v1f32 || 4880 VT == MVT::v2f32 || VT == MVT::v4f32)) { 4881 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 4882 // For the reciprocal estimates, convergence is quadratic, so the number 4883 // of digits is doubled after each iteration. In ARMv8, the accuracy of 4884 // the initial estimate is 2^-8. Thus the number of extra steps to refine 4885 // the result for float (23 mantissa bits) is 2 and for double (52 4886 // mantissa bits) is 3. 4887 ExtraSteps = VT == MVT::f64 ? 3 : 2; 4888 4889 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 4890 } 4891 4892 return SDValue(); 4893 } 4894 4895 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 4896 SelectionDAG &DAG, int Enabled, 4897 int &ExtraSteps, 4898 bool &UseOneConst, 4899 bool Reciprocal) const { 4900 if (Enabled == ReciprocalEstimate::Enabled || 4901 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 4902 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 4903 DAG, ExtraSteps)) { 4904 SDLoc DL(Operand); 4905 EVT VT = Operand.getValueType(); 4906 4907 SDNodeFlags Flags; 4908 Flags.setUnsafeAlgebra(true); 4909 4910 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 4911 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 4912 for (int i = ExtraSteps; i > 0; --i) { 4913 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 4914 Flags); 4915 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 4916 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 4917 } 4918 4919 if (!Reciprocal) { 4920 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 4921 VT); 4922 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 4923 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 4924 4925 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 4926 // Correct the result if the operand is 0.0. 4927 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 4928 VT, Eq, Operand, Estimate); 4929 } 4930 4931 ExtraSteps = 0; 4932 return Estimate; 4933 } 4934 4935 return SDValue(); 4936 } 4937 4938 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 4939 SelectionDAG &DAG, int Enabled, 4940 int &ExtraSteps) const { 4941 if (Enabled == ReciprocalEstimate::Enabled) 4942 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 4943 DAG, ExtraSteps)) { 4944 SDLoc DL(Operand); 4945 EVT VT = Operand.getValueType(); 4946 4947 SDNodeFlags Flags; 4948 Flags.setUnsafeAlgebra(true); 4949 4950 // Newton reciprocal iteration: E * (2 - X * E) 4951 // AArch64 reciprocal iteration instruction: (2 - M * N) 4952 for (int i = ExtraSteps; i > 0; --i) { 4953 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 4954 Estimate, Flags); 4955 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 4956 } 4957 4958 ExtraSteps = 0; 4959 return Estimate; 4960 } 4961 4962 return SDValue(); 4963 } 4964 4965 //===----------------------------------------------------------------------===// 4966 // AArch64 Inline Assembly Support 4967 //===----------------------------------------------------------------------===// 4968 4969 // Table of Constraints 4970 // TODO: This is the current set of constraints supported by ARM for the 4971 // compiler, not all of them may make sense, e.g. S may be difficult to support. 4972 // 4973 // r - A general register 4974 // w - An FP/SIMD register of some size in the range v0-v31 4975 // x - An FP/SIMD register of some size in the range v0-v15 4976 // I - Constant that can be used with an ADD instruction 4977 // J - Constant that can be used with a SUB instruction 4978 // K - Constant that can be used with a 32-bit logical instruction 4979 // L - Constant that can be used with a 64-bit logical instruction 4980 // M - Constant that can be used as a 32-bit MOV immediate 4981 // N - Constant that can be used as a 64-bit MOV immediate 4982 // Q - A memory reference with base register and no offset 4983 // S - A symbolic address 4984 // Y - Floating point constant zero 4985 // Z - Integer constant zero 4986 // 4987 // Note that general register operands will be output using their 64-bit x 4988 // register name, whatever the size of the variable, unless the asm operand 4989 // is prefixed by the %w modifier. Floating-point and SIMD register operands 4990 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 4991 // %q modifier. 4992 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4993 // At this point, we have to lower this constraint to something else, so we 4994 // lower it to an "r" or "w". However, by doing this we will force the result 4995 // to be in register, while the X constraint is much more permissive. 4996 // 4997 // Although we are correct (we are free to emit anything, without 4998 // constraints), we might break use cases that would expect us to be more 4999 // efficient and emit something else. 5000 if (!Subtarget->hasFPARMv8()) 5001 return "r"; 5002 5003 if (ConstraintVT.isFloatingPoint()) 5004 return "w"; 5005 5006 if (ConstraintVT.isVector() && 5007 (ConstraintVT.getSizeInBits() == 64 || 5008 ConstraintVT.getSizeInBits() == 128)) 5009 return "w"; 5010 5011 return "r"; 5012 } 5013 5014 /// getConstraintType - Given a constraint letter, return the type of 5015 /// constraint it is for this target. 5016 AArch64TargetLowering::ConstraintType 5017 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 5018 if (Constraint.size() == 1) { 5019 switch (Constraint[0]) { 5020 default: 5021 break; 5022 case 'z': 5023 return C_Other; 5024 case 'x': 5025 case 'w': 5026 return C_RegisterClass; 5027 // An address with a single base register. Due to the way we 5028 // currently handle addresses it is the same as 'r'. 5029 case 'Q': 5030 return C_Memory; 5031 } 5032 } 5033 return TargetLowering::getConstraintType(Constraint); 5034 } 5035 5036 /// Examine constraint type and operand type and determine a weight value. 5037 /// This object must already have been set up with the operand type 5038 /// and the current alternative constraint selected. 5039 TargetLowering::ConstraintWeight 5040 AArch64TargetLowering::getSingleConstraintMatchWeight( 5041 AsmOperandInfo &info, const char *constraint) const { 5042 ConstraintWeight weight = CW_Invalid; 5043 Value *CallOperandVal = info.CallOperandVal; 5044 // If we don't have a value, we can't do a match, 5045 // but allow it at the lowest weight. 5046 if (!CallOperandVal) 5047 return CW_Default; 5048 Type *type = CallOperandVal->getType(); 5049 // Look at the constraint type. 5050 switch (*constraint) { 5051 default: 5052 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 5053 break; 5054 case 'x': 5055 case 'w': 5056 if (type->isFloatingPointTy() || type->isVectorTy()) 5057 weight = CW_Register; 5058 break; 5059 case 'z': 5060 weight = CW_Constant; 5061 break; 5062 } 5063 return weight; 5064 } 5065 5066 std::pair<unsigned, const TargetRegisterClass *> 5067 AArch64TargetLowering::getRegForInlineAsmConstraint( 5068 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 5069 if (Constraint.size() == 1) { 5070 switch (Constraint[0]) { 5071 case 'r': 5072 if (VT.getSizeInBits() == 64) 5073 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 5074 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 5075 case 'w': 5076 if (VT.getSizeInBits() == 16) 5077 return std::make_pair(0U, &AArch64::FPR16RegClass); 5078 if (VT.getSizeInBits() == 32) 5079 return std::make_pair(0U, &AArch64::FPR32RegClass); 5080 if (VT.getSizeInBits() == 64) 5081 return std::make_pair(0U, &AArch64::FPR64RegClass); 5082 if (VT.getSizeInBits() == 128) 5083 return std::make_pair(0U, &AArch64::FPR128RegClass); 5084 break; 5085 // The instructions that this constraint is designed for can 5086 // only take 128-bit registers so just use that regclass. 5087 case 'x': 5088 if (VT.getSizeInBits() == 128) 5089 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 5090 break; 5091 } 5092 } 5093 if (StringRef("{cc}").equals_lower(Constraint)) 5094 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 5095 5096 // Use the default implementation in TargetLowering to convert the register 5097 // constraint into a member of a register class. 5098 std::pair<unsigned, const TargetRegisterClass *> Res; 5099 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 5100 5101 // Not found as a standard register? 5102 if (!Res.second) { 5103 unsigned Size = Constraint.size(); 5104 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 5105 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 5106 int RegNo; 5107 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 5108 if (!Failed && RegNo >= 0 && RegNo <= 31) { 5109 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 5110 // By default we'll emit v0-v31 for this unless there's a modifier where 5111 // we'll emit the correct register as well. 5112 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 5113 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 5114 Res.second = &AArch64::FPR64RegClass; 5115 } else { 5116 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 5117 Res.second = &AArch64::FPR128RegClass; 5118 } 5119 } 5120 } 5121 } 5122 5123 return Res; 5124 } 5125 5126 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 5127 /// vector. If it is invalid, don't add anything to Ops. 5128 void AArch64TargetLowering::LowerAsmOperandForConstraint( 5129 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 5130 SelectionDAG &DAG) const { 5131 SDValue Result; 5132 5133 // Currently only support length 1 constraints. 5134 if (Constraint.length() != 1) 5135 return; 5136 5137 char ConstraintLetter = Constraint[0]; 5138 switch (ConstraintLetter) { 5139 default: 5140 break; 5141 5142 // This set of constraints deal with valid constants for various instructions. 5143 // Validate and return a target constant for them if we can. 5144 case 'z': { 5145 // 'z' maps to xzr or wzr so it needs an input of 0. 5146 if (!isNullConstant(Op)) 5147 return; 5148 5149 if (Op.getValueType() == MVT::i64) 5150 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 5151 else 5152 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 5153 break; 5154 } 5155 5156 case 'I': 5157 case 'J': 5158 case 'K': 5159 case 'L': 5160 case 'M': 5161 case 'N': 5162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 5163 if (!C) 5164 return; 5165 5166 // Grab the value and do some validation. 5167 uint64_t CVal = C->getZExtValue(); 5168 switch (ConstraintLetter) { 5169 // The I constraint applies only to simple ADD or SUB immediate operands: 5170 // i.e. 0 to 4095 with optional shift by 12 5171 // The J constraint applies only to ADD or SUB immediates that would be 5172 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 5173 // instruction [or vice versa], in other words -1 to -4095 with optional 5174 // left shift by 12. 5175 case 'I': 5176 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 5177 break; 5178 return; 5179 case 'J': { 5180 uint64_t NVal = -C->getSExtValue(); 5181 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 5182 CVal = C->getSExtValue(); 5183 break; 5184 } 5185 return; 5186 } 5187 // The K and L constraints apply *only* to logical immediates, including 5188 // what used to be the MOVI alias for ORR (though the MOVI alias has now 5189 // been removed and MOV should be used). So these constraints have to 5190 // distinguish between bit patterns that are valid 32-bit or 64-bit 5191 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 5192 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 5193 // versa. 5194 case 'K': 5195 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5196 break; 5197 return; 5198 case 'L': 5199 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5200 break; 5201 return; 5202 // The M and N constraints are a superset of K and L respectively, for use 5203 // with the MOV (immediate) alias. As well as the logical immediates they 5204 // also match 32 or 64-bit immediates that can be loaded either using a 5205 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 5206 // (M) or 64-bit 0x1234000000000000 (N) etc. 5207 // As a note some of this code is liberally stolen from the asm parser. 5208 case 'M': { 5209 if (!isUInt<32>(CVal)) 5210 return; 5211 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5212 break; 5213 if ((CVal & 0xFFFF) == CVal) 5214 break; 5215 if ((CVal & 0xFFFF0000ULL) == CVal) 5216 break; 5217 uint64_t NCVal = ~(uint32_t)CVal; 5218 if ((NCVal & 0xFFFFULL) == NCVal) 5219 break; 5220 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5221 break; 5222 return; 5223 } 5224 case 'N': { 5225 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5226 break; 5227 if ((CVal & 0xFFFFULL) == CVal) 5228 break; 5229 if ((CVal & 0xFFFF0000ULL) == CVal) 5230 break; 5231 if ((CVal & 0xFFFF00000000ULL) == CVal) 5232 break; 5233 if ((CVal & 0xFFFF000000000000ULL) == CVal) 5234 break; 5235 uint64_t NCVal = ~CVal; 5236 if ((NCVal & 0xFFFFULL) == NCVal) 5237 break; 5238 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5239 break; 5240 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 5241 break; 5242 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 5243 break; 5244 return; 5245 } 5246 default: 5247 return; 5248 } 5249 5250 // All assembler immediates are 64-bit integers. 5251 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 5252 break; 5253 } 5254 5255 if (Result.getNode()) { 5256 Ops.push_back(Result); 5257 return; 5258 } 5259 5260 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 5261 } 5262 5263 //===----------------------------------------------------------------------===// 5264 // AArch64 Advanced SIMD Support 5265 //===----------------------------------------------------------------------===// 5266 5267 /// WidenVector - Given a value in the V64 register class, produce the 5268 /// equivalent value in the V128 register class. 5269 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 5270 EVT VT = V64Reg.getValueType(); 5271 unsigned NarrowSize = VT.getVectorNumElements(); 5272 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5273 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 5274 SDLoc DL(V64Reg); 5275 5276 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 5277 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 5278 } 5279 5280 /// getExtFactor - Determine the adjustment factor for the position when 5281 /// generating an "extract from vector registers" instruction. 5282 static unsigned getExtFactor(SDValue &V) { 5283 EVT EltType = V.getValueType().getVectorElementType(); 5284 return EltType.getSizeInBits() / 8; 5285 } 5286 5287 /// NarrowVector - Given a value in the V128 register class, produce the 5288 /// equivalent value in the V64 register class. 5289 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 5290 EVT VT = V128Reg.getValueType(); 5291 unsigned WideSize = VT.getVectorNumElements(); 5292 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5293 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 5294 SDLoc DL(V128Reg); 5295 5296 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 5297 } 5298 5299 // Gather data to see if the operation can be modelled as a 5300 // shuffle in combination with VEXTs. 5301 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 5302 SelectionDAG &DAG) const { 5303 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5304 SDLoc dl(Op); 5305 EVT VT = Op.getValueType(); 5306 unsigned NumElts = VT.getVectorNumElements(); 5307 5308 struct ShuffleSourceInfo { 5309 SDValue Vec; 5310 unsigned MinElt; 5311 unsigned MaxElt; 5312 5313 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5314 // be compatible with the shuffle we intend to construct. As a result 5315 // ShuffleVec will be some sliding window into the original Vec. 5316 SDValue ShuffleVec; 5317 5318 // Code should guarantee that element i in Vec starts at element "WindowBase 5319 // + i * WindowScale in ShuffleVec". 5320 int WindowBase; 5321 int WindowScale; 5322 5323 ShuffleSourceInfo(SDValue Vec) 5324 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 5325 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 5326 5327 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5328 }; 5329 5330 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5331 // node. 5332 SmallVector<ShuffleSourceInfo, 2> Sources; 5333 for (unsigned i = 0; i < NumElts; ++i) { 5334 SDValue V = Op.getOperand(i); 5335 if (V.isUndef()) 5336 continue; 5337 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5338 !isa<ConstantSDNode>(V.getOperand(1))) { 5339 // A shuffle can only come from building a vector from various 5340 // elements of other vectors, provided their indices are constant. 5341 return SDValue(); 5342 } 5343 5344 // Add this element source to the list if it's not already there. 5345 SDValue SourceVec = V.getOperand(0); 5346 auto Source = find(Sources, SourceVec); 5347 if (Source == Sources.end()) 5348 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5349 5350 // Update the minimum and maximum lane number seen. 5351 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5352 Source->MinElt = std::min(Source->MinElt, EltNo); 5353 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5354 } 5355 5356 // Currently only do something sane when at most two source vectors 5357 // are involved. 5358 if (Sources.size() > 2) 5359 return SDValue(); 5360 5361 // Find out the smallest element size among result and two sources, and use 5362 // it as element size to build the shuffle_vector. 5363 EVT SmallestEltTy = VT.getVectorElementType(); 5364 for (auto &Source : Sources) { 5365 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5366 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5367 SmallestEltTy = SrcEltTy; 5368 } 5369 } 5370 unsigned ResMultiplier = 5371 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 5372 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5373 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5374 5375 // If the source vector is too wide or too narrow, we may nevertheless be able 5376 // to construct a compatible shuffle either by concatenating it with UNDEF or 5377 // extracting a suitable range of elements. 5378 for (auto &Src : Sources) { 5379 EVT SrcVT = Src.ShuffleVec.getValueType(); 5380 5381 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5382 continue; 5383 5384 // This stage of the search produces a source with the same element type as 5385 // the original, but with a total width matching the BUILD_VECTOR output. 5386 EVT EltVT = SrcVT.getVectorElementType(); 5387 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5388 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5389 5390 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5391 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5392 // We can pad out the smaller vector for free, so if it's part of a 5393 // shuffle... 5394 Src.ShuffleVec = 5395 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5396 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5397 continue; 5398 } 5399 5400 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5401 5402 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5403 // Span too large for a VEXT to cope 5404 return SDValue(); 5405 } 5406 5407 if (Src.MinElt >= NumSrcElts) { 5408 // The extraction can just take the second half 5409 Src.ShuffleVec = 5410 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5411 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5412 Src.WindowBase = -NumSrcElts; 5413 } else if (Src.MaxElt < NumSrcElts) { 5414 // The extraction can just take the first half 5415 Src.ShuffleVec = 5416 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5417 DAG.getConstant(0, dl, MVT::i64)); 5418 } else { 5419 // An actual VEXT is needed 5420 SDValue VEXTSrc1 = 5421 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5422 DAG.getConstant(0, dl, MVT::i64)); 5423 SDValue VEXTSrc2 = 5424 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5425 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5426 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5427 5428 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5429 VEXTSrc2, 5430 DAG.getConstant(Imm, dl, MVT::i32)); 5431 Src.WindowBase = -Src.MinElt; 5432 } 5433 } 5434 5435 // Another possible incompatibility occurs from the vector element types. We 5436 // can fix this by bitcasting the source vectors to the same type we intend 5437 // for the shuffle. 5438 for (auto &Src : Sources) { 5439 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5440 if (SrcEltTy == SmallestEltTy) 5441 continue; 5442 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5443 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5444 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5445 Src.WindowBase *= Src.WindowScale; 5446 } 5447 5448 // Final sanity check before we try to actually produce a shuffle. 5449 DEBUG( 5450 for (auto Src : Sources) 5451 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5452 ); 5453 5454 // The stars all align, our next step is to produce the mask for the shuffle. 5455 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5456 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 5457 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5458 SDValue Entry = Op.getOperand(i); 5459 if (Entry.isUndef()) 5460 continue; 5461 5462 auto Src = find(Sources, Entry.getOperand(0)); 5463 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5464 5465 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5466 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5467 // segment. 5468 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5469 int BitsDefined = 5470 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 5471 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5472 5473 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5474 // starting at the appropriate offset. 5475 int *LaneMask = &Mask[i * ResMultiplier]; 5476 5477 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5478 ExtractBase += NumElts * (Src - Sources.begin()); 5479 for (int j = 0; j < LanesDefined; ++j) 5480 LaneMask[j] = ExtractBase + j; 5481 } 5482 5483 // Final check before we try to produce nonsense... 5484 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5485 return SDValue(); 5486 5487 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5488 for (unsigned i = 0; i < Sources.size(); ++i) 5489 ShuffleOps[i] = Sources[i].ShuffleVec; 5490 5491 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5492 ShuffleOps[1], Mask); 5493 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5494 } 5495 5496 // check if an EXT instruction can handle the shuffle mask when the 5497 // vector sources of the shuffle are the same. 5498 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5499 unsigned NumElts = VT.getVectorNumElements(); 5500 5501 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5502 if (M[0] < 0) 5503 return false; 5504 5505 Imm = M[0]; 5506 5507 // If this is a VEXT shuffle, the immediate value is the index of the first 5508 // element. The other shuffle indices must be the successive elements after 5509 // the first one. 5510 unsigned ExpectedElt = Imm; 5511 for (unsigned i = 1; i < NumElts; ++i) { 5512 // Increment the expected index. If it wraps around, just follow it 5513 // back to index zero and keep going. 5514 ++ExpectedElt; 5515 if (ExpectedElt == NumElts) 5516 ExpectedElt = 0; 5517 5518 if (M[i] < 0) 5519 continue; // ignore UNDEF indices 5520 if (ExpectedElt != static_cast<unsigned>(M[i])) 5521 return false; 5522 } 5523 5524 return true; 5525 } 5526 5527 // check if an EXT instruction can handle the shuffle mask when the 5528 // vector sources of the shuffle are different. 5529 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5530 unsigned &Imm) { 5531 // Look for the first non-undef element. 5532 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 5533 5534 // Benefit form APInt to handle overflow when calculating expected element. 5535 unsigned NumElts = VT.getVectorNumElements(); 5536 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5537 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5538 // The following shuffle indices must be the successive elements after the 5539 // first real element. 5540 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5541 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5542 if (FirstWrongElt != M.end()) 5543 return false; 5544 5545 // The index of an EXT is the first element if it is not UNDEF. 5546 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5547 // value of the first element. E.g. 5548 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5549 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5550 // ExpectedElt is the last mask index plus 1. 5551 Imm = ExpectedElt.getZExtValue(); 5552 5553 // There are two difference cases requiring to reverse input vectors. 5554 // For example, for vector <4 x i32> we have the following cases, 5555 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5556 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5557 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5558 // to reverse two input vectors. 5559 if (Imm < NumElts) 5560 ReverseEXT = true; 5561 else 5562 Imm -= NumElts; 5563 5564 return true; 5565 } 5566 5567 /// isREVMask - Check if a vector shuffle corresponds to a REV 5568 /// instruction with the specified blocksize. (The order of the elements 5569 /// within each block of the vector is reversed.) 5570 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5571 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5572 "Only possible block sizes for REV are: 16, 32, 64"); 5573 5574 unsigned EltSz = VT.getScalarSizeInBits(); 5575 if (EltSz == 64) 5576 return false; 5577 5578 unsigned NumElts = VT.getVectorNumElements(); 5579 unsigned BlockElts = M[0] + 1; 5580 // If the first shuffle index is UNDEF, be optimistic. 5581 if (M[0] < 0) 5582 BlockElts = BlockSize / EltSz; 5583 5584 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5585 return false; 5586 5587 for (unsigned i = 0; i < NumElts; ++i) { 5588 if (M[i] < 0) 5589 continue; // ignore UNDEF indices 5590 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5591 return false; 5592 } 5593 5594 return true; 5595 } 5596 5597 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5598 unsigned NumElts = VT.getVectorNumElements(); 5599 WhichResult = (M[0] == 0 ? 0 : 1); 5600 unsigned Idx = WhichResult * NumElts / 2; 5601 for (unsigned i = 0; i != NumElts; i += 2) { 5602 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5603 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5604 return false; 5605 Idx += 1; 5606 } 5607 5608 return true; 5609 } 5610 5611 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5612 unsigned NumElts = VT.getVectorNumElements(); 5613 WhichResult = (M[0] == 0 ? 0 : 1); 5614 for (unsigned i = 0; i != NumElts; ++i) { 5615 if (M[i] < 0) 5616 continue; // ignore UNDEF indices 5617 if ((unsigned)M[i] != 2 * i + WhichResult) 5618 return false; 5619 } 5620 5621 return true; 5622 } 5623 5624 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5625 unsigned NumElts = VT.getVectorNumElements(); 5626 WhichResult = (M[0] == 0 ? 0 : 1); 5627 for (unsigned i = 0; i < NumElts; i += 2) { 5628 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5629 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5630 return false; 5631 } 5632 return true; 5633 } 5634 5635 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5636 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5637 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5638 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5639 unsigned NumElts = VT.getVectorNumElements(); 5640 WhichResult = (M[0] == 0 ? 0 : 1); 5641 unsigned Idx = WhichResult * NumElts / 2; 5642 for (unsigned i = 0; i != NumElts; i += 2) { 5643 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5644 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5645 return false; 5646 Idx += 1; 5647 } 5648 5649 return true; 5650 } 5651 5652 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5653 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5654 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5655 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5656 unsigned Half = VT.getVectorNumElements() / 2; 5657 WhichResult = (M[0] == 0 ? 0 : 1); 5658 for (unsigned j = 0; j != 2; ++j) { 5659 unsigned Idx = WhichResult; 5660 for (unsigned i = 0; i != Half; ++i) { 5661 int MIdx = M[i + j * Half]; 5662 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5663 return false; 5664 Idx += 2; 5665 } 5666 } 5667 5668 return true; 5669 } 5670 5671 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5672 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5673 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5674 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5675 unsigned NumElts = VT.getVectorNumElements(); 5676 WhichResult = (M[0] == 0 ? 0 : 1); 5677 for (unsigned i = 0; i < NumElts; i += 2) { 5678 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5679 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5680 return false; 5681 } 5682 return true; 5683 } 5684 5685 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5686 bool &DstIsLeft, int &Anomaly) { 5687 if (M.size() != static_cast<size_t>(NumInputElements)) 5688 return false; 5689 5690 int NumLHSMatch = 0, NumRHSMatch = 0; 5691 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5692 5693 for (int i = 0; i < NumInputElements; ++i) { 5694 if (M[i] == -1) { 5695 ++NumLHSMatch; 5696 ++NumRHSMatch; 5697 continue; 5698 } 5699 5700 if (M[i] == i) 5701 ++NumLHSMatch; 5702 else 5703 LastLHSMismatch = i; 5704 5705 if (M[i] == i + NumInputElements) 5706 ++NumRHSMatch; 5707 else 5708 LastRHSMismatch = i; 5709 } 5710 5711 if (NumLHSMatch == NumInputElements - 1) { 5712 DstIsLeft = true; 5713 Anomaly = LastLHSMismatch; 5714 return true; 5715 } else if (NumRHSMatch == NumInputElements - 1) { 5716 DstIsLeft = false; 5717 Anomaly = LastRHSMismatch; 5718 return true; 5719 } 5720 5721 return false; 5722 } 5723 5724 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5725 if (VT.getSizeInBits() != 128) 5726 return false; 5727 5728 unsigned NumElts = VT.getVectorNumElements(); 5729 5730 for (int I = 0, E = NumElts / 2; I != E; I++) { 5731 if (Mask[I] != I) 5732 return false; 5733 } 5734 5735 int Offset = NumElts / 2; 5736 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5737 if (Mask[I] != I + SplitLHS * Offset) 5738 return false; 5739 } 5740 5741 return true; 5742 } 5743 5744 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5745 SDLoc DL(Op); 5746 EVT VT = Op.getValueType(); 5747 SDValue V0 = Op.getOperand(0); 5748 SDValue V1 = Op.getOperand(1); 5749 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5750 5751 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5752 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5753 return SDValue(); 5754 5755 bool SplitV0 = V0.getValueSizeInBits() == 128; 5756 5757 if (!isConcatMask(Mask, VT, SplitV0)) 5758 return SDValue(); 5759 5760 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5761 VT.getVectorNumElements() / 2); 5762 if (SplitV0) { 5763 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5764 DAG.getConstant(0, DL, MVT::i64)); 5765 } 5766 if (V1.getValueSizeInBits() == 128) { 5767 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5768 DAG.getConstant(0, DL, MVT::i64)); 5769 } 5770 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5771 } 5772 5773 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5774 /// the specified operations to build the shuffle. 5775 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5776 SDValue RHS, SelectionDAG &DAG, 5777 const SDLoc &dl) { 5778 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5779 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5780 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5781 5782 enum { 5783 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5784 OP_VREV, 5785 OP_VDUP0, 5786 OP_VDUP1, 5787 OP_VDUP2, 5788 OP_VDUP3, 5789 OP_VEXT1, 5790 OP_VEXT2, 5791 OP_VEXT3, 5792 OP_VUZPL, // VUZP, left result 5793 OP_VUZPR, // VUZP, right result 5794 OP_VZIPL, // VZIP, left result 5795 OP_VZIPR, // VZIP, right result 5796 OP_VTRNL, // VTRN, left result 5797 OP_VTRNR // VTRN, right result 5798 }; 5799 5800 if (OpNum == OP_COPY) { 5801 if (LHSID == (1 * 9 + 2) * 9 + 3) 5802 return LHS; 5803 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5804 return RHS; 5805 } 5806 5807 SDValue OpLHS, OpRHS; 5808 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5809 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5810 EVT VT = OpLHS.getValueType(); 5811 5812 switch (OpNum) { 5813 default: 5814 llvm_unreachable("Unknown shuffle opcode!"); 5815 case OP_VREV: 5816 // VREV divides the vector in half and swaps within the half. 5817 if (VT.getVectorElementType() == MVT::i32 || 5818 VT.getVectorElementType() == MVT::f32) 5819 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5820 // vrev <4 x i16> -> REV32 5821 if (VT.getVectorElementType() == MVT::i16 || 5822 VT.getVectorElementType() == MVT::f16) 5823 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5824 // vrev <4 x i8> -> REV16 5825 assert(VT.getVectorElementType() == MVT::i8); 5826 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5827 case OP_VDUP0: 5828 case OP_VDUP1: 5829 case OP_VDUP2: 5830 case OP_VDUP3: { 5831 EVT EltTy = VT.getVectorElementType(); 5832 unsigned Opcode; 5833 if (EltTy == MVT::i8) 5834 Opcode = AArch64ISD::DUPLANE8; 5835 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5836 Opcode = AArch64ISD::DUPLANE16; 5837 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5838 Opcode = AArch64ISD::DUPLANE32; 5839 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5840 Opcode = AArch64ISD::DUPLANE64; 5841 else 5842 llvm_unreachable("Invalid vector element type?"); 5843 5844 if (VT.getSizeInBits() == 64) 5845 OpLHS = WidenVector(OpLHS, DAG); 5846 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5847 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5848 } 5849 case OP_VEXT1: 5850 case OP_VEXT2: 5851 case OP_VEXT3: { 5852 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5853 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5854 DAG.getConstant(Imm, dl, MVT::i32)); 5855 } 5856 case OP_VUZPL: 5857 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5858 OpRHS); 5859 case OP_VUZPR: 5860 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5861 OpRHS); 5862 case OP_VZIPL: 5863 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5864 OpRHS); 5865 case OP_VZIPR: 5866 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5867 OpRHS); 5868 case OP_VTRNL: 5869 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5870 OpRHS); 5871 case OP_VTRNR: 5872 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5873 OpRHS); 5874 } 5875 } 5876 5877 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5878 SelectionDAG &DAG) { 5879 // Check to see if we can use the TBL instruction. 5880 SDValue V1 = Op.getOperand(0); 5881 SDValue V2 = Op.getOperand(1); 5882 SDLoc DL(Op); 5883 5884 EVT EltVT = Op.getValueType().getVectorElementType(); 5885 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5886 5887 SmallVector<SDValue, 8> TBLMask; 5888 for (int Val : ShuffleMask) { 5889 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 5890 unsigned Offset = Byte + Val * BytesPerElt; 5891 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 5892 } 5893 } 5894 5895 MVT IndexVT = MVT::v8i8; 5896 unsigned IndexLen = 8; 5897 if (Op.getValueSizeInBits() == 128) { 5898 IndexVT = MVT::v16i8; 5899 IndexLen = 16; 5900 } 5901 5902 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 5903 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 5904 5905 SDValue Shuffle; 5906 if (V2.getNode()->isUndef()) { 5907 if (IndexLen == 8) 5908 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 5909 Shuffle = DAG.getNode( 5910 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5911 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5912 DAG.getBuildVector(IndexVT, DL, 5913 makeArrayRef(TBLMask.data(), IndexLen))); 5914 } else { 5915 if (IndexLen == 8) { 5916 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 5917 Shuffle = DAG.getNode( 5918 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5919 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5920 DAG.getBuildVector(IndexVT, DL, 5921 makeArrayRef(TBLMask.data(), IndexLen))); 5922 } else { 5923 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 5924 // cannot currently represent the register constraints on the input 5925 // table registers. 5926 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 5927 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 5928 // IndexLen)); 5929 Shuffle = DAG.getNode( 5930 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5931 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 5932 V2Cst, DAG.getBuildVector(IndexVT, DL, 5933 makeArrayRef(TBLMask.data(), IndexLen))); 5934 } 5935 } 5936 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 5937 } 5938 5939 static unsigned getDUPLANEOp(EVT EltType) { 5940 if (EltType == MVT::i8) 5941 return AArch64ISD::DUPLANE8; 5942 if (EltType == MVT::i16 || EltType == MVT::f16) 5943 return AArch64ISD::DUPLANE16; 5944 if (EltType == MVT::i32 || EltType == MVT::f32) 5945 return AArch64ISD::DUPLANE32; 5946 if (EltType == MVT::i64 || EltType == MVT::f64) 5947 return AArch64ISD::DUPLANE64; 5948 5949 llvm_unreachable("Invalid vector element type?"); 5950 } 5951 5952 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 5953 SelectionDAG &DAG) const { 5954 SDLoc dl(Op); 5955 EVT VT = Op.getValueType(); 5956 5957 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5958 5959 // Convert shuffles that are directly supported on NEON to target-specific 5960 // DAG nodes, instead of keeping them as shuffles and matching them again 5961 // during code selection. This is more efficient and avoids the possibility 5962 // of inconsistencies between legalization and selection. 5963 ArrayRef<int> ShuffleMask = SVN->getMask(); 5964 5965 SDValue V1 = Op.getOperand(0); 5966 SDValue V2 = Op.getOperand(1); 5967 5968 if (SVN->isSplat()) { 5969 int Lane = SVN->getSplatIndex(); 5970 // If this is undef splat, generate it via "just" vdup, if possible. 5971 if (Lane == -1) 5972 Lane = 0; 5973 5974 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 5975 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 5976 V1.getOperand(0)); 5977 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 5978 // constant. If so, we can just reference the lane's definition directly. 5979 if (V1.getOpcode() == ISD::BUILD_VECTOR && 5980 !isa<ConstantSDNode>(V1.getOperand(Lane))) 5981 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 5982 5983 // Otherwise, duplicate from the lane of the input vector. 5984 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 5985 5986 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 5987 // to make a vector of the same size as this SHUFFLE. We can ignore the 5988 // extract entirely, and canonicalise the concat using WidenVector. 5989 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 5990 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 5991 V1 = V1.getOperand(0); 5992 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 5993 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 5994 Lane -= Idx * VT.getVectorNumElements() / 2; 5995 V1 = WidenVector(V1.getOperand(Idx), DAG); 5996 } else if (VT.getSizeInBits() == 64) 5997 V1 = WidenVector(V1, DAG); 5998 5999 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 6000 } 6001 6002 if (isREVMask(ShuffleMask, VT, 64)) 6003 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 6004 if (isREVMask(ShuffleMask, VT, 32)) 6005 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 6006 if (isREVMask(ShuffleMask, VT, 16)) 6007 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 6008 6009 bool ReverseEXT = false; 6010 unsigned Imm; 6011 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 6012 if (ReverseEXT) 6013 std::swap(V1, V2); 6014 Imm *= getExtFactor(V1); 6015 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 6016 DAG.getConstant(Imm, dl, MVT::i32)); 6017 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 6018 Imm *= getExtFactor(V1); 6019 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 6020 DAG.getConstant(Imm, dl, MVT::i32)); 6021 } 6022 6023 unsigned WhichResult; 6024 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 6025 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6026 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6027 } 6028 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 6029 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6030 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6031 } 6032 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 6033 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6034 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6035 } 6036 6037 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6038 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6039 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6040 } 6041 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6042 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6043 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6044 } 6045 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6046 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6047 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6048 } 6049 6050 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 6051 return Concat; 6052 6053 bool DstIsLeft; 6054 int Anomaly; 6055 int NumInputElements = V1.getValueType().getVectorNumElements(); 6056 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 6057 SDValue DstVec = DstIsLeft ? V1 : V2; 6058 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 6059 6060 SDValue SrcVec = V1; 6061 int SrcLane = ShuffleMask[Anomaly]; 6062 if (SrcLane >= NumInputElements) { 6063 SrcVec = V2; 6064 SrcLane -= VT.getVectorNumElements(); 6065 } 6066 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 6067 6068 EVT ScalarVT = VT.getVectorElementType(); 6069 6070 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 6071 ScalarVT = MVT::i32; 6072 6073 return DAG.getNode( 6074 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 6075 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 6076 DstLaneV); 6077 } 6078 6079 // If the shuffle is not directly supported and it has 4 elements, use 6080 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6081 unsigned NumElts = VT.getVectorNumElements(); 6082 if (NumElts == 4) { 6083 unsigned PFIndexes[4]; 6084 for (unsigned i = 0; i != 4; ++i) { 6085 if (ShuffleMask[i] < 0) 6086 PFIndexes[i] = 8; 6087 else 6088 PFIndexes[i] = ShuffleMask[i]; 6089 } 6090 6091 // Compute the index in the perfect shuffle table. 6092 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6093 PFIndexes[2] * 9 + PFIndexes[3]; 6094 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6095 unsigned Cost = (PFEntry >> 30); 6096 6097 if (Cost <= 4) 6098 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6099 } 6100 6101 return GenerateTBL(Op, ShuffleMask, DAG); 6102 } 6103 6104 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 6105 APInt &UndefBits) { 6106 EVT VT = BVN->getValueType(0); 6107 APInt SplatBits, SplatUndef; 6108 unsigned SplatBitSize; 6109 bool HasAnyUndefs; 6110 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6111 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 6112 6113 for (unsigned i = 0; i < NumSplats; ++i) { 6114 CnstBits <<= SplatBitSize; 6115 UndefBits <<= SplatBitSize; 6116 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 6117 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 6118 } 6119 6120 return true; 6121 } 6122 6123 return false; 6124 } 6125 6126 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 6127 SelectionDAG &DAG) const { 6128 BuildVectorSDNode *BVN = 6129 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6130 SDValue LHS = Op.getOperand(0); 6131 SDLoc dl(Op); 6132 EVT VT = Op.getValueType(); 6133 6134 if (!BVN) 6135 return Op; 6136 6137 APInt CnstBits(VT.getSizeInBits(), 0); 6138 APInt UndefBits(VT.getSizeInBits(), 0); 6139 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6140 // We only have BIC vector immediate instruction, which is and-not. 6141 CnstBits = ~CnstBits; 6142 6143 // We make use of a little bit of goto ickiness in order to avoid having to 6144 // duplicate the immediate matching logic for the undef toggled case. 6145 bool SecondTry = false; 6146 AttemptModImm: 6147 6148 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6149 CnstBits = CnstBits.zextOrTrunc(64); 6150 uint64_t CnstVal = CnstBits.getZExtValue(); 6151 6152 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6153 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6154 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6155 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6156 DAG.getConstant(CnstVal, dl, MVT::i32), 6157 DAG.getConstant(0, dl, MVT::i32)); 6158 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6159 } 6160 6161 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6162 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6163 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6164 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6165 DAG.getConstant(CnstVal, dl, MVT::i32), 6166 DAG.getConstant(8, dl, MVT::i32)); 6167 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6168 } 6169 6170 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6171 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6172 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6173 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6174 DAG.getConstant(CnstVal, dl, MVT::i32), 6175 DAG.getConstant(16, dl, MVT::i32)); 6176 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6177 } 6178 6179 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6180 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6181 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6182 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6183 DAG.getConstant(CnstVal, dl, MVT::i32), 6184 DAG.getConstant(24, dl, MVT::i32)); 6185 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6186 } 6187 6188 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6189 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6190 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6191 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6192 DAG.getConstant(CnstVal, dl, MVT::i32), 6193 DAG.getConstant(0, dl, MVT::i32)); 6194 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6195 } 6196 6197 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6198 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6199 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6200 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6201 DAG.getConstant(CnstVal, dl, MVT::i32), 6202 DAG.getConstant(8, dl, MVT::i32)); 6203 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6204 } 6205 } 6206 6207 if (SecondTry) 6208 goto FailedModImm; 6209 SecondTry = true; 6210 CnstBits = ~UndefBits; 6211 goto AttemptModImm; 6212 } 6213 6214 // We can always fall back to a non-immediate AND. 6215 FailedModImm: 6216 return Op; 6217 } 6218 6219 // Specialized code to quickly find if PotentialBVec is a BuildVector that 6220 // consists of only the same constant int value, returned in reference arg 6221 // ConstVal 6222 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 6223 uint64_t &ConstVal) { 6224 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 6225 if (!Bvec) 6226 return false; 6227 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 6228 if (!FirstElt) 6229 return false; 6230 EVT VT = Bvec->getValueType(0); 6231 unsigned NumElts = VT.getVectorNumElements(); 6232 for (unsigned i = 1; i < NumElts; ++i) 6233 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 6234 return false; 6235 ConstVal = FirstElt->getZExtValue(); 6236 return true; 6237 } 6238 6239 static unsigned getIntrinsicID(const SDNode *N) { 6240 unsigned Opcode = N->getOpcode(); 6241 switch (Opcode) { 6242 default: 6243 return Intrinsic::not_intrinsic; 6244 case ISD::INTRINSIC_WO_CHAIN: { 6245 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6246 if (IID < Intrinsic::num_intrinsics) 6247 return IID; 6248 return Intrinsic::not_intrinsic; 6249 } 6250 } 6251 } 6252 6253 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 6254 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 6255 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 6256 // Also, logical shift right -> sri, with the same structure. 6257 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 6258 EVT VT = N->getValueType(0); 6259 6260 if (!VT.isVector()) 6261 return SDValue(); 6262 6263 SDLoc DL(N); 6264 6265 // Is the first op an AND? 6266 const SDValue And = N->getOperand(0); 6267 if (And.getOpcode() != ISD::AND) 6268 return SDValue(); 6269 6270 // Is the second op an shl or lshr? 6271 SDValue Shift = N->getOperand(1); 6272 // This will have been turned into: AArch64ISD::VSHL vector, #shift 6273 // or AArch64ISD::VLSHR vector, #shift 6274 unsigned ShiftOpc = Shift.getOpcode(); 6275 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 6276 return SDValue(); 6277 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 6278 6279 // Is the shift amount constant? 6280 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 6281 if (!C2node) 6282 return SDValue(); 6283 6284 // Is the and mask vector all constant? 6285 uint64_t C1; 6286 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 6287 return SDValue(); 6288 6289 // Is C1 == ~C2, taking into account how much one can shift elements of a 6290 // particular size? 6291 uint64_t C2 = C2node->getZExtValue(); 6292 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 6293 if (C2 > ElemSizeInBits) 6294 return SDValue(); 6295 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 6296 if ((C1 & ElemMask) != (~C2 & ElemMask)) 6297 return SDValue(); 6298 6299 SDValue X = And.getOperand(0); 6300 SDValue Y = Shift.getOperand(0); 6301 6302 unsigned Intrin = 6303 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 6304 SDValue ResultSLI = 6305 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6306 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 6307 Shift.getOperand(1)); 6308 6309 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 6310 DEBUG(N->dump(&DAG)); 6311 DEBUG(dbgs() << "into: \n"); 6312 DEBUG(ResultSLI->dump(&DAG)); 6313 6314 ++NumShiftInserts; 6315 return ResultSLI; 6316 } 6317 6318 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 6319 SelectionDAG &DAG) const { 6320 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 6321 if (EnableAArch64SlrGeneration) { 6322 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 6323 return Res; 6324 } 6325 6326 BuildVectorSDNode *BVN = 6327 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 6328 SDValue LHS = Op.getOperand(1); 6329 SDLoc dl(Op); 6330 EVT VT = Op.getValueType(); 6331 6332 // OR commutes, so try swapping the operands. 6333 if (!BVN) { 6334 LHS = Op.getOperand(0); 6335 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6336 } 6337 if (!BVN) 6338 return Op; 6339 6340 APInt CnstBits(VT.getSizeInBits(), 0); 6341 APInt UndefBits(VT.getSizeInBits(), 0); 6342 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6343 // We make use of a little bit of goto ickiness in order to avoid having to 6344 // duplicate the immediate matching logic for the undef toggled case. 6345 bool SecondTry = false; 6346 AttemptModImm: 6347 6348 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6349 CnstBits = CnstBits.zextOrTrunc(64); 6350 uint64_t CnstVal = CnstBits.getZExtValue(); 6351 6352 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6353 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6354 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6355 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6356 DAG.getConstant(CnstVal, dl, MVT::i32), 6357 DAG.getConstant(0, dl, MVT::i32)); 6358 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6359 } 6360 6361 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6362 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6363 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6364 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6365 DAG.getConstant(CnstVal, dl, MVT::i32), 6366 DAG.getConstant(8, dl, MVT::i32)); 6367 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6368 } 6369 6370 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6371 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6372 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6373 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6374 DAG.getConstant(CnstVal, dl, MVT::i32), 6375 DAG.getConstant(16, dl, MVT::i32)); 6376 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6377 } 6378 6379 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6380 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6381 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6382 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6383 DAG.getConstant(CnstVal, dl, MVT::i32), 6384 DAG.getConstant(24, dl, MVT::i32)); 6385 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6386 } 6387 6388 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6389 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6390 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6391 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6392 DAG.getConstant(CnstVal, dl, MVT::i32), 6393 DAG.getConstant(0, dl, MVT::i32)); 6394 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6395 } 6396 6397 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6398 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6399 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6400 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6401 DAG.getConstant(CnstVal, dl, MVT::i32), 6402 DAG.getConstant(8, dl, MVT::i32)); 6403 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6404 } 6405 } 6406 6407 if (SecondTry) 6408 goto FailedModImm; 6409 SecondTry = true; 6410 CnstBits = UndefBits; 6411 goto AttemptModImm; 6412 } 6413 6414 // We can always fall back to a non-immediate OR. 6415 FailedModImm: 6416 return Op; 6417 } 6418 6419 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6420 // be truncated to fit element width. 6421 static SDValue NormalizeBuildVector(SDValue Op, 6422 SelectionDAG &DAG) { 6423 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6424 SDLoc dl(Op); 6425 EVT VT = Op.getValueType(); 6426 EVT EltTy= VT.getVectorElementType(); 6427 6428 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6429 return Op; 6430 6431 SmallVector<SDValue, 16> Ops; 6432 for (SDValue Lane : Op->ops()) { 6433 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6434 APInt LowBits(EltTy.getSizeInBits(), 6435 CstLane->getZExtValue()); 6436 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6437 } 6438 Ops.push_back(Lane); 6439 } 6440 return DAG.getBuildVector(VT, dl, Ops); 6441 } 6442 6443 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6444 SelectionDAG &DAG) const { 6445 SDLoc dl(Op); 6446 EVT VT = Op.getValueType(); 6447 Op = NormalizeBuildVector(Op, DAG); 6448 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6449 6450 APInt CnstBits(VT.getSizeInBits(), 0); 6451 APInt UndefBits(VT.getSizeInBits(), 0); 6452 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6453 // We make use of a little bit of goto ickiness in order to avoid having to 6454 // duplicate the immediate matching logic for the undef toggled case. 6455 bool SecondTry = false; 6456 AttemptModImm: 6457 6458 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6459 CnstBits = CnstBits.zextOrTrunc(64); 6460 uint64_t CnstVal = CnstBits.getZExtValue(); 6461 6462 // Certain magic vector constants (used to express things like NOT 6463 // and NEG) are passed through unmodified. This allows codegen patterns 6464 // for these operations to match. Special-purpose patterns will lower 6465 // these immediates to MOVIs if it proves necessary. 6466 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6467 return Op; 6468 6469 // The many faces of MOVI... 6470 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6471 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6472 if (VT.getSizeInBits() == 128) { 6473 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6474 DAG.getConstant(CnstVal, dl, MVT::i32)); 6475 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6476 } 6477 6478 // Support the V64 version via subregister insertion. 6479 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6480 DAG.getConstant(CnstVal, dl, MVT::i32)); 6481 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6482 } 6483 6484 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6485 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6486 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6487 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6488 DAG.getConstant(CnstVal, dl, MVT::i32), 6489 DAG.getConstant(0, dl, MVT::i32)); 6490 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6491 } 6492 6493 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6494 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6495 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6496 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6497 DAG.getConstant(CnstVal, dl, MVT::i32), 6498 DAG.getConstant(8, dl, MVT::i32)); 6499 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6500 } 6501 6502 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6503 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6504 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6505 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6506 DAG.getConstant(CnstVal, dl, MVT::i32), 6507 DAG.getConstant(16, dl, MVT::i32)); 6508 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6509 } 6510 6511 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6512 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6513 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6514 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6515 DAG.getConstant(CnstVal, dl, MVT::i32), 6516 DAG.getConstant(24, dl, MVT::i32)); 6517 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6518 } 6519 6520 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6521 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6522 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6523 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6524 DAG.getConstant(CnstVal, dl, MVT::i32), 6525 DAG.getConstant(0, dl, MVT::i32)); 6526 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6527 } 6528 6529 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6530 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6531 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6532 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6533 DAG.getConstant(CnstVal, dl, MVT::i32), 6534 DAG.getConstant(8, dl, MVT::i32)); 6535 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6536 } 6537 6538 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6539 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6540 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6541 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6542 DAG.getConstant(CnstVal, dl, MVT::i32), 6543 DAG.getConstant(264, dl, MVT::i32)); 6544 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6545 } 6546 6547 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6548 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6549 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6550 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6551 DAG.getConstant(CnstVal, dl, MVT::i32), 6552 DAG.getConstant(272, dl, MVT::i32)); 6553 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6554 } 6555 6556 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6557 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6558 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6559 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6560 DAG.getConstant(CnstVal, dl, MVT::i32)); 6561 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6562 } 6563 6564 // The few faces of FMOV... 6565 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6566 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6567 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6568 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6569 DAG.getConstant(CnstVal, dl, MVT::i32)); 6570 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6571 } 6572 6573 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6574 VT.getSizeInBits() == 128) { 6575 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6576 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6577 DAG.getConstant(CnstVal, dl, MVT::i32)); 6578 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6579 } 6580 6581 // The many faces of MVNI... 6582 CnstVal = ~CnstVal; 6583 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6584 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6585 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6586 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6587 DAG.getConstant(CnstVal, dl, MVT::i32), 6588 DAG.getConstant(0, dl, MVT::i32)); 6589 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6590 } 6591 6592 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6593 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6594 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6595 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6596 DAG.getConstant(CnstVal, dl, MVT::i32), 6597 DAG.getConstant(8, dl, MVT::i32)); 6598 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6599 } 6600 6601 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6602 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6603 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6604 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6605 DAG.getConstant(CnstVal, dl, MVT::i32), 6606 DAG.getConstant(16, dl, MVT::i32)); 6607 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6608 } 6609 6610 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6611 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6612 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6613 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6614 DAG.getConstant(CnstVal, dl, MVT::i32), 6615 DAG.getConstant(24, dl, MVT::i32)); 6616 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6617 } 6618 6619 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6620 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6621 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6622 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6623 DAG.getConstant(CnstVal, dl, MVT::i32), 6624 DAG.getConstant(0, dl, MVT::i32)); 6625 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6626 } 6627 6628 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6629 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6631 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6632 DAG.getConstant(CnstVal, dl, MVT::i32), 6633 DAG.getConstant(8, dl, MVT::i32)); 6634 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6635 } 6636 6637 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6638 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6639 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6640 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6641 DAG.getConstant(CnstVal, dl, MVT::i32), 6642 DAG.getConstant(264, dl, MVT::i32)); 6643 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6644 } 6645 6646 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6647 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6648 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6649 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6650 DAG.getConstant(CnstVal, dl, MVT::i32), 6651 DAG.getConstant(272, dl, MVT::i32)); 6652 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6653 } 6654 } 6655 6656 if (SecondTry) 6657 goto FailedModImm; 6658 SecondTry = true; 6659 CnstBits = UndefBits; 6660 goto AttemptModImm; 6661 } 6662 FailedModImm: 6663 6664 // Scan through the operands to find some interesting properties we can 6665 // exploit: 6666 // 1) If only one value is used, we can use a DUP, or 6667 // 2) if only the low element is not undef, we can just insert that, or 6668 // 3) if only one constant value is used (w/ some non-constant lanes), 6669 // we can splat the constant value into the whole vector then fill 6670 // in the non-constant lanes. 6671 // 4) FIXME: If different constant values are used, but we can intelligently 6672 // select the values we'll be overwriting for the non-constant 6673 // lanes such that we can directly materialize the vector 6674 // some other way (MOVI, e.g.), we can be sneaky. 6675 unsigned NumElts = VT.getVectorNumElements(); 6676 bool isOnlyLowElement = true; 6677 bool usesOnlyOneValue = true; 6678 bool usesOnlyOneConstantValue = true; 6679 bool isConstant = true; 6680 unsigned NumConstantLanes = 0; 6681 SDValue Value; 6682 SDValue ConstantValue; 6683 for (unsigned i = 0; i < NumElts; ++i) { 6684 SDValue V = Op.getOperand(i); 6685 if (V.isUndef()) 6686 continue; 6687 if (i > 0) 6688 isOnlyLowElement = false; 6689 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6690 isConstant = false; 6691 6692 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6693 ++NumConstantLanes; 6694 if (!ConstantValue.getNode()) 6695 ConstantValue = V; 6696 else if (ConstantValue != V) 6697 usesOnlyOneConstantValue = false; 6698 } 6699 6700 if (!Value.getNode()) 6701 Value = V; 6702 else if (V != Value) 6703 usesOnlyOneValue = false; 6704 } 6705 6706 if (!Value.getNode()) 6707 return DAG.getUNDEF(VT); 6708 6709 if (isOnlyLowElement) 6710 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6711 6712 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6713 // i32 and try again. 6714 if (usesOnlyOneValue) { 6715 if (!isConstant) { 6716 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6717 Value.getValueType() != VT) 6718 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6719 6720 // This is actually a DUPLANExx operation, which keeps everything vectory. 6721 6722 // DUPLANE works on 128-bit vectors, widen it if necessary. 6723 SDValue Lane = Value.getOperand(1); 6724 Value = Value.getOperand(0); 6725 if (Value.getValueSizeInBits() == 64) 6726 Value = WidenVector(Value, DAG); 6727 6728 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6729 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6730 } 6731 6732 if (VT.getVectorElementType().isFloatingPoint()) { 6733 SmallVector<SDValue, 8> Ops; 6734 EVT EltTy = VT.getVectorElementType(); 6735 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6736 "Unsupported floating-point vector type"); 6737 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6738 for (unsigned i = 0; i < NumElts; ++i) 6739 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6740 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6741 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6742 Val = LowerBUILD_VECTOR(Val, DAG); 6743 if (Val.getNode()) 6744 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6745 } 6746 } 6747 6748 // If there was only one constant value used and for more than one lane, 6749 // start by splatting that value, then replace the non-constant lanes. This 6750 // is better than the default, which will perform a separate initialization 6751 // for each lane. 6752 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6753 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6754 // Now insert the non-constant lanes. 6755 for (unsigned i = 0; i < NumElts; ++i) { 6756 SDValue V = Op.getOperand(i); 6757 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6758 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6759 // Note that type legalization likely mucked about with the VT of the 6760 // source operand, so we may have to convert it here before inserting. 6761 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6762 } 6763 } 6764 return Val; 6765 } 6766 6767 // If all elements are constants and the case above didn't get hit, fall back 6768 // to the default expansion, which will generate a load from the constant 6769 // pool. 6770 if (isConstant) 6771 return SDValue(); 6772 6773 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6774 if (NumElts >= 4) { 6775 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6776 return shuffle; 6777 } 6778 6779 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6780 // know the default expansion would otherwise fall back on something even 6781 // worse. For a vector with one or two non-undef values, that's 6782 // scalar_to_vector for the elements followed by a shuffle (provided the 6783 // shuffle is valid for the target) and materialization element by element 6784 // on the stack followed by a load for everything else. 6785 if (!isConstant && !usesOnlyOneValue) { 6786 SDValue Vec = DAG.getUNDEF(VT); 6787 SDValue Op0 = Op.getOperand(0); 6788 unsigned i = 0; 6789 6790 // Use SCALAR_TO_VECTOR for lane zero to 6791 // a) Avoid a RMW dependency on the full vector register, and 6792 // b) Allow the register coalescer to fold away the copy if the 6793 // value is already in an S or D register, and we're forced to emit an 6794 // INSERT_SUBREG that we can't fold anywhere. 6795 // 6796 // We also allow types like i8 and i16 which are illegal scalar but legal 6797 // vector element types. After type-legalization the inserted value is 6798 // extended (i32) and it is safe to cast them to the vector type by ignoring 6799 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 6800 if (!Op0.isUndef()) { 6801 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 6802 ++i; 6803 } 6804 for (; i < NumElts; ++i) { 6805 SDValue V = Op.getOperand(i); 6806 if (V.isUndef()) 6807 continue; 6808 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6809 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6810 } 6811 return Vec; 6812 } 6813 6814 // Just use the default expansion. We failed to find a better alternative. 6815 return SDValue(); 6816 } 6817 6818 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6819 SelectionDAG &DAG) const { 6820 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6821 6822 // Check for non-constant or out of range lane. 6823 EVT VT = Op.getOperand(0).getValueType(); 6824 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6825 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6826 return SDValue(); 6827 6828 6829 // Insertion/extraction are legal for V128 types. 6830 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6831 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6832 VT == MVT::v8f16) 6833 return Op; 6834 6835 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6836 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6837 return SDValue(); 6838 6839 // For V64 types, we perform insertion by expanding the value 6840 // to a V128 type and perform the insertion on that. 6841 SDLoc DL(Op); 6842 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6843 EVT WideTy = WideVec.getValueType(); 6844 6845 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6846 Op.getOperand(1), Op.getOperand(2)); 6847 // Re-narrow the resultant vector. 6848 return NarrowVector(Node, DAG); 6849 } 6850 6851 SDValue 6852 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6853 SelectionDAG &DAG) const { 6854 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6855 6856 // Check for non-constant or out of range lane. 6857 EVT VT = Op.getOperand(0).getValueType(); 6858 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6859 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6860 return SDValue(); 6861 6862 6863 // Insertion/extraction are legal for V128 types. 6864 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6865 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6866 VT == MVT::v8f16) 6867 return Op; 6868 6869 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6870 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6871 return SDValue(); 6872 6873 // For V64 types, we perform extraction by expanding the value 6874 // to a V128 type and perform the extraction on that. 6875 SDLoc DL(Op); 6876 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6877 EVT WideTy = WideVec.getValueType(); 6878 6879 EVT ExtrTy = WideTy.getVectorElementType(); 6880 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 6881 ExtrTy = MVT::i32; 6882 6883 // For extractions, we just return the result directly. 6884 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 6885 Op.getOperand(1)); 6886 } 6887 6888 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 6889 SelectionDAG &DAG) const { 6890 EVT VT = Op.getOperand(0).getValueType(); 6891 SDLoc dl(Op); 6892 // Just in case... 6893 if (!VT.isVector()) 6894 return SDValue(); 6895 6896 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6897 if (!Cst) 6898 return SDValue(); 6899 unsigned Val = Cst->getZExtValue(); 6900 6901 unsigned Size = Op.getValueSizeInBits(); 6902 6903 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 6904 if (Val == 0) 6905 return Op; 6906 6907 // If this is extracting the upper 64-bits of a 128-bit vector, we match 6908 // that directly. 6909 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 6910 return Op; 6911 6912 return SDValue(); 6913 } 6914 6915 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6916 EVT VT) const { 6917 if (VT.getVectorNumElements() == 4 && 6918 (VT.is128BitVector() || VT.is64BitVector())) { 6919 unsigned PFIndexes[4]; 6920 for (unsigned i = 0; i != 4; ++i) { 6921 if (M[i] < 0) 6922 PFIndexes[i] = 8; 6923 else 6924 PFIndexes[i] = M[i]; 6925 } 6926 6927 // Compute the index in the perfect shuffle table. 6928 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6929 PFIndexes[2] * 9 + PFIndexes[3]; 6930 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6931 unsigned Cost = (PFEntry >> 30); 6932 6933 if (Cost <= 4) 6934 return true; 6935 } 6936 6937 bool DummyBool; 6938 int DummyInt; 6939 unsigned DummyUnsigned; 6940 6941 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 6942 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 6943 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 6944 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 6945 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 6946 isZIPMask(M, VT, DummyUnsigned) || 6947 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 6948 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 6949 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 6950 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 6951 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 6952 } 6953 6954 /// getVShiftImm - Check if this is a valid build_vector for the immediate 6955 /// operand of a vector shift operation, where all the elements of the 6956 /// build_vector must have the same constant integer value. 6957 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6958 // Ignore bit_converts. 6959 while (Op.getOpcode() == ISD::BITCAST) 6960 Op = Op.getOperand(0); 6961 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6962 APInt SplatBits, SplatUndef; 6963 unsigned SplatBitSize; 6964 bool HasAnyUndefs; 6965 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 6966 HasAnyUndefs, ElementBits) || 6967 SplatBitSize > ElementBits) 6968 return false; 6969 Cnt = SplatBits.getSExtValue(); 6970 return true; 6971 } 6972 6973 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6974 /// operand of a vector shift left operation. That value must be in the range: 6975 /// 0 <= Value < ElementBits for a left shift; or 6976 /// 0 <= Value <= ElementBits for a long left shift. 6977 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6978 assert(VT.isVector() && "vector shift count is not a vector type"); 6979 int64_t ElementBits = VT.getScalarSizeInBits(); 6980 if (!getVShiftImm(Op, ElementBits, Cnt)) 6981 return false; 6982 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6983 } 6984 6985 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6986 /// operand of a vector shift right operation. The value must be in the range: 6987 /// 1 <= Value <= ElementBits for a right shift; or 6988 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 6989 assert(VT.isVector() && "vector shift count is not a vector type"); 6990 int64_t ElementBits = VT.getScalarSizeInBits(); 6991 if (!getVShiftImm(Op, ElementBits, Cnt)) 6992 return false; 6993 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6994 } 6995 6996 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 6997 SelectionDAG &DAG) const { 6998 EVT VT = Op.getValueType(); 6999 SDLoc DL(Op); 7000 int64_t Cnt; 7001 7002 if (!Op.getOperand(1).getValueType().isVector()) 7003 return Op; 7004 unsigned EltSize = VT.getScalarSizeInBits(); 7005 7006 switch (Op.getOpcode()) { 7007 default: 7008 llvm_unreachable("unexpected shift opcode"); 7009 7010 case ISD::SHL: 7011 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 7012 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 7013 DAG.getConstant(Cnt, DL, MVT::i32)); 7014 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7015 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 7016 MVT::i32), 7017 Op.getOperand(0), Op.getOperand(1)); 7018 case ISD::SRA: 7019 case ISD::SRL: 7020 // Right shift immediate 7021 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 7022 unsigned Opc = 7023 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 7024 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 7025 DAG.getConstant(Cnt, DL, MVT::i32)); 7026 } 7027 7028 // Right shift register. Note, there is not a shift right register 7029 // instruction, but the shift left register instruction takes a signed 7030 // value, where negative numbers specify a right shift. 7031 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 7032 : Intrinsic::aarch64_neon_ushl; 7033 // negate the shift amount 7034 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 7035 SDValue NegShiftLeft = 7036 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7037 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 7038 NegShift); 7039 return NegShiftLeft; 7040 } 7041 7042 return SDValue(); 7043 } 7044 7045 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 7046 AArch64CC::CondCode CC, bool NoNans, EVT VT, 7047 const SDLoc &dl, SelectionDAG &DAG) { 7048 EVT SrcVT = LHS.getValueType(); 7049 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 7050 "function only supposed to emit natural comparisons"); 7051 7052 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 7053 APInt CnstBits(VT.getSizeInBits(), 0); 7054 APInt UndefBits(VT.getSizeInBits(), 0); 7055 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 7056 bool IsZero = IsCnst && (CnstBits == 0); 7057 7058 if (SrcVT.getVectorElementType().isFloatingPoint()) { 7059 switch (CC) { 7060 default: 7061 return SDValue(); 7062 case AArch64CC::NE: { 7063 SDValue Fcmeq; 7064 if (IsZero) 7065 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7066 else 7067 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7068 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 7069 } 7070 case AArch64CC::EQ: 7071 if (IsZero) 7072 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7073 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7074 case AArch64CC::GE: 7075 if (IsZero) 7076 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 7077 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 7078 case AArch64CC::GT: 7079 if (IsZero) 7080 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 7081 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 7082 case AArch64CC::LS: 7083 if (IsZero) 7084 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 7085 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 7086 case AArch64CC::LT: 7087 if (!NoNans) 7088 return SDValue(); 7089 // If we ignore NaNs then we can use to the MI implementation. 7090 LLVM_FALLTHROUGH; 7091 case AArch64CC::MI: 7092 if (IsZero) 7093 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 7094 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 7095 } 7096 } 7097 7098 switch (CC) { 7099 default: 7100 return SDValue(); 7101 case AArch64CC::NE: { 7102 SDValue Cmeq; 7103 if (IsZero) 7104 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7105 else 7106 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7107 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 7108 } 7109 case AArch64CC::EQ: 7110 if (IsZero) 7111 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7112 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7113 case AArch64CC::GE: 7114 if (IsZero) 7115 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 7116 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 7117 case AArch64CC::GT: 7118 if (IsZero) 7119 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 7120 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 7121 case AArch64CC::LE: 7122 if (IsZero) 7123 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 7124 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 7125 case AArch64CC::LS: 7126 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 7127 case AArch64CC::LO: 7128 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 7129 case AArch64CC::LT: 7130 if (IsZero) 7131 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 7132 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 7133 case AArch64CC::HI: 7134 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 7135 case AArch64CC::HS: 7136 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 7137 } 7138 } 7139 7140 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 7141 SelectionDAG &DAG) const { 7142 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7143 SDValue LHS = Op.getOperand(0); 7144 SDValue RHS = Op.getOperand(1); 7145 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 7146 SDLoc dl(Op); 7147 7148 if (LHS.getValueType().getVectorElementType().isInteger()) { 7149 assert(LHS.getValueType() == RHS.getValueType()); 7150 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 7151 SDValue Cmp = 7152 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 7153 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7154 } 7155 7156 if (LHS.getValueType().getVectorElementType() == MVT::f16) 7157 return SDValue(); 7158 7159 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 7160 LHS.getValueType().getVectorElementType() == MVT::f64); 7161 7162 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 7163 // clean. Some of them require two branches to implement. 7164 AArch64CC::CondCode CC1, CC2; 7165 bool ShouldInvert; 7166 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 7167 7168 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 7169 SDValue Cmp = 7170 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 7171 if (!Cmp.getNode()) 7172 return SDValue(); 7173 7174 if (CC2 != AArch64CC::AL) { 7175 SDValue Cmp2 = 7176 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 7177 if (!Cmp2.getNode()) 7178 return SDValue(); 7179 7180 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 7181 } 7182 7183 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7184 7185 if (ShouldInvert) 7186 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 7187 7188 return Cmp; 7189 } 7190 7191 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 7192 SelectionDAG &DAG) { 7193 SDValue VecOp = ScalarOp.getOperand(0); 7194 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 7195 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 7196 DAG.getConstant(0, DL, MVT::i64)); 7197 } 7198 7199 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 7200 SelectionDAG &DAG) const { 7201 SDLoc dl(Op); 7202 switch (Op.getOpcode()) { 7203 case ISD::VECREDUCE_ADD: 7204 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 7205 case ISD::VECREDUCE_SMAX: 7206 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 7207 case ISD::VECREDUCE_SMIN: 7208 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 7209 case ISD::VECREDUCE_UMAX: 7210 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 7211 case ISD::VECREDUCE_UMIN: 7212 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 7213 case ISD::VECREDUCE_FMAX: { 7214 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 7215 return DAG.getNode( 7216 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7217 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 7218 Op.getOperand(0)); 7219 } 7220 case ISD::VECREDUCE_FMIN: { 7221 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 7222 return DAG.getNode( 7223 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7224 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 7225 Op.getOperand(0)); 7226 } 7227 default: 7228 llvm_unreachable("Unhandled reduction"); 7229 } 7230 } 7231 7232 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 7233 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 7234 /// specified in the intrinsic calls. 7235 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 7236 const CallInst &I, 7237 unsigned Intrinsic) const { 7238 auto &DL = I.getModule()->getDataLayout(); 7239 switch (Intrinsic) { 7240 case Intrinsic::aarch64_neon_ld2: 7241 case Intrinsic::aarch64_neon_ld3: 7242 case Intrinsic::aarch64_neon_ld4: 7243 case Intrinsic::aarch64_neon_ld1x2: 7244 case Intrinsic::aarch64_neon_ld1x3: 7245 case Intrinsic::aarch64_neon_ld1x4: 7246 case Intrinsic::aarch64_neon_ld2lane: 7247 case Intrinsic::aarch64_neon_ld3lane: 7248 case Intrinsic::aarch64_neon_ld4lane: 7249 case Intrinsic::aarch64_neon_ld2r: 7250 case Intrinsic::aarch64_neon_ld3r: 7251 case Intrinsic::aarch64_neon_ld4r: { 7252 Info.opc = ISD::INTRINSIC_W_CHAIN; 7253 // Conservatively set memVT to the entire set of vectors loaded. 7254 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 7255 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 7256 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 7257 Info.offset = 0; 7258 Info.align = 0; 7259 Info.vol = false; // volatile loads with NEON intrinsics not supported 7260 Info.readMem = true; 7261 Info.writeMem = false; 7262 return true; 7263 } 7264 case Intrinsic::aarch64_neon_st2: 7265 case Intrinsic::aarch64_neon_st3: 7266 case Intrinsic::aarch64_neon_st4: 7267 case Intrinsic::aarch64_neon_st1x2: 7268 case Intrinsic::aarch64_neon_st1x3: 7269 case Intrinsic::aarch64_neon_st1x4: 7270 case Intrinsic::aarch64_neon_st2lane: 7271 case Intrinsic::aarch64_neon_st3lane: 7272 case Intrinsic::aarch64_neon_st4lane: { 7273 Info.opc = ISD::INTRINSIC_VOID; 7274 // Conservatively set memVT to the entire set of vectors stored. 7275 unsigned NumElts = 0; 7276 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 7277 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 7278 if (!ArgTy->isVectorTy()) 7279 break; 7280 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 7281 } 7282 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 7283 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 7284 Info.offset = 0; 7285 Info.align = 0; 7286 Info.vol = false; // volatile stores with NEON intrinsics not supported 7287 Info.readMem = false; 7288 Info.writeMem = true; 7289 return true; 7290 } 7291 case Intrinsic::aarch64_ldaxr: 7292 case Intrinsic::aarch64_ldxr: { 7293 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 7294 Info.opc = ISD::INTRINSIC_W_CHAIN; 7295 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7296 Info.ptrVal = I.getArgOperand(0); 7297 Info.offset = 0; 7298 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7299 Info.vol = true; 7300 Info.readMem = true; 7301 Info.writeMem = false; 7302 return true; 7303 } 7304 case Intrinsic::aarch64_stlxr: 7305 case Intrinsic::aarch64_stxr: { 7306 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 7307 Info.opc = ISD::INTRINSIC_W_CHAIN; 7308 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7309 Info.ptrVal = I.getArgOperand(1); 7310 Info.offset = 0; 7311 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7312 Info.vol = true; 7313 Info.readMem = false; 7314 Info.writeMem = true; 7315 return true; 7316 } 7317 case Intrinsic::aarch64_ldaxp: 7318 case Intrinsic::aarch64_ldxp: 7319 Info.opc = ISD::INTRINSIC_W_CHAIN; 7320 Info.memVT = MVT::i128; 7321 Info.ptrVal = I.getArgOperand(0); 7322 Info.offset = 0; 7323 Info.align = 16; 7324 Info.vol = true; 7325 Info.readMem = true; 7326 Info.writeMem = false; 7327 return true; 7328 case Intrinsic::aarch64_stlxp: 7329 case Intrinsic::aarch64_stxp: 7330 Info.opc = ISD::INTRINSIC_W_CHAIN; 7331 Info.memVT = MVT::i128; 7332 Info.ptrVal = I.getArgOperand(2); 7333 Info.offset = 0; 7334 Info.align = 16; 7335 Info.vol = true; 7336 Info.readMem = false; 7337 Info.writeMem = true; 7338 return true; 7339 default: 7340 break; 7341 } 7342 7343 return false; 7344 } 7345 7346 // Truncations from 64-bit GPR to 32-bit GPR is free. 7347 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 7348 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7349 return false; 7350 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7351 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7352 return NumBits1 > NumBits2; 7353 } 7354 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 7355 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7356 return false; 7357 unsigned NumBits1 = VT1.getSizeInBits(); 7358 unsigned NumBits2 = VT2.getSizeInBits(); 7359 return NumBits1 > NumBits2; 7360 } 7361 7362 /// Check if it is profitable to hoist instruction in then/else to if. 7363 /// Not profitable if I and it's user can form a FMA instruction 7364 /// because we prefer FMSUB/FMADD. 7365 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 7366 if (I->getOpcode() != Instruction::FMul) 7367 return true; 7368 7369 if (!I->hasOneUse()) 7370 return true; 7371 7372 Instruction *User = I->user_back(); 7373 7374 if (User && 7375 !(User->getOpcode() == Instruction::FSub || 7376 User->getOpcode() == Instruction::FAdd)) 7377 return true; 7378 7379 const TargetOptions &Options = getTargetMachine().Options; 7380 const DataLayout &DL = I->getModule()->getDataLayout(); 7381 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 7382 7383 return !(isFMAFasterThanFMulAndFAdd(VT) && 7384 isOperationLegalOrCustom(ISD::FMA, VT) && 7385 (Options.AllowFPOpFusion == FPOpFusion::Fast || 7386 Options.UnsafeFPMath)); 7387 } 7388 7389 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 7390 // 64-bit GPR. 7391 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 7392 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7393 return false; 7394 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7395 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7396 return NumBits1 == 32 && NumBits2 == 64; 7397 } 7398 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 7399 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7400 return false; 7401 unsigned NumBits1 = VT1.getSizeInBits(); 7402 unsigned NumBits2 = VT2.getSizeInBits(); 7403 return NumBits1 == 32 && NumBits2 == 64; 7404 } 7405 7406 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7407 EVT VT1 = Val.getValueType(); 7408 if (isZExtFree(VT1, VT2)) { 7409 return true; 7410 } 7411 7412 if (Val.getOpcode() != ISD::LOAD) 7413 return false; 7414 7415 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7416 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7417 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7418 VT1.getSizeInBits() <= 32); 7419 } 7420 7421 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7422 if (isa<FPExtInst>(Ext)) 7423 return false; 7424 7425 // Vector types are next free. 7426 if (Ext->getType()->isVectorTy()) 7427 return false; 7428 7429 for (const Use &U : Ext->uses()) { 7430 // The extension is free if we can fold it with a left shift in an 7431 // addressing mode or an arithmetic operation: add, sub, and cmp. 7432 7433 // Is there a shift? 7434 const Instruction *Instr = cast<Instruction>(U.getUser()); 7435 7436 // Is this a constant shift? 7437 switch (Instr->getOpcode()) { 7438 case Instruction::Shl: 7439 if (!isa<ConstantInt>(Instr->getOperand(1))) 7440 return false; 7441 break; 7442 case Instruction::GetElementPtr: { 7443 gep_type_iterator GTI = gep_type_begin(Instr); 7444 auto &DL = Ext->getModule()->getDataLayout(); 7445 std::advance(GTI, U.getOperandNo()-1); 7446 Type *IdxTy = GTI.getIndexedType(); 7447 // This extension will end up with a shift because of the scaling factor. 7448 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7449 // Get the shift amount based on the scaling factor: 7450 // log2(sizeof(IdxTy)) - log2(8). 7451 uint64_t ShiftAmt = 7452 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7453 // Is the constant foldable in the shift of the addressing mode? 7454 // I.e., shift amount is between 1 and 4 inclusive. 7455 if (ShiftAmt == 0 || ShiftAmt > 4) 7456 return false; 7457 break; 7458 } 7459 case Instruction::Trunc: 7460 // Check if this is a noop. 7461 // trunc(sext ty1 to ty2) to ty1. 7462 if (Instr->getType() == Ext->getOperand(0)->getType()) 7463 continue; 7464 LLVM_FALLTHROUGH; 7465 default: 7466 return false; 7467 } 7468 7469 // At this point we can use the bfm family, so this extension is free 7470 // for that use. 7471 } 7472 return true; 7473 } 7474 7475 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7476 unsigned &RequiredAligment) const { 7477 if (!LoadedType.isSimple() || 7478 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7479 return false; 7480 // Cyclone supports unaligned accesses. 7481 RequiredAligment = 0; 7482 unsigned NumBits = LoadedType.getSizeInBits(); 7483 return NumBits == 32 || NumBits == 64; 7484 } 7485 7486 /// A helper function for determining the number of interleaved accesses we 7487 /// will generate when lowering accesses of the given type. 7488 unsigned 7489 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 7490 const DataLayout &DL) const { 7491 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 7492 } 7493 7494 MachineMemOperand::Flags 7495 AArch64TargetLowering::getMMOFlags(const Instruction &I) const { 7496 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 7497 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 7498 return MOStridedAccess; 7499 return MachineMemOperand::MONone; 7500 } 7501 7502 bool AArch64TargetLowering::isLegalInterleavedAccessType( 7503 VectorType *VecTy, const DataLayout &DL) const { 7504 7505 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7506 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 7507 7508 // Ensure the number of vector elements is greater than 1. 7509 if (VecTy->getNumElements() < 2) 7510 return false; 7511 7512 // Ensure the element type is legal. 7513 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 7514 return false; 7515 7516 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 7517 // 128 will be split into multiple interleaved accesses. 7518 return VecSize == 64 || VecSize % 128 == 0; 7519 } 7520 7521 /// \brief Lower an interleaved load into a ldN intrinsic. 7522 /// 7523 /// E.g. Lower an interleaved load (Factor = 2): 7524 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7525 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7526 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7527 /// 7528 /// Into: 7529 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7530 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7531 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7532 bool AArch64TargetLowering::lowerInterleavedLoad( 7533 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7534 ArrayRef<unsigned> Indices, unsigned Factor) const { 7535 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7536 "Invalid interleave factor"); 7537 assert(!Shuffles.empty() && "Empty shufflevector input"); 7538 assert(Shuffles.size() == Indices.size() && 7539 "Unmatched number of shufflevectors and indices"); 7540 7541 const DataLayout &DL = LI->getModule()->getDataLayout(); 7542 7543 VectorType *VecTy = Shuffles[0]->getType(); 7544 7545 // Skip if we do not have NEON and skip illegal vector types. We can 7546 // "legalize" wide vector types into multiple interleaved accesses as long as 7547 // the vector types are divisible by 128. 7548 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 7549 return false; 7550 7551 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 7552 7553 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7554 // load integer vectors first and then convert to pointer vectors. 7555 Type *EltTy = VecTy->getVectorElementType(); 7556 if (EltTy->isPointerTy()) 7557 VecTy = 7558 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7559 7560 IRBuilder<> Builder(LI); 7561 7562 // The base address of the load. 7563 Value *BaseAddr = LI->getPointerOperand(); 7564 7565 if (NumLoads > 1) { 7566 // If we're going to generate more than one load, reset the sub-vector type 7567 // to something legal. 7568 VecTy = VectorType::get(VecTy->getVectorElementType(), 7569 VecTy->getVectorNumElements() / NumLoads); 7570 7571 // We will compute the pointer operand of each load from the original base 7572 // address using GEPs. Cast the base address to a pointer to the scalar 7573 // element type. 7574 BaseAddr = Builder.CreateBitCast( 7575 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 7576 LI->getPointerAddressSpace())); 7577 } 7578 7579 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7580 Type *Tys[2] = {VecTy, PtrTy}; 7581 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7582 Intrinsic::aarch64_neon_ld3, 7583 Intrinsic::aarch64_neon_ld4}; 7584 Function *LdNFunc = 7585 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7586 7587 // Holds sub-vectors extracted from the load intrinsic return values. The 7588 // sub-vectors are associated with the shufflevector instructions they will 7589 // replace. 7590 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 7591 7592 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 7593 7594 // If we're generating more than one load, compute the base address of 7595 // subsequent loads as an offset from the previous. 7596 if (LoadCount > 0) 7597 BaseAddr = Builder.CreateConstGEP1_32( 7598 BaseAddr, VecTy->getVectorNumElements() * Factor); 7599 7600 CallInst *LdN = Builder.CreateCall( 7601 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 7602 7603 // Extract and store the sub-vectors returned by the load intrinsic. 7604 for (unsigned i = 0; i < Shuffles.size(); i++) { 7605 ShuffleVectorInst *SVI = Shuffles[i]; 7606 unsigned Index = Indices[i]; 7607 7608 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7609 7610 // Convert the integer vector to pointer vector if the element is pointer. 7611 if (EltTy->isPointerTy()) 7612 SubVec = Builder.CreateIntToPtr( 7613 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 7614 VecTy->getVectorNumElements())); 7615 SubVecs[SVI].push_back(SubVec); 7616 } 7617 } 7618 7619 // Replace uses of the shufflevector instructions with the sub-vectors 7620 // returned by the load intrinsic. If a shufflevector instruction is 7621 // associated with more than one sub-vector, those sub-vectors will be 7622 // concatenated into a single wide vector. 7623 for (ShuffleVectorInst *SVI : Shuffles) { 7624 auto &SubVec = SubVecs[SVI]; 7625 auto *WideVec = 7626 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 7627 SVI->replaceAllUsesWith(WideVec); 7628 } 7629 7630 return true; 7631 } 7632 7633 /// \brief Lower an interleaved store into a stN intrinsic. 7634 /// 7635 /// E.g. Lower an interleaved store (Factor = 3): 7636 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7637 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7638 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7639 /// 7640 /// Into: 7641 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7642 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7643 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7644 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7645 /// 7646 /// Note that the new shufflevectors will be removed and we'll only generate one 7647 /// st3 instruction in CodeGen. 7648 /// 7649 /// Example for a more general valid mask (Factor 3). Lower: 7650 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 7651 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 7652 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7653 /// 7654 /// Into: 7655 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 7656 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 7657 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 7658 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7659 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7660 ShuffleVectorInst *SVI, 7661 unsigned Factor) const { 7662 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7663 "Invalid interleave factor"); 7664 7665 VectorType *VecTy = SVI->getType(); 7666 assert(VecTy->getVectorNumElements() % Factor == 0 && 7667 "Invalid interleaved store"); 7668 7669 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 7670 Type *EltTy = VecTy->getVectorElementType(); 7671 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 7672 7673 const DataLayout &DL = SI->getModule()->getDataLayout(); 7674 7675 // Skip if we do not have NEON and skip illegal vector types. We can 7676 // "legalize" wide vector types into multiple interleaved accesses as long as 7677 // the vector types are divisible by 128. 7678 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 7679 return false; 7680 7681 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 7682 7683 Value *Op0 = SVI->getOperand(0); 7684 Value *Op1 = SVI->getOperand(1); 7685 IRBuilder<> Builder(SI); 7686 7687 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7688 // vectors to integer vectors. 7689 if (EltTy->isPointerTy()) { 7690 Type *IntTy = DL.getIntPtrType(EltTy); 7691 unsigned NumOpElts = 7692 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7693 7694 // Convert to the corresponding integer vector. 7695 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7696 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7697 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7698 7699 SubVecTy = VectorType::get(IntTy, LaneLen); 7700 } 7701 7702 // The base address of the store. 7703 Value *BaseAddr = SI->getPointerOperand(); 7704 7705 if (NumStores > 1) { 7706 // If we're going to generate more than one store, reset the lane length 7707 // and sub-vector type to something legal. 7708 LaneLen /= NumStores; 7709 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 7710 7711 // We will compute the pointer operand of each store from the original base 7712 // address using GEPs. Cast the base address to a pointer to the scalar 7713 // element type. 7714 BaseAddr = Builder.CreateBitCast( 7715 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 7716 SI->getPointerAddressSpace())); 7717 } 7718 7719 auto Mask = SVI->getShuffleMask(); 7720 7721 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7722 Type *Tys[2] = {SubVecTy, PtrTy}; 7723 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7724 Intrinsic::aarch64_neon_st3, 7725 Intrinsic::aarch64_neon_st4}; 7726 Function *StNFunc = 7727 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7728 7729 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 7730 7731 SmallVector<Value *, 5> Ops; 7732 7733 // Split the shufflevector operands into sub vectors for the new stN call. 7734 for (unsigned i = 0; i < Factor; i++) { 7735 unsigned IdxI = StoreCount * LaneLen * Factor + i; 7736 if (Mask[IdxI] >= 0) { 7737 Ops.push_back(Builder.CreateShuffleVector( 7738 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 7739 } else { 7740 unsigned StartMask = 0; 7741 for (unsigned j = 1; j < LaneLen; j++) { 7742 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 7743 if (Mask[IdxJ * Factor + IdxI] >= 0) { 7744 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 7745 break; 7746 } 7747 } 7748 // Note: Filling undef gaps with random elements is ok, since 7749 // those elements were being written anyway (with undefs). 7750 // In the case of all undefs we're defaulting to using elems from 0 7751 // Note: StartMask cannot be negative, it's checked in 7752 // isReInterleaveMask 7753 Ops.push_back(Builder.CreateShuffleVector( 7754 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 7755 } 7756 } 7757 7758 // If we generating more than one store, we compute the base address of 7759 // subsequent stores as an offset from the previous. 7760 if (StoreCount > 0) 7761 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 7762 7763 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 7764 Builder.CreateCall(StNFunc, Ops); 7765 } 7766 return true; 7767 } 7768 7769 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7770 unsigned AlignCheck) { 7771 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7772 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7773 } 7774 7775 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7776 unsigned SrcAlign, bool IsMemset, 7777 bool ZeroMemset, 7778 bool MemcpyStrSrc, 7779 MachineFunction &MF) const { 7780 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7781 // instruction to materialize the v2i64 zero and one store (with restrictive 7782 // addressing mode). Just do two i64 store of zero-registers. 7783 bool Fast; 7784 const Function *F = MF.getFunction(); 7785 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7786 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7787 (memOpAlign(SrcAlign, DstAlign, 16) || 7788 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7789 return MVT::f128; 7790 7791 if (Size >= 8 && 7792 (memOpAlign(SrcAlign, DstAlign, 8) || 7793 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7794 return MVT::i64; 7795 7796 if (Size >= 4 && 7797 (memOpAlign(SrcAlign, DstAlign, 4) || 7798 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7799 return MVT::i32; 7800 7801 return MVT::Other; 7802 } 7803 7804 // 12-bit optionally shifted immediates are legal for adds. 7805 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7806 // Avoid UB for INT64_MIN. 7807 if (Immed == std::numeric_limits<int64_t>::min()) 7808 return false; 7809 // Same encoding for add/sub, just flip the sign. 7810 Immed = std::abs(Immed); 7811 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7812 } 7813 7814 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7815 // immediates is the same as for an add or a sub. 7816 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7817 return isLegalAddImmediate(Immed); 7818 } 7819 7820 /// isLegalAddressingMode - Return true if the addressing mode represented 7821 /// by AM is legal for this target, for a load/store of the specified type. 7822 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7823 const AddrMode &AM, Type *Ty, 7824 unsigned AS) const { 7825 // AArch64 has five basic addressing modes: 7826 // reg 7827 // reg + 9-bit signed offset 7828 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7829 // reg1 + reg2 7830 // reg + SIZE_IN_BYTES * reg 7831 7832 // No global is ever allowed as a base. 7833 if (AM.BaseGV) 7834 return false; 7835 7836 // No reg+reg+imm addressing. 7837 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7838 return false; 7839 7840 // check reg + imm case: 7841 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7842 uint64_t NumBytes = 0; 7843 if (Ty->isSized()) { 7844 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7845 NumBytes = NumBits / 8; 7846 if (!isPowerOf2_64(NumBits)) 7847 NumBytes = 0; 7848 } 7849 7850 if (!AM.Scale) { 7851 int64_t Offset = AM.BaseOffs; 7852 7853 // 9-bit signed offset 7854 if (isInt<9>(Offset)) 7855 return true; 7856 7857 // 12-bit unsigned offset 7858 unsigned shift = Log2_64(NumBytes); 7859 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 7860 // Must be a multiple of NumBytes (NumBytes is a power of 2) 7861 (Offset >> shift) << shift == Offset) 7862 return true; 7863 return false; 7864 } 7865 7866 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 7867 7868 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 7869 } 7870 7871 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 7872 const AddrMode &AM, Type *Ty, 7873 unsigned AS) const { 7874 // Scaling factors are not free at all. 7875 // Operands | Rt Latency 7876 // ------------------------------------------- 7877 // Rt, [Xn, Xm] | 4 7878 // ------------------------------------------- 7879 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 7880 // Rt, [Xn, Wm, <extend> #imm] | 7881 if (isLegalAddressingMode(DL, AM, Ty, AS)) 7882 // Scale represents reg2 * scale, thus account for 1 if 7883 // it is not equal to 0 or 1. 7884 return AM.Scale != 0 && AM.Scale != 1; 7885 return -1; 7886 } 7887 7888 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7889 VT = VT.getScalarType(); 7890 7891 if (!VT.isSimple()) 7892 return false; 7893 7894 switch (VT.getSimpleVT().SimpleTy) { 7895 case MVT::f32: 7896 case MVT::f64: 7897 return true; 7898 default: 7899 break; 7900 } 7901 7902 return false; 7903 } 7904 7905 const MCPhysReg * 7906 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 7907 // LR is a callee-save register, but we must treat it as clobbered by any call 7908 // site. Hence we include LR in the scratch registers, which are in turn added 7909 // as implicit-defs for stackmaps and patchpoints. 7910 static const MCPhysReg ScratchRegs[] = { 7911 AArch64::X16, AArch64::X17, AArch64::LR, 0 7912 }; 7913 return ScratchRegs; 7914 } 7915 7916 bool 7917 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 7918 EVT VT = N->getValueType(0); 7919 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 7920 // it with shift to let it be lowered to UBFX. 7921 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 7922 isa<ConstantSDNode>(N->getOperand(1))) { 7923 uint64_t TruncMask = N->getConstantOperandVal(1); 7924 if (isMask_64(TruncMask) && 7925 N->getOperand(0).getOpcode() == ISD::SRL && 7926 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 7927 return false; 7928 } 7929 return true; 7930 } 7931 7932 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 7933 Type *Ty) const { 7934 assert(Ty->isIntegerTy()); 7935 7936 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 7937 if (BitSize == 0) 7938 return false; 7939 7940 int64_t Val = Imm.getSExtValue(); 7941 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 7942 return true; 7943 7944 if ((int64_t)Val < 0) 7945 Val = ~Val; 7946 if (BitSize == 32) 7947 Val &= (1LL << 32) - 1; 7948 7949 unsigned LZ = countLeadingZeros((uint64_t)Val); 7950 unsigned Shift = (63 - LZ) / 16; 7951 // MOVZ is free so return true for one or fewer MOVK. 7952 return Shift < 3; 7953 } 7954 7955 /// Turn vector tests of the signbit in the form of: 7956 /// xor (sra X, elt_size(X)-1), -1 7957 /// into: 7958 /// cmge X, X, #0 7959 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 7960 const AArch64Subtarget *Subtarget) { 7961 EVT VT = N->getValueType(0); 7962 if (!Subtarget->hasNEON() || !VT.isVector()) 7963 return SDValue(); 7964 7965 // There must be a shift right algebraic before the xor, and the xor must be a 7966 // 'not' operation. 7967 SDValue Shift = N->getOperand(0); 7968 SDValue Ones = N->getOperand(1); 7969 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 7970 !ISD::isBuildVectorAllOnes(Ones.getNode())) 7971 return SDValue(); 7972 7973 // The shift should be smearing the sign bit across each vector element. 7974 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7975 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 7976 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 7977 return SDValue(); 7978 7979 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 7980 } 7981 7982 // Generate SUBS and CSEL for integer abs. 7983 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 7984 EVT VT = N->getValueType(0); 7985 7986 SDValue N0 = N->getOperand(0); 7987 SDValue N1 = N->getOperand(1); 7988 SDLoc DL(N); 7989 7990 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 7991 // and change it to SUB and CSEL. 7992 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 7993 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 7994 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 7995 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 7996 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 7997 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7998 N0.getOperand(0)); 7999 // Generate SUBS & CSEL. 8000 SDValue Cmp = 8001 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 8002 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 8003 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 8004 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 8005 SDValue(Cmp.getNode(), 1)); 8006 } 8007 return SDValue(); 8008 } 8009 8010 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 8011 TargetLowering::DAGCombinerInfo &DCI, 8012 const AArch64Subtarget *Subtarget) { 8013 if (DCI.isBeforeLegalizeOps()) 8014 return SDValue(); 8015 8016 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 8017 return Cmp; 8018 8019 return performIntegerAbsCombine(N, DAG); 8020 } 8021 8022 SDValue 8023 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8024 SelectionDAG &DAG, 8025 std::vector<SDNode *> *Created) const { 8026 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 8027 if (isIntDivCheap(N->getValueType(0), Attr)) 8028 return SDValue(N,0); // Lower SDIV as SDIV 8029 8030 // fold (sdiv X, pow2) 8031 EVT VT = N->getValueType(0); 8032 if ((VT != MVT::i32 && VT != MVT::i64) || 8033 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 8034 return SDValue(); 8035 8036 SDLoc DL(N); 8037 SDValue N0 = N->getOperand(0); 8038 unsigned Lg2 = Divisor.countTrailingZeros(); 8039 SDValue Zero = DAG.getConstant(0, DL, VT); 8040 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 8041 8042 // Add (N0 < 0) ? Pow2 - 1 : 0; 8043 SDValue CCVal; 8044 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 8045 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 8046 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 8047 8048 if (Created) { 8049 Created->push_back(Cmp.getNode()); 8050 Created->push_back(Add.getNode()); 8051 Created->push_back(CSel.getNode()); 8052 } 8053 8054 // Divide by pow2. 8055 SDValue SRA = 8056 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 8057 8058 // If we're dividing by a positive value, we're done. Otherwise, we must 8059 // negate the result. 8060 if (Divisor.isNonNegative()) 8061 return SRA; 8062 8063 if (Created) 8064 Created->push_back(SRA.getNode()); 8065 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 8066 } 8067 8068 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 8069 TargetLowering::DAGCombinerInfo &DCI, 8070 const AArch64Subtarget *Subtarget) { 8071 if (DCI.isBeforeLegalizeOps()) 8072 return SDValue(); 8073 8074 // The below optimizations require a constant RHS. 8075 if (!isa<ConstantSDNode>(N->getOperand(1))) 8076 return SDValue(); 8077 8078 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 8079 const APInt &ConstValue = C->getAPIntValue(); 8080 8081 // Multiplication of a power of two plus/minus one can be done more 8082 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 8083 // future CPUs have a cheaper MADD instruction, this may need to be 8084 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 8085 // 64-bit is 5 cycles, so this is always a win. 8086 // More aggressively, some multiplications N0 * C can be lowered to 8087 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 8088 // e.g. 6=3*2=(2+1)*2. 8089 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 8090 // which equals to (1+2)*16-(1+2). 8091 SDValue N0 = N->getOperand(0); 8092 // TrailingZeroes is used to test if the mul can be lowered to 8093 // shift+add+shift. 8094 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 8095 if (TrailingZeroes) { 8096 // Conservatively do not lower to shift+add+shift if the mul might be 8097 // folded into smul or umul. 8098 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 8099 isZeroExtended(N0.getNode(), DAG))) 8100 return SDValue(); 8101 // Conservatively do not lower to shift+add+shift if the mul might be 8102 // folded into madd or msub. 8103 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 8104 N->use_begin()->getOpcode() == ISD::SUB)) 8105 return SDValue(); 8106 } 8107 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 8108 // and shift+add+shift. 8109 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 8110 8111 unsigned ShiftAmt, AddSubOpc; 8112 // Is the shifted value the LHS operand of the add/sub? 8113 bool ShiftValUseIsN0 = true; 8114 // Do we need to negate the result? 8115 bool NegateResult = false; 8116 8117 if (ConstValue.isNonNegative()) { 8118 // (mul x, 2^N + 1) => (add (shl x, N), x) 8119 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8120 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 8121 APInt SCVMinus1 = ShiftedConstValue - 1; 8122 APInt CVPlus1 = ConstValue + 1; 8123 if (SCVMinus1.isPowerOf2()) { 8124 ShiftAmt = SCVMinus1.logBase2(); 8125 AddSubOpc = ISD::ADD; 8126 } else if (CVPlus1.isPowerOf2()) { 8127 ShiftAmt = CVPlus1.logBase2(); 8128 AddSubOpc = ISD::SUB; 8129 } else 8130 return SDValue(); 8131 } else { 8132 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8133 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8134 APInt CVNegPlus1 = -ConstValue + 1; 8135 APInt CVNegMinus1 = -ConstValue - 1; 8136 if (CVNegPlus1.isPowerOf2()) { 8137 ShiftAmt = CVNegPlus1.logBase2(); 8138 AddSubOpc = ISD::SUB; 8139 ShiftValUseIsN0 = false; 8140 } else if (CVNegMinus1.isPowerOf2()) { 8141 ShiftAmt = CVNegMinus1.logBase2(); 8142 AddSubOpc = ISD::ADD; 8143 NegateResult = true; 8144 } else 8145 return SDValue(); 8146 } 8147 8148 SDLoc DL(N); 8149 EVT VT = N->getValueType(0); 8150 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 8151 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 8152 8153 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 8154 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 8155 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 8156 assert(!(NegateResult && TrailingZeroes) && 8157 "NegateResult and TrailingZeroes cannot both be true for now."); 8158 // Negate the result. 8159 if (NegateResult) 8160 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 8161 // Shift the result. 8162 if (TrailingZeroes) 8163 return DAG.getNode(ISD::SHL, DL, VT, Res, 8164 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 8165 return Res; 8166 } 8167 8168 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 8169 SelectionDAG &DAG) { 8170 // Take advantage of vector comparisons producing 0 or -1 in each lane to 8171 // optimize away operation when it's from a constant. 8172 // 8173 // The general transformation is: 8174 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 8175 // AND(VECTOR_CMP(x,y), constant2) 8176 // constant2 = UNARYOP(constant) 8177 8178 // Early exit if this isn't a vector operation, the operand of the 8179 // unary operation isn't a bitwise AND, or if the sizes of the operations 8180 // aren't the same. 8181 EVT VT = N->getValueType(0); 8182 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 8183 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 8184 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 8185 return SDValue(); 8186 8187 // Now check that the other operand of the AND is a constant. We could 8188 // make the transformation for non-constant splats as well, but it's unclear 8189 // that would be a benefit as it would not eliminate any operations, just 8190 // perform one more step in scalar code before moving to the vector unit. 8191 if (BuildVectorSDNode *BV = 8192 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 8193 // Bail out if the vector isn't a constant. 8194 if (!BV->isConstant()) 8195 return SDValue(); 8196 8197 // Everything checks out. Build up the new and improved node. 8198 SDLoc DL(N); 8199 EVT IntVT = BV->getValueType(0); 8200 // Create a new constant of the appropriate type for the transformed 8201 // DAG. 8202 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 8203 // The AND node needs bitcasts to/from an integer vector type around it. 8204 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 8205 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 8206 N->getOperand(0)->getOperand(0), MaskConst); 8207 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 8208 return Res; 8209 } 8210 8211 return SDValue(); 8212 } 8213 8214 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 8215 const AArch64Subtarget *Subtarget) { 8216 // First try to optimize away the conversion when it's conditionally from 8217 // a constant. Vectors only. 8218 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 8219 return Res; 8220 8221 EVT VT = N->getValueType(0); 8222 if (VT != MVT::f32 && VT != MVT::f64) 8223 return SDValue(); 8224 8225 // Only optimize when the source and destination types have the same width. 8226 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 8227 return SDValue(); 8228 8229 // If the result of an integer load is only used by an integer-to-float 8230 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 8231 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 8232 SDValue N0 = N->getOperand(0); 8233 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8234 // Do not change the width of a volatile load. 8235 !cast<LoadSDNode>(N0)->isVolatile()) { 8236 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8237 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8238 LN0->getPointerInfo(), LN0->getAlignment(), 8239 LN0->getMemOperand()->getFlags()); 8240 8241 // Make sure successors of the original load stay after it by updating them 8242 // to use the new Chain. 8243 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 8244 8245 unsigned Opcode = 8246 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 8247 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 8248 } 8249 8250 return SDValue(); 8251 } 8252 8253 /// Fold a floating-point multiply by power of two into floating-point to 8254 /// fixed-point conversion. 8255 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 8256 TargetLowering::DAGCombinerInfo &DCI, 8257 const AArch64Subtarget *Subtarget) { 8258 if (!Subtarget->hasNEON()) 8259 return SDValue(); 8260 8261 SDValue Op = N->getOperand(0); 8262 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 8263 Op.getOpcode() != ISD::FMUL) 8264 return SDValue(); 8265 8266 SDValue ConstVec = Op->getOperand(1); 8267 if (!isa<BuildVectorSDNode>(ConstVec)) 8268 return SDValue(); 8269 8270 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 8271 uint32_t FloatBits = FloatTy.getSizeInBits(); 8272 if (FloatBits != 32 && FloatBits != 64) 8273 return SDValue(); 8274 8275 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 8276 uint32_t IntBits = IntTy.getSizeInBits(); 8277 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 8278 return SDValue(); 8279 8280 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 8281 if (IntBits > FloatBits) 8282 return SDValue(); 8283 8284 BitVector UndefElements; 8285 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 8286 int32_t Bits = IntBits == 64 ? 64 : 32; 8287 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 8288 if (C == -1 || C == 0 || C > Bits) 8289 return SDValue(); 8290 8291 MVT ResTy; 8292 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8293 switch (NumLanes) { 8294 default: 8295 return SDValue(); 8296 case 2: 8297 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 8298 break; 8299 case 4: 8300 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 8301 break; 8302 } 8303 8304 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 8305 return SDValue(); 8306 8307 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 8308 "Illegal vector type after legalization"); 8309 8310 SDLoc DL(N); 8311 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8312 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 8313 : Intrinsic::aarch64_neon_vcvtfp2fxu; 8314 SDValue FixConv = 8315 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 8316 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 8317 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 8318 // We can handle smaller integers by generating an extra trunc. 8319 if (IntBits < FloatBits) 8320 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 8321 8322 return FixConv; 8323 } 8324 8325 /// Fold a floating-point divide by power of two into fixed-point to 8326 /// floating-point conversion. 8327 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 8328 TargetLowering::DAGCombinerInfo &DCI, 8329 const AArch64Subtarget *Subtarget) { 8330 if (!Subtarget->hasNEON()) 8331 return SDValue(); 8332 8333 SDValue Op = N->getOperand(0); 8334 unsigned Opc = Op->getOpcode(); 8335 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 8336 !Op.getOperand(0).getValueType().isSimple() || 8337 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 8338 return SDValue(); 8339 8340 SDValue ConstVec = N->getOperand(1); 8341 if (!isa<BuildVectorSDNode>(ConstVec)) 8342 return SDValue(); 8343 8344 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 8345 int32_t IntBits = IntTy.getSizeInBits(); 8346 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 8347 return SDValue(); 8348 8349 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 8350 int32_t FloatBits = FloatTy.getSizeInBits(); 8351 if (FloatBits != 32 && FloatBits != 64) 8352 return SDValue(); 8353 8354 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 8355 if (IntBits > FloatBits) 8356 return SDValue(); 8357 8358 BitVector UndefElements; 8359 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 8360 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 8361 if (C == -1 || C == 0 || C > FloatBits) 8362 return SDValue(); 8363 8364 MVT ResTy; 8365 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8366 switch (NumLanes) { 8367 default: 8368 return SDValue(); 8369 case 2: 8370 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 8371 break; 8372 case 4: 8373 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 8374 break; 8375 } 8376 8377 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 8378 return SDValue(); 8379 8380 SDLoc DL(N); 8381 SDValue ConvInput = Op.getOperand(0); 8382 bool IsSigned = Opc == ISD::SINT_TO_FP; 8383 if (IntBits < FloatBits) 8384 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 8385 ResTy, ConvInput); 8386 8387 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 8388 : Intrinsic::aarch64_neon_vcvtfxu2fp; 8389 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 8390 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 8391 DAG.getConstant(C, DL, MVT::i32)); 8392 } 8393 8394 /// An EXTR instruction is made up of two shifts, ORed together. This helper 8395 /// searches for and classifies those shifts. 8396 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 8397 bool &FromHi) { 8398 if (N.getOpcode() == ISD::SHL) 8399 FromHi = false; 8400 else if (N.getOpcode() == ISD::SRL) 8401 FromHi = true; 8402 else 8403 return false; 8404 8405 if (!isa<ConstantSDNode>(N.getOperand(1))) 8406 return false; 8407 8408 ShiftAmount = N->getConstantOperandVal(1); 8409 Src = N->getOperand(0); 8410 return true; 8411 } 8412 8413 /// EXTR instruction extracts a contiguous chunk of bits from two existing 8414 /// registers viewed as a high/low pair. This function looks for the pattern: 8415 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 8416 /// with an EXTR. Can't quite be done in TableGen because the two immediates 8417 /// aren't independent. 8418 static SDValue tryCombineToEXTR(SDNode *N, 8419 TargetLowering::DAGCombinerInfo &DCI) { 8420 SelectionDAG &DAG = DCI.DAG; 8421 SDLoc DL(N); 8422 EVT VT = N->getValueType(0); 8423 8424 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 8425 8426 if (VT != MVT::i32 && VT != MVT::i64) 8427 return SDValue(); 8428 8429 SDValue LHS; 8430 uint32_t ShiftLHS = 0; 8431 bool LHSFromHi = false; 8432 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 8433 return SDValue(); 8434 8435 SDValue RHS; 8436 uint32_t ShiftRHS = 0; 8437 bool RHSFromHi = false; 8438 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 8439 return SDValue(); 8440 8441 // If they're both trying to come from the high part of the register, they're 8442 // not really an EXTR. 8443 if (LHSFromHi == RHSFromHi) 8444 return SDValue(); 8445 8446 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 8447 return SDValue(); 8448 8449 if (LHSFromHi) { 8450 std::swap(LHS, RHS); 8451 std::swap(ShiftLHS, ShiftRHS); 8452 } 8453 8454 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 8455 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 8456 } 8457 8458 static SDValue tryCombineToBSL(SDNode *N, 8459 TargetLowering::DAGCombinerInfo &DCI) { 8460 EVT VT = N->getValueType(0); 8461 SelectionDAG &DAG = DCI.DAG; 8462 SDLoc DL(N); 8463 8464 if (!VT.isVector()) 8465 return SDValue(); 8466 8467 SDValue N0 = N->getOperand(0); 8468 if (N0.getOpcode() != ISD::AND) 8469 return SDValue(); 8470 8471 SDValue N1 = N->getOperand(1); 8472 if (N1.getOpcode() != ISD::AND) 8473 return SDValue(); 8474 8475 // We only have to look for constant vectors here since the general, variable 8476 // case can be handled in TableGen. 8477 unsigned Bits = VT.getScalarSizeInBits(); 8478 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 8479 for (int i = 1; i >= 0; --i) 8480 for (int j = 1; j >= 0; --j) { 8481 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 8482 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 8483 if (!BVN0 || !BVN1) 8484 continue; 8485 8486 bool FoundMatch = true; 8487 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 8488 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 8489 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 8490 if (!CN0 || !CN1 || 8491 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 8492 FoundMatch = false; 8493 break; 8494 } 8495 } 8496 8497 if (FoundMatch) 8498 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 8499 N0->getOperand(1 - i), N1->getOperand(1 - j)); 8500 } 8501 8502 return SDValue(); 8503 } 8504 8505 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8506 const AArch64Subtarget *Subtarget) { 8507 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 8508 SelectionDAG &DAG = DCI.DAG; 8509 EVT VT = N->getValueType(0); 8510 8511 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8512 return SDValue(); 8513 8514 if (SDValue Res = tryCombineToEXTR(N, DCI)) 8515 return Res; 8516 8517 if (SDValue Res = tryCombineToBSL(N, DCI)) 8518 return Res; 8519 8520 return SDValue(); 8521 } 8522 8523 static SDValue performSRLCombine(SDNode *N, 8524 TargetLowering::DAGCombinerInfo &DCI) { 8525 SelectionDAG &DAG = DCI.DAG; 8526 EVT VT = N->getValueType(0); 8527 if (VT != MVT::i32 && VT != MVT::i64) 8528 return SDValue(); 8529 8530 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 8531 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 8532 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 8533 SDValue N0 = N->getOperand(0); 8534 if (N0.getOpcode() == ISD::BSWAP) { 8535 SDLoc DL(N); 8536 SDValue N1 = N->getOperand(1); 8537 SDValue N00 = N0.getOperand(0); 8538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 8539 uint64_t ShiftAmt = C->getZExtValue(); 8540 if (VT == MVT::i32 && ShiftAmt == 16 && 8541 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 8542 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8543 if (VT == MVT::i64 && ShiftAmt == 32 && 8544 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 8545 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8546 } 8547 } 8548 return SDValue(); 8549 } 8550 8551 static SDValue performBitcastCombine(SDNode *N, 8552 TargetLowering::DAGCombinerInfo &DCI, 8553 SelectionDAG &DAG) { 8554 // Wait 'til after everything is legalized to try this. That way we have 8555 // legal vector types and such. 8556 if (DCI.isBeforeLegalizeOps()) 8557 return SDValue(); 8558 8559 // Remove extraneous bitcasts around an extract_subvector. 8560 // For example, 8561 // (v4i16 (bitconvert 8562 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 8563 // becomes 8564 // (extract_subvector ((v8i16 ...), (i64 4))) 8565 8566 // Only interested in 64-bit vectors as the ultimate result. 8567 EVT VT = N->getValueType(0); 8568 if (!VT.isVector()) 8569 return SDValue(); 8570 if (VT.getSimpleVT().getSizeInBits() != 64) 8571 return SDValue(); 8572 // Is the operand an extract_subvector starting at the beginning or halfway 8573 // point of the vector? A low half may also come through as an 8574 // EXTRACT_SUBREG, so look for that, too. 8575 SDValue Op0 = N->getOperand(0); 8576 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 8577 !(Op0->isMachineOpcode() && 8578 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 8579 return SDValue(); 8580 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 8581 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8582 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 8583 return SDValue(); 8584 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 8585 if (idx != AArch64::dsub) 8586 return SDValue(); 8587 // The dsub reference is equivalent to a lane zero subvector reference. 8588 idx = 0; 8589 } 8590 // Look through the bitcast of the input to the extract. 8591 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 8592 return SDValue(); 8593 SDValue Source = Op0->getOperand(0)->getOperand(0); 8594 // If the source type has twice the number of elements as our destination 8595 // type, we know this is an extract of the high or low half of the vector. 8596 EVT SVT = Source->getValueType(0); 8597 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 8598 return SDValue(); 8599 8600 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 8601 8602 // Create the simplified form to just extract the low or high half of the 8603 // vector directly rather than bothering with the bitcasts. 8604 SDLoc dl(N); 8605 unsigned NumElements = VT.getVectorNumElements(); 8606 if (idx) { 8607 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8608 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8609 } else { 8610 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8611 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8612 Source, SubReg), 8613 0); 8614 } 8615 } 8616 8617 static SDValue performConcatVectorsCombine(SDNode *N, 8618 TargetLowering::DAGCombinerInfo &DCI, 8619 SelectionDAG &DAG) { 8620 SDLoc dl(N); 8621 EVT VT = N->getValueType(0); 8622 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8623 8624 // Optimize concat_vectors of truncated vectors, where the intermediate 8625 // type is illegal, to avoid said illegality, e.g., 8626 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8627 // (v2i16 (truncate (v2i64))))) 8628 // -> 8629 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8630 // (v4i32 (bitcast (v2i64))), 8631 // <0, 2, 4, 6>))) 8632 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8633 // on both input and result type, so we might generate worse code. 8634 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8635 if (N->getNumOperands() == 2 && 8636 N0->getOpcode() == ISD::TRUNCATE && 8637 N1->getOpcode() == ISD::TRUNCATE) { 8638 SDValue N00 = N0->getOperand(0); 8639 SDValue N10 = N1->getOperand(0); 8640 EVT N00VT = N00.getValueType(); 8641 8642 if (N00VT == N10.getValueType() && 8643 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8644 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8645 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8646 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8647 for (size_t i = 0; i < Mask.size(); ++i) 8648 Mask[i] = i * 2; 8649 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8650 DAG.getVectorShuffle( 8651 MidVT, dl, 8652 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8653 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8654 } 8655 } 8656 8657 // Wait 'til after everything is legalized to try this. That way we have 8658 // legal vector types and such. 8659 if (DCI.isBeforeLegalizeOps()) 8660 return SDValue(); 8661 8662 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8663 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8664 // canonicalise to that. 8665 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8666 assert(VT.getScalarSizeInBits() == 64); 8667 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8668 DAG.getConstant(0, dl, MVT::i64)); 8669 } 8670 8671 // Canonicalise concat_vectors so that the right-hand vector has as few 8672 // bit-casts as possible before its real operation. The primary matching 8673 // destination for these operations will be the narrowing "2" instructions, 8674 // which depend on the operation being performed on this right-hand vector. 8675 // For example, 8676 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8677 // becomes 8678 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8679 8680 if (N1->getOpcode() != ISD::BITCAST) 8681 return SDValue(); 8682 SDValue RHS = N1->getOperand(0); 8683 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8684 // If the RHS is not a vector, this is not the pattern we're looking for. 8685 if (!RHSTy.isVector()) 8686 return SDValue(); 8687 8688 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8689 8690 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8691 RHSTy.getVectorNumElements() * 2); 8692 return DAG.getNode(ISD::BITCAST, dl, VT, 8693 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8694 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8695 RHS)); 8696 } 8697 8698 static SDValue tryCombineFixedPointConvert(SDNode *N, 8699 TargetLowering::DAGCombinerInfo &DCI, 8700 SelectionDAG &DAG) { 8701 // Wait 'til after everything is legalized to try this. That way we have 8702 // legal vector types and such. 8703 if (DCI.isBeforeLegalizeOps()) 8704 return SDValue(); 8705 // Transform a scalar conversion of a value from a lane extract into a 8706 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8707 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8708 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8709 // 8710 // The second form interacts better with instruction selection and the 8711 // register allocator to avoid cross-class register copies that aren't 8712 // coalescable due to a lane reference. 8713 8714 // Check the operand and see if it originates from a lane extract. 8715 SDValue Op1 = N->getOperand(1); 8716 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8717 // Yep, no additional predication needed. Perform the transform. 8718 SDValue IID = N->getOperand(0); 8719 SDValue Shift = N->getOperand(2); 8720 SDValue Vec = Op1.getOperand(0); 8721 SDValue Lane = Op1.getOperand(1); 8722 EVT ResTy = N->getValueType(0); 8723 EVT VecResTy; 8724 SDLoc DL(N); 8725 8726 // The vector width should be 128 bits by the time we get here, even 8727 // if it started as 64 bits (the extract_vector handling will have 8728 // done so). 8729 assert(Vec.getValueSizeInBits() == 128 && 8730 "unexpected vector size on extract_vector_elt!"); 8731 if (Vec.getValueType() == MVT::v4i32) 8732 VecResTy = MVT::v4f32; 8733 else if (Vec.getValueType() == MVT::v2i64) 8734 VecResTy = MVT::v2f64; 8735 else 8736 llvm_unreachable("unexpected vector type!"); 8737 8738 SDValue Convert = 8739 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8740 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8741 } 8742 return SDValue(); 8743 } 8744 8745 // AArch64 high-vector "long" operations are formed by performing the non-high 8746 // version on an extract_subvector of each operand which gets the high half: 8747 // 8748 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8749 // 8750 // However, there are cases which don't have an extract_high explicitly, but 8751 // have another operation that can be made compatible with one for free. For 8752 // example: 8753 // 8754 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8755 // 8756 // This routine does the actual conversion of such DUPs, once outer routines 8757 // have determined that everything else is in order. 8758 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8759 // similarly here. 8760 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8761 switch (N.getOpcode()) { 8762 case AArch64ISD::DUP: 8763 case AArch64ISD::DUPLANE8: 8764 case AArch64ISD::DUPLANE16: 8765 case AArch64ISD::DUPLANE32: 8766 case AArch64ISD::DUPLANE64: 8767 case AArch64ISD::MOVI: 8768 case AArch64ISD::MOVIshift: 8769 case AArch64ISD::MOVIedit: 8770 case AArch64ISD::MOVImsl: 8771 case AArch64ISD::MVNIshift: 8772 case AArch64ISD::MVNImsl: 8773 break; 8774 default: 8775 // FMOV could be supported, but isn't very useful, as it would only occur 8776 // if you passed a bitcast' floating point immediate to an eligible long 8777 // integer op (addl, smull, ...). 8778 return SDValue(); 8779 } 8780 8781 MVT NarrowTy = N.getSimpleValueType(); 8782 if (!NarrowTy.is64BitVector()) 8783 return SDValue(); 8784 8785 MVT ElementTy = NarrowTy.getVectorElementType(); 8786 unsigned NumElems = NarrowTy.getVectorNumElements(); 8787 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8788 8789 SDLoc dl(N); 8790 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8791 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8792 DAG.getConstant(NumElems, dl, MVT::i64)); 8793 } 8794 8795 static bool isEssentiallyExtractSubvector(SDValue N) { 8796 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8797 return true; 8798 8799 return N.getOpcode() == ISD::BITCAST && 8800 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8801 } 8802 8803 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8804 struct GenericSetCCInfo { 8805 const SDValue *Opnd0; 8806 const SDValue *Opnd1; 8807 ISD::CondCode CC; 8808 }; 8809 8810 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8811 struct AArch64SetCCInfo { 8812 const SDValue *Cmp; 8813 AArch64CC::CondCode CC; 8814 }; 8815 8816 /// \brief Helper structure to keep track of SetCC information. 8817 union SetCCInfo { 8818 GenericSetCCInfo Generic; 8819 AArch64SetCCInfo AArch64; 8820 }; 8821 8822 /// \brief Helper structure to be able to read SetCC information. If set to 8823 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8824 /// GenericSetCCInfo. 8825 struct SetCCInfoAndKind { 8826 SetCCInfo Info; 8827 bool IsAArch64; 8828 }; 8829 8830 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8831 /// an 8832 /// AArch64 lowered one. 8833 /// \p SetCCInfo is filled accordingly. 8834 /// \post SetCCInfo is meanginfull only when this function returns true. 8835 /// \return True when Op is a kind of SET_CC operation. 8836 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8837 // If this is a setcc, this is straight forward. 8838 if (Op.getOpcode() == ISD::SETCC) { 8839 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8840 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8841 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8842 SetCCInfo.IsAArch64 = false; 8843 return true; 8844 } 8845 // Otherwise, check if this is a matching csel instruction. 8846 // In other words: 8847 // - csel 1, 0, cc 8848 // - csel 0, 1, !cc 8849 if (Op.getOpcode() != AArch64ISD::CSEL) 8850 return false; 8851 // Set the information about the operands. 8852 // TODO: we want the operands of the Cmp not the csel 8853 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8854 SetCCInfo.IsAArch64 = true; 8855 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8856 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8857 8858 // Check that the operands matches the constraints: 8859 // (1) Both operands must be constants. 8860 // (2) One must be 1 and the other must be 0. 8861 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 8862 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8863 8864 // Check (1). 8865 if (!TValue || !FValue) 8866 return false; 8867 8868 // Check (2). 8869 if (!TValue->isOne()) { 8870 // Update the comparison when we are interested in !cc. 8871 std::swap(TValue, FValue); 8872 SetCCInfo.Info.AArch64.CC = 8873 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 8874 } 8875 return TValue->isOne() && FValue->isNullValue(); 8876 } 8877 8878 // Returns true if Op is setcc or zext of setcc. 8879 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 8880 if (isSetCC(Op, Info)) 8881 return true; 8882 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 8883 isSetCC(Op->getOperand(0), Info)); 8884 } 8885 8886 // The folding we want to perform is: 8887 // (add x, [zext] (setcc cc ...) ) 8888 // --> 8889 // (csel x, (add x, 1), !cc ...) 8890 // 8891 // The latter will get matched to a CSINC instruction. 8892 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 8893 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 8894 SDValue LHS = Op->getOperand(0); 8895 SDValue RHS = Op->getOperand(1); 8896 SetCCInfoAndKind InfoAndKind; 8897 8898 // If neither operand is a SET_CC, give up. 8899 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 8900 std::swap(LHS, RHS); 8901 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 8902 return SDValue(); 8903 } 8904 8905 // FIXME: This could be generatized to work for FP comparisons. 8906 EVT CmpVT = InfoAndKind.IsAArch64 8907 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 8908 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 8909 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 8910 return SDValue(); 8911 8912 SDValue CCVal; 8913 SDValue Cmp; 8914 SDLoc dl(Op); 8915 if (InfoAndKind.IsAArch64) { 8916 CCVal = DAG.getConstant( 8917 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 8918 MVT::i32); 8919 Cmp = *InfoAndKind.Info.AArch64.Cmp; 8920 } else 8921 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 8922 *InfoAndKind.Info.Generic.Opnd1, 8923 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 8924 CCVal, DAG, dl); 8925 8926 EVT VT = Op->getValueType(0); 8927 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 8928 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 8929 } 8930 8931 // The basic add/sub long vector instructions have variants with "2" on the end 8932 // which act on the high-half of their inputs. They are normally matched by 8933 // patterns like: 8934 // 8935 // (add (zeroext (extract_high LHS)), 8936 // (zeroext (extract_high RHS))) 8937 // -> uaddl2 vD, vN, vM 8938 // 8939 // However, if one of the extracts is something like a duplicate, this 8940 // instruction can still be used profitably. This function puts the DAG into a 8941 // more appropriate form for those patterns to trigger. 8942 static SDValue performAddSubLongCombine(SDNode *N, 8943 TargetLowering::DAGCombinerInfo &DCI, 8944 SelectionDAG &DAG) { 8945 if (DCI.isBeforeLegalizeOps()) 8946 return SDValue(); 8947 8948 MVT VT = N->getSimpleValueType(0); 8949 if (!VT.is128BitVector()) { 8950 if (N->getOpcode() == ISD::ADD) 8951 return performSetccAddFolding(N, DAG); 8952 return SDValue(); 8953 } 8954 8955 // Make sure both branches are extended in the same way. 8956 SDValue LHS = N->getOperand(0); 8957 SDValue RHS = N->getOperand(1); 8958 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 8959 LHS.getOpcode() != ISD::SIGN_EXTEND) || 8960 LHS.getOpcode() != RHS.getOpcode()) 8961 return SDValue(); 8962 8963 unsigned ExtType = LHS.getOpcode(); 8964 8965 // It's not worth doing if at least one of the inputs isn't already an 8966 // extract, but we don't know which it'll be so we have to try both. 8967 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 8968 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 8969 if (!RHS.getNode()) 8970 return SDValue(); 8971 8972 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 8973 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 8974 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 8975 if (!LHS.getNode()) 8976 return SDValue(); 8977 8978 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 8979 } 8980 8981 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 8982 } 8983 8984 // Massage DAGs which we can use the high-half "long" operations on into 8985 // something isel will recognize better. E.g. 8986 // 8987 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 8988 // (aarch64_neon_umull (extract_high (v2i64 vec))) 8989 // (extract_high (v2i64 (dup128 scalar))))) 8990 // 8991 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 8992 TargetLowering::DAGCombinerInfo &DCI, 8993 SelectionDAG &DAG) { 8994 if (DCI.isBeforeLegalizeOps()) 8995 return SDValue(); 8996 8997 SDValue LHS = N->getOperand(1); 8998 SDValue RHS = N->getOperand(2); 8999 assert(LHS.getValueType().is64BitVector() && 9000 RHS.getValueType().is64BitVector() && 9001 "unexpected shape for long operation"); 9002 9003 // Either node could be a DUP, but it's not worth doing both of them (you'd 9004 // just as well use the non-high version) so look for a corresponding extract 9005 // operation on the other "wing". 9006 if (isEssentiallyExtractSubvector(LHS)) { 9007 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 9008 if (!RHS.getNode()) 9009 return SDValue(); 9010 } else if (isEssentiallyExtractSubvector(RHS)) { 9011 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 9012 if (!LHS.getNode()) 9013 return SDValue(); 9014 } 9015 9016 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 9017 N->getOperand(0), LHS, RHS); 9018 } 9019 9020 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 9021 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 9022 unsigned ElemBits = ElemTy.getSizeInBits(); 9023 9024 int64_t ShiftAmount; 9025 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 9026 APInt SplatValue, SplatUndef; 9027 unsigned SplatBitSize; 9028 bool HasAnyUndefs; 9029 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 9030 HasAnyUndefs, ElemBits) || 9031 SplatBitSize != ElemBits) 9032 return SDValue(); 9033 9034 ShiftAmount = SplatValue.getSExtValue(); 9035 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 9036 ShiftAmount = CVN->getSExtValue(); 9037 } else 9038 return SDValue(); 9039 9040 unsigned Opcode; 9041 bool IsRightShift; 9042 switch (IID) { 9043 default: 9044 llvm_unreachable("Unknown shift intrinsic"); 9045 case Intrinsic::aarch64_neon_sqshl: 9046 Opcode = AArch64ISD::SQSHL_I; 9047 IsRightShift = false; 9048 break; 9049 case Intrinsic::aarch64_neon_uqshl: 9050 Opcode = AArch64ISD::UQSHL_I; 9051 IsRightShift = false; 9052 break; 9053 case Intrinsic::aarch64_neon_srshl: 9054 Opcode = AArch64ISD::SRSHR_I; 9055 IsRightShift = true; 9056 break; 9057 case Intrinsic::aarch64_neon_urshl: 9058 Opcode = AArch64ISD::URSHR_I; 9059 IsRightShift = true; 9060 break; 9061 case Intrinsic::aarch64_neon_sqshlu: 9062 Opcode = AArch64ISD::SQSHLU_I; 9063 IsRightShift = false; 9064 break; 9065 } 9066 9067 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 9068 SDLoc dl(N); 9069 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 9070 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 9071 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 9072 SDLoc dl(N); 9073 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 9074 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 9075 } 9076 9077 return SDValue(); 9078 } 9079 9080 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 9081 // the intrinsics must be legal and take an i32, this means there's almost 9082 // certainly going to be a zext in the DAG which we can eliminate. 9083 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 9084 SDValue AndN = N->getOperand(2); 9085 if (AndN.getOpcode() != ISD::AND) 9086 return SDValue(); 9087 9088 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 9089 if (!CMask || CMask->getZExtValue() != Mask) 9090 return SDValue(); 9091 9092 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 9093 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 9094 } 9095 9096 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 9097 SelectionDAG &DAG) { 9098 SDLoc dl(N); 9099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 9100 DAG.getNode(Opc, dl, 9101 N->getOperand(1).getSimpleValueType(), 9102 N->getOperand(1)), 9103 DAG.getConstant(0, dl, MVT::i64)); 9104 } 9105 9106 static SDValue performIntrinsicCombine(SDNode *N, 9107 TargetLowering::DAGCombinerInfo &DCI, 9108 const AArch64Subtarget *Subtarget) { 9109 SelectionDAG &DAG = DCI.DAG; 9110 unsigned IID = getIntrinsicID(N); 9111 switch (IID) { 9112 default: 9113 break; 9114 case Intrinsic::aarch64_neon_vcvtfxs2fp: 9115 case Intrinsic::aarch64_neon_vcvtfxu2fp: 9116 return tryCombineFixedPointConvert(N, DCI, DAG); 9117 case Intrinsic::aarch64_neon_saddv: 9118 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 9119 case Intrinsic::aarch64_neon_uaddv: 9120 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 9121 case Intrinsic::aarch64_neon_sminv: 9122 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 9123 case Intrinsic::aarch64_neon_uminv: 9124 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 9125 case Intrinsic::aarch64_neon_smaxv: 9126 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 9127 case Intrinsic::aarch64_neon_umaxv: 9128 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 9129 case Intrinsic::aarch64_neon_fmax: 9130 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 9131 N->getOperand(1), N->getOperand(2)); 9132 case Intrinsic::aarch64_neon_fmin: 9133 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 9134 N->getOperand(1), N->getOperand(2)); 9135 case Intrinsic::aarch64_neon_fmaxnm: 9136 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 9137 N->getOperand(1), N->getOperand(2)); 9138 case Intrinsic::aarch64_neon_fminnm: 9139 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 9140 N->getOperand(1), N->getOperand(2)); 9141 case Intrinsic::aarch64_neon_smull: 9142 case Intrinsic::aarch64_neon_umull: 9143 case Intrinsic::aarch64_neon_pmull: 9144 case Intrinsic::aarch64_neon_sqdmull: 9145 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 9146 case Intrinsic::aarch64_neon_sqshl: 9147 case Intrinsic::aarch64_neon_uqshl: 9148 case Intrinsic::aarch64_neon_sqshlu: 9149 case Intrinsic::aarch64_neon_srshl: 9150 case Intrinsic::aarch64_neon_urshl: 9151 return tryCombineShiftImm(IID, N, DAG); 9152 case Intrinsic::aarch64_crc32b: 9153 case Intrinsic::aarch64_crc32cb: 9154 return tryCombineCRC32(0xff, N, DAG); 9155 case Intrinsic::aarch64_crc32h: 9156 case Intrinsic::aarch64_crc32ch: 9157 return tryCombineCRC32(0xffff, N, DAG); 9158 } 9159 return SDValue(); 9160 } 9161 9162 static SDValue performExtendCombine(SDNode *N, 9163 TargetLowering::DAGCombinerInfo &DCI, 9164 SelectionDAG &DAG) { 9165 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 9166 // we can convert that DUP into another extract_high (of a bigger DUP), which 9167 // helps the backend to decide that an sabdl2 would be useful, saving a real 9168 // extract_high operation. 9169 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 9170 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 9171 SDNode *ABDNode = N->getOperand(0).getNode(); 9172 unsigned IID = getIntrinsicID(ABDNode); 9173 if (IID == Intrinsic::aarch64_neon_sabd || 9174 IID == Intrinsic::aarch64_neon_uabd) { 9175 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 9176 if (!NewABD.getNode()) 9177 return SDValue(); 9178 9179 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 9180 NewABD); 9181 } 9182 } 9183 9184 // This is effectively a custom type legalization for AArch64. 9185 // 9186 // Type legalization will split an extend of a small, legal, type to a larger 9187 // illegal type by first splitting the destination type, often creating 9188 // illegal source types, which then get legalized in isel-confusing ways, 9189 // leading to really terrible codegen. E.g., 9190 // %result = v8i32 sext v8i8 %value 9191 // becomes 9192 // %losrc = extract_subreg %value, ... 9193 // %hisrc = extract_subreg %value, ... 9194 // %lo = v4i32 sext v4i8 %losrc 9195 // %hi = v4i32 sext v4i8 %hisrc 9196 // Things go rapidly downhill from there. 9197 // 9198 // For AArch64, the [sz]ext vector instructions can only go up one element 9199 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 9200 // take two instructions. 9201 // 9202 // This implies that the most efficient way to do the extend from v8i8 9203 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 9204 // the normal splitting to happen for the v8i16->v8i32. 9205 9206 // This is pre-legalization to catch some cases where the default 9207 // type legalization will create ill-tempered code. 9208 if (!DCI.isBeforeLegalizeOps()) 9209 return SDValue(); 9210 9211 // We're only interested in cleaning things up for non-legal vector types 9212 // here. If both the source and destination are legal, things will just 9213 // work naturally without any fiddling. 9214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9215 EVT ResVT = N->getValueType(0); 9216 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 9217 return SDValue(); 9218 // If the vector type isn't a simple VT, it's beyond the scope of what 9219 // we're worried about here. Let legalization do its thing and hope for 9220 // the best. 9221 SDValue Src = N->getOperand(0); 9222 EVT SrcVT = Src->getValueType(0); 9223 if (!ResVT.isSimple() || !SrcVT.isSimple()) 9224 return SDValue(); 9225 9226 // If the source VT is a 64-bit vector, we can play games and get the 9227 // better results we want. 9228 if (SrcVT.getSizeInBits() != 64) 9229 return SDValue(); 9230 9231 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 9232 unsigned ElementCount = SrcVT.getVectorNumElements(); 9233 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 9234 SDLoc DL(N); 9235 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 9236 9237 // Now split the rest of the operation into two halves, each with a 64 9238 // bit source. 9239 EVT LoVT, HiVT; 9240 SDValue Lo, Hi; 9241 unsigned NumElements = ResVT.getVectorNumElements(); 9242 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 9243 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 9244 ResVT.getVectorElementType(), NumElements / 2); 9245 9246 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 9247 LoVT.getVectorNumElements()); 9248 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 9249 DAG.getConstant(0, DL, MVT::i64)); 9250 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 9251 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 9252 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 9253 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 9254 9255 // Now combine the parts back together so we still have a single result 9256 // like the combiner expects. 9257 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 9258 } 9259 9260 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 9261 SDValue SplatVal, unsigned NumVecElts) { 9262 unsigned OrigAlignment = St.getAlignment(); 9263 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 9264 9265 // Create scalar stores. This is at least as good as the code sequence for a 9266 // split unaligned store which is a dup.s, ext.b, and two stores. 9267 // Most of the time the three stores should be replaced by store pair 9268 // instructions (stp). 9269 SDLoc DL(&St); 9270 SDValue BasePtr = St.getBasePtr(); 9271 uint64_t BaseOffset = 0; 9272 9273 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 9274 SDValue NewST1 = 9275 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 9276 OrigAlignment, St.getMemOperand()->getFlags()); 9277 9278 // As this in ISel, we will not merge this add which may degrade results. 9279 if (BasePtr->getOpcode() == ISD::ADD && 9280 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 9281 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 9282 BasePtr = BasePtr->getOperand(0); 9283 } 9284 9285 unsigned Offset = EltOffset; 9286 while (--NumVecElts) { 9287 unsigned Alignment = MinAlign(OrigAlignment, Offset); 9288 SDValue OffsetPtr = 9289 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9290 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 9291 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 9292 PtrInfo.getWithOffset(Offset), Alignment, 9293 St.getMemOperand()->getFlags()); 9294 Offset += EltOffset; 9295 } 9296 return NewST1; 9297 } 9298 9299 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 9300 /// load store optimizer pass will merge them to store pair stores. This should 9301 /// be better than a movi to create the vector zero followed by a vector store 9302 /// if the zero constant is not re-used, since one instructions and one register 9303 /// live range will be removed. 9304 /// 9305 /// For example, the final generated code should be: 9306 /// 9307 /// stp xzr, xzr, [x0] 9308 /// 9309 /// instead of: 9310 /// 9311 /// movi v0.2d, #0 9312 /// str q0, [x0] 9313 /// 9314 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 9315 SDValue StVal = St.getValue(); 9316 EVT VT = StVal.getValueType(); 9317 9318 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 9319 // 2, 3 or 4 i32 elements. 9320 int NumVecElts = VT.getVectorNumElements(); 9321 if (!(((NumVecElts == 2 || NumVecElts == 3) && 9322 VT.getVectorElementType().getSizeInBits() == 64) || 9323 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 9324 VT.getVectorElementType().getSizeInBits() == 32))) 9325 return SDValue(); 9326 9327 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 9328 return SDValue(); 9329 9330 // If the zero constant has more than one use then the vector store could be 9331 // better since the constant mov will be amortized and stp q instructions 9332 // should be able to be formed. 9333 if (!StVal.hasOneUse()) 9334 return SDValue(); 9335 9336 // If the immediate offset of the address operand is too large for the stp 9337 // instruction, then bail out. 9338 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 9339 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 9340 if (Offset < -512 || Offset > 504) 9341 return SDValue(); 9342 } 9343 9344 for (int I = 0; I < NumVecElts; ++I) { 9345 SDValue EltVal = StVal.getOperand(I); 9346 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 9347 return SDValue(); 9348 } 9349 9350 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from 9351 // undoing this transformation. 9352 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32 9353 ? DAG.getRegister(AArch64::WZR, MVT::i32) 9354 : DAG.getRegister(AArch64::XZR, MVT::i64); 9355 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 9356 } 9357 9358 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 9359 /// value. The load store optimizer pass will merge them to store pair stores. 9360 /// This has better performance than a splat of the scalar followed by a split 9361 /// vector store. Even if the stores are not merged it is four stores vs a dup, 9362 /// followed by an ext.b and two stores. 9363 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 9364 SDValue StVal = St.getValue(); 9365 EVT VT = StVal.getValueType(); 9366 9367 // Don't replace floating point stores, they possibly won't be transformed to 9368 // stp because of the store pair suppress pass. 9369 if (VT.isFloatingPoint()) 9370 return SDValue(); 9371 9372 // We can express a splat as store pair(s) for 2 or 4 elements. 9373 unsigned NumVecElts = VT.getVectorNumElements(); 9374 if (NumVecElts != 4 && NumVecElts != 2) 9375 return SDValue(); 9376 9377 // Check that this is a splat. 9378 // Make sure that each of the relevant vector element locations are inserted 9379 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 9380 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 9381 SDValue SplatVal; 9382 for (unsigned I = 0; I < NumVecElts; ++I) { 9383 // Check for insert vector elements. 9384 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 9385 return SDValue(); 9386 9387 // Check that same value is inserted at each vector element. 9388 if (I == 0) 9389 SplatVal = StVal.getOperand(1); 9390 else if (StVal.getOperand(1) != SplatVal) 9391 return SDValue(); 9392 9393 // Check insert element index. 9394 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 9395 if (!CIndex) 9396 return SDValue(); 9397 uint64_t IndexVal = CIndex->getZExtValue(); 9398 if (IndexVal >= NumVecElts) 9399 return SDValue(); 9400 IndexNotInserted.reset(IndexVal); 9401 9402 StVal = StVal.getOperand(0); 9403 } 9404 // Check that all vector element locations were inserted to. 9405 if (IndexNotInserted.any()) 9406 return SDValue(); 9407 9408 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 9409 } 9410 9411 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 9412 SelectionDAG &DAG, 9413 const AArch64Subtarget *Subtarget) { 9414 if (!DCI.isBeforeLegalize()) 9415 return SDValue(); 9416 9417 StoreSDNode *S = cast<StoreSDNode>(N); 9418 if (S->isVolatile() || S->isIndexed()) 9419 return SDValue(); 9420 9421 SDValue StVal = S->getValue(); 9422 EVT VT = StVal.getValueType(); 9423 if (!VT.isVector()) 9424 return SDValue(); 9425 9426 // If we get a splat of zeros, convert this vector store to a store of 9427 // scalars. They will be merged into store pairs of xzr thereby removing one 9428 // instruction and one register. 9429 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 9430 return ReplacedZeroSplat; 9431 9432 // FIXME: The logic for deciding if an unaligned store should be split should 9433 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 9434 // a call to that function here. 9435 9436 if (!Subtarget->isMisaligned128StoreSlow()) 9437 return SDValue(); 9438 9439 // Don't split at -Oz. 9440 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 9441 return SDValue(); 9442 9443 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 9444 // those up regresses performance on micro-benchmarks and olden/bh. 9445 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 9446 return SDValue(); 9447 9448 // Split unaligned 16B stores. They are terrible for performance. 9449 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 9450 // extensions can use this to mark that it does not want splitting to happen 9451 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 9452 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 9453 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 9454 S->getAlignment() <= 2) 9455 return SDValue(); 9456 9457 // If we get a splat of a scalar convert this vector store to a store of 9458 // scalars. They will be merged into store pairs thereby removing two 9459 // instructions. 9460 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 9461 return ReplacedSplat; 9462 9463 SDLoc DL(S); 9464 unsigned NumElts = VT.getVectorNumElements() / 2; 9465 // Split VT into two. 9466 EVT HalfVT = 9467 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 9468 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9469 DAG.getConstant(0, DL, MVT::i64)); 9470 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9471 DAG.getConstant(NumElts, DL, MVT::i64)); 9472 SDValue BasePtr = S->getBasePtr(); 9473 SDValue NewST1 = 9474 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 9475 S->getAlignment(), S->getMemOperand()->getFlags()); 9476 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9477 DAG.getConstant(8, DL, MVT::i64)); 9478 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 9479 S->getPointerInfo(), S->getAlignment(), 9480 S->getMemOperand()->getFlags()); 9481 } 9482 9483 /// Target-specific DAG combine function for post-increment LD1 (lane) and 9484 /// post-increment LD1R. 9485 static SDValue performPostLD1Combine(SDNode *N, 9486 TargetLowering::DAGCombinerInfo &DCI, 9487 bool IsLaneOp) { 9488 if (DCI.isBeforeLegalizeOps()) 9489 return SDValue(); 9490 9491 SelectionDAG &DAG = DCI.DAG; 9492 EVT VT = N->getValueType(0); 9493 9494 unsigned LoadIdx = IsLaneOp ? 1 : 0; 9495 SDNode *LD = N->getOperand(LoadIdx).getNode(); 9496 // If it is not LOAD, can not do such combine. 9497 if (LD->getOpcode() != ISD::LOAD) 9498 return SDValue(); 9499 9500 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 9501 EVT MemVT = LoadSDN->getMemoryVT(); 9502 // Check if memory operand is the same type as the vector element. 9503 if (MemVT != VT.getVectorElementType()) 9504 return SDValue(); 9505 9506 // Check if there are other uses. If so, do not combine as it will introduce 9507 // an extra load. 9508 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 9509 ++UI) { 9510 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 9511 continue; 9512 if (*UI != N) 9513 return SDValue(); 9514 } 9515 9516 SDValue Addr = LD->getOperand(1); 9517 SDValue Vector = N->getOperand(0); 9518 // Search for a use of the address operand that is an increment. 9519 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 9520 Addr.getNode()->use_end(); UI != UE; ++UI) { 9521 SDNode *User = *UI; 9522 if (User->getOpcode() != ISD::ADD 9523 || UI.getUse().getResNo() != Addr.getResNo()) 9524 continue; 9525 9526 // Check that the add is independent of the load. Otherwise, folding it 9527 // would create a cycle. 9528 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 9529 continue; 9530 // Also check that add is not used in the vector operand. This would also 9531 // create a cycle. 9532 if (User->isPredecessorOf(Vector.getNode())) 9533 continue; 9534 9535 // If the increment is a constant, it must match the memory ref size. 9536 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9537 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9538 uint32_t IncVal = CInc->getZExtValue(); 9539 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 9540 if (IncVal != NumBytes) 9541 continue; 9542 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9543 } 9544 9545 // Finally, check that the vector doesn't depend on the load. 9546 // Again, this would create a cycle. 9547 // The load depending on the vector is fine, as that's the case for the 9548 // LD1*post we'll eventually generate anyway. 9549 if (LoadSDN->isPredecessorOf(Vector.getNode())) 9550 continue; 9551 9552 SmallVector<SDValue, 8> Ops; 9553 Ops.push_back(LD->getOperand(0)); // Chain 9554 if (IsLaneOp) { 9555 Ops.push_back(Vector); // The vector to be inserted 9556 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 9557 } 9558 Ops.push_back(Addr); 9559 Ops.push_back(Inc); 9560 9561 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 9562 SDVTList SDTys = DAG.getVTList(Tys); 9563 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 9564 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 9565 MemVT, 9566 LoadSDN->getMemOperand()); 9567 9568 // Update the uses. 9569 SDValue NewResults[] = { 9570 SDValue(LD, 0), // The result of load 9571 SDValue(UpdN.getNode(), 2) // Chain 9572 }; 9573 DCI.CombineTo(LD, NewResults); 9574 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 9575 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 9576 9577 break; 9578 } 9579 return SDValue(); 9580 } 9581 9582 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 9583 /// address translation. 9584 static bool performTBISimplification(SDValue Addr, 9585 TargetLowering::DAGCombinerInfo &DCI, 9586 SelectionDAG &DAG) { 9587 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 9588 KnownBits Known; 9589 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9590 !DCI.isBeforeLegalizeOps()); 9591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9592 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 9593 DCI.CommitTargetLoweringOpt(TLO); 9594 return true; 9595 } 9596 return false; 9597 } 9598 9599 static SDValue performSTORECombine(SDNode *N, 9600 TargetLowering::DAGCombinerInfo &DCI, 9601 SelectionDAG &DAG, 9602 const AArch64Subtarget *Subtarget) { 9603 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 9604 return Split; 9605 9606 if (Subtarget->supportsAddressTopByteIgnored() && 9607 performTBISimplification(N->getOperand(2), DCI, DAG)) 9608 return SDValue(N, 0); 9609 9610 return SDValue(); 9611 } 9612 9613 9614 /// Target-specific DAG combine function for NEON load/store intrinsics 9615 /// to merge base address updates. 9616 static SDValue performNEONPostLDSTCombine(SDNode *N, 9617 TargetLowering::DAGCombinerInfo &DCI, 9618 SelectionDAG &DAG) { 9619 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9620 return SDValue(); 9621 9622 unsigned AddrOpIdx = N->getNumOperands() - 1; 9623 SDValue Addr = N->getOperand(AddrOpIdx); 9624 9625 // Search for a use of the address operand that is an increment. 9626 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9627 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9628 SDNode *User = *UI; 9629 if (User->getOpcode() != ISD::ADD || 9630 UI.getUse().getResNo() != Addr.getResNo()) 9631 continue; 9632 9633 // Check that the add is independent of the load/store. Otherwise, folding 9634 // it would create a cycle. 9635 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9636 continue; 9637 9638 // Find the new opcode for the updating load/store. 9639 bool IsStore = false; 9640 bool IsLaneOp = false; 9641 bool IsDupOp = false; 9642 unsigned NewOpc = 0; 9643 unsigned NumVecs = 0; 9644 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9645 switch (IntNo) { 9646 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9647 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9648 NumVecs = 2; break; 9649 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9650 NumVecs = 3; break; 9651 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9652 NumVecs = 4; break; 9653 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9654 NumVecs = 2; IsStore = true; break; 9655 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9656 NumVecs = 3; IsStore = true; break; 9657 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9658 NumVecs = 4; IsStore = true; break; 9659 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9660 NumVecs = 2; break; 9661 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9662 NumVecs = 3; break; 9663 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9664 NumVecs = 4; break; 9665 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9666 NumVecs = 2; IsStore = true; break; 9667 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9668 NumVecs = 3; IsStore = true; break; 9669 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9670 NumVecs = 4; IsStore = true; break; 9671 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9672 NumVecs = 2; IsDupOp = true; break; 9673 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9674 NumVecs = 3; IsDupOp = true; break; 9675 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9676 NumVecs = 4; IsDupOp = true; break; 9677 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9678 NumVecs = 2; IsLaneOp = true; break; 9679 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9680 NumVecs = 3; IsLaneOp = true; break; 9681 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9682 NumVecs = 4; IsLaneOp = true; break; 9683 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9684 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9685 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9686 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9687 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9688 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9689 } 9690 9691 EVT VecTy; 9692 if (IsStore) 9693 VecTy = N->getOperand(2).getValueType(); 9694 else 9695 VecTy = N->getValueType(0); 9696 9697 // If the increment is a constant, it must match the memory ref size. 9698 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9699 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9700 uint32_t IncVal = CInc->getZExtValue(); 9701 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9702 if (IsLaneOp || IsDupOp) 9703 NumBytes /= VecTy.getVectorNumElements(); 9704 if (IncVal != NumBytes) 9705 continue; 9706 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9707 } 9708 SmallVector<SDValue, 8> Ops; 9709 Ops.push_back(N->getOperand(0)); // Incoming chain 9710 // Load lane and store have vector list as input. 9711 if (IsLaneOp || IsStore) 9712 for (unsigned i = 2; i < AddrOpIdx; ++i) 9713 Ops.push_back(N->getOperand(i)); 9714 Ops.push_back(Addr); // Base register 9715 Ops.push_back(Inc); 9716 9717 // Return Types. 9718 EVT Tys[6]; 9719 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9720 unsigned n; 9721 for (n = 0; n < NumResultVecs; ++n) 9722 Tys[n] = VecTy; 9723 Tys[n++] = MVT::i64; // Type of write back register 9724 Tys[n] = MVT::Other; // Type of the chain 9725 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9726 9727 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9728 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9729 MemInt->getMemoryVT(), 9730 MemInt->getMemOperand()); 9731 9732 // Update the uses. 9733 std::vector<SDValue> NewResults; 9734 for (unsigned i = 0; i < NumResultVecs; ++i) { 9735 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9736 } 9737 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9738 DCI.CombineTo(N, NewResults); 9739 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9740 9741 break; 9742 } 9743 return SDValue(); 9744 } 9745 9746 // Checks to see if the value is the prescribed width and returns information 9747 // about its extension mode. 9748 static 9749 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9750 ExtType = ISD::NON_EXTLOAD; 9751 switch(V.getNode()->getOpcode()) { 9752 default: 9753 return false; 9754 case ISD::LOAD: { 9755 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9756 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9757 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9758 ExtType = LoadNode->getExtensionType(); 9759 return true; 9760 } 9761 return false; 9762 } 9763 case ISD::AssertSext: { 9764 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9765 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9766 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9767 ExtType = ISD::SEXTLOAD; 9768 return true; 9769 } 9770 return false; 9771 } 9772 case ISD::AssertZext: { 9773 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9774 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9775 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9776 ExtType = ISD::ZEXTLOAD; 9777 return true; 9778 } 9779 return false; 9780 } 9781 case ISD::Constant: 9782 case ISD::TargetConstant: { 9783 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9784 1LL << (width - 1); 9785 } 9786 } 9787 9788 return true; 9789 } 9790 9791 // This function does a whole lot of voodoo to determine if the tests are 9792 // equivalent without and with a mask. Essentially what happens is that given a 9793 // DAG resembling: 9794 // 9795 // +-------------+ +-------------+ +-------------+ +-------------+ 9796 // | Input | | AddConstant | | CompConstant| | CC | 9797 // +-------------+ +-------------+ +-------------+ +-------------+ 9798 // | | | | 9799 // V V | +----------+ 9800 // +-------------+ +----+ | | 9801 // | ADD | |0xff| | | 9802 // +-------------+ +----+ | | 9803 // | | | | 9804 // V V | | 9805 // +-------------+ | | 9806 // | AND | | | 9807 // +-------------+ | | 9808 // | | | 9809 // +-----+ | | 9810 // | | | 9811 // V V V 9812 // +-------------+ 9813 // | CMP | 9814 // +-------------+ 9815 // 9816 // The AND node may be safely removed for some combinations of inputs. In 9817 // particular we need to take into account the extension type of the Input, 9818 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9819 // width of the input (this can work for any width inputs, the above graph is 9820 // specific to 8 bits. 9821 // 9822 // The specific equations were worked out by generating output tables for each 9823 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9824 // problem was simplified by working with 4 bit inputs, which means we only 9825 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9826 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9827 // patterns present in both extensions (0,7). For every distinct set of 9828 // AddConstant and CompConstants bit patterns we can consider the masked and 9829 // unmasked versions to be equivalent if the result of this function is true for 9830 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9831 // 9832 // sub w8, w0, w1 9833 // and w10, w8, #0x0f 9834 // cmp w8, w2 9835 // cset w9, AArch64CC 9836 // cmp w10, w2 9837 // cset w11, AArch64CC 9838 // cmp w9, w11 9839 // cset w0, eq 9840 // ret 9841 // 9842 // Since the above function shows when the outputs are equivalent it defines 9843 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9844 // would be expensive to run during compiles. The equations below were written 9845 // in a test harness that confirmed they gave equivalent outputs to the above 9846 // for all inputs function, so they can be used determine if the removal is 9847 // legal instead. 9848 // 9849 // isEquivalentMaskless() is the code for testing if the AND can be removed 9850 // factored out of the DAG recognition as the DAG can take several forms. 9851 9852 static bool isEquivalentMaskless(unsigned CC, unsigned width, 9853 ISD::LoadExtType ExtType, int AddConstant, 9854 int CompConstant) { 9855 // By being careful about our equations and only writing the in term 9856 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 9857 // make them generally applicable to all bit widths. 9858 int MaxUInt = (1 << width); 9859 9860 // For the purposes of these comparisons sign extending the type is 9861 // equivalent to zero extending the add and displacing it by half the integer 9862 // width. Provided we are careful and make sure our equations are valid over 9863 // the whole range we can just adjust the input and avoid writing equations 9864 // for sign extended inputs. 9865 if (ExtType == ISD::SEXTLOAD) 9866 AddConstant -= (1 << (width-1)); 9867 9868 switch(CC) { 9869 case AArch64CC::LE: 9870 case AArch64CC::GT: 9871 if ((AddConstant == 0) || 9872 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 9873 (AddConstant >= 0 && CompConstant < 0) || 9874 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 9875 return true; 9876 break; 9877 case AArch64CC::LT: 9878 case AArch64CC::GE: 9879 if ((AddConstant == 0) || 9880 (AddConstant >= 0 && CompConstant <= 0) || 9881 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 9882 return true; 9883 break; 9884 case AArch64CC::HI: 9885 case AArch64CC::LS: 9886 if ((AddConstant >= 0 && CompConstant < 0) || 9887 (AddConstant <= 0 && CompConstant >= -1 && 9888 CompConstant < AddConstant + MaxUInt)) 9889 return true; 9890 break; 9891 case AArch64CC::PL: 9892 case AArch64CC::MI: 9893 if ((AddConstant == 0) || 9894 (AddConstant > 0 && CompConstant <= 0) || 9895 (AddConstant < 0 && CompConstant <= AddConstant)) 9896 return true; 9897 break; 9898 case AArch64CC::LO: 9899 case AArch64CC::HS: 9900 if ((AddConstant >= 0 && CompConstant <= 0) || 9901 (AddConstant <= 0 && CompConstant >= 0 && 9902 CompConstant <= AddConstant + MaxUInt)) 9903 return true; 9904 break; 9905 case AArch64CC::EQ: 9906 case AArch64CC::NE: 9907 if ((AddConstant > 0 && CompConstant < 0) || 9908 (AddConstant < 0 && CompConstant >= 0 && 9909 CompConstant < AddConstant + MaxUInt) || 9910 (AddConstant >= 0 && CompConstant >= 0 && 9911 CompConstant >= AddConstant) || 9912 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 9913 return true; 9914 break; 9915 case AArch64CC::VS: 9916 case AArch64CC::VC: 9917 case AArch64CC::AL: 9918 case AArch64CC::NV: 9919 return true; 9920 case AArch64CC::Invalid: 9921 break; 9922 } 9923 9924 return false; 9925 } 9926 9927 static 9928 SDValue performCONDCombine(SDNode *N, 9929 TargetLowering::DAGCombinerInfo &DCI, 9930 SelectionDAG &DAG, unsigned CCIndex, 9931 unsigned CmpIndex) { 9932 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 9933 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 9934 unsigned CondOpcode = SubsNode->getOpcode(); 9935 9936 if (CondOpcode != AArch64ISD::SUBS) 9937 return SDValue(); 9938 9939 // There is a SUBS feeding this condition. Is it fed by a mask we can 9940 // use? 9941 9942 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 9943 unsigned MaskBits = 0; 9944 9945 if (AndNode->getOpcode() != ISD::AND) 9946 return SDValue(); 9947 9948 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 9949 uint32_t CNV = CN->getZExtValue(); 9950 if (CNV == 255) 9951 MaskBits = 8; 9952 else if (CNV == 65535) 9953 MaskBits = 16; 9954 } 9955 9956 if (!MaskBits) 9957 return SDValue(); 9958 9959 SDValue AddValue = AndNode->getOperand(0); 9960 9961 if (AddValue.getOpcode() != ISD::ADD) 9962 return SDValue(); 9963 9964 // The basic dag structure is correct, grab the inputs and validate them. 9965 9966 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 9967 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 9968 SDValue SubsInputValue = SubsNode->getOperand(1); 9969 9970 // The mask is present and the provenance of all the values is a smaller type, 9971 // lets see if the mask is superfluous. 9972 9973 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 9974 !isa<ConstantSDNode>(SubsInputValue.getNode())) 9975 return SDValue(); 9976 9977 ISD::LoadExtType ExtType; 9978 9979 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 9980 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 9981 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 9982 return SDValue(); 9983 9984 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 9985 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 9986 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 9987 return SDValue(); 9988 9989 // The AND is not necessary, remove it. 9990 9991 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 9992 SubsNode->getValueType(1)); 9993 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 9994 9995 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 9996 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 9997 9998 return SDValue(N, 0); 9999 } 10000 10001 // Optimize compare with zero and branch. 10002 static SDValue performBRCONDCombine(SDNode *N, 10003 TargetLowering::DAGCombinerInfo &DCI, 10004 SelectionDAG &DAG) { 10005 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 10006 N = NV.getNode(); 10007 SDValue Chain = N->getOperand(0); 10008 SDValue Dest = N->getOperand(1); 10009 SDValue CCVal = N->getOperand(2); 10010 SDValue Cmp = N->getOperand(3); 10011 10012 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 10013 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 10014 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 10015 return SDValue(); 10016 10017 unsigned CmpOpc = Cmp.getOpcode(); 10018 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 10019 return SDValue(); 10020 10021 // Only attempt folding if there is only one use of the flag and no use of the 10022 // value. 10023 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 10024 return SDValue(); 10025 10026 SDValue LHS = Cmp.getOperand(0); 10027 SDValue RHS = Cmp.getOperand(1); 10028 10029 assert(LHS.getValueType() == RHS.getValueType() && 10030 "Expected the value type to be the same for both operands!"); 10031 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 10032 return SDValue(); 10033 10034 if (isNullConstant(LHS)) 10035 std::swap(LHS, RHS); 10036 10037 if (!isNullConstant(RHS)) 10038 return SDValue(); 10039 10040 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 10041 LHS.getOpcode() == ISD::SRL) 10042 return SDValue(); 10043 10044 // Fold the compare into the branch instruction. 10045 SDValue BR; 10046 if (CC == AArch64CC::EQ) 10047 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 10048 else 10049 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 10050 10051 // Do not add new nodes to DAG combiner worklist. 10052 DCI.CombineTo(N, BR, false); 10053 10054 return SDValue(); 10055 } 10056 10057 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 10058 // as well as whether the test should be inverted. This code is required to 10059 // catch these cases (as opposed to standard dag combines) because 10060 // AArch64ISD::TBZ is matched during legalization. 10061 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 10062 SelectionDAG &DAG) { 10063 10064 if (!Op->hasOneUse()) 10065 return Op; 10066 10067 // We don't handle undef/constant-fold cases below, as they should have 10068 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 10069 // etc.) 10070 10071 // (tbz (trunc x), b) -> (tbz x, b) 10072 // This case is just here to enable more of the below cases to be caught. 10073 if (Op->getOpcode() == ISD::TRUNCATE && 10074 Bit < Op->getValueType(0).getSizeInBits()) { 10075 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10076 } 10077 10078 if (Op->getNumOperands() != 2) 10079 return Op; 10080 10081 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 10082 if (!C) 10083 return Op; 10084 10085 switch (Op->getOpcode()) { 10086 default: 10087 return Op; 10088 10089 // (tbz (and x, m), b) -> (tbz x, b) 10090 case ISD::AND: 10091 if ((C->getZExtValue() >> Bit) & 1) 10092 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10093 return Op; 10094 10095 // (tbz (shl x, c), b) -> (tbz x, b-c) 10096 case ISD::SHL: 10097 if (C->getZExtValue() <= Bit && 10098 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 10099 Bit = Bit - C->getZExtValue(); 10100 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10101 } 10102 return Op; 10103 10104 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 10105 case ISD::SRA: 10106 Bit = Bit + C->getZExtValue(); 10107 if (Bit >= Op->getValueType(0).getSizeInBits()) 10108 Bit = Op->getValueType(0).getSizeInBits() - 1; 10109 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10110 10111 // (tbz (srl x, c), b) -> (tbz x, b+c) 10112 case ISD::SRL: 10113 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 10114 Bit = Bit + C->getZExtValue(); 10115 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10116 } 10117 return Op; 10118 10119 // (tbz (xor x, -1), b) -> (tbnz x, b) 10120 case ISD::XOR: 10121 if ((C->getZExtValue() >> Bit) & 1) 10122 Invert = !Invert; 10123 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10124 } 10125 } 10126 10127 // Optimize test single bit zero/non-zero and branch. 10128 static SDValue performTBZCombine(SDNode *N, 10129 TargetLowering::DAGCombinerInfo &DCI, 10130 SelectionDAG &DAG) { 10131 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10132 bool Invert = false; 10133 SDValue TestSrc = N->getOperand(1); 10134 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 10135 10136 if (TestSrc == NewTestSrc) 10137 return SDValue(); 10138 10139 unsigned NewOpc = N->getOpcode(); 10140 if (Invert) { 10141 if (NewOpc == AArch64ISD::TBZ) 10142 NewOpc = AArch64ISD::TBNZ; 10143 else { 10144 assert(NewOpc == AArch64ISD::TBNZ); 10145 NewOpc = AArch64ISD::TBZ; 10146 } 10147 } 10148 10149 SDLoc DL(N); 10150 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 10151 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 10152 } 10153 10154 // vselect (v1i1 setcc) -> 10155 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 10156 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 10157 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 10158 // such VSELECT. 10159 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 10160 SDValue N0 = N->getOperand(0); 10161 EVT CCVT = N0.getValueType(); 10162 10163 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 10164 CCVT.getVectorElementType() != MVT::i1) 10165 return SDValue(); 10166 10167 EVT ResVT = N->getValueType(0); 10168 EVT CmpVT = N0.getOperand(0).getValueType(); 10169 // Only combine when the result type is of the same size as the compared 10170 // operands. 10171 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 10172 return SDValue(); 10173 10174 SDValue IfTrue = N->getOperand(1); 10175 SDValue IfFalse = N->getOperand(2); 10176 SDValue SetCC = 10177 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 10178 N0.getOperand(0), N0.getOperand(1), 10179 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10180 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 10181 IfTrue, IfFalse); 10182 } 10183 10184 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 10185 /// the compare-mask instructions rather than going via NZCV, even if LHS and 10186 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 10187 /// with a vector one followed by a DUP shuffle on the result. 10188 static SDValue performSelectCombine(SDNode *N, 10189 TargetLowering::DAGCombinerInfo &DCI) { 10190 SelectionDAG &DAG = DCI.DAG; 10191 SDValue N0 = N->getOperand(0); 10192 EVT ResVT = N->getValueType(0); 10193 10194 if (N0.getOpcode() != ISD::SETCC) 10195 return SDValue(); 10196 10197 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 10198 // scalar SetCCResultType. We also don't expect vectors, because we assume 10199 // that selects fed by vector SETCCs are canonicalized to VSELECT. 10200 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 10201 "Scalar-SETCC feeding SELECT has unexpected result type!"); 10202 10203 // If NumMaskElts == 0, the comparison is larger than select result. The 10204 // largest real NEON comparison is 64-bits per lane, which means the result is 10205 // at most 32-bits and an illegal vector. Just bail out for now. 10206 EVT SrcVT = N0.getOperand(0).getValueType(); 10207 10208 // Don't try to do this optimization when the setcc itself has i1 operands. 10209 // There are no legal vectors of i1, so this would be pointless. 10210 if (SrcVT == MVT::i1) 10211 return SDValue(); 10212 10213 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 10214 if (!ResVT.isVector() || NumMaskElts == 0) 10215 return SDValue(); 10216 10217 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 10218 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 10219 10220 // Also bail out if the vector CCVT isn't the same size as ResVT. 10221 // This can happen if the SETCC operand size doesn't divide the ResVT size 10222 // (e.g., f64 vs v3f32). 10223 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 10224 return SDValue(); 10225 10226 // Make sure we didn't create illegal types, if we're not supposed to. 10227 assert(DCI.isBeforeLegalize() || 10228 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 10229 10230 // First perform a vector comparison, where lane 0 is the one we're interested 10231 // in. 10232 SDLoc DL(N0); 10233 SDValue LHS = 10234 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 10235 SDValue RHS = 10236 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 10237 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 10238 10239 // Now duplicate the comparison mask we want across all other lanes. 10240 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 10241 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 10242 Mask = DAG.getNode(ISD::BITCAST, DL, 10243 ResVT.changeVectorElementTypeToInteger(), Mask); 10244 10245 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 10246 } 10247 10248 /// Get rid of unnecessary NVCASTs (that don't change the type). 10249 static SDValue performNVCASTCombine(SDNode *N) { 10250 if (N->getValueType(0) == N->getOperand(0).getValueType()) 10251 return N->getOperand(0); 10252 10253 return SDValue(); 10254 } 10255 10256 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 10257 DAGCombinerInfo &DCI) const { 10258 SelectionDAG &DAG = DCI.DAG; 10259 switch (N->getOpcode()) { 10260 default: 10261 break; 10262 case ISD::ADD: 10263 case ISD::SUB: 10264 return performAddSubLongCombine(N, DCI, DAG); 10265 case ISD::XOR: 10266 return performXorCombine(N, DAG, DCI, Subtarget); 10267 case ISD::MUL: 10268 return performMulCombine(N, DAG, DCI, Subtarget); 10269 case ISD::SINT_TO_FP: 10270 case ISD::UINT_TO_FP: 10271 return performIntToFpCombine(N, DAG, Subtarget); 10272 case ISD::FP_TO_SINT: 10273 case ISD::FP_TO_UINT: 10274 return performFpToIntCombine(N, DAG, DCI, Subtarget); 10275 case ISD::FDIV: 10276 return performFDivCombine(N, DAG, DCI, Subtarget); 10277 case ISD::OR: 10278 return performORCombine(N, DCI, Subtarget); 10279 case ISD::SRL: 10280 return performSRLCombine(N, DCI); 10281 case ISD::INTRINSIC_WO_CHAIN: 10282 return performIntrinsicCombine(N, DCI, Subtarget); 10283 case ISD::ANY_EXTEND: 10284 case ISD::ZERO_EXTEND: 10285 case ISD::SIGN_EXTEND: 10286 return performExtendCombine(N, DCI, DAG); 10287 case ISD::BITCAST: 10288 return performBitcastCombine(N, DCI, DAG); 10289 case ISD::CONCAT_VECTORS: 10290 return performConcatVectorsCombine(N, DCI, DAG); 10291 case ISD::SELECT: 10292 return performSelectCombine(N, DCI); 10293 case ISD::VSELECT: 10294 return performVSelectCombine(N, DCI.DAG); 10295 case ISD::LOAD: 10296 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 10297 return SDValue(N, 0); 10298 break; 10299 case ISD::STORE: 10300 return performSTORECombine(N, DCI, DAG, Subtarget); 10301 case AArch64ISD::BRCOND: 10302 return performBRCONDCombine(N, DCI, DAG); 10303 case AArch64ISD::TBNZ: 10304 case AArch64ISD::TBZ: 10305 return performTBZCombine(N, DCI, DAG); 10306 case AArch64ISD::CSEL: 10307 return performCONDCombine(N, DCI, DAG, 2, 3); 10308 case AArch64ISD::DUP: 10309 return performPostLD1Combine(N, DCI, false); 10310 case AArch64ISD::NVCAST: 10311 return performNVCASTCombine(N); 10312 case ISD::INSERT_VECTOR_ELT: 10313 return performPostLD1Combine(N, DCI, true); 10314 case ISD::INTRINSIC_VOID: 10315 case ISD::INTRINSIC_W_CHAIN: 10316 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10317 case Intrinsic::aarch64_neon_ld2: 10318 case Intrinsic::aarch64_neon_ld3: 10319 case Intrinsic::aarch64_neon_ld4: 10320 case Intrinsic::aarch64_neon_ld1x2: 10321 case Intrinsic::aarch64_neon_ld1x3: 10322 case Intrinsic::aarch64_neon_ld1x4: 10323 case Intrinsic::aarch64_neon_ld2lane: 10324 case Intrinsic::aarch64_neon_ld3lane: 10325 case Intrinsic::aarch64_neon_ld4lane: 10326 case Intrinsic::aarch64_neon_ld2r: 10327 case Intrinsic::aarch64_neon_ld3r: 10328 case Intrinsic::aarch64_neon_ld4r: 10329 case Intrinsic::aarch64_neon_st2: 10330 case Intrinsic::aarch64_neon_st3: 10331 case Intrinsic::aarch64_neon_st4: 10332 case Intrinsic::aarch64_neon_st1x2: 10333 case Intrinsic::aarch64_neon_st1x3: 10334 case Intrinsic::aarch64_neon_st1x4: 10335 case Intrinsic::aarch64_neon_st2lane: 10336 case Intrinsic::aarch64_neon_st3lane: 10337 case Intrinsic::aarch64_neon_st4lane: 10338 return performNEONPostLDSTCombine(N, DCI, DAG); 10339 default: 10340 break; 10341 } 10342 } 10343 return SDValue(); 10344 } 10345 10346 // Check if the return value is used as only a return value, as otherwise 10347 // we can't perform a tail-call. In particular, we need to check for 10348 // target ISD nodes that are returns and any other "odd" constructs 10349 // that the generic analysis code won't necessarily catch. 10350 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 10351 SDValue &Chain) const { 10352 if (N->getNumValues() != 1) 10353 return false; 10354 if (!N->hasNUsesOfValue(1, 0)) 10355 return false; 10356 10357 SDValue TCChain = Chain; 10358 SDNode *Copy = *N->use_begin(); 10359 if (Copy->getOpcode() == ISD::CopyToReg) { 10360 // If the copy has a glue operand, we conservatively assume it isn't safe to 10361 // perform a tail call. 10362 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 10363 MVT::Glue) 10364 return false; 10365 TCChain = Copy->getOperand(0); 10366 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 10367 return false; 10368 10369 bool HasRet = false; 10370 for (SDNode *Node : Copy->uses()) { 10371 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 10372 return false; 10373 HasRet = true; 10374 } 10375 10376 if (!HasRet) 10377 return false; 10378 10379 Chain = TCChain; 10380 return true; 10381 } 10382 10383 // Return whether the an instruction can potentially be optimized to a tail 10384 // call. This will cause the optimizers to attempt to move, or duplicate, 10385 // return instructions to help enable tail call optimizations for this 10386 // instruction. 10387 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10388 return CI->isTailCall(); 10389 } 10390 10391 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 10392 SDValue &Offset, 10393 ISD::MemIndexedMode &AM, 10394 bool &IsInc, 10395 SelectionDAG &DAG) const { 10396 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 10397 return false; 10398 10399 Base = Op->getOperand(0); 10400 // All of the indexed addressing mode instructions take a signed 10401 // 9 bit immediate offset. 10402 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 10403 int64_t RHSC = RHS->getSExtValue(); 10404 if (Op->getOpcode() == ISD::SUB) 10405 RHSC = -(uint64_t)RHSC; 10406 if (!isInt<9>(RHSC)) 10407 return false; 10408 IsInc = (Op->getOpcode() == ISD::ADD); 10409 Offset = Op->getOperand(1); 10410 return true; 10411 } 10412 return false; 10413 } 10414 10415 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10416 SDValue &Offset, 10417 ISD::MemIndexedMode &AM, 10418 SelectionDAG &DAG) const { 10419 EVT VT; 10420 SDValue Ptr; 10421 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10422 VT = LD->getMemoryVT(); 10423 Ptr = LD->getBasePtr(); 10424 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10425 VT = ST->getMemoryVT(); 10426 Ptr = ST->getBasePtr(); 10427 } else 10428 return false; 10429 10430 bool IsInc; 10431 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 10432 return false; 10433 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 10434 return true; 10435 } 10436 10437 bool AArch64TargetLowering::getPostIndexedAddressParts( 10438 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10439 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10440 EVT VT; 10441 SDValue Ptr; 10442 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10443 VT = LD->getMemoryVT(); 10444 Ptr = LD->getBasePtr(); 10445 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10446 VT = ST->getMemoryVT(); 10447 Ptr = ST->getBasePtr(); 10448 } else 10449 return false; 10450 10451 bool IsInc; 10452 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10453 return false; 10454 // Post-indexing updates the base, so it's not a valid transform 10455 // if that's not the same as the load's pointer. 10456 if (Ptr != Base) 10457 return false; 10458 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10459 return true; 10460 } 10461 10462 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10463 SelectionDAG &DAG) { 10464 SDLoc DL(N); 10465 SDValue Op = N->getOperand(0); 10466 10467 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10468 return; 10469 10470 Op = SDValue( 10471 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10472 DAG.getUNDEF(MVT::i32), Op, 10473 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10474 0); 10475 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10476 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10477 } 10478 10479 static void ReplaceReductionResults(SDNode *N, 10480 SmallVectorImpl<SDValue> &Results, 10481 SelectionDAG &DAG, unsigned InterOp, 10482 unsigned AcrossOp) { 10483 EVT LoVT, HiVT; 10484 SDValue Lo, Hi; 10485 SDLoc dl(N); 10486 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10487 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10488 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10489 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10490 Results.push_back(SplitVal); 10491 } 10492 10493 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 10494 SDLoc DL(N); 10495 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 10496 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 10497 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 10498 DAG.getConstant(64, DL, MVT::i64))); 10499 return std::make_pair(Lo, Hi); 10500 } 10501 10502 static void ReplaceCMP_SWAP_128Results(SDNode *N, 10503 SmallVectorImpl<SDValue> & Results, 10504 SelectionDAG &DAG) { 10505 assert(N->getValueType(0) == MVT::i128 && 10506 "AtomicCmpSwap on types less than 128 should be legal"); 10507 auto Desired = splitInt128(N->getOperand(2), DAG); 10508 auto New = splitInt128(N->getOperand(3), DAG); 10509 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 10510 New.first, New.second, N->getOperand(0)}; 10511 SDNode *CmpSwap = DAG.getMachineNode( 10512 AArch64::CMP_SWAP_128, SDLoc(N), 10513 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 10514 10515 MachineFunction &MF = DAG.getMachineFunction(); 10516 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 10517 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 10518 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 10519 10520 Results.push_back(SDValue(CmpSwap, 0)); 10521 Results.push_back(SDValue(CmpSwap, 1)); 10522 Results.push_back(SDValue(CmpSwap, 3)); 10523 } 10524 10525 void AArch64TargetLowering::ReplaceNodeResults( 10526 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10527 switch (N->getOpcode()) { 10528 default: 10529 llvm_unreachable("Don't know how to custom expand this"); 10530 case ISD::BITCAST: 10531 ReplaceBITCASTResults(N, Results, DAG); 10532 return; 10533 case ISD::VECREDUCE_ADD: 10534 case ISD::VECREDUCE_SMAX: 10535 case ISD::VECREDUCE_SMIN: 10536 case ISD::VECREDUCE_UMAX: 10537 case ISD::VECREDUCE_UMIN: 10538 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 10539 return; 10540 10541 case AArch64ISD::SADDV: 10542 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10543 return; 10544 case AArch64ISD::UADDV: 10545 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10546 return; 10547 case AArch64ISD::SMINV: 10548 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10549 return; 10550 case AArch64ISD::UMINV: 10551 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10552 return; 10553 case AArch64ISD::SMAXV: 10554 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10555 return; 10556 case AArch64ISD::UMAXV: 10557 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10558 return; 10559 case ISD::FP_TO_UINT: 10560 case ISD::FP_TO_SINT: 10561 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10562 // Let normal code take care of it by not adding anything to Results. 10563 return; 10564 case ISD::ATOMIC_CMP_SWAP: 10565 ReplaceCMP_SWAP_128Results(N, Results, DAG); 10566 return; 10567 } 10568 } 10569 10570 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10571 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 10572 return TargetLowering::useLoadStackGuardNode(); 10573 return true; 10574 } 10575 10576 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10577 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10578 // reciprocal if there are three or more FDIVs. 10579 return 3; 10580 } 10581 10582 TargetLoweringBase::LegalizeTypeAction 10583 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10584 MVT SVT = VT.getSimpleVT(); 10585 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10586 // v4i16, v2i32 instead of to promote. 10587 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10588 || SVT == MVT::v1f32) 10589 return TypeWidenVector; 10590 10591 return TargetLoweringBase::getPreferredVectorAction(VT); 10592 } 10593 10594 // Loads and stores less than 128-bits are already atomic; ones above that 10595 // are doomed anyway, so defer to the default libcall and blame the OS when 10596 // things go wrong. 10597 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10598 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10599 return Size == 128; 10600 } 10601 10602 // Loads and stores less than 128-bits are already atomic; ones above that 10603 // are doomed anyway, so defer to the default libcall and blame the OS when 10604 // things go wrong. 10605 TargetLowering::AtomicExpansionKind 10606 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10607 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10608 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10609 } 10610 10611 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10612 TargetLowering::AtomicExpansionKind 10613 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10614 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10615 if (Size > 128) return AtomicExpansionKind::None; 10616 // Nand not supported in LSE. 10617 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 10618 // Leave 128 bits to LLSC. 10619 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 10620 } 10621 10622 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10623 AtomicCmpXchgInst *AI) const { 10624 // If subtarget has LSE, leave cmpxchg intact for codegen. 10625 if (Subtarget->hasLSE()) return false; 10626 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 10627 // implement cmpxchg without spilling. If the address being exchanged is also 10628 // on the stack and close enough to the spill slot, this can lead to a 10629 // situation where the monitor always gets cleared and the atomic operation 10630 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 10631 return getTargetMachine().getOptLevel() != 0; 10632 } 10633 10634 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10635 AtomicOrdering Ord) const { 10636 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10637 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10638 bool IsAcquire = isAcquireOrStronger(Ord); 10639 10640 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10641 // intrinsic must return {i64, i64} and we have to recombine them into a 10642 // single i128 here. 10643 if (ValTy->getPrimitiveSizeInBits() == 128) { 10644 Intrinsic::ID Int = 10645 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10646 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 10647 10648 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10649 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10650 10651 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10652 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10653 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10654 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10655 return Builder.CreateOr( 10656 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10657 } 10658 10659 Type *Tys[] = { Addr->getType() }; 10660 Intrinsic::ID Int = 10661 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10662 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 10663 10664 return Builder.CreateTruncOrBitCast( 10665 Builder.CreateCall(Ldxr, Addr), 10666 cast<PointerType>(Addr->getType())->getElementType()); 10667 } 10668 10669 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10670 IRBuilder<> &Builder) const { 10671 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10672 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10673 } 10674 10675 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10676 Value *Val, Value *Addr, 10677 AtomicOrdering Ord) const { 10678 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10679 bool IsRelease = isReleaseOrStronger(Ord); 10680 10681 // Since the intrinsics must have legal type, the i128 intrinsics take two 10682 // parameters: "i64, i64". We must marshal Val into the appropriate form 10683 // before the call. 10684 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10685 Intrinsic::ID Int = 10686 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10687 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10688 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10689 10690 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10691 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10692 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10693 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10694 } 10695 10696 Intrinsic::ID Int = 10697 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10698 Type *Tys[] = { Addr->getType() }; 10699 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10700 10701 return Builder.CreateCall(Stxr, 10702 {Builder.CreateZExtOrBitCast( 10703 Val, Stxr->getFunctionType()->getParamType(0)), 10704 Addr}); 10705 } 10706 10707 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10708 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10709 return Ty->isArrayTy(); 10710 } 10711 10712 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10713 EVT) const { 10714 return false; 10715 } 10716 10717 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 10718 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10719 Function *ThreadPointerFunc = 10720 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10721 return IRB.CreatePointerCast( 10722 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset), 10723 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10724 } 10725 10726 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 10727 // Android provides a fixed TLS slot for the stack cookie. See the definition 10728 // of TLS_SLOT_STACK_GUARD in 10729 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10730 if (Subtarget->isTargetAndroid()) 10731 return UseTlsOffset(IRB, 0x28); 10732 10733 // Fuchsia is similar. 10734 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value. 10735 if (Subtarget->isTargetFuchsia()) 10736 return UseTlsOffset(IRB, -0x10); 10737 10738 return TargetLowering::getIRStackGuard(IRB); 10739 } 10740 10741 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10742 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10743 // definition of TLS_SLOT_SAFESTACK in 10744 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10745 if (Subtarget->isTargetAndroid()) 10746 return UseTlsOffset(IRB, 0x48); 10747 10748 // Fuchsia is similar. 10749 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value. 10750 if (Subtarget->isTargetFuchsia()) 10751 return UseTlsOffset(IRB, -0x8); 10752 10753 return TargetLowering::getSafeStackPointerLocation(IRB); 10754 } 10755 10756 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 10757 const Instruction &AndI) const { 10758 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 10759 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 10760 // may be beneficial to sink in other cases, but we would have to check that 10761 // the cmp would not get folded into the br to form a cbz for these to be 10762 // beneficial. 10763 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 10764 if (!Mask) 10765 return false; 10766 return Mask->getUniqueInteger().isPowerOf2(); 10767 } 10768 10769 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10770 // Update IsSplitCSR in AArch64unctionInfo. 10771 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10772 AFI->setIsSplitCSR(true); 10773 } 10774 10775 void AArch64TargetLowering::insertCopiesSplitCSR( 10776 MachineBasicBlock *Entry, 10777 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10778 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10779 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10780 if (!IStart) 10781 return; 10782 10783 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10784 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10785 MachineBasicBlock::iterator MBBI = Entry->begin(); 10786 for (const MCPhysReg *I = IStart; *I; ++I) { 10787 const TargetRegisterClass *RC = nullptr; 10788 if (AArch64::GPR64RegClass.contains(*I)) 10789 RC = &AArch64::GPR64RegClass; 10790 else if (AArch64::FPR64RegClass.contains(*I)) 10791 RC = &AArch64::FPR64RegClass; 10792 else 10793 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10794 10795 unsigned NewVR = MRI->createVirtualRegister(RC); 10796 // Create copy from CSR to a virtual register. 10797 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10798 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10799 // nounwind. If we want to generalize this later, we may need to emit 10800 // CFI pseudo-instructions. 10801 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10802 Attribute::NoUnwind) && 10803 "Function should be nounwind in insertCopiesSplitCSR!"); 10804 Entry->addLiveIn(*I); 10805 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10806 .addReg(*I); 10807 10808 // Insert the copy-back instructions right before the terminator. 10809 for (auto *Exit : Exits) 10810 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10811 TII->get(TargetOpcode::COPY), *I) 10812 .addReg(NewVR); 10813 } 10814 } 10815 10816 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 10817 // Integer division on AArch64 is expensive. However, when aggressively 10818 // optimizing for code size, we prefer to use a div instruction, as it is 10819 // usually smaller than the alternative sequence. 10820 // The exception to this is vector division. Since AArch64 doesn't have vector 10821 // integer division, leaving the division as-is is a loss even in terms of 10822 // size, because it will have to be scalarized, while the alternative code 10823 // sequence can be performed in vector form. 10824 bool OptSize = 10825 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 10826 return OptSize && !VT.isVector(); 10827 } 10828 10829 unsigned 10830 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 10831 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 10832 return getPointerTy(DL).getSizeInBits(); 10833 10834 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 10835 } 10836