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 "AArch64Subtarget.h" 19 #include "AArch64TargetMachine.h" 20 #include "AArch64TargetObjectFile.h" 21 #include "MCTargetDesc/AArch64AddressingModes.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/GetElementPtrTypeIterator.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/Type.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetOptions.h" 36 using namespace llvm; 37 38 #define DEBUG_TYPE "aarch64-lower" 39 40 STATISTIC(NumTailCalls, "Number of tail calls"); 41 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 42 43 // Place holder until extr generation is tested fully. 44 static cl::opt<bool> 45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden, 46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"), 47 cl::init(true)); 48 49 static cl::opt<bool> 50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 51 cl::desc("Allow AArch64 SLI/SRI formation"), 52 cl::init(false)); 53 54 // FIXME: The necessary dtprel relocations don't seem to be supported 55 // well in the GNU bfd and gold linkers at the moment. Therefore, by 56 // default, for now, fall back to GeneralDynamic code generation. 57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 58 "aarch64-elf-ldtls-generation", cl::Hidden, 59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 60 cl::init(false)); 61 62 /// Value type used for condition codes. 63 static const MVT MVT_CC = MVT::i32; 64 65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 66 const AArch64Subtarget &STI) 67 : TargetLowering(TM), Subtarget(&STI) { 68 69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 70 // we have to make something up. Arbitrarily, choose ZeroOrOne. 71 setBooleanContents(ZeroOrOneBooleanContent); 72 // When comparing vectors the result sets the different elements in the 73 // vector to all-one or all-zero. 74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 75 76 // Set up the register classes. 77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 79 80 if (Subtarget->hasFPARMv8()) { 81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 85 } 86 87 if (Subtarget->hasNEON()) { 88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 90 // Someone set us up the NEON. 91 addDRTypeForNEON(MVT::v2f32); 92 addDRTypeForNEON(MVT::v8i8); 93 addDRTypeForNEON(MVT::v4i16); 94 addDRTypeForNEON(MVT::v2i32); 95 addDRTypeForNEON(MVT::v1i64); 96 addDRTypeForNEON(MVT::v1f64); 97 addDRTypeForNEON(MVT::v4f16); 98 99 addQRTypeForNEON(MVT::v4f32); 100 addQRTypeForNEON(MVT::v2f64); 101 addQRTypeForNEON(MVT::v16i8); 102 addQRTypeForNEON(MVT::v8i16); 103 addQRTypeForNEON(MVT::v4i32); 104 addQRTypeForNEON(MVT::v2i64); 105 addQRTypeForNEON(MVT::v8f16); 106 } 107 108 // Compute derived properties from the register classes 109 computeRegisterProperties(Subtarget->getRegisterInfo()); 110 111 // Provide all sorts of operation actions 112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 114 setOperationAction(ISD::SETCC, MVT::i32, Custom); 115 setOperationAction(ISD::SETCC, MVT::i64, Custom); 116 setOperationAction(ISD::SETCC, MVT::f32, Custom); 117 setOperationAction(ISD::SETCC, MVT::f64, Custom); 118 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 119 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 120 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 121 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 122 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 123 setOperationAction(ISD::SELECT, MVT::i32, Custom); 124 setOperationAction(ISD::SELECT, MVT::i64, Custom); 125 setOperationAction(ISD::SELECT, MVT::f32, Custom); 126 setOperationAction(ISD::SELECT, MVT::f64, Custom); 127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 131 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 132 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 133 134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 137 138 setOperationAction(ISD::FREM, MVT::f32, Expand); 139 setOperationAction(ISD::FREM, MVT::f64, Expand); 140 setOperationAction(ISD::FREM, MVT::f80, Expand); 141 142 // Custom lowering hooks are needed for XOR 143 // to fold it into CSINC/CSINV. 144 setOperationAction(ISD::XOR, MVT::i32, Custom); 145 setOperationAction(ISD::XOR, MVT::i64, Custom); 146 147 // Custom lowering hooks are needed for OR 148 // to fold it into CCMP. 149 setOperationAction(ISD::OR, MVT::i32, Custom); 150 setOperationAction(ISD::OR, MVT::i64, Custom); 151 152 // Custom lowering hooks are needed for AND 153 // to fold it into CCMP. 154 setOperationAction(ISD::AND, MVT::i32, Custom); 155 setOperationAction(ISD::AND, MVT::i64, Custom); 156 157 // Virtually no operation on f128 is legal, but LLVM can't expand them when 158 // there's a valid register class, so we need custom operations in most cases. 159 setOperationAction(ISD::FABS, MVT::f128, Expand); 160 setOperationAction(ISD::FADD, MVT::f128, Custom); 161 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 162 setOperationAction(ISD::FCOS, MVT::f128, Expand); 163 setOperationAction(ISD::FDIV, MVT::f128, Custom); 164 setOperationAction(ISD::FMA, MVT::f128, Expand); 165 setOperationAction(ISD::FMUL, MVT::f128, Custom); 166 setOperationAction(ISD::FNEG, MVT::f128, Expand); 167 setOperationAction(ISD::FPOW, MVT::f128, Expand); 168 setOperationAction(ISD::FREM, MVT::f128, Expand); 169 setOperationAction(ISD::FRINT, MVT::f128, Expand); 170 setOperationAction(ISD::FSIN, MVT::f128, Expand); 171 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 172 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 173 setOperationAction(ISD::FSUB, MVT::f128, Custom); 174 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 175 setOperationAction(ISD::SETCC, MVT::f128, Custom); 176 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 177 setOperationAction(ISD::SELECT, MVT::f128, Custom); 178 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 179 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 180 181 // Lowering for many of the conversions is actually specified by the non-f128 182 // type. The LowerXXX function will be trivial when f128 isn't involved. 183 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 184 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 185 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 186 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 187 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 188 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 189 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 190 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 191 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 192 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 193 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 194 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 195 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 196 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 197 198 // Variable arguments. 199 setOperationAction(ISD::VASTART, MVT::Other, Custom); 200 setOperationAction(ISD::VAARG, MVT::Other, Custom); 201 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 202 setOperationAction(ISD::VAEND, MVT::Other, Expand); 203 204 // Variable-sized objects. 205 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 206 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 207 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 208 209 // Constant pool entries 210 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 211 212 // BlockAddress 213 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 214 215 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 216 setOperationAction(ISD::ADDC, MVT::i32, Custom); 217 setOperationAction(ISD::ADDE, MVT::i32, Custom); 218 setOperationAction(ISD::SUBC, MVT::i32, Custom); 219 setOperationAction(ISD::SUBE, MVT::i32, Custom); 220 setOperationAction(ISD::ADDC, MVT::i64, Custom); 221 setOperationAction(ISD::ADDE, MVT::i64, Custom); 222 setOperationAction(ISD::SUBC, MVT::i64, Custom); 223 setOperationAction(ISD::SUBE, MVT::i64, Custom); 224 225 // AArch64 lacks both left-rotate and popcount instructions. 226 setOperationAction(ISD::ROTL, MVT::i32, Expand); 227 setOperationAction(ISD::ROTL, MVT::i64, Expand); 228 for (MVT VT : MVT::vector_valuetypes()) { 229 setOperationAction(ISD::ROTL, VT, Expand); 230 setOperationAction(ISD::ROTR, VT, Expand); 231 } 232 233 // AArch64 doesn't have {U|S}MUL_LOHI. 234 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 235 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 236 237 238 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 239 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 240 241 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 242 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 243 for (MVT VT : MVT::vector_valuetypes()) { 244 setOperationAction(ISD::SDIVREM, VT, Expand); 245 setOperationAction(ISD::UDIVREM, VT, Expand); 246 } 247 setOperationAction(ISD::SREM, MVT::i32, Expand); 248 setOperationAction(ISD::SREM, MVT::i64, Expand); 249 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 250 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 251 setOperationAction(ISD::UREM, MVT::i32, Expand); 252 setOperationAction(ISD::UREM, MVT::i64, Expand); 253 254 // Custom lower Add/Sub/Mul with overflow. 255 setOperationAction(ISD::SADDO, MVT::i32, Custom); 256 setOperationAction(ISD::SADDO, MVT::i64, Custom); 257 setOperationAction(ISD::UADDO, MVT::i32, Custom); 258 setOperationAction(ISD::UADDO, MVT::i64, Custom); 259 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 260 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 261 setOperationAction(ISD::USUBO, MVT::i32, Custom); 262 setOperationAction(ISD::USUBO, MVT::i64, Custom); 263 setOperationAction(ISD::SMULO, MVT::i32, Custom); 264 setOperationAction(ISD::SMULO, MVT::i64, Custom); 265 setOperationAction(ISD::UMULO, MVT::i32, Custom); 266 setOperationAction(ISD::UMULO, MVT::i64, Custom); 267 268 setOperationAction(ISD::FSIN, MVT::f32, Expand); 269 setOperationAction(ISD::FSIN, MVT::f64, Expand); 270 setOperationAction(ISD::FCOS, MVT::f32, Expand); 271 setOperationAction(ISD::FCOS, MVT::f64, Expand); 272 setOperationAction(ISD::FPOW, MVT::f32, Expand); 273 setOperationAction(ISD::FPOW, MVT::f64, Expand); 274 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 275 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 276 277 // f16 is a storage-only type, always promote it to f32. 278 setOperationAction(ISD::SETCC, MVT::f16, Promote); 279 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 280 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 281 setOperationAction(ISD::SELECT, MVT::f16, Promote); 282 setOperationAction(ISD::FADD, MVT::f16, Promote); 283 setOperationAction(ISD::FSUB, MVT::f16, Promote); 284 setOperationAction(ISD::FMUL, MVT::f16, Promote); 285 setOperationAction(ISD::FDIV, MVT::f16, Promote); 286 setOperationAction(ISD::FREM, MVT::f16, Promote); 287 setOperationAction(ISD::FMA, MVT::f16, Promote); 288 setOperationAction(ISD::FNEG, MVT::f16, Promote); 289 setOperationAction(ISD::FABS, MVT::f16, Promote); 290 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 291 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 292 setOperationAction(ISD::FCOS, MVT::f16, Promote); 293 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 294 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 295 setOperationAction(ISD::FPOW, MVT::f16, Promote); 296 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 297 setOperationAction(ISD::FRINT, MVT::f16, Promote); 298 setOperationAction(ISD::FSIN, MVT::f16, Promote); 299 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 300 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 301 setOperationAction(ISD::FEXP, MVT::f16, Promote); 302 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 303 setOperationAction(ISD::FLOG, MVT::f16, Promote); 304 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 305 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 306 setOperationAction(ISD::FROUND, MVT::f16, Promote); 307 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 308 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 309 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 310 setOperationAction(ISD::FMINNAN, MVT::f16, Promote); 311 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote); 312 313 // v4f16 is also a storage-only type, so promote it to v4f32 when that is 314 // known to be safe. 315 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 316 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 317 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 318 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 319 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 320 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 321 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 322 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 323 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 324 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 325 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 326 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 327 328 // Expand all other v4f16 operations. 329 // FIXME: We could generate better code by promoting some operations to 330 // a pair of v4f32s 331 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 332 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 333 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 334 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 335 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 336 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 337 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 338 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 339 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 340 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 341 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 342 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 343 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 344 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 345 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 346 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 347 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 348 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 349 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 350 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 351 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 352 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 353 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 354 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 355 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 356 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 357 358 359 // v8f16 is also a storage-only type, so expand it. 360 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 361 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 362 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 363 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 364 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 365 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 366 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 367 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 368 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 369 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 370 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 371 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 372 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 373 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 374 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 375 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 376 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 377 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 378 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 379 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 380 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 381 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 382 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 383 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 384 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 385 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 386 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 387 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 388 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 389 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 390 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 391 392 // AArch64 has implementations of a lot of rounding-like FP operations. 393 for (MVT Ty : {MVT::f32, MVT::f64}) { 394 setOperationAction(ISD::FFLOOR, Ty, Legal); 395 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 396 setOperationAction(ISD::FCEIL, Ty, Legal); 397 setOperationAction(ISD::FRINT, Ty, Legal); 398 setOperationAction(ISD::FTRUNC, Ty, Legal); 399 setOperationAction(ISD::FROUND, Ty, Legal); 400 setOperationAction(ISD::FMINNUM, Ty, Legal); 401 setOperationAction(ISD::FMAXNUM, Ty, Legal); 402 setOperationAction(ISD::FMINNAN, Ty, Legal); 403 setOperationAction(ISD::FMAXNAN, Ty, Legal); 404 } 405 406 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 407 408 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 409 410 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 411 // This requires the Performance Monitors extension. 412 if (Subtarget->hasPerfMon()) 413 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 414 415 if (Subtarget->isTargetMachO()) { 416 // For iOS, we don't want to the normal expansion of a libcall to 417 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 418 // traffic. 419 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 420 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 421 } else { 422 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 423 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 424 } 425 426 // Make floating-point constants legal for the large code model, so they don't 427 // become loads from the constant pool. 428 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 429 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 430 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 431 } 432 433 // AArch64 does not have floating-point extending loads, i1 sign-extending 434 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 435 for (MVT VT : MVT::fp_valuetypes()) { 436 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 437 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 438 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 439 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 440 } 441 for (MVT VT : MVT::integer_valuetypes()) 442 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 443 444 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 445 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 446 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 447 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 448 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 449 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 450 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 451 452 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 453 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 454 455 // Indexed loads and stores are supported. 456 for (unsigned im = (unsigned)ISD::PRE_INC; 457 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 458 setIndexedLoadAction(im, MVT::i8, Legal); 459 setIndexedLoadAction(im, MVT::i16, Legal); 460 setIndexedLoadAction(im, MVT::i32, Legal); 461 setIndexedLoadAction(im, MVT::i64, Legal); 462 setIndexedLoadAction(im, MVT::f64, Legal); 463 setIndexedLoadAction(im, MVT::f32, Legal); 464 setIndexedLoadAction(im, MVT::f16, Legal); 465 setIndexedStoreAction(im, MVT::i8, Legal); 466 setIndexedStoreAction(im, MVT::i16, Legal); 467 setIndexedStoreAction(im, MVT::i32, Legal); 468 setIndexedStoreAction(im, MVT::i64, Legal); 469 setIndexedStoreAction(im, MVT::f64, Legal); 470 setIndexedStoreAction(im, MVT::f32, Legal); 471 setIndexedStoreAction(im, MVT::f16, Legal); 472 } 473 474 // Trap. 475 setOperationAction(ISD::TRAP, MVT::Other, Legal); 476 477 // We combine OR nodes for bitfield operations. 478 setTargetDAGCombine(ISD::OR); 479 480 // Vector add and sub nodes may conceal a high-half opportunity. 481 // Also, try to fold ADD into CSINC/CSINV.. 482 setTargetDAGCombine(ISD::ADD); 483 setTargetDAGCombine(ISD::SUB); 484 485 setTargetDAGCombine(ISD::XOR); 486 setTargetDAGCombine(ISD::SINT_TO_FP); 487 setTargetDAGCombine(ISD::UINT_TO_FP); 488 489 setTargetDAGCombine(ISD::FP_TO_SINT); 490 setTargetDAGCombine(ISD::FP_TO_UINT); 491 setTargetDAGCombine(ISD::FDIV); 492 493 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 494 495 setTargetDAGCombine(ISD::ANY_EXTEND); 496 setTargetDAGCombine(ISD::ZERO_EXTEND); 497 setTargetDAGCombine(ISD::SIGN_EXTEND); 498 setTargetDAGCombine(ISD::BITCAST); 499 setTargetDAGCombine(ISD::CONCAT_VECTORS); 500 setTargetDAGCombine(ISD::STORE); 501 if (Subtarget->supportsAddressTopByteIgnored()) 502 setTargetDAGCombine(ISD::LOAD); 503 504 setTargetDAGCombine(ISD::MUL); 505 506 setTargetDAGCombine(ISD::SELECT); 507 setTargetDAGCombine(ISD::VSELECT); 508 509 setTargetDAGCombine(ISD::INTRINSIC_VOID); 510 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 511 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 512 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 513 514 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8; 515 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4; 516 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4; 517 518 setStackPointerRegisterToSaveRestore(AArch64::SP); 519 520 setSchedulingPreference(Sched::Hybrid); 521 522 // Enable TBZ/TBNZ 523 MaskAndBranchFoldingIsLegal = true; 524 EnableExtLdPromotion = true; 525 526 setMinFunctionAlignment(2); 527 528 setHasExtractBitsInsn(true); 529 530 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 531 532 if (Subtarget->hasNEON()) { 533 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 534 // silliness like this: 535 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 536 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 537 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 538 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 539 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 540 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 541 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 542 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 543 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 544 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 545 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 546 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 547 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 548 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 549 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 550 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 551 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 552 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 553 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 554 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 555 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 556 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 557 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 558 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 559 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 560 561 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 562 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 563 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 564 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 565 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 566 567 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 568 569 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 570 // elements smaller than i32, so promote the input to i32 first. 571 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote); 572 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote); 573 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote); 574 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote); 575 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16 576 // -> v8f16 conversions. 577 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote); 578 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote); 579 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 580 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote); 581 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 582 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 583 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 584 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 585 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 586 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 587 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 588 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 589 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 590 591 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 592 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 593 594 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand); 595 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand); 596 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand); 597 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand); 598 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand); 599 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand); 600 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand); 601 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand); 602 603 // AArch64 doesn't have MUL.2d: 604 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 605 // Custom handling for some quad-vector types to detect MULL. 606 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 607 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 608 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 609 610 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 611 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 612 // Likewise, narrowing and extending vector loads/stores aren't handled 613 // directly. 614 for (MVT VT : MVT::vector_valuetypes()) { 615 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 616 617 setOperationAction(ISD::MULHS, VT, Expand); 618 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 619 setOperationAction(ISD::MULHU, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 622 setOperationAction(ISD::BSWAP, VT, Expand); 623 624 for (MVT InnerVT : MVT::vector_valuetypes()) { 625 setTruncStoreAction(VT, InnerVT, Expand); 626 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 627 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 628 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 629 } 630 } 631 632 // AArch64 has implementations of a lot of rounding-like FP operations. 633 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 634 setOperationAction(ISD::FFLOOR, Ty, Legal); 635 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 636 setOperationAction(ISD::FCEIL, Ty, Legal); 637 setOperationAction(ISD::FRINT, Ty, Legal); 638 setOperationAction(ISD::FTRUNC, Ty, Legal); 639 setOperationAction(ISD::FROUND, Ty, Legal); 640 } 641 } 642 643 // Prefer likely predicted branches to selects on out-of-order cores. 644 if (Subtarget->isCortexA57() || Subtarget->isKryo()) 645 PredictableSelectIsExpensive = true; 646 } 647 648 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 649 if (VT == MVT::v2f32 || VT == MVT::v4f16) { 650 setOperationAction(ISD::LOAD, VT, Promote); 651 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32); 652 653 setOperationAction(ISD::STORE, VT, Promote); 654 AddPromotedToType(ISD::STORE, VT, MVT::v2i32); 655 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) { 656 setOperationAction(ISD::LOAD, VT, Promote); 657 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64); 658 659 setOperationAction(ISD::STORE, VT, Promote); 660 AddPromotedToType(ISD::STORE, VT, MVT::v2i64); 661 } 662 663 // Mark vector float intrinsics as expand. 664 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 665 setOperationAction(ISD::FSIN, VT, Expand); 666 setOperationAction(ISD::FCOS, VT, Expand); 667 setOperationAction(ISD::FPOWI, VT, Expand); 668 setOperationAction(ISD::FPOW, VT, Expand); 669 setOperationAction(ISD::FLOG, VT, Expand); 670 setOperationAction(ISD::FLOG2, VT, Expand); 671 setOperationAction(ISD::FLOG10, VT, Expand); 672 setOperationAction(ISD::FEXP, VT, Expand); 673 setOperationAction(ISD::FEXP2, VT, Expand); 674 675 // But we do support custom-lowering for FCOPYSIGN. 676 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 677 } 678 679 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 680 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 681 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 682 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 683 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 684 setOperationAction(ISD::SRA, VT, Custom); 685 setOperationAction(ISD::SRL, VT, Custom); 686 setOperationAction(ISD::SHL, VT, Custom); 687 setOperationAction(ISD::AND, VT, Custom); 688 setOperationAction(ISD::OR, VT, Custom); 689 setOperationAction(ISD::SETCC, VT, Custom); 690 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 691 692 setOperationAction(ISD::SELECT, VT, Expand); 693 setOperationAction(ISD::SELECT_CC, VT, Expand); 694 setOperationAction(ISD::VSELECT, VT, Expand); 695 for (MVT InnerVT : MVT::all_valuetypes()) 696 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 697 698 // CNT supports only B element sizes. 699 if (VT != MVT::v8i8 && VT != MVT::v16i8) 700 setOperationAction(ISD::CTPOP, VT, Expand); 701 702 setOperationAction(ISD::UDIV, VT, Expand); 703 setOperationAction(ISD::SDIV, VT, Expand); 704 setOperationAction(ISD::UREM, VT, Expand); 705 setOperationAction(ISD::SREM, VT, Expand); 706 setOperationAction(ISD::FREM, VT, Expand); 707 708 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 709 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 710 711 // [SU][MIN|MAX] are available for all NEON types apart from i64. 712 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 713 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 714 setOperationAction(Opcode, VT, Legal); 715 716 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!). 717 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16) 718 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN, 719 ISD::FMINNUM, ISD::FMAXNUM}) 720 setOperationAction(Opcode, VT, Legal); 721 722 if (Subtarget->isLittleEndian()) { 723 for (unsigned im = (unsigned)ISD::PRE_INC; 724 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 725 setIndexedLoadAction(im, VT, Legal); 726 setIndexedStoreAction(im, VT, Legal); 727 } 728 } 729 } 730 731 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 732 addRegisterClass(VT, &AArch64::FPR64RegClass); 733 addTypeForNEON(VT, MVT::v2i32); 734 } 735 736 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 737 addRegisterClass(VT, &AArch64::FPR128RegClass); 738 addTypeForNEON(VT, MVT::v4i32); 739 } 740 741 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 742 EVT VT) const { 743 if (!VT.isVector()) 744 return MVT::i32; 745 return VT.changeVectorElementTypeToInteger(); 746 } 747 748 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 749 /// Mask are known to be either zero or one and return them in the 750 /// KnownZero/KnownOne bitsets. 751 void AArch64TargetLowering::computeKnownBitsForTargetNode( 752 const SDValue Op, APInt &KnownZero, APInt &KnownOne, 753 const SelectionDAG &DAG, unsigned Depth) const { 754 switch (Op.getOpcode()) { 755 default: 756 break; 757 case AArch64ISD::CSEL: { 758 APInt KnownZero2, KnownOne2; 759 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1); 760 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1); 761 KnownZero &= KnownZero2; 762 KnownOne &= KnownOne2; 763 break; 764 } 765 case ISD::INTRINSIC_W_CHAIN: { 766 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 767 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 768 switch (IntID) { 769 default: return; 770 case Intrinsic::aarch64_ldaxr: 771 case Intrinsic::aarch64_ldxr: { 772 unsigned BitWidth = KnownOne.getBitWidth(); 773 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 774 unsigned MemBits = VT.getScalarType().getSizeInBits(); 775 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 776 return; 777 } 778 } 779 break; 780 } 781 case ISD::INTRINSIC_WO_CHAIN: 782 case ISD::INTRINSIC_VOID: { 783 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 784 switch (IntNo) { 785 default: 786 break; 787 case Intrinsic::aarch64_neon_umaxv: 788 case Intrinsic::aarch64_neon_uminv: { 789 // Figure out the datatype of the vector operand. The UMINV instruction 790 // will zero extend the result, so we can mark as known zero all the 791 // bits larger than the element datatype. 32-bit or larget doesn't need 792 // this as those are legal types and will be handled by isel directly. 793 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 794 unsigned BitWidth = KnownZero.getBitWidth(); 795 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 796 assert(BitWidth >= 8 && "Unexpected width!"); 797 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 798 KnownZero |= Mask; 799 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 800 assert(BitWidth >= 16 && "Unexpected width!"); 801 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 802 KnownZero |= Mask; 803 } 804 break; 805 } break; 806 } 807 } 808 } 809 } 810 811 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 812 EVT) const { 813 return MVT::i64; 814 } 815 816 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 817 unsigned AddrSpace, 818 unsigned Align, 819 bool *Fast) const { 820 if (Subtarget->requiresStrictAlign()) 821 return false; 822 823 // FIXME: This is mostly true for Cyclone, but not necessarily others. 824 if (Fast) { 825 // FIXME: Define an attribute for slow unaligned accesses instead of 826 // relying on the CPU type as a proxy. 827 // On Cyclone, unaligned 128-bit stores are slow. 828 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 || 829 // See comments in performSTORECombine() for more details about 830 // these conditions. 831 832 // Code that uses clang vector extensions can mark that it 833 // wants unaligned accesses to be treated as fast by 834 // underspecifying alignment to be 1 or 2. 835 Align <= 2 || 836 837 // Disregard v2i64. Memcpy lowering produces those and splitting 838 // them regresses performance on micro-benchmarks and olden/bh. 839 VT == MVT::v2i64; 840 } 841 return true; 842 } 843 844 FastISel * 845 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 846 const TargetLibraryInfo *libInfo) const { 847 return AArch64::createFastISel(funcInfo, libInfo); 848 } 849 850 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 851 switch ((AArch64ISD::NodeType)Opcode) { 852 case AArch64ISD::FIRST_NUMBER: break; 853 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 854 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 855 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 856 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 857 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 858 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 859 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 860 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 861 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 862 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 863 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 864 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 865 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 866 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 867 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 868 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 869 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 870 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 871 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 872 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 873 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 874 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 875 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 876 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 877 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 878 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 879 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 880 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 881 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 882 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 883 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 884 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 885 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 886 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 887 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 888 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 889 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 890 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 891 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 892 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 893 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 894 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 895 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 896 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 897 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 898 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 899 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 900 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 901 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 902 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 903 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 904 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 905 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 906 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 907 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 908 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 909 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 910 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 911 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 912 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 913 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 914 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 915 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 916 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 917 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 918 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 919 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 920 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 921 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 922 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 923 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 924 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 925 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 926 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 927 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 928 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 929 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 930 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 931 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 932 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 933 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 934 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 935 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 936 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 937 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 938 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 939 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 940 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 941 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 942 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 943 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 944 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 945 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 946 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 947 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 948 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 949 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 950 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 951 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 952 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 953 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 954 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 955 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 956 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 957 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 958 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 959 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 960 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 961 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 962 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 963 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 964 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 965 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 966 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 967 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 968 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 969 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 970 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 971 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 972 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 973 } 974 return nullptr; 975 } 976 977 MachineBasicBlock * 978 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI, 979 MachineBasicBlock *MBB) const { 980 // We materialise the F128CSEL pseudo-instruction as some control flow and a 981 // phi node: 982 983 // OrigBB: 984 // [... previous instrs leading to comparison ...] 985 // b.ne TrueBB 986 // b EndBB 987 // TrueBB: 988 // ; Fallthrough 989 // EndBB: 990 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 991 992 MachineFunction *MF = MBB->getParent(); 993 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 994 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 995 DebugLoc DL = MI->getDebugLoc(); 996 MachineFunction::iterator It = ++MBB->getIterator(); 997 998 unsigned DestReg = MI->getOperand(0).getReg(); 999 unsigned IfTrueReg = MI->getOperand(1).getReg(); 1000 unsigned IfFalseReg = MI->getOperand(2).getReg(); 1001 unsigned CondCode = MI->getOperand(3).getImm(); 1002 bool NZCVKilled = MI->getOperand(4).isKill(); 1003 1004 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1005 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1006 MF->insert(It, TrueBB); 1007 MF->insert(It, EndBB); 1008 1009 // Transfer rest of current basic-block to EndBB 1010 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1011 MBB->end()); 1012 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1013 1014 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1015 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1016 MBB->addSuccessor(TrueBB); 1017 MBB->addSuccessor(EndBB); 1018 1019 // TrueBB falls through to the end. 1020 TrueBB->addSuccessor(EndBB); 1021 1022 if (!NZCVKilled) { 1023 TrueBB->addLiveIn(AArch64::NZCV); 1024 EndBB->addLiveIn(AArch64::NZCV); 1025 } 1026 1027 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1028 .addReg(IfTrueReg) 1029 .addMBB(TrueBB) 1030 .addReg(IfFalseReg) 1031 .addMBB(MBB); 1032 1033 MI->eraseFromParent(); 1034 return EndBB; 1035 } 1036 1037 MachineBasicBlock * 1038 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 1039 MachineBasicBlock *BB) const { 1040 switch (MI->getOpcode()) { 1041 default: 1042 #ifndef NDEBUG 1043 MI->dump(); 1044 #endif 1045 llvm_unreachable("Unexpected instruction for custom inserter!"); 1046 1047 case AArch64::F128CSEL: 1048 return EmitF128CSEL(MI, BB); 1049 1050 case TargetOpcode::STACKMAP: 1051 case TargetOpcode::PATCHPOINT: 1052 return emitPatchPoint(MI, BB); 1053 } 1054 } 1055 1056 //===----------------------------------------------------------------------===// 1057 // AArch64 Lowering private implementation. 1058 //===----------------------------------------------------------------------===// 1059 1060 //===----------------------------------------------------------------------===// 1061 // Lowering Code 1062 //===----------------------------------------------------------------------===// 1063 1064 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1065 /// CC 1066 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1067 switch (CC) { 1068 default: 1069 llvm_unreachable("Unknown condition code!"); 1070 case ISD::SETNE: 1071 return AArch64CC::NE; 1072 case ISD::SETEQ: 1073 return AArch64CC::EQ; 1074 case ISD::SETGT: 1075 return AArch64CC::GT; 1076 case ISD::SETGE: 1077 return AArch64CC::GE; 1078 case ISD::SETLT: 1079 return AArch64CC::LT; 1080 case ISD::SETLE: 1081 return AArch64CC::LE; 1082 case ISD::SETUGT: 1083 return AArch64CC::HI; 1084 case ISD::SETUGE: 1085 return AArch64CC::HS; 1086 case ISD::SETULT: 1087 return AArch64CC::LO; 1088 case ISD::SETULE: 1089 return AArch64CC::LS; 1090 } 1091 } 1092 1093 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1094 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1095 AArch64CC::CondCode &CondCode, 1096 AArch64CC::CondCode &CondCode2) { 1097 CondCode2 = AArch64CC::AL; 1098 switch (CC) { 1099 default: 1100 llvm_unreachable("Unknown FP condition!"); 1101 case ISD::SETEQ: 1102 case ISD::SETOEQ: 1103 CondCode = AArch64CC::EQ; 1104 break; 1105 case ISD::SETGT: 1106 case ISD::SETOGT: 1107 CondCode = AArch64CC::GT; 1108 break; 1109 case ISD::SETGE: 1110 case ISD::SETOGE: 1111 CondCode = AArch64CC::GE; 1112 break; 1113 case ISD::SETOLT: 1114 CondCode = AArch64CC::MI; 1115 break; 1116 case ISD::SETOLE: 1117 CondCode = AArch64CC::LS; 1118 break; 1119 case ISD::SETONE: 1120 CondCode = AArch64CC::MI; 1121 CondCode2 = AArch64CC::GT; 1122 break; 1123 case ISD::SETO: 1124 CondCode = AArch64CC::VC; 1125 break; 1126 case ISD::SETUO: 1127 CondCode = AArch64CC::VS; 1128 break; 1129 case ISD::SETUEQ: 1130 CondCode = AArch64CC::EQ; 1131 CondCode2 = AArch64CC::VS; 1132 break; 1133 case ISD::SETUGT: 1134 CondCode = AArch64CC::HI; 1135 break; 1136 case ISD::SETUGE: 1137 CondCode = AArch64CC::PL; 1138 break; 1139 case ISD::SETLT: 1140 case ISD::SETULT: 1141 CondCode = AArch64CC::LT; 1142 break; 1143 case ISD::SETLE: 1144 case ISD::SETULE: 1145 CondCode = AArch64CC::LE; 1146 break; 1147 case ISD::SETNE: 1148 case ISD::SETUNE: 1149 CondCode = AArch64CC::NE; 1150 break; 1151 } 1152 } 1153 1154 /// Convert a DAG fp condition code to an AArch64 CC. 1155 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1156 /// should be AND'ed instead of OR'ed. 1157 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1158 AArch64CC::CondCode &CondCode, 1159 AArch64CC::CondCode &CondCode2) { 1160 CondCode2 = AArch64CC::AL; 1161 switch (CC) { 1162 default: 1163 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1164 assert(CondCode2 == AArch64CC::AL); 1165 break; 1166 case ISD::SETONE: 1167 // (a one b) 1168 // == ((a olt b) || (a ogt b)) 1169 // == ((a ord b) && (a une b)) 1170 CondCode = AArch64CC::VC; 1171 CondCode2 = AArch64CC::NE; 1172 break; 1173 case ISD::SETUEQ: 1174 // (a ueq b) 1175 // == ((a uno b) || (a oeq b)) 1176 // == ((a ule b) && (a uge b)) 1177 CondCode = AArch64CC::PL; 1178 CondCode2 = AArch64CC::LE; 1179 break; 1180 } 1181 } 1182 1183 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1184 /// CC usable with the vector instructions. Fewer operations are available 1185 /// without a real NZCV register, so we have to use less efficient combinations 1186 /// to get the same effect. 1187 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1188 AArch64CC::CondCode &CondCode, 1189 AArch64CC::CondCode &CondCode2, 1190 bool &Invert) { 1191 Invert = false; 1192 switch (CC) { 1193 default: 1194 // Mostly the scalar mappings work fine. 1195 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1196 break; 1197 case ISD::SETUO: 1198 Invert = true; // Fallthrough 1199 case ISD::SETO: 1200 CondCode = AArch64CC::MI; 1201 CondCode2 = AArch64CC::GE; 1202 break; 1203 case ISD::SETUEQ: 1204 case ISD::SETULT: 1205 case ISD::SETULE: 1206 case ISD::SETUGT: 1207 case ISD::SETUGE: 1208 // All of the compare-mask comparisons are ordered, but we can switch 1209 // between the two by a double inversion. E.g. ULE == !OGT. 1210 Invert = true; 1211 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1212 break; 1213 } 1214 } 1215 1216 static bool isLegalArithImmed(uint64_t C) { 1217 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1218 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1219 } 1220 1221 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1222 SDLoc dl, SelectionDAG &DAG) { 1223 EVT VT = LHS.getValueType(); 1224 1225 if (VT.isFloatingPoint()) { 1226 assert(VT != MVT::f128); 1227 if (VT == MVT::f16) { 1228 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1229 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1230 } 1231 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1232 } 1233 1234 // The CMP instruction is just an alias for SUBS, and representing it as 1235 // SUBS means that it's possible to get CSE with subtract operations. 1236 // A later phase can perform the optimization of setting the destination 1237 // register to WZR/XZR if it ends up being unused. 1238 unsigned Opcode = AArch64ISD::SUBS; 1239 1240 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 1241 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1242 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on 1243 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags 1244 // can be set differently by this operation. It comes down to whether 1245 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1246 // everything is fine. If not then the optimization is wrong. Thus general 1247 // comparisons are only valid if op2 != 0. 1248 1249 // So, finally, the only LLVM-native comparisons that don't mention C and V 1250 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1251 // the absence of information about op2. 1252 Opcode = AArch64ISD::ADDS; 1253 RHS = RHS.getOperand(1); 1254 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1255 !isUnsignedIntSetCC(CC)) { 1256 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1257 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1258 // of the signed comparisons. 1259 Opcode = AArch64ISD::ANDS; 1260 RHS = LHS.getOperand(1); 1261 LHS = LHS.getOperand(0); 1262 } 1263 1264 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1265 .getValue(1); 1266 } 1267 1268 /// \defgroup AArch64CCMP CMP;CCMP matching 1269 /// 1270 /// These functions deal with the formation of CMP;CCMP;... sequences. 1271 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1272 /// a comparison. They set the NZCV flags to a predefined value if their 1273 /// predicate is false. This allows to express arbitrary conjunctions, for 1274 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))" 1275 /// expressed as: 1276 /// cmp A 1277 /// ccmp B, inv(CB), CA 1278 /// check for CB flags 1279 /// 1280 /// In general we can create code for arbitrary "... (and (and A B) C)" 1281 /// sequences. We can also implement some "or" expressions, because "(or A B)" 1282 /// is equivalent to "not (and (not A) (not B))" and we can implement some 1283 /// negation operations: 1284 /// We can negate the results of a single comparison by inverting the flags 1285 /// used when the predicate fails and inverting the flags tested in the next 1286 /// instruction; We can also negate the results of the whole previous 1287 /// conditional compare sequence by inverting the flags tested in the next 1288 /// instruction. However there is no way to negate the result of a partial 1289 /// sequence. 1290 /// 1291 /// Therefore on encountering an "or" expression we can negate the subtree on 1292 /// one side and have to be able to push the negate to the leafs of the subtree 1293 /// on the other side (see also the comments in code). As complete example: 1294 /// "or (or (setCA (cmp A)) (setCB (cmp B))) 1295 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1296 /// is transformed to 1297 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D)))) 1298 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1299 /// and implemented as: 1300 /// cmp C 1301 /// ccmp D, inv(CD), CC 1302 /// ccmp A, CA, inv(CD) 1303 /// ccmp B, CB, inv(CA) 1304 /// check for CB flags 1305 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented 1306 /// by conditional compare sequences. 1307 /// @{ 1308 1309 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1310 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1311 ISD::CondCode CC, SDValue CCOp, 1312 AArch64CC::CondCode Predicate, 1313 AArch64CC::CondCode OutCC, 1314 SDLoc DL, SelectionDAG &DAG) { 1315 unsigned Opcode = 0; 1316 if (LHS.getValueType().isFloatingPoint()) { 1317 assert(LHS.getValueType() != MVT::f128); 1318 if (LHS.getValueType() == MVT::f16) { 1319 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1320 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1321 } 1322 Opcode = AArch64ISD::FCCMP; 1323 } else if (RHS.getOpcode() == ISD::SUB) { 1324 SDValue SubOp0 = RHS.getOperand(0); 1325 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1326 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1327 Opcode = AArch64ISD::CCMN; 1328 RHS = RHS.getOperand(1); 1329 } 1330 } 1331 if (Opcode == 0) 1332 Opcode = AArch64ISD::CCMP; 1333 1334 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1335 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1336 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1337 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1338 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1339 } 1340 1341 /// Returns true if @p Val is a tree of AND/OR/SETCC operations. 1342 /// CanPushNegate is set to true if we can push a negate operation through 1343 /// the tree in a was that we are left with AND operations and negate operations 1344 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to 1345 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be 1346 /// brought into such a form. 1347 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate, 1348 unsigned Depth = 0) { 1349 if (!Val.hasOneUse()) 1350 return false; 1351 unsigned Opcode = Val->getOpcode(); 1352 if (Opcode == ISD::SETCC) { 1353 if (Val->getOperand(0).getValueType() == MVT::f128) 1354 return false; 1355 CanNegate = true; 1356 return true; 1357 } 1358 // Protect against exponential runtime and stack overflow. 1359 if (Depth > 6) 1360 return false; 1361 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1362 SDValue O0 = Val->getOperand(0); 1363 SDValue O1 = Val->getOperand(1); 1364 bool CanNegateL; 1365 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1)) 1366 return false; 1367 bool CanNegateR; 1368 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1)) 1369 return false; 1370 1371 if (Opcode == ISD::OR) { 1372 // For an OR expression we need to be able to negate at least one side or 1373 // we cannot do the transformation at all. 1374 if (!CanNegateL && !CanNegateR) 1375 return false; 1376 // We can however change a (not (or x y)) to (and (not x) (not y)) if we 1377 // can negate the x and y subtrees. 1378 CanNegate = CanNegateL && CanNegateR; 1379 } else { 1380 // If the operands are OR expressions then we finally need to negate their 1381 // outputs, we can only do that for the operand with emitted last by 1382 // negating OutCC, not for both operands. 1383 bool NeedsNegOutL = O0->getOpcode() == ISD::OR; 1384 bool NeedsNegOutR = O1->getOpcode() == ISD::OR; 1385 if (NeedsNegOutL && NeedsNegOutR) 1386 return false; 1387 // We cannot negate an AND operation (it would become an OR), 1388 CanNegate = false; 1389 } 1390 return true; 1391 } 1392 return false; 1393 } 1394 1395 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1396 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1397 /// Tries to transform the given i1 producing node @p Val to a series compare 1398 /// and conditional compare operations. @returns an NZCV flags producing node 1399 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1400 /// transformation was not possible. 1401 /// On recursive invocations @p PushNegate may be set to true to have negation 1402 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate 1403 /// for the comparisons in the current subtree; @p Depth limits the search 1404 /// depth to avoid stack overflow. 1405 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val, 1406 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1407 AArch64CC::CondCode Predicate) { 1408 // We're at a tree leaf, produce a conditional comparison operation. 1409 unsigned Opcode = Val->getOpcode(); 1410 if (Opcode == ISD::SETCC) { 1411 SDValue LHS = Val->getOperand(0); 1412 SDValue RHS = Val->getOperand(1); 1413 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1414 bool isInteger = LHS.getValueType().isInteger(); 1415 if (Negate) 1416 CC = getSetCCInverse(CC, isInteger); 1417 SDLoc DL(Val); 1418 // Determine OutCC and handle FP special case. 1419 if (isInteger) { 1420 OutCC = changeIntCCToAArch64CC(CC); 1421 } else { 1422 assert(LHS.getValueType().isFloatingPoint()); 1423 AArch64CC::CondCode ExtraCC; 1424 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1425 // Some floating point conditions can't be tested with a single condition 1426 // code. Construct an additional comparison in this case. 1427 if (ExtraCC != AArch64CC::AL) { 1428 SDValue ExtraCmp; 1429 if (!CCOp.getNode()) 1430 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1431 else 1432 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1433 ExtraCC, DL, DAG); 1434 CCOp = ExtraCmp; 1435 Predicate = ExtraCC; 1436 } 1437 } 1438 1439 // Produce a normal comparison if we are first in the chain 1440 if (!CCOp) 1441 return emitComparison(LHS, RHS, CC, DL, DAG); 1442 // Otherwise produce a ccmp. 1443 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1444 DAG); 1445 } 1446 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) && 1447 "Valid conjunction/disjunction tree"); 1448 1449 // Check if both sides can be transformed. 1450 SDValue LHS = Val->getOperand(0); 1451 SDValue RHS = Val->getOperand(1); 1452 1453 // In case of an OR we need to negate our operands and the result. 1454 // (A v B) <=> not(not(A) ^ not(B)) 1455 bool NegateOpsAndResult = Opcode == ISD::OR; 1456 // We can negate the results of all previous operations by inverting the 1457 // predicate flags giving us a free negation for one side. The other side 1458 // must be negatable by itself. 1459 if (NegateOpsAndResult) { 1460 // See which side we can negate. 1461 bool CanNegateL; 1462 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL); 1463 assert(isValidL && "Valid conjunction/disjunction tree"); 1464 (void)isValidL; 1465 1466 #ifndef NDEBUG 1467 bool CanNegateR; 1468 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR); 1469 assert(isValidR && "Valid conjunction/disjunction tree"); 1470 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree"); 1471 #endif 1472 1473 // Order the side which we cannot negate to RHS so we can emit it first. 1474 if (!CanNegateL) 1475 std::swap(LHS, RHS); 1476 } else { 1477 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR; 1478 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) && 1479 "Valid conjunction/disjunction tree"); 1480 // Order the side where we need to negate the output flags to RHS so it 1481 // gets emitted first. 1482 if (NeedsNegOutL) 1483 std::swap(LHS, RHS); 1484 } 1485 1486 // Emit RHS. If we want to negate the tree we only need to push a negate 1487 // through if we are already in a PushNegate case, otherwise we can negate 1488 // the "flags to test" afterwards. 1489 AArch64CC::CondCode RHSCC; 1490 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate, 1491 CCOp, Predicate); 1492 if (NegateOpsAndResult && !Negate) 1493 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1494 // Emit LHS. We may need to negate it. 1495 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC, 1496 NegateOpsAndResult, CmpR, 1497 RHSCC); 1498 // If we transformed an OR to and AND then we have to negate the result 1499 // (or absorb the Negate parameter). 1500 if (NegateOpsAndResult && !Negate) 1501 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1502 return CmpL; 1503 } 1504 1505 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1506 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1507 /// \see emitConjunctionDisjunctionTreeRec(). 1508 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val, 1509 AArch64CC::CondCode &OutCC) { 1510 bool CanNegate; 1511 if (!isConjunctionDisjunctionTree(Val, CanNegate)) 1512 return SDValue(); 1513 1514 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(), 1515 AArch64CC::AL); 1516 } 1517 1518 /// @} 1519 1520 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1521 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) { 1522 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1523 EVT VT = RHS.getValueType(); 1524 uint64_t C = RHSC->getZExtValue(); 1525 if (!isLegalArithImmed(C)) { 1526 // Constant does not fit, try adjusting it by one? 1527 switch (CC) { 1528 default: 1529 break; 1530 case ISD::SETLT: 1531 case ISD::SETGE: 1532 if ((VT == MVT::i32 && C != 0x80000000 && 1533 isLegalArithImmed((uint32_t)(C - 1))) || 1534 (VT == MVT::i64 && C != 0x80000000ULL && 1535 isLegalArithImmed(C - 1ULL))) { 1536 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1537 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1538 RHS = DAG.getConstant(C, dl, VT); 1539 } 1540 break; 1541 case ISD::SETULT: 1542 case ISD::SETUGE: 1543 if ((VT == MVT::i32 && C != 0 && 1544 isLegalArithImmed((uint32_t)(C - 1))) || 1545 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1546 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1547 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1548 RHS = DAG.getConstant(C, dl, VT); 1549 } 1550 break; 1551 case ISD::SETLE: 1552 case ISD::SETGT: 1553 if ((VT == MVT::i32 && C != INT32_MAX && 1554 isLegalArithImmed((uint32_t)(C + 1))) || 1555 (VT == MVT::i64 && C != INT64_MAX && 1556 isLegalArithImmed(C + 1ULL))) { 1557 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1558 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1559 RHS = DAG.getConstant(C, dl, VT); 1560 } 1561 break; 1562 case ISD::SETULE: 1563 case ISD::SETUGT: 1564 if ((VT == MVT::i32 && C != UINT32_MAX && 1565 isLegalArithImmed((uint32_t)(C + 1))) || 1566 (VT == MVT::i64 && C != UINT64_MAX && 1567 isLegalArithImmed(C + 1ULL))) { 1568 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1569 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1570 RHS = DAG.getConstant(C, dl, VT); 1571 } 1572 break; 1573 } 1574 } 1575 } 1576 SDValue Cmp; 1577 AArch64CC::CondCode AArch64CC; 1578 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1579 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1580 1581 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1582 // For the i8 operand, the largest immediate is 255, so this can be easily 1583 // encoded in the compare instruction. For the i16 operand, however, the 1584 // largest immediate cannot be encoded in the compare. 1585 // Therefore, use a sign extending load and cmn to avoid materializing the 1586 // -1 constant. For example, 1587 // movz w1, #65535 1588 // ldrh w0, [x0, #0] 1589 // cmp w0, w1 1590 // > 1591 // ldrsh w0, [x0, #0] 1592 // cmn w0, #1 1593 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1594 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1595 // ensure both the LHS and RHS are truly zero extended and to make sure the 1596 // transformation is profitable. 1597 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1598 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1599 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1600 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1601 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1602 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1603 SDValue SExt = 1604 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1605 DAG.getValueType(MVT::i16)); 1606 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1607 RHS.getValueType()), 1608 CC, dl, DAG); 1609 AArch64CC = changeIntCCToAArch64CC(CC); 1610 } 1611 } 1612 1613 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 1614 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) { 1615 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 1616 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 1617 } 1618 } 1619 } 1620 1621 if (!Cmp) { 1622 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 1623 AArch64CC = changeIntCCToAArch64CC(CC); 1624 } 1625 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 1626 return Cmp; 1627 } 1628 1629 // Attempt to form conditional compare sequences for and/or trees 1630 // with setcc leafs. 1631 static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) { 1632 SDValue LHS = Op.getOperand(0); 1633 SDValue RHS = Op.getOperand(1); 1634 if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC)) 1635 return Op; 1636 1637 bool CanNegate; 1638 if (!isConjunctionDisjunctionTree(Op, CanNegate)) 1639 return SDValue(); 1640 1641 EVT VT = Op.getValueType(); 1642 SDLoc DL(Op); 1643 SDValue TVal = DAG.getConstant(1, DL, VT); 1644 SDValue FVal = DAG.getConstant(0, DL, VT); 1645 SDValue CCVal; 1646 SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL); 1647 return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp); 1648 } 1649 1650 static std::pair<SDValue, SDValue> 1651 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 1652 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 1653 "Unsupported value type"); 1654 SDValue Value, Overflow; 1655 SDLoc DL(Op); 1656 SDValue LHS = Op.getOperand(0); 1657 SDValue RHS = Op.getOperand(1); 1658 unsigned Opc = 0; 1659 switch (Op.getOpcode()) { 1660 default: 1661 llvm_unreachable("Unknown overflow instruction!"); 1662 case ISD::SADDO: 1663 Opc = AArch64ISD::ADDS; 1664 CC = AArch64CC::VS; 1665 break; 1666 case ISD::UADDO: 1667 Opc = AArch64ISD::ADDS; 1668 CC = AArch64CC::HS; 1669 break; 1670 case ISD::SSUBO: 1671 Opc = AArch64ISD::SUBS; 1672 CC = AArch64CC::VS; 1673 break; 1674 case ISD::USUBO: 1675 Opc = AArch64ISD::SUBS; 1676 CC = AArch64CC::LO; 1677 break; 1678 // Multiply needs a little bit extra work. 1679 case ISD::SMULO: 1680 case ISD::UMULO: { 1681 CC = AArch64CC::NE; 1682 bool IsSigned = Op.getOpcode() == ISD::SMULO; 1683 if (Op.getValueType() == MVT::i32) { 1684 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1685 // For a 32 bit multiply with overflow check we want the instruction 1686 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 1687 // need to generate the following pattern: 1688 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 1689 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 1690 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 1691 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1692 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 1693 DAG.getConstant(0, DL, MVT::i64)); 1694 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 1695 // operation. We need to clear out the upper 32 bits, because we used a 1696 // widening multiply that wrote all 64 bits. In the end this should be a 1697 // noop. 1698 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 1699 if (IsSigned) { 1700 // The signed overflow check requires more than just a simple check for 1701 // any bit set in the upper 32 bits of the result. These bits could be 1702 // just the sign bits of a negative number. To perform the overflow 1703 // check we have to arithmetic shift right the 32nd bit of the result by 1704 // 31 bits. Then we compare the result to the upper 32 bits. 1705 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 1706 DAG.getConstant(32, DL, MVT::i64)); 1707 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 1708 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 1709 DAG.getConstant(31, DL, MVT::i64)); 1710 // It is important that LowerBits is last, otherwise the arithmetic 1711 // shift will not be folded into the compare (SUBS). 1712 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 1713 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1714 .getValue(1); 1715 } else { 1716 // The overflow check for unsigned multiply is easy. We only need to 1717 // check if any of the upper 32 bits are set. This can be done with a 1718 // CMP (shifted register). For that we need to generate the following 1719 // pattern: 1720 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 1721 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 1722 DAG.getConstant(32, DL, MVT::i64)); 1723 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1724 Overflow = 1725 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1726 DAG.getConstant(0, DL, MVT::i64), 1727 UpperBits).getValue(1); 1728 } 1729 break; 1730 } 1731 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 1732 // For the 64 bit multiply 1733 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1734 if (IsSigned) { 1735 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 1736 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 1737 DAG.getConstant(63, DL, MVT::i64)); 1738 // It is important that LowerBits is last, otherwise the arithmetic 1739 // shift will not be folded into the compare (SUBS). 1740 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1741 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1742 .getValue(1); 1743 } else { 1744 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 1745 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1746 Overflow = 1747 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1748 DAG.getConstant(0, DL, MVT::i64), 1749 UpperBits).getValue(1); 1750 } 1751 break; 1752 } 1753 } // switch (...) 1754 1755 if (Opc) { 1756 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 1757 1758 // Emit the AArch64 operation with overflow check. 1759 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 1760 Overflow = Value.getValue(1); 1761 } 1762 return std::make_pair(Value, Overflow); 1763 } 1764 1765 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 1766 RTLIB::Libcall Call) const { 1767 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1768 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 1769 } 1770 1771 SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const { 1772 if (Op.getValueType().isVector()) 1773 return LowerVectorAND(Op, DAG); 1774 return tryLowerToAArch64Cmp(Op, DAG); 1775 } 1776 1777 SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const { 1778 if (Op.getValueType().isVector()) 1779 return LowerVectorOR(Op, DAG); 1780 return tryLowerToAArch64Cmp(Op, DAG); 1781 } 1782 1783 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1784 SDValue Sel = Op.getOperand(0); 1785 SDValue Other = Op.getOperand(1); 1786 1787 // If neither operand is a SELECT_CC, give up. 1788 if (Sel.getOpcode() != ISD::SELECT_CC) 1789 std::swap(Sel, Other); 1790 if (Sel.getOpcode() != ISD::SELECT_CC) 1791 return Op; 1792 1793 // The folding we want to perform is: 1794 // (xor x, (select_cc a, b, cc, 0, -1) ) 1795 // --> 1796 // (csel x, (xor x, -1), cc ...) 1797 // 1798 // The latter will get matched to a CSINV instruction. 1799 1800 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 1801 SDValue LHS = Sel.getOperand(0); 1802 SDValue RHS = Sel.getOperand(1); 1803 SDValue TVal = Sel.getOperand(2); 1804 SDValue FVal = Sel.getOperand(3); 1805 SDLoc dl(Sel); 1806 1807 // FIXME: This could be generalized to non-integer comparisons. 1808 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 1809 return Op; 1810 1811 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 1812 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 1813 1814 // The values aren't constants, this isn't the pattern we're looking for. 1815 if (!CFVal || !CTVal) 1816 return Op; 1817 1818 // We can commute the SELECT_CC by inverting the condition. This 1819 // might be needed to make this fit into a CSINV pattern. 1820 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 1821 std::swap(TVal, FVal); 1822 std::swap(CTVal, CFVal); 1823 CC = ISD::getSetCCInverse(CC, true); 1824 } 1825 1826 // If the constants line up, perform the transform! 1827 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 1828 SDValue CCVal; 1829 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 1830 1831 FVal = Other; 1832 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 1833 DAG.getConstant(-1ULL, dl, Other.getValueType())); 1834 1835 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 1836 CCVal, Cmp); 1837 } 1838 1839 return Op; 1840 } 1841 1842 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 1843 EVT VT = Op.getValueType(); 1844 1845 // Let legalize expand this if it isn't a legal type yet. 1846 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 1847 return SDValue(); 1848 1849 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 1850 1851 unsigned Opc; 1852 bool ExtraOp = false; 1853 switch (Op.getOpcode()) { 1854 default: 1855 llvm_unreachable("Invalid code"); 1856 case ISD::ADDC: 1857 Opc = AArch64ISD::ADDS; 1858 break; 1859 case ISD::SUBC: 1860 Opc = AArch64ISD::SUBS; 1861 break; 1862 case ISD::ADDE: 1863 Opc = AArch64ISD::ADCS; 1864 ExtraOp = true; 1865 break; 1866 case ISD::SUBE: 1867 Opc = AArch64ISD::SBCS; 1868 ExtraOp = true; 1869 break; 1870 } 1871 1872 if (!ExtraOp) 1873 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 1874 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 1875 Op.getOperand(2)); 1876 } 1877 1878 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 1879 // Let legalize expand this if it isn't a legal type yet. 1880 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 1881 return SDValue(); 1882 1883 SDLoc dl(Op); 1884 AArch64CC::CondCode CC; 1885 // The actual operation that sets the overflow or carry flag. 1886 SDValue Value, Overflow; 1887 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 1888 1889 // We use 0 and 1 as false and true values. 1890 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 1891 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 1892 1893 // We use an inverted condition, because the conditional select is inverted 1894 // too. This will allow it to be selected to a single instruction: 1895 // CSINC Wd, WZR, WZR, invert(cond). 1896 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 1897 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 1898 CCVal, Overflow); 1899 1900 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 1901 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 1902 } 1903 1904 // Prefetch operands are: 1905 // 1: Address to prefetch 1906 // 2: bool isWrite 1907 // 3: int locality (0 = no locality ... 3 = extreme locality) 1908 // 4: bool isDataCache 1909 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 1910 SDLoc DL(Op); 1911 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 1912 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 1913 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 1914 1915 bool IsStream = !Locality; 1916 // When the locality number is set 1917 if (Locality) { 1918 // The front-end should have filtered out the out-of-range values 1919 assert(Locality <= 3 && "Prefetch locality out-of-range"); 1920 // The locality degree is the opposite of the cache speed. 1921 // Put the number the other way around. 1922 // The encoding starts at 0 for level 1 1923 Locality = 3 - Locality; 1924 } 1925 1926 // built the mask value encoding the expected behavior. 1927 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 1928 (!IsData << 3) | // IsDataCache bit 1929 (Locality << 1) | // Cache level bits 1930 (unsigned)IsStream; // Stream bit 1931 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 1932 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 1933 } 1934 1935 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 1936 SelectionDAG &DAG) const { 1937 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 1938 1939 RTLIB::Libcall LC; 1940 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 1941 1942 return LowerF128Call(Op, DAG, LC); 1943 } 1944 1945 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 1946 SelectionDAG &DAG) const { 1947 if (Op.getOperand(0).getValueType() != MVT::f128) { 1948 // It's legal except when f128 is involved 1949 return Op; 1950 } 1951 1952 RTLIB::Libcall LC; 1953 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 1954 1955 // FP_ROUND node has a second operand indicating whether it is known to be 1956 // precise. That doesn't take part in the LibCall so we can't directly use 1957 // LowerF128Call. 1958 SDValue SrcVal = Op.getOperand(0); 1959 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 1960 SDLoc(Op)).first; 1961 } 1962 1963 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 1964 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 1965 // Any additional optimization in this function should be recorded 1966 // in the cost tables. 1967 EVT InVT = Op.getOperand(0).getValueType(); 1968 EVT VT = Op.getValueType(); 1969 unsigned NumElts = InVT.getVectorNumElements(); 1970 1971 // f16 vectors are promoted to f32 before a conversion. 1972 if (InVT.getVectorElementType() == MVT::f16) { 1973 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 1974 SDLoc dl(Op); 1975 return DAG.getNode( 1976 Op.getOpcode(), dl, Op.getValueType(), 1977 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 1978 } 1979 1980 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 1981 SDLoc dl(Op); 1982 SDValue Cv = 1983 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 1984 Op.getOperand(0)); 1985 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 1986 } 1987 1988 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 1989 SDLoc dl(Op); 1990 MVT ExtVT = 1991 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 1992 VT.getVectorNumElements()); 1993 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 1994 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 1995 } 1996 1997 // Type changing conversions are illegal. 1998 return Op; 1999 } 2000 2001 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2002 SelectionDAG &DAG) const { 2003 if (Op.getOperand(0).getValueType().isVector()) 2004 return LowerVectorFP_TO_INT(Op, DAG); 2005 2006 // f16 conversions are promoted to f32. 2007 if (Op.getOperand(0).getValueType() == MVT::f16) { 2008 SDLoc dl(Op); 2009 return DAG.getNode( 2010 Op.getOpcode(), dl, Op.getValueType(), 2011 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2012 } 2013 2014 if (Op.getOperand(0).getValueType() != MVT::f128) { 2015 // It's legal except when f128 is involved 2016 return Op; 2017 } 2018 2019 RTLIB::Libcall LC; 2020 if (Op.getOpcode() == ISD::FP_TO_SINT) 2021 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2022 else 2023 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2024 2025 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2026 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2027 } 2028 2029 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2030 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2031 // Any additional optimization in this function should be recorded 2032 // in the cost tables. 2033 EVT VT = Op.getValueType(); 2034 SDLoc dl(Op); 2035 SDValue In = Op.getOperand(0); 2036 EVT InVT = In.getValueType(); 2037 2038 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2039 MVT CastVT = 2040 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2041 InVT.getVectorNumElements()); 2042 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2043 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2044 } 2045 2046 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2047 unsigned CastOpc = 2048 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2049 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2050 In = DAG.getNode(CastOpc, dl, CastVT, In); 2051 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2052 } 2053 2054 return Op; 2055 } 2056 2057 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2058 SelectionDAG &DAG) const { 2059 if (Op.getValueType().isVector()) 2060 return LowerVectorINT_TO_FP(Op, DAG); 2061 2062 // f16 conversions are promoted to f32. 2063 if (Op.getValueType() == MVT::f16) { 2064 SDLoc dl(Op); 2065 return DAG.getNode( 2066 ISD::FP_ROUND, dl, MVT::f16, 2067 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2068 DAG.getIntPtrConstant(0, dl)); 2069 } 2070 2071 // i128 conversions are libcalls. 2072 if (Op.getOperand(0).getValueType() == MVT::i128) 2073 return SDValue(); 2074 2075 // Other conversions are legal, unless it's to the completely software-based 2076 // fp128. 2077 if (Op.getValueType() != MVT::f128) 2078 return Op; 2079 2080 RTLIB::Libcall LC; 2081 if (Op.getOpcode() == ISD::SINT_TO_FP) 2082 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2083 else 2084 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2085 2086 return LowerF128Call(Op, DAG, LC); 2087 } 2088 2089 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2090 SelectionDAG &DAG) const { 2091 // For iOS, we want to call an alternative entry point: __sincos_stret, 2092 // which returns the values in two S / D registers. 2093 SDLoc dl(Op); 2094 SDValue Arg = Op.getOperand(0); 2095 EVT ArgVT = Arg.getValueType(); 2096 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2097 2098 ArgListTy Args; 2099 ArgListEntry Entry; 2100 2101 Entry.Node = Arg; 2102 Entry.Ty = ArgTy; 2103 Entry.isSExt = false; 2104 Entry.isZExt = false; 2105 Args.push_back(Entry); 2106 2107 const char *LibcallName = 2108 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2109 SDValue Callee = 2110 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2111 2112 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 2113 TargetLowering::CallLoweringInfo CLI(DAG); 2114 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 2115 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0); 2116 2117 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2118 return CallResult.first; 2119 } 2120 2121 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2122 if (Op.getValueType() != MVT::f16) 2123 return SDValue(); 2124 2125 assert(Op.getOperand(0).getValueType() == MVT::i16); 2126 SDLoc DL(Op); 2127 2128 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2129 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2130 return SDValue( 2131 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2132 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2133 0); 2134 } 2135 2136 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2137 if (OrigVT.getSizeInBits() >= 64) 2138 return OrigVT; 2139 2140 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2141 2142 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2143 switch (OrigSimpleTy) { 2144 default: llvm_unreachable("Unexpected Vector Type"); 2145 case MVT::v2i8: 2146 case MVT::v2i16: 2147 return MVT::v2i32; 2148 case MVT::v4i8: 2149 return MVT::v4i16; 2150 } 2151 } 2152 2153 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2154 const EVT &OrigTy, 2155 const EVT &ExtTy, 2156 unsigned ExtOpcode) { 2157 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2158 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2159 // 64-bits we need to insert a new extension so that it will be 64-bits. 2160 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2161 if (OrigTy.getSizeInBits() >= 64) 2162 return N; 2163 2164 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2165 EVT NewVT = getExtensionTo64Bits(OrigTy); 2166 2167 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2168 } 2169 2170 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2171 bool isSigned) { 2172 EVT VT = N->getValueType(0); 2173 2174 if (N->getOpcode() != ISD::BUILD_VECTOR) 2175 return false; 2176 2177 for (const SDValue &Elt : N->op_values()) { 2178 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2179 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 2180 unsigned HalfSize = EltSize / 2; 2181 if (isSigned) { 2182 if (!isIntN(HalfSize, C->getSExtValue())) 2183 return false; 2184 } else { 2185 if (!isUIntN(HalfSize, C->getZExtValue())) 2186 return false; 2187 } 2188 continue; 2189 } 2190 return false; 2191 } 2192 2193 return true; 2194 } 2195 2196 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2197 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2198 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2199 N->getOperand(0)->getValueType(0), 2200 N->getValueType(0), 2201 N->getOpcode()); 2202 2203 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2204 EVT VT = N->getValueType(0); 2205 SDLoc dl(N); 2206 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 2207 unsigned NumElts = VT.getVectorNumElements(); 2208 MVT TruncVT = MVT::getIntegerVT(EltSize); 2209 SmallVector<SDValue, 8> Ops; 2210 for (unsigned i = 0; i != NumElts; ++i) { 2211 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2212 const APInt &CInt = C->getAPIntValue(); 2213 // Element types smaller than 32 bits are not legal, so use i32 elements. 2214 // The values are implicitly truncated so sext vs. zext doesn't matter. 2215 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2216 } 2217 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2218 } 2219 2220 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2221 if (N->getOpcode() == ISD::SIGN_EXTEND) 2222 return true; 2223 if (isExtendedBUILD_VECTOR(N, DAG, true)) 2224 return true; 2225 return false; 2226 } 2227 2228 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2229 if (N->getOpcode() == ISD::ZERO_EXTEND) 2230 return true; 2231 if (isExtendedBUILD_VECTOR(N, DAG, false)) 2232 return true; 2233 return false; 2234 } 2235 2236 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2237 unsigned Opcode = N->getOpcode(); 2238 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2239 SDNode *N0 = N->getOperand(0).getNode(); 2240 SDNode *N1 = N->getOperand(1).getNode(); 2241 return N0->hasOneUse() && N1->hasOneUse() && 2242 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2243 } 2244 return false; 2245 } 2246 2247 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2248 unsigned Opcode = N->getOpcode(); 2249 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2250 SDNode *N0 = N->getOperand(0).getNode(); 2251 SDNode *N1 = N->getOperand(1).getNode(); 2252 return N0->hasOneUse() && N1->hasOneUse() && 2253 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2254 } 2255 return false; 2256 } 2257 2258 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2259 // Multiplications are only custom-lowered for 128-bit vectors so that 2260 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2261 EVT VT = Op.getValueType(); 2262 assert(VT.is128BitVector() && VT.isInteger() && 2263 "unexpected type for custom-lowering ISD::MUL"); 2264 SDNode *N0 = Op.getOperand(0).getNode(); 2265 SDNode *N1 = Op.getOperand(1).getNode(); 2266 unsigned NewOpc = 0; 2267 bool isMLA = false; 2268 bool isN0SExt = isSignExtended(N0, DAG); 2269 bool isN1SExt = isSignExtended(N1, DAG); 2270 if (isN0SExt && isN1SExt) 2271 NewOpc = AArch64ISD::SMULL; 2272 else { 2273 bool isN0ZExt = isZeroExtended(N0, DAG); 2274 bool isN1ZExt = isZeroExtended(N1, DAG); 2275 if (isN0ZExt && isN1ZExt) 2276 NewOpc = AArch64ISD::UMULL; 2277 else if (isN1SExt || isN1ZExt) { 2278 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2279 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2280 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2281 NewOpc = AArch64ISD::SMULL; 2282 isMLA = true; 2283 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2284 NewOpc = AArch64ISD::UMULL; 2285 isMLA = true; 2286 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2287 std::swap(N0, N1); 2288 NewOpc = AArch64ISD::UMULL; 2289 isMLA = true; 2290 } 2291 } 2292 2293 if (!NewOpc) { 2294 if (VT == MVT::v2i64) 2295 // Fall through to expand this. It is not legal. 2296 return SDValue(); 2297 else 2298 // Other vector multiplications are legal. 2299 return Op; 2300 } 2301 } 2302 2303 // Legalize to a S/UMULL instruction 2304 SDLoc DL(Op); 2305 SDValue Op0; 2306 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2307 if (!isMLA) { 2308 Op0 = skipExtensionForVectorMULL(N0, DAG); 2309 assert(Op0.getValueType().is64BitVector() && 2310 Op1.getValueType().is64BitVector() && 2311 "unexpected types for extended operands to VMULL"); 2312 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2313 } 2314 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2315 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2316 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2317 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2318 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2319 EVT Op1VT = Op1.getValueType(); 2320 return DAG.getNode(N0->getOpcode(), DL, VT, 2321 DAG.getNode(NewOpc, DL, VT, 2322 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2323 DAG.getNode(NewOpc, DL, VT, 2324 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2325 } 2326 2327 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2328 SelectionDAG &DAG) const { 2329 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2330 SDLoc dl(Op); 2331 switch (IntNo) { 2332 default: return SDValue(); // Don't custom lower most intrinsics. 2333 case Intrinsic::thread_pointer: { 2334 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2335 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2336 } 2337 case Intrinsic::aarch64_neon_smax: 2338 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2339 Op.getOperand(1), Op.getOperand(2)); 2340 case Intrinsic::aarch64_neon_umax: 2341 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2342 Op.getOperand(1), Op.getOperand(2)); 2343 case Intrinsic::aarch64_neon_smin: 2344 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2345 Op.getOperand(1), Op.getOperand(2)); 2346 case Intrinsic::aarch64_neon_umin: 2347 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2348 Op.getOperand(1), Op.getOperand(2)); 2349 } 2350 } 2351 2352 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2353 SelectionDAG &DAG) const { 2354 switch (Op.getOpcode()) { 2355 default: 2356 llvm_unreachable("unimplemented operand"); 2357 return SDValue(); 2358 case ISD::BITCAST: 2359 return LowerBITCAST(Op, DAG); 2360 case ISD::GlobalAddress: 2361 return LowerGlobalAddress(Op, DAG); 2362 case ISD::GlobalTLSAddress: 2363 return LowerGlobalTLSAddress(Op, DAG); 2364 case ISD::SETCC: 2365 return LowerSETCC(Op, DAG); 2366 case ISD::BR_CC: 2367 return LowerBR_CC(Op, DAG); 2368 case ISD::SELECT: 2369 return LowerSELECT(Op, DAG); 2370 case ISD::SELECT_CC: 2371 return LowerSELECT_CC(Op, DAG); 2372 case ISD::JumpTable: 2373 return LowerJumpTable(Op, DAG); 2374 case ISD::ConstantPool: 2375 return LowerConstantPool(Op, DAG); 2376 case ISD::BlockAddress: 2377 return LowerBlockAddress(Op, DAG); 2378 case ISD::VASTART: 2379 return LowerVASTART(Op, DAG); 2380 case ISD::VACOPY: 2381 return LowerVACOPY(Op, DAG); 2382 case ISD::VAARG: 2383 return LowerVAARG(Op, DAG); 2384 case ISD::ADDC: 2385 case ISD::ADDE: 2386 case ISD::SUBC: 2387 case ISD::SUBE: 2388 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2389 case ISD::SADDO: 2390 case ISD::UADDO: 2391 case ISD::SSUBO: 2392 case ISD::USUBO: 2393 case ISD::SMULO: 2394 case ISD::UMULO: 2395 return LowerXALUO(Op, DAG); 2396 case ISD::FADD: 2397 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2398 case ISD::FSUB: 2399 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2400 case ISD::FMUL: 2401 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2402 case ISD::FDIV: 2403 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2404 case ISD::FP_ROUND: 2405 return LowerFP_ROUND(Op, DAG); 2406 case ISD::FP_EXTEND: 2407 return LowerFP_EXTEND(Op, DAG); 2408 case ISD::FRAMEADDR: 2409 return LowerFRAMEADDR(Op, DAG); 2410 case ISD::RETURNADDR: 2411 return LowerRETURNADDR(Op, DAG); 2412 case ISD::INSERT_VECTOR_ELT: 2413 return LowerINSERT_VECTOR_ELT(Op, DAG); 2414 case ISD::EXTRACT_VECTOR_ELT: 2415 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2416 case ISD::BUILD_VECTOR: 2417 return LowerBUILD_VECTOR(Op, DAG); 2418 case ISD::VECTOR_SHUFFLE: 2419 return LowerVECTOR_SHUFFLE(Op, DAG); 2420 case ISD::EXTRACT_SUBVECTOR: 2421 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2422 case ISD::SRA: 2423 case ISD::SRL: 2424 case ISD::SHL: 2425 return LowerVectorSRA_SRL_SHL(Op, DAG); 2426 case ISD::SHL_PARTS: 2427 return LowerShiftLeftParts(Op, DAG); 2428 case ISD::SRL_PARTS: 2429 case ISD::SRA_PARTS: 2430 return LowerShiftRightParts(Op, DAG); 2431 case ISD::CTPOP: 2432 return LowerCTPOP(Op, DAG); 2433 case ISD::FCOPYSIGN: 2434 return LowerFCOPYSIGN(Op, DAG); 2435 case ISD::AND: 2436 return LowerAND(Op, DAG); 2437 case ISD::OR: 2438 return LowerOR(Op, DAG); 2439 case ISD::XOR: 2440 return LowerXOR(Op, DAG); 2441 case ISD::PREFETCH: 2442 return LowerPREFETCH(Op, DAG); 2443 case ISD::SINT_TO_FP: 2444 case ISD::UINT_TO_FP: 2445 return LowerINT_TO_FP(Op, DAG); 2446 case ISD::FP_TO_SINT: 2447 case ISD::FP_TO_UINT: 2448 return LowerFP_TO_INT(Op, DAG); 2449 case ISD::FSINCOS: 2450 return LowerFSINCOS(Op, DAG); 2451 case ISD::MUL: 2452 return LowerMUL(Op, DAG); 2453 case ISD::INTRINSIC_WO_CHAIN: 2454 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2455 } 2456 } 2457 2458 //===----------------------------------------------------------------------===// 2459 // Calling Convention Implementation 2460 //===----------------------------------------------------------------------===// 2461 2462 #include "AArch64GenCallingConv.inc" 2463 2464 /// Selects the correct CCAssignFn for a given CallingConvention value. 2465 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2466 bool IsVarArg) const { 2467 switch (CC) { 2468 default: 2469 llvm_unreachable("Unsupported calling convention."); 2470 case CallingConv::WebKit_JS: 2471 return CC_AArch64_WebKit_JS; 2472 case CallingConv::GHC: 2473 return CC_AArch64_GHC; 2474 case CallingConv::C: 2475 case CallingConv::Fast: 2476 case CallingConv::PreserveMost: 2477 case CallingConv::CXX_FAST_TLS: 2478 if (!Subtarget->isTargetDarwin()) 2479 return CC_AArch64_AAPCS; 2480 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2481 } 2482 } 2483 2484 SDValue AArch64TargetLowering::LowerFormalArguments( 2485 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2486 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG, 2487 SmallVectorImpl<SDValue> &InVals) const { 2488 MachineFunction &MF = DAG.getMachineFunction(); 2489 MachineFrameInfo *MFI = MF.getFrameInfo(); 2490 2491 // Assign locations to all of the incoming arguments. 2492 SmallVector<CCValAssign, 16> ArgLocs; 2493 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2494 *DAG.getContext()); 2495 2496 // At this point, Ins[].VT may already be promoted to i32. To correctly 2497 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2498 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2499 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2500 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2501 // LocVT. 2502 unsigned NumArgs = Ins.size(); 2503 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2504 unsigned CurArgIdx = 0; 2505 for (unsigned i = 0; i != NumArgs; ++i) { 2506 MVT ValVT = Ins[i].VT; 2507 if (Ins[i].isOrigArg()) { 2508 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2509 CurArgIdx = Ins[i].getOrigArgIndex(); 2510 2511 // Get type of the original argument. 2512 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2513 /*AllowUnknown*/ true); 2514 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2515 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2516 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2517 ValVT = MVT::i8; 2518 else if (ActualMVT == MVT::i16) 2519 ValVT = MVT::i16; 2520 } 2521 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2522 bool Res = 2523 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2524 assert(!Res && "Call operand has unhandled type"); 2525 (void)Res; 2526 } 2527 assert(ArgLocs.size() == Ins.size()); 2528 SmallVector<SDValue, 16> ArgValues; 2529 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2530 CCValAssign &VA = ArgLocs[i]; 2531 2532 if (Ins[i].Flags.isByVal()) { 2533 // Byval is used for HFAs in the PCS, but the system should work in a 2534 // non-compliant manner for larger structs. 2535 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2536 int Size = Ins[i].Flags.getByValSize(); 2537 unsigned NumRegs = (Size + 7) / 8; 2538 2539 // FIXME: This works on big-endian for composite byvals, which are the common 2540 // case. It should also work for fundamental types too. 2541 unsigned FrameIdx = 2542 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2543 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2544 InVals.push_back(FrameIdxN); 2545 2546 continue; 2547 } 2548 2549 if (VA.isRegLoc()) { 2550 // Arguments stored in registers. 2551 EVT RegVT = VA.getLocVT(); 2552 2553 SDValue ArgValue; 2554 const TargetRegisterClass *RC; 2555 2556 if (RegVT == MVT::i32) 2557 RC = &AArch64::GPR32RegClass; 2558 else if (RegVT == MVT::i64) 2559 RC = &AArch64::GPR64RegClass; 2560 else if (RegVT == MVT::f16) 2561 RC = &AArch64::FPR16RegClass; 2562 else if (RegVT == MVT::f32) 2563 RC = &AArch64::FPR32RegClass; 2564 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2565 RC = &AArch64::FPR64RegClass; 2566 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2567 RC = &AArch64::FPR128RegClass; 2568 else 2569 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2570 2571 // Transform the arguments in physical registers into virtual ones. 2572 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2573 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2574 2575 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2576 // to 64 bits. Insert an assert[sz]ext to capture this, then 2577 // truncate to the right size. 2578 switch (VA.getLocInfo()) { 2579 default: 2580 llvm_unreachable("Unknown loc info!"); 2581 case CCValAssign::Full: 2582 break; 2583 case CCValAssign::BCvt: 2584 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2585 break; 2586 case CCValAssign::AExt: 2587 case CCValAssign::SExt: 2588 case CCValAssign::ZExt: 2589 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2590 // nodes after our lowering. 2591 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2592 break; 2593 } 2594 2595 InVals.push_back(ArgValue); 2596 2597 } else { // VA.isRegLoc() 2598 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2599 unsigned ArgOffset = VA.getLocMemOffset(); 2600 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2601 2602 uint32_t BEAlign = 0; 2603 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2604 !Ins[i].Flags.isInConsecutiveRegs()) 2605 BEAlign = 8 - ArgSize; 2606 2607 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2608 2609 // Create load nodes to retrieve arguments from the stack. 2610 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2611 SDValue ArgValue; 2612 2613 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2614 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2615 MVT MemVT = VA.getValVT(); 2616 2617 switch (VA.getLocInfo()) { 2618 default: 2619 break; 2620 case CCValAssign::BCvt: 2621 MemVT = VA.getLocVT(); 2622 break; 2623 case CCValAssign::SExt: 2624 ExtType = ISD::SEXTLOAD; 2625 break; 2626 case CCValAssign::ZExt: 2627 ExtType = ISD::ZEXTLOAD; 2628 break; 2629 case CCValAssign::AExt: 2630 ExtType = ISD::EXTLOAD; 2631 break; 2632 } 2633 2634 ArgValue = DAG.getExtLoad( 2635 ExtType, DL, VA.getLocVT(), Chain, FIN, 2636 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2637 MemVT, false, false, false, 0); 2638 2639 InVals.push_back(ArgValue); 2640 } 2641 } 2642 2643 // varargs 2644 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2645 if (isVarArg) { 2646 if (!Subtarget->isTargetDarwin()) { 2647 // The AAPCS variadic function ABI is identical to the non-variadic 2648 // one. As a result there may be more arguments in registers and we should 2649 // save them for future reference. 2650 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2651 } 2652 2653 // This will point to the next argument passed via stack. 2654 unsigned StackOffset = CCInfo.getNextStackOffset(); 2655 // We currently pass all varargs at 8-byte alignment. 2656 StackOffset = ((StackOffset + 7) & ~7); 2657 FuncInfo->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true)); 2658 } 2659 2660 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2661 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2662 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2663 // This is a non-standard ABI so by fiat I say we're allowed to make full 2664 // use of the stack area to be popped, which must be aligned to 16 bytes in 2665 // any case: 2666 StackArgSize = alignTo(StackArgSize, 16); 2667 2668 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2669 // a multiple of 16. 2670 FuncInfo->setArgumentStackToRestore(StackArgSize); 2671 2672 // This realignment carries over to the available bytes below. Our own 2673 // callers will guarantee the space is free by giving an aligned value to 2674 // CALLSEQ_START. 2675 } 2676 // Even if we're not expected to free up the space, it's useful to know how 2677 // much is there while considering tail calls (because we can reuse it). 2678 FuncInfo->setBytesInStackArgArea(StackArgSize); 2679 2680 return Chain; 2681 } 2682 2683 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2684 SelectionDAG &DAG, SDLoc DL, 2685 SDValue &Chain) const { 2686 MachineFunction &MF = DAG.getMachineFunction(); 2687 MachineFrameInfo *MFI = MF.getFrameInfo(); 2688 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2689 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2690 2691 SmallVector<SDValue, 8> MemOps; 2692 2693 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2694 AArch64::X3, AArch64::X4, AArch64::X5, 2695 AArch64::X6, AArch64::X7 }; 2696 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2697 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2698 2699 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2700 int GPRIdx = 0; 2701 if (GPRSaveSize != 0) { 2702 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false); 2703 2704 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2705 2706 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2707 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2708 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2709 SDValue Store = DAG.getStore( 2710 Val.getValue(1), DL, Val, FIN, 2711 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false, 2712 false, 0); 2713 MemOps.push_back(Store); 2714 FIN = 2715 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2716 } 2717 } 2718 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2719 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2720 2721 if (Subtarget->hasFPARMv8()) { 2722 static const MCPhysReg FPRArgRegs[] = { 2723 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2724 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2725 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2726 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2727 2728 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2729 int FPRIdx = 0; 2730 if (FPRSaveSize != 0) { 2731 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false); 2732 2733 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2734 2735 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2736 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2737 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2738 2739 SDValue Store = DAG.getStore( 2740 Val.getValue(1), DL, Val, FIN, 2741 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16), 2742 false, false, 0); 2743 MemOps.push_back(Store); 2744 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 2745 DAG.getConstant(16, DL, PtrVT)); 2746 } 2747 } 2748 FuncInfo->setVarArgsFPRIndex(FPRIdx); 2749 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 2750 } 2751 2752 if (!MemOps.empty()) { 2753 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2754 } 2755 } 2756 2757 /// LowerCallResult - Lower the result values of a call into the 2758 /// appropriate copies out of appropriate physical registers. 2759 SDValue AArch64TargetLowering::LowerCallResult( 2760 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2761 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG, 2762 SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2763 SDValue ThisVal) const { 2764 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 2765 ? RetCC_AArch64_WebKit_JS 2766 : RetCC_AArch64_AAPCS; 2767 // Assign locations to each value returned by this call. 2768 SmallVector<CCValAssign, 16> RVLocs; 2769 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2770 *DAG.getContext()); 2771 CCInfo.AnalyzeCallResult(Ins, RetCC); 2772 2773 // Copy all of the result registers out of their specified physreg. 2774 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2775 CCValAssign VA = RVLocs[i]; 2776 2777 // Pass 'this' value directly from the argument to return value, to avoid 2778 // reg unit interference 2779 if (i == 0 && isThisReturn) { 2780 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 2781 "unexpected return calling convention register assignment"); 2782 InVals.push_back(ThisVal); 2783 continue; 2784 } 2785 2786 SDValue Val = 2787 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2788 Chain = Val.getValue(1); 2789 InFlag = Val.getValue(2); 2790 2791 switch (VA.getLocInfo()) { 2792 default: 2793 llvm_unreachable("Unknown loc info!"); 2794 case CCValAssign::Full: 2795 break; 2796 case CCValAssign::BCvt: 2797 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2798 break; 2799 } 2800 2801 InVals.push_back(Val); 2802 } 2803 2804 return Chain; 2805 } 2806 2807 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 2808 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2809 const SmallVectorImpl<ISD::OutputArg> &Outs, 2810 const SmallVectorImpl<SDValue> &OutVals, 2811 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2812 // For CallingConv::C this function knows whether the ABI needs 2813 // changing. That's not true for other conventions so they will have to opt in 2814 // manually. 2815 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 2816 return false; 2817 2818 MachineFunction &MF = DAG.getMachineFunction(); 2819 const Function *CallerF = MF.getFunction(); 2820 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2821 bool CCMatch = CallerCC == CalleeCC; 2822 2823 // Byval parameters hand the function a pointer directly into the stack area 2824 // we want to reuse during a tail call. Working around this *is* possible (see 2825 // X86) but less efficient and uglier in LowerCall. 2826 for (Function::const_arg_iterator i = CallerF->arg_begin(), 2827 e = CallerF->arg_end(); 2828 i != e; ++i) 2829 if (i->hasByValAttr()) 2830 return false; 2831 2832 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2833 return IsTailCallConvention(CalleeCC) && CCMatch; 2834 } 2835 2836 // Externally-defined functions with weak linkage should not be 2837 // tail-called on AArch64 when the OS does not support dynamic 2838 // pre-emption of symbols, as the AAELF spec requires normal calls 2839 // to undefined weak functions to be replaced with a NOP or jump to the 2840 // next instruction. The behaviour of branch instructions in this 2841 // situation (as used for tail calls) is implementation-defined, so we 2842 // cannot rely on the linker replacing the tail call with a return. 2843 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2844 const GlobalValue *GV = G->getGlobal(); 2845 const Triple &TT = getTargetMachine().getTargetTriple(); 2846 if (GV->hasExternalWeakLinkage() && 2847 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2848 return false; 2849 } 2850 2851 // Now we search for cases where we can use a tail call without changing the 2852 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 2853 // concept. 2854 2855 // I want anyone implementing a new calling convention to think long and hard 2856 // about this assert. 2857 assert((!isVarArg || CalleeCC == CallingConv::C) && 2858 "Unexpected variadic calling convention"); 2859 2860 LLVMContext &C = *DAG.getContext(); 2861 if (isVarArg && !Outs.empty()) { 2862 // At least two cases here: if caller is fastcc then we can't have any 2863 // memory arguments (we'd be expected to clean up the stack afterwards). If 2864 // caller is C then we could potentially use its argument area. 2865 2866 // FIXME: for now we take the most conservative of these in both cases: 2867 // disallow all variadic memory operands. 2868 SmallVector<CCValAssign, 16> ArgLocs; 2869 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2870 2871 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 2872 for (const CCValAssign &ArgLoc : ArgLocs) 2873 if (!ArgLoc.isRegLoc()) 2874 return false; 2875 } 2876 2877 // Check that the call results are passed in the same way. 2878 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2879 CCAssignFnForCall(CalleeCC, isVarArg), 2880 CCAssignFnForCall(CallerCC, isVarArg))) 2881 return false; 2882 // The callee has to preserve all registers the caller needs to preserve. 2883 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 2884 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2885 if (!CCMatch) { 2886 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2887 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2888 return false; 2889 } 2890 2891 // Nothing more to check if the callee is taking no arguments 2892 if (Outs.empty()) 2893 return true; 2894 2895 SmallVector<CCValAssign, 16> ArgLocs; 2896 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2897 2898 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2899 2900 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2901 2902 // If the stack arguments for this call do not fit into our own save area then 2903 // the call cannot be made tail. 2904 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2905 return false; 2906 2907 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2908 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2909 return false; 2910 2911 return true; 2912 } 2913 2914 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 2915 SelectionDAG &DAG, 2916 MachineFrameInfo *MFI, 2917 int ClobberedFI) const { 2918 SmallVector<SDValue, 8> ArgChains; 2919 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI); 2920 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1; 2921 2922 // Include the original chain at the beginning of the list. When this is 2923 // used by target LowerCall hooks, this helps legalize find the 2924 // CALLSEQ_BEGIN node. 2925 ArgChains.push_back(Chain); 2926 2927 // Add a chain value for each stack argument corresponding 2928 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 2929 UE = DAG.getEntryNode().getNode()->use_end(); 2930 U != UE; ++U) 2931 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 2932 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 2933 if (FI->getIndex() < 0) { 2934 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex()); 2935 int64_t InLastByte = InFirstByte; 2936 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1; 2937 2938 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 2939 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 2940 ArgChains.push_back(SDValue(L, 1)); 2941 } 2942 2943 // Build a tokenfactor for all the chains. 2944 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 2945 } 2946 2947 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 2948 bool TailCallOpt) const { 2949 return CallCC == CallingConv::Fast && TailCallOpt; 2950 } 2951 2952 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const { 2953 return CallCC == CallingConv::Fast || 2954 CallCC == CallingConv::PreserveMost; 2955 } 2956 2957 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 2958 /// and add input and output parameter nodes. 2959 SDValue 2960 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 2961 SmallVectorImpl<SDValue> &InVals) const { 2962 SelectionDAG &DAG = CLI.DAG; 2963 SDLoc &DL = CLI.DL; 2964 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2965 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2966 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2967 SDValue Chain = CLI.Chain; 2968 SDValue Callee = CLI.Callee; 2969 bool &IsTailCall = CLI.IsTailCall; 2970 CallingConv::ID CallConv = CLI.CallConv; 2971 bool IsVarArg = CLI.IsVarArg; 2972 2973 MachineFunction &MF = DAG.getMachineFunction(); 2974 bool IsThisReturn = false; 2975 2976 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2977 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2978 bool IsSibCall = false; 2979 2980 if (IsTailCall) { 2981 // Check if it's really possible to do a tail call. 2982 IsTailCall = isEligibleForTailCallOptimization( 2983 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2984 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall()) 2985 report_fatal_error("failed to perform tail call elimination on a call " 2986 "site marked musttail"); 2987 2988 // A sibling call is one where we're under the usual C ABI and not planning 2989 // to change that but can still do a tail call: 2990 if (!TailCallOpt && IsTailCall) 2991 IsSibCall = true; 2992 2993 if (IsTailCall) 2994 ++NumTailCalls; 2995 } 2996 2997 // Analyze operands of the call, assigning locations to each operand. 2998 SmallVector<CCValAssign, 16> ArgLocs; 2999 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3000 *DAG.getContext()); 3001 3002 if (IsVarArg) { 3003 // Handle fixed and variable vector arguments differently. 3004 // Variable vector arguments always go into memory. 3005 unsigned NumArgs = Outs.size(); 3006 3007 for (unsigned i = 0; i != NumArgs; ++i) { 3008 MVT ArgVT = Outs[i].VT; 3009 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3010 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3011 /*IsVarArg=*/ !Outs[i].IsFixed); 3012 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3013 assert(!Res && "Call operand has unhandled type"); 3014 (void)Res; 3015 } 3016 } else { 3017 // At this point, Outs[].VT may already be promoted to i32. To correctly 3018 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3019 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3020 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3021 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3022 // LocVT. 3023 unsigned NumArgs = Outs.size(); 3024 for (unsigned i = 0; i != NumArgs; ++i) { 3025 MVT ValVT = Outs[i].VT; 3026 // Get type of the original argument. 3027 EVT ActualVT = getValueType(DAG.getDataLayout(), 3028 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3029 /*AllowUnknown*/ true); 3030 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3031 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3032 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3033 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3034 ValVT = MVT::i8; 3035 else if (ActualMVT == MVT::i16) 3036 ValVT = MVT::i16; 3037 3038 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3039 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3040 assert(!Res && "Call operand has unhandled type"); 3041 (void)Res; 3042 } 3043 } 3044 3045 // Get a count of how many bytes are to be pushed on the stack. 3046 unsigned NumBytes = CCInfo.getNextStackOffset(); 3047 3048 if (IsSibCall) { 3049 // Since we're not changing the ABI to make this a tail call, the memory 3050 // operands are already available in the caller's incoming argument space. 3051 NumBytes = 0; 3052 } 3053 3054 // FPDiff is the byte offset of the call's argument area from the callee's. 3055 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3056 // by this amount for a tail call. In a sibling call it must be 0 because the 3057 // caller will deallocate the entire stack and the callee still expects its 3058 // arguments to begin at SP+0. Completely unused for non-tail calls. 3059 int FPDiff = 0; 3060 3061 if (IsTailCall && !IsSibCall) { 3062 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3063 3064 // Since callee will pop argument stack as a tail call, we must keep the 3065 // popped size 16-byte aligned. 3066 NumBytes = alignTo(NumBytes, 16); 3067 3068 // FPDiff will be negative if this tail call requires more space than we 3069 // would automatically have in our incoming argument space. Positive if we 3070 // can actually shrink the stack. 3071 FPDiff = NumReusableBytes - NumBytes; 3072 3073 // The stack pointer must be 16-byte aligned at all times it's used for a 3074 // memory operation, which in practice means at *all* times and in 3075 // particular across call boundaries. Therefore our own arguments started at 3076 // a 16-byte aligned SP and the delta applied for the tail call should 3077 // satisfy the same constraint. 3078 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3079 } 3080 3081 // Adjust the stack pointer for the new arguments... 3082 // These operations are automatically eliminated by the prolog/epilog pass 3083 if (!IsSibCall) 3084 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, 3085 true), 3086 DL); 3087 3088 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3089 getPointerTy(DAG.getDataLayout())); 3090 3091 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3092 SmallVector<SDValue, 8> MemOpChains; 3093 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3094 3095 // Walk the register/memloc assignments, inserting copies/loads. 3096 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3097 ++i, ++realArgIdx) { 3098 CCValAssign &VA = ArgLocs[i]; 3099 SDValue Arg = OutVals[realArgIdx]; 3100 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3101 3102 // Promote the value if needed. 3103 switch (VA.getLocInfo()) { 3104 default: 3105 llvm_unreachable("Unknown loc info!"); 3106 case CCValAssign::Full: 3107 break; 3108 case CCValAssign::SExt: 3109 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3110 break; 3111 case CCValAssign::ZExt: 3112 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3113 break; 3114 case CCValAssign::AExt: 3115 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3116 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3117 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3118 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3119 } 3120 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3121 break; 3122 case CCValAssign::BCvt: 3123 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3124 break; 3125 case CCValAssign::FPExt: 3126 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3127 break; 3128 } 3129 3130 if (VA.isRegLoc()) { 3131 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) { 3132 assert(VA.getLocVT() == MVT::i64 && 3133 "unexpected calling convention register assignment"); 3134 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3135 "unexpected use of 'returned'"); 3136 IsThisReturn = true; 3137 } 3138 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3139 } else { 3140 assert(VA.isMemLoc()); 3141 3142 SDValue DstAddr; 3143 MachinePointerInfo DstInfo; 3144 3145 // FIXME: This works on big-endian for composite byvals, which are the 3146 // common case. It should also work for fundamental types too. 3147 uint32_t BEAlign = 0; 3148 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3149 : VA.getValVT().getSizeInBits(); 3150 OpSize = (OpSize + 7) / 8; 3151 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3152 !Flags.isInConsecutiveRegs()) { 3153 if (OpSize < 8) 3154 BEAlign = 8 - OpSize; 3155 } 3156 unsigned LocMemOffset = VA.getLocMemOffset(); 3157 int32_t Offset = LocMemOffset + BEAlign; 3158 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3159 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3160 3161 if (IsTailCall) { 3162 Offset = Offset + FPDiff; 3163 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 3164 3165 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3166 DstInfo = 3167 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3168 3169 // Make sure any stack arguments overlapping with where we're storing 3170 // are loaded before this eventual operation. Otherwise they'll be 3171 // clobbered. 3172 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3173 } else { 3174 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3175 3176 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3177 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3178 LocMemOffset); 3179 } 3180 3181 if (Outs[i].Flags.isByVal()) { 3182 SDValue SizeNode = 3183 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3184 SDValue Cpy = DAG.getMemcpy( 3185 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3186 /*isVol = */ false, /*AlwaysInline = */ false, 3187 /*isTailCall = */ false, 3188 DstInfo, MachinePointerInfo()); 3189 3190 MemOpChains.push_back(Cpy); 3191 } else { 3192 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3193 // promoted to a legal register type i32, we should truncate Arg back to 3194 // i1/i8/i16. 3195 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3196 VA.getValVT() == MVT::i16) 3197 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3198 3199 SDValue Store = 3200 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0); 3201 MemOpChains.push_back(Store); 3202 } 3203 } 3204 } 3205 3206 if (!MemOpChains.empty()) 3207 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3208 3209 // Build a sequence of copy-to-reg nodes chained together with token chain 3210 // and flag operands which copy the outgoing args into the appropriate regs. 3211 SDValue InFlag; 3212 for (auto &RegToPass : RegsToPass) { 3213 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3214 RegToPass.second, InFlag); 3215 InFlag = Chain.getValue(1); 3216 } 3217 3218 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3219 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3220 // node so that legalize doesn't hack it. 3221 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3222 Subtarget->isTargetMachO()) { 3223 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3224 const GlobalValue *GV = G->getGlobal(); 3225 bool InternalLinkage = GV->hasInternalLinkage(); 3226 if (InternalLinkage) 3227 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3228 else { 3229 Callee = 3230 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3231 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3232 } 3233 } else if (ExternalSymbolSDNode *S = 3234 dyn_cast<ExternalSymbolSDNode>(Callee)) { 3235 const char *Sym = S->getSymbol(); 3236 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3237 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3238 } 3239 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3240 const GlobalValue *GV = G->getGlobal(); 3241 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3242 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3243 const char *Sym = S->getSymbol(); 3244 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3245 } 3246 3247 // We don't usually want to end the call-sequence here because we would tidy 3248 // the frame up *after* the call, however in the ABI-changing tail-call case 3249 // we've carefully laid out the parameters so that when sp is reset they'll be 3250 // in the correct location. 3251 if (IsTailCall && !IsSibCall) { 3252 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3253 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3254 InFlag = Chain.getValue(1); 3255 } 3256 3257 std::vector<SDValue> Ops; 3258 Ops.push_back(Chain); 3259 Ops.push_back(Callee); 3260 3261 if (IsTailCall) { 3262 // Each tail call may have to adjust the stack by a different amount, so 3263 // this information must travel along with the operation for eventual 3264 // consumption by emitEpilogue. 3265 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3266 } 3267 3268 // Add argument registers to the end of the list so that they are known live 3269 // into the call. 3270 for (auto &RegToPass : RegsToPass) 3271 Ops.push_back(DAG.getRegister(RegToPass.first, 3272 RegToPass.second.getValueType())); 3273 3274 // Add a register mask operand representing the call-preserved registers. 3275 const uint32_t *Mask; 3276 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3277 if (IsThisReturn) { 3278 // For 'this' returns, use the X0-preserving mask if applicable 3279 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3280 if (!Mask) { 3281 IsThisReturn = false; 3282 Mask = TRI->getCallPreservedMask(MF, CallConv); 3283 } 3284 } else 3285 Mask = TRI->getCallPreservedMask(MF, CallConv); 3286 3287 assert(Mask && "Missing call preserved mask for calling convention"); 3288 Ops.push_back(DAG.getRegisterMask(Mask)); 3289 3290 if (InFlag.getNode()) 3291 Ops.push_back(InFlag); 3292 3293 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3294 3295 // If we're doing a tall call, use a TC_RETURN here rather than an 3296 // actual call instruction. 3297 if (IsTailCall) { 3298 MF.getFrameInfo()->setHasTailCall(); 3299 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3300 } 3301 3302 // Returns a chain and a flag for retval copy to use. 3303 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3304 InFlag = Chain.getValue(1); 3305 3306 uint64_t CalleePopBytes = 3307 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3308 3309 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3310 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3311 InFlag, DL); 3312 if (!Ins.empty()) 3313 InFlag = Chain.getValue(1); 3314 3315 // Handle result values, copying them out of physregs into vregs that we 3316 // return. 3317 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3318 InVals, IsThisReturn, 3319 IsThisReturn ? OutVals[0] : SDValue()); 3320 } 3321 3322 bool AArch64TargetLowering::CanLowerReturn( 3323 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3324 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3325 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3326 ? RetCC_AArch64_WebKit_JS 3327 : RetCC_AArch64_AAPCS; 3328 SmallVector<CCValAssign, 16> RVLocs; 3329 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3330 return CCInfo.CheckReturn(Outs, RetCC); 3331 } 3332 3333 SDValue 3334 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3335 bool isVarArg, 3336 const SmallVectorImpl<ISD::OutputArg> &Outs, 3337 const SmallVectorImpl<SDValue> &OutVals, 3338 SDLoc DL, SelectionDAG &DAG) const { 3339 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3340 ? RetCC_AArch64_WebKit_JS 3341 : RetCC_AArch64_AAPCS; 3342 SmallVector<CCValAssign, 16> RVLocs; 3343 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3344 *DAG.getContext()); 3345 CCInfo.AnalyzeReturn(Outs, RetCC); 3346 3347 // Copy the result values into the output registers. 3348 SDValue Flag; 3349 SmallVector<SDValue, 4> RetOps(1, Chain); 3350 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3351 ++i, ++realRVLocIdx) { 3352 CCValAssign &VA = RVLocs[i]; 3353 assert(VA.isRegLoc() && "Can only return in registers!"); 3354 SDValue Arg = OutVals[realRVLocIdx]; 3355 3356 switch (VA.getLocInfo()) { 3357 default: 3358 llvm_unreachable("Unknown loc info!"); 3359 case CCValAssign::Full: 3360 if (Outs[i].ArgVT == MVT::i1) { 3361 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3362 // value. This is strictly redundant on Darwin (which uses "zeroext 3363 // i1"), but will be optimised out before ISel. 3364 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3365 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3366 } 3367 break; 3368 case CCValAssign::BCvt: 3369 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3370 break; 3371 } 3372 3373 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3374 Flag = Chain.getValue(1); 3375 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3376 } 3377 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3378 const MCPhysReg *I = 3379 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3380 if (I) { 3381 for (; *I; ++I) { 3382 if (AArch64::GPR64RegClass.contains(*I)) 3383 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3384 else if (AArch64::FPR64RegClass.contains(*I)) 3385 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3386 else 3387 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3388 } 3389 } 3390 3391 RetOps[0] = Chain; // Update chain. 3392 3393 // Add the flag if we have it. 3394 if (Flag.getNode()) 3395 RetOps.push_back(Flag); 3396 3397 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3398 } 3399 3400 //===----------------------------------------------------------------------===// 3401 // Other Lowering Code 3402 //===----------------------------------------------------------------------===// 3403 3404 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3405 SelectionDAG &DAG) const { 3406 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3407 SDLoc DL(Op); 3408 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3409 const GlobalValue *GV = GN->getGlobal(); 3410 unsigned char OpFlags = 3411 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3412 3413 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3414 "unexpected offset in global node"); 3415 3416 // This also catched the large code model case for Darwin. 3417 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3418 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 3419 // FIXME: Once remat is capable of dealing with instructions with register 3420 // operands, expand this into two nodes instead of using a wrapper node. 3421 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 3422 } 3423 3424 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) { 3425 assert(getTargetMachine().getCodeModel() == CodeModel::Small && 3426 "use of MO_CONSTPOOL only supported on small model"); 3427 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE); 3428 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 3429 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC; 3430 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags); 3431 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 3432 SDValue GlobalAddr = DAG.getLoad( 3433 PtrVT, DL, DAG.getEntryNode(), PoolAddr, 3434 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 3435 /*isVolatile=*/false, 3436 /*isNonTemporal=*/true, 3437 /*isInvariant=*/true, 8); 3438 if (GN->getOffset() != 0) 3439 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr, 3440 DAG.getConstant(GN->getOffset(), DL, PtrVT)); 3441 return GlobalAddr; 3442 } 3443 3444 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3445 const unsigned char MO_NC = AArch64II::MO_NC; 3446 return DAG.getNode( 3447 AArch64ISD::WrapperLarge, DL, PtrVT, 3448 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3), 3449 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 3450 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 3451 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 3452 } else { 3453 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and 3454 // the only correct model on Darwin. 3455 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 3456 OpFlags | AArch64II::MO_PAGE); 3457 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC; 3458 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags); 3459 3460 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 3461 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 3462 } 3463 } 3464 3465 /// \brief Convert a TLS address reference into the correct sequence of loads 3466 /// and calls to compute the variable's address (for Darwin, currently) and 3467 /// return an SDValue containing the final node. 3468 3469 /// Darwin only has one TLS scheme which must be capable of dealing with the 3470 /// fully general situation, in the worst case. This means: 3471 /// + "extern __thread" declaration. 3472 /// + Defined in a possibly unknown dynamic library. 3473 /// 3474 /// The general system is that each __thread variable has a [3 x i64] descriptor 3475 /// which contains information used by the runtime to calculate the address. The 3476 /// only part of this the compiler needs to know about is the first xword, which 3477 /// contains a function pointer that must be called with the address of the 3478 /// entire descriptor in "x0". 3479 /// 3480 /// Since this descriptor may be in a different unit, in general even the 3481 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3482 /// is: 3483 /// adrp x0, _var@TLVPPAGE 3484 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3485 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3486 /// ; the function pointer 3487 /// blr x1 ; Uses descriptor address in x0 3488 /// ; Address of _var is now in x0. 3489 /// 3490 /// If the address of _var's descriptor *is* known to the linker, then it can 3491 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3492 /// a slight efficiency gain. 3493 SDValue 3494 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3495 SelectionDAG &DAG) const { 3496 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3497 3498 SDLoc DL(Op); 3499 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3500 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3501 3502 SDValue TLVPAddr = 3503 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3504 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3505 3506 // The first entry in the descriptor is a function pointer that we must call 3507 // to obtain the address of the variable. 3508 SDValue Chain = DAG.getEntryNode(); 3509 SDValue FuncTLVGet = 3510 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, 3511 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, 3512 true, true, 8); 3513 Chain = FuncTLVGet.getValue(1); 3514 3515 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3516 MFI->setAdjustsStack(true); 3517 3518 // TLS calls preserve all registers except those that absolutely must be 3519 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3520 // silly). 3521 const uint32_t *Mask = 3522 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3523 3524 // Finally, we can make the call. This is just a degenerate version of a 3525 // normal AArch64 call node: x0 takes the address of the descriptor, and 3526 // returns the address of the variable in this thread. 3527 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3528 Chain = 3529 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3530 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3531 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3532 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3533 } 3534 3535 /// When accessing thread-local variables under either the general-dynamic or 3536 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3537 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3538 /// is a function pointer to carry out the resolution. 3539 /// 3540 /// The sequence is: 3541 /// adrp x0, :tlsdesc:var 3542 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3543 /// add x0, x0, #:tlsdesc_lo12:var 3544 /// .tlsdesccall var 3545 /// blr x1 3546 /// (TPIDR_EL0 offset now in x0) 3547 /// 3548 /// The above sequence must be produced unscheduled, to enable the linker to 3549 /// optimize/relax this sequence. 3550 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3551 /// above sequence, and expanded really late in the compilation flow, to ensure 3552 /// the sequence is produced as per above. 3553 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL, 3554 SelectionDAG &DAG) const { 3555 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3556 3557 SDValue Chain = DAG.getEntryNode(); 3558 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3559 3560 SmallVector<SDValue, 2> Ops; 3561 Ops.push_back(Chain); 3562 Ops.push_back(SymAddr); 3563 3564 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops); 3565 SDValue Glue = Chain.getValue(1); 3566 3567 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3568 } 3569 3570 SDValue 3571 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3572 SelectionDAG &DAG) const { 3573 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3574 assert(getTargetMachine().getCodeModel() == CodeModel::Small && 3575 "ELF TLS only supported in small memory model"); 3576 // Different choices can be made for the maximum size of the TLS area for a 3577 // module. For the small address model, the default TLS size is 16MiB and the 3578 // maximum TLS size is 4GiB. 3579 // FIXME: add -mtls-size command line option and make it control the 16MiB 3580 // vs. 4GiB code sequence generation. 3581 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3582 3583 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3584 3585 if (DAG.getTarget().Options.EmulatedTLS) 3586 return LowerToTLSEmulatedModel(GA, DAG); 3587 3588 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3589 if (Model == TLSModel::LocalDynamic) 3590 Model = TLSModel::GeneralDynamic; 3591 } 3592 3593 SDValue TPOff; 3594 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3595 SDLoc DL(Op); 3596 const GlobalValue *GV = GA->getGlobal(); 3597 3598 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3599 3600 if (Model == TLSModel::LocalExec) { 3601 SDValue HiVar = DAG.getTargetGlobalAddress( 3602 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3603 SDValue LoVar = DAG.getTargetGlobalAddress( 3604 GV, DL, PtrVT, 0, 3605 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3606 3607 SDValue TPWithOff_lo = 3608 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3609 HiVar, 3610 DAG.getTargetConstant(0, DL, MVT::i32)), 3611 0); 3612 SDValue TPWithOff = 3613 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3614 LoVar, 3615 DAG.getTargetConstant(0, DL, MVT::i32)), 3616 0); 3617 return TPWithOff; 3618 } else if (Model == TLSModel::InitialExec) { 3619 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3620 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3621 } else if (Model == TLSModel::LocalDynamic) { 3622 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3623 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3624 // the beginning of the module's TLS region, followed by a DTPREL offset 3625 // calculation. 3626 3627 // These accesses will need deduplicating if there's more than one. 3628 AArch64FunctionInfo *MFI = 3629 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3630 MFI->incNumLocalDynamicTLSAccesses(); 3631 3632 // The call needs a relocation too for linker relaxation. It doesn't make 3633 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3634 // the address. 3635 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3636 AArch64II::MO_TLS); 3637 3638 // Now we can calculate the offset from TPIDR_EL0 to this module's 3639 // thread-local area. 3640 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3641 3642 // Now use :dtprel_whatever: operations to calculate this variable's offset 3643 // in its thread-storage area. 3644 SDValue HiVar = DAG.getTargetGlobalAddress( 3645 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3646 SDValue LoVar = DAG.getTargetGlobalAddress( 3647 GV, DL, MVT::i64, 0, 3648 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3649 3650 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3651 DAG.getTargetConstant(0, DL, MVT::i32)), 3652 0); 3653 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3654 DAG.getTargetConstant(0, DL, MVT::i32)), 3655 0); 3656 } else if (Model == TLSModel::GeneralDynamic) { 3657 // The call needs a relocation too for linker relaxation. It doesn't make 3658 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3659 // the address. 3660 SDValue SymAddr = 3661 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3662 3663 // Finally we can make a call to calculate the offset from tpidr_el0. 3664 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3665 } else 3666 llvm_unreachable("Unsupported ELF TLS access model"); 3667 3668 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3669 } 3670 3671 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3672 SelectionDAG &DAG) const { 3673 if (Subtarget->isTargetDarwin()) 3674 return LowerDarwinGlobalTLSAddress(Op, DAG); 3675 else if (Subtarget->isTargetELF()) 3676 return LowerELFGlobalTLSAddress(Op, DAG); 3677 3678 llvm_unreachable("Unexpected platform trying to use TLS"); 3679 } 3680 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3681 SDValue Chain = Op.getOperand(0); 3682 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3683 SDValue LHS = Op.getOperand(2); 3684 SDValue RHS = Op.getOperand(3); 3685 SDValue Dest = Op.getOperand(4); 3686 SDLoc dl(Op); 3687 3688 // Handle f128 first, since lowering it will result in comparing the return 3689 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3690 // is expecting to deal with. 3691 if (LHS.getValueType() == MVT::f128) { 3692 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3693 3694 // If softenSetCCOperands returned a scalar, we need to compare the result 3695 // against zero to select between true and false values. 3696 if (!RHS.getNode()) { 3697 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3698 CC = ISD::SETNE; 3699 } 3700 } 3701 3702 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 3703 // instruction. 3704 unsigned Opc = LHS.getOpcode(); 3705 if (LHS.getResNo() == 1 && isOneConstant(RHS) && 3706 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3707 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 3708 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 3709 "Unexpected condition code."); 3710 // Only lower legal XALUO ops. 3711 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 3712 return SDValue(); 3713 3714 // The actual operation with overflow check. 3715 AArch64CC::CondCode OFCC; 3716 SDValue Value, Overflow; 3717 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 3718 3719 if (CC == ISD::SETNE) 3720 OFCC = getInvertedCondCode(OFCC); 3721 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 3722 3723 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3724 Overflow); 3725 } 3726 3727 if (LHS.getValueType().isInteger()) { 3728 assert((LHS.getValueType() == RHS.getValueType()) && 3729 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3730 3731 // If the RHS of the comparison is zero, we can potentially fold this 3732 // to a specialized branch. 3733 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 3734 if (RHSC && RHSC->getZExtValue() == 0) { 3735 if (CC == ISD::SETEQ) { 3736 // See if we can use a TBZ to fold in an AND as well. 3737 // TBZ has a smaller branch displacement than CBZ. If the offset is 3738 // out of bounds, a late MI-layer pass rewrites branches. 3739 // 403.gcc is an example that hits this case. 3740 if (LHS.getOpcode() == ISD::AND && 3741 isa<ConstantSDNode>(LHS.getOperand(1)) && 3742 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3743 SDValue Test = LHS.getOperand(0); 3744 uint64_t Mask = LHS.getConstantOperandVal(1); 3745 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 3746 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3747 Dest); 3748 } 3749 3750 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 3751 } else if (CC == ISD::SETNE) { 3752 // See if we can use a TBZ to fold in an AND as well. 3753 // TBZ has a smaller branch displacement than CBZ. If the offset is 3754 // out of bounds, a late MI-layer pass rewrites branches. 3755 // 403.gcc is an example that hits this case. 3756 if (LHS.getOpcode() == ISD::AND && 3757 isa<ConstantSDNode>(LHS.getOperand(1)) && 3758 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3759 SDValue Test = LHS.getOperand(0); 3760 uint64_t Mask = LHS.getConstantOperandVal(1); 3761 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 3762 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3763 Dest); 3764 } 3765 3766 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 3767 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 3768 // Don't combine AND since emitComparison converts the AND to an ANDS 3769 // (a.k.a. TST) and the test in the test bit and branch instruction 3770 // becomes redundant. This would also increase register pressure. 3771 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1; 3772 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 3773 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3774 } 3775 } 3776 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 3777 LHS.getOpcode() != ISD::AND) { 3778 // Don't combine AND since emitComparison converts the AND to an ANDS 3779 // (a.k.a. TST) and the test in the test bit and branch instruction 3780 // becomes redundant. This would also increase register pressure. 3781 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1; 3782 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 3783 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3784 } 3785 3786 SDValue CCVal; 3787 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 3788 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3789 Cmp); 3790 } 3791 3792 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3793 3794 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 3795 // clean. Some of them require two branches to implement. 3796 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3797 AArch64CC::CondCode CC1, CC2; 3798 changeFPCCToAArch64CC(CC, CC1, CC2); 3799 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3800 SDValue BR1 = 3801 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 3802 if (CC2 != AArch64CC::AL) { 3803 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3804 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 3805 Cmp); 3806 } 3807 3808 return BR1; 3809 } 3810 3811 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 3812 SelectionDAG &DAG) const { 3813 EVT VT = Op.getValueType(); 3814 SDLoc DL(Op); 3815 3816 SDValue In1 = Op.getOperand(0); 3817 SDValue In2 = Op.getOperand(1); 3818 EVT SrcVT = In2.getValueType(); 3819 3820 if (SrcVT.bitsLT(VT)) 3821 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 3822 else if (SrcVT.bitsGT(VT)) 3823 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 3824 3825 EVT VecVT; 3826 EVT EltVT; 3827 uint64_t EltMask; 3828 SDValue VecVal1, VecVal2; 3829 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 3830 EltVT = MVT::i32; 3831 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 3832 EltMask = 0x80000000ULL; 3833 3834 if (!VT.isVector()) { 3835 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3836 DAG.getUNDEF(VecVT), In1); 3837 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3838 DAG.getUNDEF(VecVT), In2); 3839 } else { 3840 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3841 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3842 } 3843 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 3844 EltVT = MVT::i64; 3845 VecVT = MVT::v2i64; 3846 3847 // We want to materialize a mask with the high bit set, but the AdvSIMD 3848 // immediate moves cannot materialize that in a single instruction for 3849 // 64-bit elements. Instead, materialize zero and then negate it. 3850 EltMask = 0; 3851 3852 if (!VT.isVector()) { 3853 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3854 DAG.getUNDEF(VecVT), In1); 3855 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3856 DAG.getUNDEF(VecVT), In2); 3857 } else { 3858 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3859 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3860 } 3861 } else { 3862 llvm_unreachable("Invalid type for copysign!"); 3863 } 3864 3865 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 3866 3867 // If we couldn't materialize the mask above, then the mask vector will be 3868 // the zero vector, and we need to negate it here. 3869 if (VT == MVT::f64 || VT == MVT::v2f64) { 3870 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 3871 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 3872 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 3873 } 3874 3875 SDValue Sel = 3876 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 3877 3878 if (VT == MVT::f32) 3879 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 3880 else if (VT == MVT::f64) 3881 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 3882 else 3883 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 3884 } 3885 3886 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 3887 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 3888 Attribute::NoImplicitFloat)) 3889 return SDValue(); 3890 3891 if (!Subtarget->hasNEON()) 3892 return SDValue(); 3893 3894 // While there is no integer popcount instruction, it can 3895 // be more efficiently lowered to the following sequence that uses 3896 // AdvSIMD registers/instructions as long as the copies to/from 3897 // the AdvSIMD registers are cheap. 3898 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 3899 // CNT V0.8B, V0.8B // 8xbyte pop-counts 3900 // ADDV B0, V0.8B // sum 8xbyte pop-counts 3901 // UMOV X0, V0.B[0] // copy byte result back to integer reg 3902 SDValue Val = Op.getOperand(0); 3903 SDLoc DL(Op); 3904 EVT VT = Op.getValueType(); 3905 3906 if (VT == MVT::i32) 3907 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 3908 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 3909 3910 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 3911 SDValue UaddLV = DAG.getNode( 3912 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 3913 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 3914 3915 if (VT == MVT::i64) 3916 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 3917 return UaddLV; 3918 } 3919 3920 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3921 3922 if (Op.getValueType().isVector()) 3923 return LowerVSETCC(Op, DAG); 3924 3925 SDValue LHS = Op.getOperand(0); 3926 SDValue RHS = Op.getOperand(1); 3927 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3928 SDLoc dl(Op); 3929 3930 // We chose ZeroOrOneBooleanContents, so use zero and one. 3931 EVT VT = Op.getValueType(); 3932 SDValue TVal = DAG.getConstant(1, dl, VT); 3933 SDValue FVal = DAG.getConstant(0, dl, VT); 3934 3935 // Handle f128 first, since one possible outcome is a normal integer 3936 // comparison which gets picked up by the next if statement. 3937 if (LHS.getValueType() == MVT::f128) { 3938 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3939 3940 // If softenSetCCOperands returned a scalar, use it. 3941 if (!RHS.getNode()) { 3942 assert(LHS.getValueType() == Op.getValueType() && 3943 "Unexpected setcc expansion!"); 3944 return LHS; 3945 } 3946 } 3947 3948 if (LHS.getValueType().isInteger()) { 3949 SDValue CCVal; 3950 SDValue Cmp = 3951 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 3952 3953 // Note that we inverted the condition above, so we reverse the order of 3954 // the true and false operands here. This will allow the setcc to be 3955 // matched to a single CSINC instruction. 3956 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 3957 } 3958 3959 // Now we know we're dealing with FP values. 3960 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3961 3962 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 3963 // and do the comparison. 3964 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3965 3966 AArch64CC::CondCode CC1, CC2; 3967 changeFPCCToAArch64CC(CC, CC1, CC2); 3968 if (CC2 == AArch64CC::AL) { 3969 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 3970 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3971 3972 // Note that we inverted the condition above, so we reverse the order of 3973 // the true and false operands here. This will allow the setcc to be 3974 // matched to a single CSINC instruction. 3975 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 3976 } else { 3977 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 3978 // totally clean. Some of them require two CSELs to implement. As is in 3979 // this case, we emit the first CSEL and then emit a second using the output 3980 // of the first as the RHS. We're effectively OR'ing the two CC's together. 3981 3982 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 3983 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3984 SDValue CS1 = 3985 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 3986 3987 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3988 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 3989 } 3990 } 3991 3992 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 3993 SDValue RHS, SDValue TVal, 3994 SDValue FVal, SDLoc dl, 3995 SelectionDAG &DAG) const { 3996 // Handle f128 first, because it will result in a comparison of some RTLIB 3997 // call result against zero. 3998 if (LHS.getValueType() == MVT::f128) { 3999 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4000 4001 // If softenSetCCOperands returned a scalar, we need to compare the result 4002 // against zero to select between true and false values. 4003 if (!RHS.getNode()) { 4004 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4005 CC = ISD::SETNE; 4006 } 4007 } 4008 4009 // Also handle f16, for which we need to do a f32 comparison. 4010 if (LHS.getValueType() == MVT::f16) { 4011 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 4012 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 4013 } 4014 4015 // Next, handle integers. 4016 if (LHS.getValueType().isInteger()) { 4017 assert((LHS.getValueType() == RHS.getValueType()) && 4018 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4019 4020 unsigned Opcode = AArch64ISD::CSEL; 4021 4022 // If both the TVal and the FVal are constants, see if we can swap them in 4023 // order to for a CSINV or CSINC out of them. 4024 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4025 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4026 4027 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4028 std::swap(TVal, FVal); 4029 std::swap(CTVal, CFVal); 4030 CC = ISD::getSetCCInverse(CC, true); 4031 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4032 std::swap(TVal, FVal); 4033 std::swap(CTVal, CFVal); 4034 CC = ISD::getSetCCInverse(CC, true); 4035 } else if (TVal.getOpcode() == ISD::XOR) { 4036 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4037 // with a CSINV rather than a CSEL. 4038 if (isAllOnesConstant(TVal.getOperand(1))) { 4039 std::swap(TVal, FVal); 4040 std::swap(CTVal, CFVal); 4041 CC = ISD::getSetCCInverse(CC, true); 4042 } 4043 } else if (TVal.getOpcode() == ISD::SUB) { 4044 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4045 // that we can match with a CSNEG rather than a CSEL. 4046 if (isNullConstant(TVal.getOperand(0))) { 4047 std::swap(TVal, FVal); 4048 std::swap(CTVal, CFVal); 4049 CC = ISD::getSetCCInverse(CC, true); 4050 } 4051 } else if (CTVal && CFVal) { 4052 const int64_t TrueVal = CTVal->getSExtValue(); 4053 const int64_t FalseVal = CFVal->getSExtValue(); 4054 bool Swap = false; 4055 4056 // If both TVal and FVal are constants, see if FVal is the 4057 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4058 // instead of a CSEL in that case. 4059 if (TrueVal == ~FalseVal) { 4060 Opcode = AArch64ISD::CSINV; 4061 } else if (TrueVal == -FalseVal) { 4062 Opcode = AArch64ISD::CSNEG; 4063 } else if (TVal.getValueType() == MVT::i32) { 4064 // If our operands are only 32-bit wide, make sure we use 32-bit 4065 // arithmetic for the check whether we can use CSINC. This ensures that 4066 // the addition in the check will wrap around properly in case there is 4067 // an overflow (which would not be the case if we do the check with 4068 // 64-bit arithmetic). 4069 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4070 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4071 4072 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4073 Opcode = AArch64ISD::CSINC; 4074 4075 if (TrueVal32 > FalseVal32) { 4076 Swap = true; 4077 } 4078 } 4079 // 64-bit check whether we can use CSINC. 4080 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4081 Opcode = AArch64ISD::CSINC; 4082 4083 if (TrueVal > FalseVal) { 4084 Swap = true; 4085 } 4086 } 4087 4088 // Swap TVal and FVal if necessary. 4089 if (Swap) { 4090 std::swap(TVal, FVal); 4091 std::swap(CTVal, CFVal); 4092 CC = ISD::getSetCCInverse(CC, true); 4093 } 4094 4095 if (Opcode != AArch64ISD::CSEL) { 4096 // Drop FVal since we can get its value by simply inverting/negating 4097 // TVal. 4098 FVal = TVal; 4099 } 4100 } 4101 4102 SDValue CCVal; 4103 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4104 4105 EVT VT = TVal.getValueType(); 4106 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4107 } 4108 4109 // Now we know we're dealing with FP values. 4110 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4111 assert(LHS.getValueType() == RHS.getValueType()); 4112 EVT VT = TVal.getValueType(); 4113 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4114 4115 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4116 // clean. Some of them require two CSELs to implement. 4117 AArch64CC::CondCode CC1, CC2; 4118 changeFPCCToAArch64CC(CC, CC1, CC2); 4119 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4120 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4121 4122 // If we need a second CSEL, emit it, using the output of the first as the 4123 // RHS. We're effectively OR'ing the two CC's together. 4124 if (CC2 != AArch64CC::AL) { 4125 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4126 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4127 } 4128 4129 // Otherwise, return the output of the first CSEL. 4130 return CS1; 4131 } 4132 4133 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4134 SelectionDAG &DAG) const { 4135 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4136 SDValue LHS = Op.getOperand(0); 4137 SDValue RHS = Op.getOperand(1); 4138 SDValue TVal = Op.getOperand(2); 4139 SDValue FVal = Op.getOperand(3); 4140 SDLoc DL(Op); 4141 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4142 } 4143 4144 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4145 SelectionDAG &DAG) const { 4146 SDValue CCVal = Op->getOperand(0); 4147 SDValue TVal = Op->getOperand(1); 4148 SDValue FVal = Op->getOperand(2); 4149 SDLoc DL(Op); 4150 4151 unsigned Opc = CCVal.getOpcode(); 4152 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4153 // instruction. 4154 if (CCVal.getResNo() == 1 && 4155 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4156 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4157 // Only lower legal XALUO ops. 4158 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4159 return SDValue(); 4160 4161 AArch64CC::CondCode OFCC; 4162 SDValue Value, Overflow; 4163 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4164 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4165 4166 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4167 CCVal, Overflow); 4168 } 4169 4170 // Lower it the same way as we would lower a SELECT_CC node. 4171 ISD::CondCode CC; 4172 SDValue LHS, RHS; 4173 if (CCVal.getOpcode() == ISD::SETCC) { 4174 LHS = CCVal.getOperand(0); 4175 RHS = CCVal.getOperand(1); 4176 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4177 } else { 4178 LHS = CCVal; 4179 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4180 CC = ISD::SETNE; 4181 } 4182 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4183 } 4184 4185 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4186 SelectionDAG &DAG) const { 4187 // Jump table entries as PC relative offsets. No additional tweaking 4188 // is necessary here. Just get the address of the jump table. 4189 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4190 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4191 SDLoc DL(Op); 4192 4193 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4194 !Subtarget->isTargetMachO()) { 4195 const unsigned char MO_NC = AArch64II::MO_NC; 4196 return DAG.getNode( 4197 AArch64ISD::WrapperLarge, DL, PtrVT, 4198 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3), 4199 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC), 4200 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC), 4201 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4202 AArch64II::MO_G0 | MO_NC)); 4203 } 4204 4205 SDValue Hi = 4206 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE); 4207 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4208 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4209 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4210 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4211 } 4212 4213 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4214 SelectionDAG &DAG) const { 4215 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4216 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4217 SDLoc DL(Op); 4218 4219 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4220 // Use the GOT for the large code model on iOS. 4221 if (Subtarget->isTargetMachO()) { 4222 SDValue GotAddr = DAG.getTargetConstantPool( 4223 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4224 AArch64II::MO_GOT); 4225 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 4226 } 4227 4228 const unsigned char MO_NC = AArch64II::MO_NC; 4229 return DAG.getNode( 4230 AArch64ISD::WrapperLarge, DL, PtrVT, 4231 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4232 CP->getOffset(), AArch64II::MO_G3), 4233 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4234 CP->getOffset(), AArch64II::MO_G2 | MO_NC), 4235 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4236 CP->getOffset(), AArch64II::MO_G1 | MO_NC), 4237 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4238 CP->getOffset(), AArch64II::MO_G0 | MO_NC)); 4239 } else { 4240 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on 4241 // ELF, the only valid one on Darwin. 4242 SDValue Hi = 4243 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4244 CP->getOffset(), AArch64II::MO_PAGE); 4245 SDValue Lo = DAG.getTargetConstantPool( 4246 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4247 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4248 4249 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4250 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4251 } 4252 } 4253 4254 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4255 SelectionDAG &DAG) const { 4256 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 4257 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4258 SDLoc DL(Op); 4259 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4260 !Subtarget->isTargetMachO()) { 4261 const unsigned char MO_NC = AArch64II::MO_NC; 4262 return DAG.getNode( 4263 AArch64ISD::WrapperLarge, DL, PtrVT, 4264 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3), 4265 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 4266 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 4267 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 4268 } else { 4269 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE); 4270 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF | 4271 AArch64II::MO_NC); 4272 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4273 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4274 } 4275 } 4276 4277 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4278 SelectionDAG &DAG) const { 4279 AArch64FunctionInfo *FuncInfo = 4280 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4281 4282 SDLoc DL(Op); 4283 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4284 getPointerTy(DAG.getDataLayout())); 4285 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4286 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4287 MachinePointerInfo(SV), false, false, 0); 4288 } 4289 4290 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4291 SelectionDAG &DAG) const { 4292 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4293 // Standard, section B.3. 4294 MachineFunction &MF = DAG.getMachineFunction(); 4295 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4296 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4297 SDLoc DL(Op); 4298 4299 SDValue Chain = Op.getOperand(0); 4300 SDValue VAList = Op.getOperand(1); 4301 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4302 SmallVector<SDValue, 4> MemOps; 4303 4304 // void *__stack at offset 0 4305 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4306 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4307 MachinePointerInfo(SV), false, false, 8)); 4308 4309 // void *__gr_top at offset 8 4310 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4311 if (GPRSize > 0) { 4312 SDValue GRTop, GRTopAddr; 4313 4314 GRTopAddr = 4315 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4316 4317 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4318 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4319 DAG.getConstant(GPRSize, DL, PtrVT)); 4320 4321 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4322 MachinePointerInfo(SV, 8), false, false, 8)); 4323 } 4324 4325 // void *__vr_top at offset 16 4326 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4327 if (FPRSize > 0) { 4328 SDValue VRTop, VRTopAddr; 4329 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4330 DAG.getConstant(16, DL, PtrVT)); 4331 4332 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4333 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4334 DAG.getConstant(FPRSize, DL, PtrVT)); 4335 4336 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4337 MachinePointerInfo(SV, 16), false, false, 8)); 4338 } 4339 4340 // int __gr_offs at offset 24 4341 SDValue GROffsAddr = 4342 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4343 MemOps.push_back(DAG.getStore(Chain, DL, 4344 DAG.getConstant(-GPRSize, DL, MVT::i32), 4345 GROffsAddr, MachinePointerInfo(SV, 24), false, 4346 false, 4)); 4347 4348 // int __vr_offs at offset 28 4349 SDValue VROffsAddr = 4350 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4351 MemOps.push_back(DAG.getStore(Chain, DL, 4352 DAG.getConstant(-FPRSize, DL, MVT::i32), 4353 VROffsAddr, MachinePointerInfo(SV, 28), false, 4354 false, 4)); 4355 4356 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4357 } 4358 4359 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4360 SelectionDAG &DAG) const { 4361 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG) 4362 : LowerAAPCS_VASTART(Op, DAG); 4363 } 4364 4365 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4366 SelectionDAG &DAG) const { 4367 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4368 // pointer. 4369 SDLoc DL(Op); 4370 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32; 4371 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4372 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4373 4374 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4375 Op.getOperand(2), 4376 DAG.getConstant(VaListSize, DL, MVT::i32), 4377 8, false, false, false, MachinePointerInfo(DestSV), 4378 MachinePointerInfo(SrcSV)); 4379 } 4380 4381 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4382 assert(Subtarget->isTargetDarwin() && 4383 "automatic va_arg instruction only works on Darwin"); 4384 4385 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4386 EVT VT = Op.getValueType(); 4387 SDLoc DL(Op); 4388 SDValue Chain = Op.getOperand(0); 4389 SDValue Addr = Op.getOperand(1); 4390 unsigned Align = Op.getConstantOperandVal(3); 4391 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4392 4393 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V), 4394 false, false, false, 0); 4395 Chain = VAList.getValue(1); 4396 4397 if (Align > 8) { 4398 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4399 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4400 DAG.getConstant(Align - 1, DL, PtrVT)); 4401 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4402 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4403 } 4404 4405 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4406 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4407 4408 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4409 // up to 64 bits. At the very least, we have to increase the striding of the 4410 // vaargs list to match this, and for FP values we need to introduce 4411 // FP_ROUND nodes as well. 4412 if (VT.isInteger() && !VT.isVector()) 4413 ArgSize = 8; 4414 bool NeedFPTrunc = false; 4415 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4416 ArgSize = 8; 4417 NeedFPTrunc = true; 4418 } 4419 4420 // Increment the pointer, VAList, to the next vaarg 4421 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4422 DAG.getConstant(ArgSize, DL, PtrVT)); 4423 // Store the incremented VAList to the legalized pointer 4424 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V), 4425 false, false, 0); 4426 4427 // Load the actual argument out of the pointer VAList 4428 if (NeedFPTrunc) { 4429 // Load the value as an f64. 4430 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList, 4431 MachinePointerInfo(), false, false, false, 0); 4432 // Round the value down to an f32. 4433 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4434 DAG.getIntPtrConstant(1, DL)); 4435 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4436 // Merge the rounded value with the chain output of the load. 4437 return DAG.getMergeValues(Ops, DL); 4438 } 4439 4440 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false, 4441 false, false, 0); 4442 } 4443 4444 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4445 SelectionDAG &DAG) const { 4446 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4447 MFI->setFrameAddressIsTaken(true); 4448 4449 EVT VT = Op.getValueType(); 4450 SDLoc DL(Op); 4451 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4452 SDValue FrameAddr = 4453 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4454 while (Depth--) 4455 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4456 MachinePointerInfo(), false, false, false, 0); 4457 return FrameAddr; 4458 } 4459 4460 // FIXME? Maybe this could be a TableGen attribute on some registers and 4461 // this table could be generated automatically from RegInfo. 4462 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4463 SelectionDAG &DAG) const { 4464 unsigned Reg = StringSwitch<unsigned>(RegName) 4465 .Case("sp", AArch64::SP) 4466 .Default(0); 4467 if (Reg) 4468 return Reg; 4469 report_fatal_error(Twine("Invalid register name \"" 4470 + StringRef(RegName) + "\".")); 4471 } 4472 4473 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4474 SelectionDAG &DAG) const { 4475 MachineFunction &MF = DAG.getMachineFunction(); 4476 MachineFrameInfo *MFI = MF.getFrameInfo(); 4477 MFI->setReturnAddressIsTaken(true); 4478 4479 EVT VT = Op.getValueType(); 4480 SDLoc DL(Op); 4481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4482 if (Depth) { 4483 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4484 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4485 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4486 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4487 MachinePointerInfo(), false, false, false, 0); 4488 } 4489 4490 // Return LR, which contains the return address. Mark it an implicit live-in. 4491 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4492 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4493 } 4494 4495 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4496 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4497 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4498 SelectionDAG &DAG) const { 4499 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4500 EVT VT = Op.getValueType(); 4501 unsigned VTBits = VT.getSizeInBits(); 4502 SDLoc dl(Op); 4503 SDValue ShOpLo = Op.getOperand(0); 4504 SDValue ShOpHi = Op.getOperand(1); 4505 SDValue ShAmt = Op.getOperand(2); 4506 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4507 4508 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4509 4510 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4511 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4512 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4513 4514 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4515 // is "undef". We wanted 0, so CSEL it directly. 4516 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4517 ISD::SETEQ, dl, DAG); 4518 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4519 HiBitsForLo = 4520 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4521 HiBitsForLo, CCVal, Cmp); 4522 4523 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4524 DAG.getConstant(VTBits, dl, MVT::i64)); 4525 4526 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4527 SDValue LoForNormalShift = 4528 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4529 4530 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4531 dl, DAG); 4532 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4533 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4534 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4535 LoForNormalShift, CCVal, Cmp); 4536 4537 // AArch64 shifts larger than the register width are wrapped rather than 4538 // clamped, so we can't just emit "hi >> x". 4539 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4540 SDValue HiForBigShift = 4541 Opc == ISD::SRA 4542 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4543 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4544 : DAG.getConstant(0, dl, VT); 4545 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4546 HiForNormalShift, CCVal, Cmp); 4547 4548 SDValue Ops[2] = { Lo, Hi }; 4549 return DAG.getMergeValues(Ops, dl); 4550 } 4551 4552 4553 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4554 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4555 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4556 SelectionDAG &DAG) const { 4557 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4558 EVT VT = Op.getValueType(); 4559 unsigned VTBits = VT.getSizeInBits(); 4560 SDLoc dl(Op); 4561 SDValue ShOpLo = Op.getOperand(0); 4562 SDValue ShOpHi = Op.getOperand(1); 4563 SDValue ShAmt = Op.getOperand(2); 4564 4565 assert(Op.getOpcode() == ISD::SHL_PARTS); 4566 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4567 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4568 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4569 4570 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4571 // is "undef". We wanted 0, so CSEL it directly. 4572 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4573 ISD::SETEQ, dl, DAG); 4574 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4575 LoBitsForHi = 4576 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4577 LoBitsForHi, CCVal, Cmp); 4578 4579 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4580 DAG.getConstant(VTBits, dl, MVT::i64)); 4581 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4582 SDValue HiForNormalShift = 4583 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4584 4585 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4586 4587 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4588 dl, DAG); 4589 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4590 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4591 HiForNormalShift, CCVal, Cmp); 4592 4593 // AArch64 shifts of larger than register sizes are wrapped rather than 4594 // clamped, so we can't just emit "lo << a" if a is too big. 4595 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4596 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4597 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4598 LoForNormalShift, CCVal, Cmp); 4599 4600 SDValue Ops[2] = { Lo, Hi }; 4601 return DAG.getMergeValues(Ops, dl); 4602 } 4603 4604 bool AArch64TargetLowering::isOffsetFoldingLegal( 4605 const GlobalAddressSDNode *GA) const { 4606 // The AArch64 target doesn't support folding offsets into global addresses. 4607 return false; 4608 } 4609 4610 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4611 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4612 // FIXME: We should be able to handle f128 as well with a clever lowering. 4613 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32)) 4614 return true; 4615 4616 if (VT == MVT::f64) 4617 return AArch64_AM::getFP64Imm(Imm) != -1; 4618 else if (VT == MVT::f32) 4619 return AArch64_AM::getFP32Imm(Imm) != -1; 4620 return false; 4621 } 4622 4623 //===----------------------------------------------------------------------===// 4624 // AArch64 Optimization Hooks 4625 //===----------------------------------------------------------------------===// 4626 4627 //===----------------------------------------------------------------------===// 4628 // AArch64 Inline Assembly Support 4629 //===----------------------------------------------------------------------===// 4630 4631 // Table of Constraints 4632 // TODO: This is the current set of constraints supported by ARM for the 4633 // compiler, not all of them may make sense, e.g. S may be difficult to support. 4634 // 4635 // r - A general register 4636 // w - An FP/SIMD register of some size in the range v0-v31 4637 // x - An FP/SIMD register of some size in the range v0-v15 4638 // I - Constant that can be used with an ADD instruction 4639 // J - Constant that can be used with a SUB instruction 4640 // K - Constant that can be used with a 32-bit logical instruction 4641 // L - Constant that can be used with a 64-bit logical instruction 4642 // M - Constant that can be used as a 32-bit MOV immediate 4643 // N - Constant that can be used as a 64-bit MOV immediate 4644 // Q - A memory reference with base register and no offset 4645 // S - A symbolic address 4646 // Y - Floating point constant zero 4647 // Z - Integer constant zero 4648 // 4649 // Note that general register operands will be output using their 64-bit x 4650 // register name, whatever the size of the variable, unless the asm operand 4651 // is prefixed by the %w modifier. Floating-point and SIMD register operands 4652 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 4653 // %q modifier. 4654 4655 /// getConstraintType - Given a constraint letter, return the type of 4656 /// constraint it is for this target. 4657 AArch64TargetLowering::ConstraintType 4658 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 4659 if (Constraint.size() == 1) { 4660 switch (Constraint[0]) { 4661 default: 4662 break; 4663 case 'z': 4664 return C_Other; 4665 case 'x': 4666 case 'w': 4667 return C_RegisterClass; 4668 // An address with a single base register. Due to the way we 4669 // currently handle addresses it is the same as 'r'. 4670 case 'Q': 4671 return C_Memory; 4672 } 4673 } 4674 return TargetLowering::getConstraintType(Constraint); 4675 } 4676 4677 /// Examine constraint type and operand type and determine a weight value. 4678 /// This object must already have been set up with the operand type 4679 /// and the current alternative constraint selected. 4680 TargetLowering::ConstraintWeight 4681 AArch64TargetLowering::getSingleConstraintMatchWeight( 4682 AsmOperandInfo &info, const char *constraint) const { 4683 ConstraintWeight weight = CW_Invalid; 4684 Value *CallOperandVal = info.CallOperandVal; 4685 // If we don't have a value, we can't do a match, 4686 // but allow it at the lowest weight. 4687 if (!CallOperandVal) 4688 return CW_Default; 4689 Type *type = CallOperandVal->getType(); 4690 // Look at the constraint type. 4691 switch (*constraint) { 4692 default: 4693 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 4694 break; 4695 case 'x': 4696 case 'w': 4697 if (type->isFloatingPointTy() || type->isVectorTy()) 4698 weight = CW_Register; 4699 break; 4700 case 'z': 4701 weight = CW_Constant; 4702 break; 4703 } 4704 return weight; 4705 } 4706 4707 std::pair<unsigned, const TargetRegisterClass *> 4708 AArch64TargetLowering::getRegForInlineAsmConstraint( 4709 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 4710 if (Constraint.size() == 1) { 4711 switch (Constraint[0]) { 4712 case 'r': 4713 if (VT.getSizeInBits() == 64) 4714 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 4715 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 4716 case 'w': 4717 if (VT == MVT::f32) 4718 return std::make_pair(0U, &AArch64::FPR32RegClass); 4719 if (VT.getSizeInBits() == 64) 4720 return std::make_pair(0U, &AArch64::FPR64RegClass); 4721 if (VT.getSizeInBits() == 128) 4722 return std::make_pair(0U, &AArch64::FPR128RegClass); 4723 break; 4724 // The instructions that this constraint is designed for can 4725 // only take 128-bit registers so just use that regclass. 4726 case 'x': 4727 if (VT.getSizeInBits() == 128) 4728 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 4729 break; 4730 } 4731 } 4732 if (StringRef("{cc}").equals_lower(Constraint)) 4733 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 4734 4735 // Use the default implementation in TargetLowering to convert the register 4736 // constraint into a member of a register class. 4737 std::pair<unsigned, const TargetRegisterClass *> Res; 4738 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4739 4740 // Not found as a standard register? 4741 if (!Res.second) { 4742 unsigned Size = Constraint.size(); 4743 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 4744 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 4745 int RegNo; 4746 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 4747 if (!Failed && RegNo >= 0 && RegNo <= 31) { 4748 // v0 - v31 are aliases of q0 - q31. 4749 // By default we'll emit v0-v31 for this unless there's a modifier where 4750 // we'll emit the correct register as well. 4751 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 4752 Res.second = &AArch64::FPR128RegClass; 4753 } 4754 } 4755 } 4756 4757 return Res; 4758 } 4759 4760 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 4761 /// vector. If it is invalid, don't add anything to Ops. 4762 void AArch64TargetLowering::LowerAsmOperandForConstraint( 4763 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 4764 SelectionDAG &DAG) const { 4765 SDValue Result; 4766 4767 // Currently only support length 1 constraints. 4768 if (Constraint.length() != 1) 4769 return; 4770 4771 char ConstraintLetter = Constraint[0]; 4772 switch (ConstraintLetter) { 4773 default: 4774 break; 4775 4776 // This set of constraints deal with valid constants for various instructions. 4777 // Validate and return a target constant for them if we can. 4778 case 'z': { 4779 // 'z' maps to xzr or wzr so it needs an input of 0. 4780 if (!isNullConstant(Op)) 4781 return; 4782 4783 if (Op.getValueType() == MVT::i64) 4784 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 4785 else 4786 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 4787 break; 4788 } 4789 4790 case 'I': 4791 case 'J': 4792 case 'K': 4793 case 'L': 4794 case 'M': 4795 case 'N': 4796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4797 if (!C) 4798 return; 4799 4800 // Grab the value and do some validation. 4801 uint64_t CVal = C->getZExtValue(); 4802 switch (ConstraintLetter) { 4803 // The I constraint applies only to simple ADD or SUB immediate operands: 4804 // i.e. 0 to 4095 with optional shift by 12 4805 // The J constraint applies only to ADD or SUB immediates that would be 4806 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 4807 // instruction [or vice versa], in other words -1 to -4095 with optional 4808 // left shift by 12. 4809 case 'I': 4810 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 4811 break; 4812 return; 4813 case 'J': { 4814 uint64_t NVal = -C->getSExtValue(); 4815 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 4816 CVal = C->getSExtValue(); 4817 break; 4818 } 4819 return; 4820 } 4821 // The K and L constraints apply *only* to logical immediates, including 4822 // what used to be the MOVI alias for ORR (though the MOVI alias has now 4823 // been removed and MOV should be used). So these constraints have to 4824 // distinguish between bit patterns that are valid 32-bit or 64-bit 4825 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 4826 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 4827 // versa. 4828 case 'K': 4829 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4830 break; 4831 return; 4832 case 'L': 4833 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4834 break; 4835 return; 4836 // The M and N constraints are a superset of K and L respectively, for use 4837 // with the MOV (immediate) alias. As well as the logical immediates they 4838 // also match 32 or 64-bit immediates that can be loaded either using a 4839 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 4840 // (M) or 64-bit 0x1234000000000000 (N) etc. 4841 // As a note some of this code is liberally stolen from the asm parser. 4842 case 'M': { 4843 if (!isUInt<32>(CVal)) 4844 return; 4845 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4846 break; 4847 if ((CVal & 0xFFFF) == CVal) 4848 break; 4849 if ((CVal & 0xFFFF0000ULL) == CVal) 4850 break; 4851 uint64_t NCVal = ~(uint32_t)CVal; 4852 if ((NCVal & 0xFFFFULL) == NCVal) 4853 break; 4854 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4855 break; 4856 return; 4857 } 4858 case 'N': { 4859 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4860 break; 4861 if ((CVal & 0xFFFFULL) == CVal) 4862 break; 4863 if ((CVal & 0xFFFF0000ULL) == CVal) 4864 break; 4865 if ((CVal & 0xFFFF00000000ULL) == CVal) 4866 break; 4867 if ((CVal & 0xFFFF000000000000ULL) == CVal) 4868 break; 4869 uint64_t NCVal = ~CVal; 4870 if ((NCVal & 0xFFFFULL) == NCVal) 4871 break; 4872 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4873 break; 4874 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 4875 break; 4876 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 4877 break; 4878 return; 4879 } 4880 default: 4881 return; 4882 } 4883 4884 // All assembler immediates are 64-bit integers. 4885 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 4886 break; 4887 } 4888 4889 if (Result.getNode()) { 4890 Ops.push_back(Result); 4891 return; 4892 } 4893 4894 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 4895 } 4896 4897 //===----------------------------------------------------------------------===// 4898 // AArch64 Advanced SIMD Support 4899 //===----------------------------------------------------------------------===// 4900 4901 /// WidenVector - Given a value in the V64 register class, produce the 4902 /// equivalent value in the V128 register class. 4903 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 4904 EVT VT = V64Reg.getValueType(); 4905 unsigned NarrowSize = VT.getVectorNumElements(); 4906 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 4907 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 4908 SDLoc DL(V64Reg); 4909 4910 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 4911 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 4912 } 4913 4914 /// getExtFactor - Determine the adjustment factor for the position when 4915 /// generating an "extract from vector registers" instruction. 4916 static unsigned getExtFactor(SDValue &V) { 4917 EVT EltType = V.getValueType().getVectorElementType(); 4918 return EltType.getSizeInBits() / 8; 4919 } 4920 4921 /// NarrowVector - Given a value in the V128 register class, produce the 4922 /// equivalent value in the V64 register class. 4923 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 4924 EVT VT = V128Reg.getValueType(); 4925 unsigned WideSize = VT.getVectorNumElements(); 4926 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 4927 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 4928 SDLoc DL(V128Reg); 4929 4930 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 4931 } 4932 4933 // Gather data to see if the operation can be modelled as a 4934 // shuffle in combination with VEXTs. 4935 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 4936 SelectionDAG &DAG) const { 4937 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 4938 SDLoc dl(Op); 4939 EVT VT = Op.getValueType(); 4940 unsigned NumElts = VT.getVectorNumElements(); 4941 4942 struct ShuffleSourceInfo { 4943 SDValue Vec; 4944 unsigned MinElt; 4945 unsigned MaxElt; 4946 4947 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 4948 // be compatible with the shuffle we intend to construct. As a result 4949 // ShuffleVec will be some sliding window into the original Vec. 4950 SDValue ShuffleVec; 4951 4952 // Code should guarantee that element i in Vec starts at element "WindowBase 4953 // + i * WindowScale in ShuffleVec". 4954 int WindowBase; 4955 int WindowScale; 4956 4957 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 4958 ShuffleSourceInfo(SDValue Vec) 4959 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 4960 WindowScale(1) {} 4961 }; 4962 4963 // First gather all vectors used as an immediate source for this BUILD_VECTOR 4964 // node. 4965 SmallVector<ShuffleSourceInfo, 2> Sources; 4966 for (unsigned i = 0; i < NumElts; ++i) { 4967 SDValue V = Op.getOperand(i); 4968 if (V.isUndef()) 4969 continue; 4970 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4971 !isa<ConstantSDNode>(V.getOperand(1))) { 4972 // A shuffle can only come from building a vector from various 4973 // elements of other vectors, provided their indices are constant. 4974 return SDValue(); 4975 } 4976 4977 // Add this element source to the list if it's not already there. 4978 SDValue SourceVec = V.getOperand(0); 4979 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 4980 if (Source == Sources.end()) 4981 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 4982 4983 // Update the minimum and maximum lane number seen. 4984 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 4985 Source->MinElt = std::min(Source->MinElt, EltNo); 4986 Source->MaxElt = std::max(Source->MaxElt, EltNo); 4987 } 4988 4989 // Currently only do something sane when at most two source vectors 4990 // are involved. 4991 if (Sources.size() > 2) 4992 return SDValue(); 4993 4994 // Find out the smallest element size among result and two sources, and use 4995 // it as element size to build the shuffle_vector. 4996 EVT SmallestEltTy = VT.getVectorElementType(); 4997 for (auto &Source : Sources) { 4998 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 4999 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5000 SmallestEltTy = SrcEltTy; 5001 } 5002 } 5003 unsigned ResMultiplier = 5004 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5005 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5006 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5007 5008 // If the source vector is too wide or too narrow, we may nevertheless be able 5009 // to construct a compatible shuffle either by concatenating it with UNDEF or 5010 // extracting a suitable range of elements. 5011 for (auto &Src : Sources) { 5012 EVT SrcVT = Src.ShuffleVec.getValueType(); 5013 5014 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5015 continue; 5016 5017 // This stage of the search produces a source with the same element type as 5018 // the original, but with a total width matching the BUILD_VECTOR output. 5019 EVT EltVT = SrcVT.getVectorElementType(); 5020 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5021 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5022 5023 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5024 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5025 // We can pad out the smaller vector for free, so if it's part of a 5026 // shuffle... 5027 Src.ShuffleVec = 5028 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5029 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5030 continue; 5031 } 5032 5033 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5034 5035 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5036 // Span too large for a VEXT to cope 5037 return SDValue(); 5038 } 5039 5040 if (Src.MinElt >= NumSrcElts) { 5041 // The extraction can just take the second half 5042 Src.ShuffleVec = 5043 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5044 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5045 Src.WindowBase = -NumSrcElts; 5046 } else if (Src.MaxElt < NumSrcElts) { 5047 // The extraction can just take the first half 5048 Src.ShuffleVec = 5049 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5050 DAG.getConstant(0, dl, MVT::i64)); 5051 } else { 5052 // An actual VEXT is needed 5053 SDValue VEXTSrc1 = 5054 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5055 DAG.getConstant(0, dl, MVT::i64)); 5056 SDValue VEXTSrc2 = 5057 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5058 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5059 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5060 5061 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5062 VEXTSrc2, 5063 DAG.getConstant(Imm, dl, MVT::i32)); 5064 Src.WindowBase = -Src.MinElt; 5065 } 5066 } 5067 5068 // Another possible incompatibility occurs from the vector element types. We 5069 // can fix this by bitcasting the source vectors to the same type we intend 5070 // for the shuffle. 5071 for (auto &Src : Sources) { 5072 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5073 if (SrcEltTy == SmallestEltTy) 5074 continue; 5075 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5076 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5077 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5078 Src.WindowBase *= Src.WindowScale; 5079 } 5080 5081 // Final sanity check before we try to actually produce a shuffle. 5082 DEBUG( 5083 for (auto Src : Sources) 5084 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5085 ); 5086 5087 // The stars all align, our next step is to produce the mask for the shuffle. 5088 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5089 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5090 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5091 SDValue Entry = Op.getOperand(i); 5092 if (Entry.isUndef()) 5093 continue; 5094 5095 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5096 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5097 5098 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5099 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5100 // segment. 5101 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5102 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5103 VT.getVectorElementType().getSizeInBits()); 5104 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5105 5106 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5107 // starting at the appropriate offset. 5108 int *LaneMask = &Mask[i * ResMultiplier]; 5109 5110 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5111 ExtractBase += NumElts * (Src - Sources.begin()); 5112 for (int j = 0; j < LanesDefined; ++j) 5113 LaneMask[j] = ExtractBase + j; 5114 } 5115 5116 // Final check before we try to produce nonsense... 5117 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5118 return SDValue(); 5119 5120 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5121 for (unsigned i = 0; i < Sources.size(); ++i) 5122 ShuffleOps[i] = Sources[i].ShuffleVec; 5123 5124 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5125 ShuffleOps[1], &Mask[0]); 5126 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5127 } 5128 5129 // check if an EXT instruction can handle the shuffle mask when the 5130 // vector sources of the shuffle are the same. 5131 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5132 unsigned NumElts = VT.getVectorNumElements(); 5133 5134 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5135 if (M[0] < 0) 5136 return false; 5137 5138 Imm = M[0]; 5139 5140 // If this is a VEXT shuffle, the immediate value is the index of the first 5141 // element. The other shuffle indices must be the successive elements after 5142 // the first one. 5143 unsigned ExpectedElt = Imm; 5144 for (unsigned i = 1; i < NumElts; ++i) { 5145 // Increment the expected index. If it wraps around, just follow it 5146 // back to index zero and keep going. 5147 ++ExpectedElt; 5148 if (ExpectedElt == NumElts) 5149 ExpectedElt = 0; 5150 5151 if (M[i] < 0) 5152 continue; // ignore UNDEF indices 5153 if (ExpectedElt != static_cast<unsigned>(M[i])) 5154 return false; 5155 } 5156 5157 return true; 5158 } 5159 5160 // check if an EXT instruction can handle the shuffle mask when the 5161 // vector sources of the shuffle are different. 5162 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5163 unsigned &Imm) { 5164 // Look for the first non-undef element. 5165 const int *FirstRealElt = std::find_if(M.begin(), M.end(), 5166 [](int Elt) {return Elt >= 0;}); 5167 5168 // Benefit form APInt to handle overflow when calculating expected element. 5169 unsigned NumElts = VT.getVectorNumElements(); 5170 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5171 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5172 // The following shuffle indices must be the successive elements after the 5173 // first real element. 5174 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5175 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5176 if (FirstWrongElt != M.end()) 5177 return false; 5178 5179 // The index of an EXT is the first element if it is not UNDEF. 5180 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5181 // value of the first element. E.g. 5182 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5183 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5184 // ExpectedElt is the last mask index plus 1. 5185 Imm = ExpectedElt.getZExtValue(); 5186 5187 // There are two difference cases requiring to reverse input vectors. 5188 // For example, for vector <4 x i32> we have the following cases, 5189 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5190 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5191 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5192 // to reverse two input vectors. 5193 if (Imm < NumElts) 5194 ReverseEXT = true; 5195 else 5196 Imm -= NumElts; 5197 5198 return true; 5199 } 5200 5201 /// isREVMask - Check if a vector shuffle corresponds to a REV 5202 /// instruction with the specified blocksize. (The order of the elements 5203 /// within each block of the vector is reversed.) 5204 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5205 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5206 "Only possible block sizes for REV are: 16, 32, 64"); 5207 5208 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5209 if (EltSz == 64) 5210 return false; 5211 5212 unsigned NumElts = VT.getVectorNumElements(); 5213 unsigned BlockElts = M[0] + 1; 5214 // If the first shuffle index is UNDEF, be optimistic. 5215 if (M[0] < 0) 5216 BlockElts = BlockSize / EltSz; 5217 5218 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5219 return false; 5220 5221 for (unsigned i = 0; i < NumElts; ++i) { 5222 if (M[i] < 0) 5223 continue; // ignore UNDEF indices 5224 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5225 return false; 5226 } 5227 5228 return true; 5229 } 5230 5231 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5232 unsigned NumElts = VT.getVectorNumElements(); 5233 WhichResult = (M[0] == 0 ? 0 : 1); 5234 unsigned Idx = WhichResult * NumElts / 2; 5235 for (unsigned i = 0; i != NumElts; i += 2) { 5236 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5237 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5238 return false; 5239 Idx += 1; 5240 } 5241 5242 return true; 5243 } 5244 5245 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5246 unsigned NumElts = VT.getVectorNumElements(); 5247 WhichResult = (M[0] == 0 ? 0 : 1); 5248 for (unsigned i = 0; i != NumElts; ++i) { 5249 if (M[i] < 0) 5250 continue; // ignore UNDEF indices 5251 if ((unsigned)M[i] != 2 * i + WhichResult) 5252 return false; 5253 } 5254 5255 return true; 5256 } 5257 5258 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5259 unsigned NumElts = VT.getVectorNumElements(); 5260 WhichResult = (M[0] == 0 ? 0 : 1); 5261 for (unsigned i = 0; i < NumElts; i += 2) { 5262 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5263 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5264 return false; 5265 } 5266 return true; 5267 } 5268 5269 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5270 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5271 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5272 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5273 unsigned NumElts = VT.getVectorNumElements(); 5274 WhichResult = (M[0] == 0 ? 0 : 1); 5275 unsigned Idx = WhichResult * NumElts / 2; 5276 for (unsigned i = 0; i != NumElts; i += 2) { 5277 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5278 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5279 return false; 5280 Idx += 1; 5281 } 5282 5283 return true; 5284 } 5285 5286 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5287 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5288 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5289 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5290 unsigned Half = VT.getVectorNumElements() / 2; 5291 WhichResult = (M[0] == 0 ? 0 : 1); 5292 for (unsigned j = 0; j != 2; ++j) { 5293 unsigned Idx = WhichResult; 5294 for (unsigned i = 0; i != Half; ++i) { 5295 int MIdx = M[i + j * Half]; 5296 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5297 return false; 5298 Idx += 2; 5299 } 5300 } 5301 5302 return true; 5303 } 5304 5305 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5306 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5307 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5308 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5309 unsigned NumElts = VT.getVectorNumElements(); 5310 WhichResult = (M[0] == 0 ? 0 : 1); 5311 for (unsigned i = 0; i < NumElts; i += 2) { 5312 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5313 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5314 return false; 5315 } 5316 return true; 5317 } 5318 5319 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5320 bool &DstIsLeft, int &Anomaly) { 5321 if (M.size() != static_cast<size_t>(NumInputElements)) 5322 return false; 5323 5324 int NumLHSMatch = 0, NumRHSMatch = 0; 5325 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5326 5327 for (int i = 0; i < NumInputElements; ++i) { 5328 if (M[i] == -1) { 5329 ++NumLHSMatch; 5330 ++NumRHSMatch; 5331 continue; 5332 } 5333 5334 if (M[i] == i) 5335 ++NumLHSMatch; 5336 else 5337 LastLHSMismatch = i; 5338 5339 if (M[i] == i + NumInputElements) 5340 ++NumRHSMatch; 5341 else 5342 LastRHSMismatch = i; 5343 } 5344 5345 if (NumLHSMatch == NumInputElements - 1) { 5346 DstIsLeft = true; 5347 Anomaly = LastLHSMismatch; 5348 return true; 5349 } else if (NumRHSMatch == NumInputElements - 1) { 5350 DstIsLeft = false; 5351 Anomaly = LastRHSMismatch; 5352 return true; 5353 } 5354 5355 return false; 5356 } 5357 5358 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5359 if (VT.getSizeInBits() != 128) 5360 return false; 5361 5362 unsigned NumElts = VT.getVectorNumElements(); 5363 5364 for (int I = 0, E = NumElts / 2; I != E; I++) { 5365 if (Mask[I] != I) 5366 return false; 5367 } 5368 5369 int Offset = NumElts / 2; 5370 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5371 if (Mask[I] != I + SplitLHS * Offset) 5372 return false; 5373 } 5374 5375 return true; 5376 } 5377 5378 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5379 SDLoc DL(Op); 5380 EVT VT = Op.getValueType(); 5381 SDValue V0 = Op.getOperand(0); 5382 SDValue V1 = Op.getOperand(1); 5383 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5384 5385 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5386 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5387 return SDValue(); 5388 5389 bool SplitV0 = V0.getValueType().getSizeInBits() == 128; 5390 5391 if (!isConcatMask(Mask, VT, SplitV0)) 5392 return SDValue(); 5393 5394 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5395 VT.getVectorNumElements() / 2); 5396 if (SplitV0) { 5397 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5398 DAG.getConstant(0, DL, MVT::i64)); 5399 } 5400 if (V1.getValueType().getSizeInBits() == 128) { 5401 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5402 DAG.getConstant(0, DL, MVT::i64)); 5403 } 5404 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5405 } 5406 5407 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5408 /// the specified operations to build the shuffle. 5409 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5410 SDValue RHS, SelectionDAG &DAG, 5411 SDLoc dl) { 5412 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5413 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5414 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5415 5416 enum { 5417 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5418 OP_VREV, 5419 OP_VDUP0, 5420 OP_VDUP1, 5421 OP_VDUP2, 5422 OP_VDUP3, 5423 OP_VEXT1, 5424 OP_VEXT2, 5425 OP_VEXT3, 5426 OP_VUZPL, // VUZP, left result 5427 OP_VUZPR, // VUZP, right result 5428 OP_VZIPL, // VZIP, left result 5429 OP_VZIPR, // VZIP, right result 5430 OP_VTRNL, // VTRN, left result 5431 OP_VTRNR // VTRN, right result 5432 }; 5433 5434 if (OpNum == OP_COPY) { 5435 if (LHSID == (1 * 9 + 2) * 9 + 3) 5436 return LHS; 5437 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5438 return RHS; 5439 } 5440 5441 SDValue OpLHS, OpRHS; 5442 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5443 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5444 EVT VT = OpLHS.getValueType(); 5445 5446 switch (OpNum) { 5447 default: 5448 llvm_unreachable("Unknown shuffle opcode!"); 5449 case OP_VREV: 5450 // VREV divides the vector in half and swaps within the half. 5451 if (VT.getVectorElementType() == MVT::i32 || 5452 VT.getVectorElementType() == MVT::f32) 5453 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5454 // vrev <4 x i16> -> REV32 5455 if (VT.getVectorElementType() == MVT::i16 || 5456 VT.getVectorElementType() == MVT::f16) 5457 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5458 // vrev <4 x i8> -> REV16 5459 assert(VT.getVectorElementType() == MVT::i8); 5460 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5461 case OP_VDUP0: 5462 case OP_VDUP1: 5463 case OP_VDUP2: 5464 case OP_VDUP3: { 5465 EVT EltTy = VT.getVectorElementType(); 5466 unsigned Opcode; 5467 if (EltTy == MVT::i8) 5468 Opcode = AArch64ISD::DUPLANE8; 5469 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5470 Opcode = AArch64ISD::DUPLANE16; 5471 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5472 Opcode = AArch64ISD::DUPLANE32; 5473 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5474 Opcode = AArch64ISD::DUPLANE64; 5475 else 5476 llvm_unreachable("Invalid vector element type?"); 5477 5478 if (VT.getSizeInBits() == 64) 5479 OpLHS = WidenVector(OpLHS, DAG); 5480 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5481 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5482 } 5483 case OP_VEXT1: 5484 case OP_VEXT2: 5485 case OP_VEXT3: { 5486 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5487 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5488 DAG.getConstant(Imm, dl, MVT::i32)); 5489 } 5490 case OP_VUZPL: 5491 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5492 OpRHS); 5493 case OP_VUZPR: 5494 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5495 OpRHS); 5496 case OP_VZIPL: 5497 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5498 OpRHS); 5499 case OP_VZIPR: 5500 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5501 OpRHS); 5502 case OP_VTRNL: 5503 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5504 OpRHS); 5505 case OP_VTRNR: 5506 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5507 OpRHS); 5508 } 5509 } 5510 5511 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5512 SelectionDAG &DAG) { 5513 // Check to see if we can use the TBL instruction. 5514 SDValue V1 = Op.getOperand(0); 5515 SDValue V2 = Op.getOperand(1); 5516 SDLoc DL(Op); 5517 5518 EVT EltVT = Op.getValueType().getVectorElementType(); 5519 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5520 5521 SmallVector<SDValue, 8> TBLMask; 5522 for (int Val : ShuffleMask) { 5523 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 5524 unsigned Offset = Byte + Val * BytesPerElt; 5525 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 5526 } 5527 } 5528 5529 MVT IndexVT = MVT::v8i8; 5530 unsigned IndexLen = 8; 5531 if (Op.getValueType().getSizeInBits() == 128) { 5532 IndexVT = MVT::v16i8; 5533 IndexLen = 16; 5534 } 5535 5536 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 5537 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 5538 5539 SDValue Shuffle; 5540 if (V2.getNode()->isUndef()) { 5541 if (IndexLen == 8) 5542 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 5543 Shuffle = DAG.getNode( 5544 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5545 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5546 DAG.getBuildVector(IndexVT, DL, 5547 makeArrayRef(TBLMask.data(), IndexLen))); 5548 } else { 5549 if (IndexLen == 8) { 5550 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 5551 Shuffle = DAG.getNode( 5552 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5553 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5554 DAG.getBuildVector(IndexVT, DL, 5555 makeArrayRef(TBLMask.data(), IndexLen))); 5556 } else { 5557 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 5558 // cannot currently represent the register constraints on the input 5559 // table registers. 5560 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 5561 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 5562 // IndexLen)); 5563 Shuffle = DAG.getNode( 5564 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5565 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 5566 V2Cst, DAG.getBuildVector(IndexVT, DL, 5567 makeArrayRef(TBLMask.data(), IndexLen))); 5568 } 5569 } 5570 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 5571 } 5572 5573 static unsigned getDUPLANEOp(EVT EltType) { 5574 if (EltType == MVT::i8) 5575 return AArch64ISD::DUPLANE8; 5576 if (EltType == MVT::i16 || EltType == MVT::f16) 5577 return AArch64ISD::DUPLANE16; 5578 if (EltType == MVT::i32 || EltType == MVT::f32) 5579 return AArch64ISD::DUPLANE32; 5580 if (EltType == MVT::i64 || EltType == MVT::f64) 5581 return AArch64ISD::DUPLANE64; 5582 5583 llvm_unreachable("Invalid vector element type?"); 5584 } 5585 5586 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 5587 SelectionDAG &DAG) const { 5588 SDLoc dl(Op); 5589 EVT VT = Op.getValueType(); 5590 5591 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5592 5593 // Convert shuffles that are directly supported on NEON to target-specific 5594 // DAG nodes, instead of keeping them as shuffles and matching them again 5595 // during code selection. This is more efficient and avoids the possibility 5596 // of inconsistencies between legalization and selection. 5597 ArrayRef<int> ShuffleMask = SVN->getMask(); 5598 5599 SDValue V1 = Op.getOperand(0); 5600 SDValue V2 = Op.getOperand(1); 5601 5602 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], 5603 V1.getValueType().getSimpleVT())) { 5604 int Lane = SVN->getSplatIndex(); 5605 // If this is undef splat, generate it via "just" vdup, if possible. 5606 if (Lane == -1) 5607 Lane = 0; 5608 5609 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 5610 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 5611 V1.getOperand(0)); 5612 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 5613 // constant. If so, we can just reference the lane's definition directly. 5614 if (V1.getOpcode() == ISD::BUILD_VECTOR && 5615 !isa<ConstantSDNode>(V1.getOperand(Lane))) 5616 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 5617 5618 // Otherwise, duplicate from the lane of the input vector. 5619 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 5620 5621 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 5622 // to make a vector of the same size as this SHUFFLE. We can ignore the 5623 // extract entirely, and canonicalise the concat using WidenVector. 5624 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 5625 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 5626 V1 = V1.getOperand(0); 5627 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 5628 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 5629 Lane -= Idx * VT.getVectorNumElements() / 2; 5630 V1 = WidenVector(V1.getOperand(Idx), DAG); 5631 } else if (VT.getSizeInBits() == 64) 5632 V1 = WidenVector(V1, DAG); 5633 5634 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 5635 } 5636 5637 if (isREVMask(ShuffleMask, VT, 64)) 5638 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 5639 if (isREVMask(ShuffleMask, VT, 32)) 5640 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 5641 if (isREVMask(ShuffleMask, VT, 16)) 5642 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 5643 5644 bool ReverseEXT = false; 5645 unsigned Imm; 5646 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 5647 if (ReverseEXT) 5648 std::swap(V1, V2); 5649 Imm *= getExtFactor(V1); 5650 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 5651 DAG.getConstant(Imm, dl, MVT::i32)); 5652 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 5653 Imm *= getExtFactor(V1); 5654 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 5655 DAG.getConstant(Imm, dl, MVT::i32)); 5656 } 5657 5658 unsigned WhichResult; 5659 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 5660 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5661 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5662 } 5663 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 5664 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5665 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5666 } 5667 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 5668 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5669 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5670 } 5671 5672 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5673 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5674 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5675 } 5676 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5677 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5678 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5679 } 5680 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5681 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5682 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5683 } 5684 5685 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 5686 return Concat; 5687 5688 bool DstIsLeft; 5689 int Anomaly; 5690 int NumInputElements = V1.getValueType().getVectorNumElements(); 5691 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 5692 SDValue DstVec = DstIsLeft ? V1 : V2; 5693 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 5694 5695 SDValue SrcVec = V1; 5696 int SrcLane = ShuffleMask[Anomaly]; 5697 if (SrcLane >= NumInputElements) { 5698 SrcVec = V2; 5699 SrcLane -= VT.getVectorNumElements(); 5700 } 5701 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 5702 5703 EVT ScalarVT = VT.getVectorElementType(); 5704 5705 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 5706 ScalarVT = MVT::i32; 5707 5708 return DAG.getNode( 5709 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 5710 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 5711 DstLaneV); 5712 } 5713 5714 // If the shuffle is not directly supported and it has 4 elements, use 5715 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5716 unsigned NumElts = VT.getVectorNumElements(); 5717 if (NumElts == 4) { 5718 unsigned PFIndexes[4]; 5719 for (unsigned i = 0; i != 4; ++i) { 5720 if (ShuffleMask[i] < 0) 5721 PFIndexes[i] = 8; 5722 else 5723 PFIndexes[i] = ShuffleMask[i]; 5724 } 5725 5726 // Compute the index in the perfect shuffle table. 5727 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 5728 PFIndexes[2] * 9 + PFIndexes[3]; 5729 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5730 unsigned Cost = (PFEntry >> 30); 5731 5732 if (Cost <= 4) 5733 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5734 } 5735 5736 return GenerateTBL(Op, ShuffleMask, DAG); 5737 } 5738 5739 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 5740 APInt &UndefBits) { 5741 EVT VT = BVN->getValueType(0); 5742 APInt SplatBits, SplatUndef; 5743 unsigned SplatBitSize; 5744 bool HasAnyUndefs; 5745 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5746 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 5747 5748 for (unsigned i = 0; i < NumSplats; ++i) { 5749 CnstBits <<= SplatBitSize; 5750 UndefBits <<= SplatBitSize; 5751 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 5752 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 5753 } 5754 5755 return true; 5756 } 5757 5758 return false; 5759 } 5760 5761 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 5762 SelectionDAG &DAG) const { 5763 BuildVectorSDNode *BVN = 5764 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 5765 SDValue LHS = Op.getOperand(0); 5766 SDLoc dl(Op); 5767 EVT VT = Op.getValueType(); 5768 5769 if (!BVN) 5770 return Op; 5771 5772 APInt CnstBits(VT.getSizeInBits(), 0); 5773 APInt UndefBits(VT.getSizeInBits(), 0); 5774 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 5775 // We only have BIC vector immediate instruction, which is and-not. 5776 CnstBits = ~CnstBits; 5777 5778 // We make use of a little bit of goto ickiness in order to avoid having to 5779 // duplicate the immediate matching logic for the undef toggled case. 5780 bool SecondTry = false; 5781 AttemptModImm: 5782 5783 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 5784 CnstBits = CnstBits.zextOrTrunc(64); 5785 uint64_t CnstVal = CnstBits.getZExtValue(); 5786 5787 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 5788 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 5789 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5790 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5791 DAG.getConstant(CnstVal, dl, MVT::i32), 5792 DAG.getConstant(0, dl, MVT::i32)); 5793 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5794 } 5795 5796 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 5797 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 5798 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5799 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5800 DAG.getConstant(CnstVal, dl, MVT::i32), 5801 DAG.getConstant(8, dl, MVT::i32)); 5802 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5803 } 5804 5805 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 5806 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 5807 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5808 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5809 DAG.getConstant(CnstVal, dl, MVT::i32), 5810 DAG.getConstant(16, dl, MVT::i32)); 5811 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5812 } 5813 5814 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 5815 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 5816 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5817 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5818 DAG.getConstant(CnstVal, dl, MVT::i32), 5819 DAG.getConstant(24, dl, MVT::i32)); 5820 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5821 } 5822 5823 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 5824 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 5825 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5826 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5827 DAG.getConstant(CnstVal, dl, MVT::i32), 5828 DAG.getConstant(0, dl, MVT::i32)); 5829 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5830 } 5831 5832 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 5833 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 5834 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5835 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5836 DAG.getConstant(CnstVal, dl, MVT::i32), 5837 DAG.getConstant(8, dl, MVT::i32)); 5838 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5839 } 5840 } 5841 5842 if (SecondTry) 5843 goto FailedModImm; 5844 SecondTry = true; 5845 CnstBits = ~UndefBits; 5846 goto AttemptModImm; 5847 } 5848 5849 // We can always fall back to a non-immediate AND. 5850 FailedModImm: 5851 return Op; 5852 } 5853 5854 // Specialized code to quickly find if PotentialBVec is a BuildVector that 5855 // consists of only the same constant int value, returned in reference arg 5856 // ConstVal 5857 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 5858 uint64_t &ConstVal) { 5859 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 5860 if (!Bvec) 5861 return false; 5862 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 5863 if (!FirstElt) 5864 return false; 5865 EVT VT = Bvec->getValueType(0); 5866 unsigned NumElts = VT.getVectorNumElements(); 5867 for (unsigned i = 1; i < NumElts; ++i) 5868 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 5869 return false; 5870 ConstVal = FirstElt->getZExtValue(); 5871 return true; 5872 } 5873 5874 static unsigned getIntrinsicID(const SDNode *N) { 5875 unsigned Opcode = N->getOpcode(); 5876 switch (Opcode) { 5877 default: 5878 return Intrinsic::not_intrinsic; 5879 case ISD::INTRINSIC_WO_CHAIN: { 5880 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5881 if (IID < Intrinsic::num_intrinsics) 5882 return IID; 5883 return Intrinsic::not_intrinsic; 5884 } 5885 } 5886 } 5887 5888 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 5889 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 5890 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 5891 // Also, logical shift right -> sri, with the same structure. 5892 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 5893 EVT VT = N->getValueType(0); 5894 5895 if (!VT.isVector()) 5896 return SDValue(); 5897 5898 SDLoc DL(N); 5899 5900 // Is the first op an AND? 5901 const SDValue And = N->getOperand(0); 5902 if (And.getOpcode() != ISD::AND) 5903 return SDValue(); 5904 5905 // Is the second op an shl or lshr? 5906 SDValue Shift = N->getOperand(1); 5907 // This will have been turned into: AArch64ISD::VSHL vector, #shift 5908 // or AArch64ISD::VLSHR vector, #shift 5909 unsigned ShiftOpc = Shift.getOpcode(); 5910 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 5911 return SDValue(); 5912 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 5913 5914 // Is the shift amount constant? 5915 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 5916 if (!C2node) 5917 return SDValue(); 5918 5919 // Is the and mask vector all constant? 5920 uint64_t C1; 5921 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 5922 return SDValue(); 5923 5924 // Is C1 == ~C2, taking into account how much one can shift elements of a 5925 // particular size? 5926 uint64_t C2 = C2node->getZExtValue(); 5927 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits(); 5928 if (C2 > ElemSizeInBits) 5929 return SDValue(); 5930 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 5931 if ((C1 & ElemMask) != (~C2 & ElemMask)) 5932 return SDValue(); 5933 5934 SDValue X = And.getOperand(0); 5935 SDValue Y = Shift.getOperand(0); 5936 5937 unsigned Intrin = 5938 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 5939 SDValue ResultSLI = 5940 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 5941 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 5942 Shift.getOperand(1)); 5943 5944 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 5945 DEBUG(N->dump(&DAG)); 5946 DEBUG(dbgs() << "into: \n"); 5947 DEBUG(ResultSLI->dump(&DAG)); 5948 5949 ++NumShiftInserts; 5950 return ResultSLI; 5951 } 5952 5953 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 5954 SelectionDAG &DAG) const { 5955 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 5956 if (EnableAArch64SlrGeneration) { 5957 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 5958 return Res; 5959 } 5960 5961 BuildVectorSDNode *BVN = 5962 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 5963 SDValue LHS = Op.getOperand(1); 5964 SDLoc dl(Op); 5965 EVT VT = Op.getValueType(); 5966 5967 // OR commutes, so try swapping the operands. 5968 if (!BVN) { 5969 LHS = Op.getOperand(0); 5970 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 5971 } 5972 if (!BVN) 5973 return Op; 5974 5975 APInt CnstBits(VT.getSizeInBits(), 0); 5976 APInt UndefBits(VT.getSizeInBits(), 0); 5977 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 5978 // We make use of a little bit of goto ickiness in order to avoid having to 5979 // duplicate the immediate matching logic for the undef toggled case. 5980 bool SecondTry = false; 5981 AttemptModImm: 5982 5983 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 5984 CnstBits = CnstBits.zextOrTrunc(64); 5985 uint64_t CnstVal = CnstBits.getZExtValue(); 5986 5987 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 5988 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 5989 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5990 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 5991 DAG.getConstant(CnstVal, dl, MVT::i32), 5992 DAG.getConstant(0, dl, MVT::i32)); 5993 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5994 } 5995 5996 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 5997 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 5998 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5999 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6000 DAG.getConstant(CnstVal, dl, MVT::i32), 6001 DAG.getConstant(8, dl, MVT::i32)); 6002 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6003 } 6004 6005 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6006 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6007 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6008 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6009 DAG.getConstant(CnstVal, dl, MVT::i32), 6010 DAG.getConstant(16, dl, MVT::i32)); 6011 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6012 } 6013 6014 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6015 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6016 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6017 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6018 DAG.getConstant(CnstVal, dl, MVT::i32), 6019 DAG.getConstant(24, dl, MVT::i32)); 6020 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6021 } 6022 6023 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6024 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6025 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6026 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6027 DAG.getConstant(CnstVal, dl, MVT::i32), 6028 DAG.getConstant(0, dl, MVT::i32)); 6029 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6030 } 6031 6032 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6033 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6034 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6035 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6036 DAG.getConstant(CnstVal, dl, MVT::i32), 6037 DAG.getConstant(8, dl, MVT::i32)); 6038 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6039 } 6040 } 6041 6042 if (SecondTry) 6043 goto FailedModImm; 6044 SecondTry = true; 6045 CnstBits = UndefBits; 6046 goto AttemptModImm; 6047 } 6048 6049 // We can always fall back to a non-immediate OR. 6050 FailedModImm: 6051 return Op; 6052 } 6053 6054 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6055 // be truncated to fit element width. 6056 static SDValue NormalizeBuildVector(SDValue Op, 6057 SelectionDAG &DAG) { 6058 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6059 SDLoc dl(Op); 6060 EVT VT = Op.getValueType(); 6061 EVT EltTy= VT.getVectorElementType(); 6062 6063 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6064 return Op; 6065 6066 SmallVector<SDValue, 16> Ops; 6067 for (SDValue Lane : Op->ops()) { 6068 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6069 APInt LowBits(EltTy.getSizeInBits(), 6070 CstLane->getZExtValue()); 6071 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6072 } 6073 Ops.push_back(Lane); 6074 } 6075 return DAG.getBuildVector(VT, dl, Ops); 6076 } 6077 6078 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6079 SelectionDAG &DAG) const { 6080 SDLoc dl(Op); 6081 EVT VT = Op.getValueType(); 6082 Op = NormalizeBuildVector(Op, DAG); 6083 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6084 6085 APInt CnstBits(VT.getSizeInBits(), 0); 6086 APInt UndefBits(VT.getSizeInBits(), 0); 6087 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6088 // We make use of a little bit of goto ickiness in order to avoid having to 6089 // duplicate the immediate matching logic for the undef toggled case. 6090 bool SecondTry = false; 6091 AttemptModImm: 6092 6093 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6094 CnstBits = CnstBits.zextOrTrunc(64); 6095 uint64_t CnstVal = CnstBits.getZExtValue(); 6096 6097 // Certain magic vector constants (used to express things like NOT 6098 // and NEG) are passed through unmodified. This allows codegen patterns 6099 // for these operations to match. Special-purpose patterns will lower 6100 // these immediates to MOVIs if it proves necessary. 6101 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6102 return Op; 6103 6104 // The many faces of MOVI... 6105 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6106 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6107 if (VT.getSizeInBits() == 128) { 6108 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6109 DAG.getConstant(CnstVal, dl, MVT::i32)); 6110 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6111 } 6112 6113 // Support the V64 version via subregister insertion. 6114 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6115 DAG.getConstant(CnstVal, dl, MVT::i32)); 6116 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6117 } 6118 6119 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6120 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6121 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6122 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6123 DAG.getConstant(CnstVal, dl, MVT::i32), 6124 DAG.getConstant(0, dl, MVT::i32)); 6125 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6126 } 6127 6128 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6129 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6130 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6131 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6132 DAG.getConstant(CnstVal, dl, MVT::i32), 6133 DAG.getConstant(8, dl, MVT::i32)); 6134 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6135 } 6136 6137 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6138 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6139 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6140 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6141 DAG.getConstant(CnstVal, dl, MVT::i32), 6142 DAG.getConstant(16, dl, MVT::i32)); 6143 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6144 } 6145 6146 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6147 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6148 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6149 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6150 DAG.getConstant(CnstVal, dl, MVT::i32), 6151 DAG.getConstant(24, dl, MVT::i32)); 6152 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6153 } 6154 6155 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6156 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6157 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6158 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6159 DAG.getConstant(CnstVal, dl, MVT::i32), 6160 DAG.getConstant(0, dl, MVT::i32)); 6161 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6162 } 6163 6164 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6165 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6166 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6167 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6168 DAG.getConstant(CnstVal, dl, MVT::i32), 6169 DAG.getConstant(8, dl, MVT::i32)); 6170 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6171 } 6172 6173 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6174 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6175 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6176 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6177 DAG.getConstant(CnstVal, dl, MVT::i32), 6178 DAG.getConstant(264, dl, MVT::i32)); 6179 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6180 } 6181 6182 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6183 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6184 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6185 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6186 DAG.getConstant(CnstVal, dl, MVT::i32), 6187 DAG.getConstant(272, dl, MVT::i32)); 6188 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6189 } 6190 6191 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6192 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6193 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6194 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6195 DAG.getConstant(CnstVal, dl, MVT::i32)); 6196 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6197 } 6198 6199 // The few faces of FMOV... 6200 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6201 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6202 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6203 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6204 DAG.getConstant(CnstVal, dl, MVT::i32)); 6205 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6206 } 6207 6208 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6209 VT.getSizeInBits() == 128) { 6210 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6211 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6212 DAG.getConstant(CnstVal, dl, MVT::i32)); 6213 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6214 } 6215 6216 // The many faces of MVNI... 6217 CnstVal = ~CnstVal; 6218 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6219 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6220 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6221 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6222 DAG.getConstant(CnstVal, dl, MVT::i32), 6223 DAG.getConstant(0, dl, MVT::i32)); 6224 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6225 } 6226 6227 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6228 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6229 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6230 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6231 DAG.getConstant(CnstVal, dl, MVT::i32), 6232 DAG.getConstant(8, dl, MVT::i32)); 6233 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6234 } 6235 6236 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6237 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6238 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6239 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6240 DAG.getConstant(CnstVal, dl, MVT::i32), 6241 DAG.getConstant(16, dl, MVT::i32)); 6242 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6243 } 6244 6245 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6246 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6247 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6248 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6249 DAG.getConstant(CnstVal, dl, MVT::i32), 6250 DAG.getConstant(24, dl, MVT::i32)); 6251 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6252 } 6253 6254 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6255 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6256 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6257 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6258 DAG.getConstant(CnstVal, dl, MVT::i32), 6259 DAG.getConstant(0, dl, MVT::i32)); 6260 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6261 } 6262 6263 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6264 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6265 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6266 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6267 DAG.getConstant(CnstVal, dl, MVT::i32), 6268 DAG.getConstant(8, dl, MVT::i32)); 6269 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6270 } 6271 6272 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6273 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6274 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6275 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6276 DAG.getConstant(CnstVal, dl, MVT::i32), 6277 DAG.getConstant(264, dl, MVT::i32)); 6278 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6279 } 6280 6281 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6282 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6283 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6284 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6285 DAG.getConstant(CnstVal, dl, MVT::i32), 6286 DAG.getConstant(272, dl, MVT::i32)); 6287 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6288 } 6289 } 6290 6291 if (SecondTry) 6292 goto FailedModImm; 6293 SecondTry = true; 6294 CnstBits = UndefBits; 6295 goto AttemptModImm; 6296 } 6297 FailedModImm: 6298 6299 // Scan through the operands to find some interesting properties we can 6300 // exploit: 6301 // 1) If only one value is used, we can use a DUP, or 6302 // 2) if only the low element is not undef, we can just insert that, or 6303 // 3) if only one constant value is used (w/ some non-constant lanes), 6304 // we can splat the constant value into the whole vector then fill 6305 // in the non-constant lanes. 6306 // 4) FIXME: If different constant values are used, but we can intelligently 6307 // select the values we'll be overwriting for the non-constant 6308 // lanes such that we can directly materialize the vector 6309 // some other way (MOVI, e.g.), we can be sneaky. 6310 unsigned NumElts = VT.getVectorNumElements(); 6311 bool isOnlyLowElement = true; 6312 bool usesOnlyOneValue = true; 6313 bool usesOnlyOneConstantValue = true; 6314 bool isConstant = true; 6315 unsigned NumConstantLanes = 0; 6316 SDValue Value; 6317 SDValue ConstantValue; 6318 for (unsigned i = 0; i < NumElts; ++i) { 6319 SDValue V = Op.getOperand(i); 6320 if (V.isUndef()) 6321 continue; 6322 if (i > 0) 6323 isOnlyLowElement = false; 6324 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6325 isConstant = false; 6326 6327 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6328 ++NumConstantLanes; 6329 if (!ConstantValue.getNode()) 6330 ConstantValue = V; 6331 else if (ConstantValue != V) 6332 usesOnlyOneConstantValue = false; 6333 } 6334 6335 if (!Value.getNode()) 6336 Value = V; 6337 else if (V != Value) 6338 usesOnlyOneValue = false; 6339 } 6340 6341 if (!Value.getNode()) 6342 return DAG.getUNDEF(VT); 6343 6344 if (isOnlyLowElement) 6345 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6346 6347 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6348 // i32 and try again. 6349 if (usesOnlyOneValue) { 6350 if (!isConstant) { 6351 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6352 Value.getValueType() != VT) 6353 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6354 6355 // This is actually a DUPLANExx operation, which keeps everything vectory. 6356 6357 // DUPLANE works on 128-bit vectors, widen it if necessary. 6358 SDValue Lane = Value.getOperand(1); 6359 Value = Value.getOperand(0); 6360 if (Value.getValueType().getSizeInBits() == 64) 6361 Value = WidenVector(Value, DAG); 6362 6363 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6364 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6365 } 6366 6367 if (VT.getVectorElementType().isFloatingPoint()) { 6368 SmallVector<SDValue, 8> Ops; 6369 EVT EltTy = VT.getVectorElementType(); 6370 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6371 "Unsupported floating-point vector type"); 6372 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6373 for (unsigned i = 0; i < NumElts; ++i) 6374 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6375 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6376 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6377 Val = LowerBUILD_VECTOR(Val, DAG); 6378 if (Val.getNode()) 6379 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6380 } 6381 } 6382 6383 // If there was only one constant value used and for more than one lane, 6384 // start by splatting that value, then replace the non-constant lanes. This 6385 // is better than the default, which will perform a separate initialization 6386 // for each lane. 6387 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6388 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6389 // Now insert the non-constant lanes. 6390 for (unsigned i = 0; i < NumElts; ++i) { 6391 SDValue V = Op.getOperand(i); 6392 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6393 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6394 // Note that type legalization likely mucked about with the VT of the 6395 // source operand, so we may have to convert it here before inserting. 6396 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6397 } 6398 } 6399 return Val; 6400 } 6401 6402 // If all elements are constants and the case above didn't get hit, fall back 6403 // to the default expansion, which will generate a load from the constant 6404 // pool. 6405 if (isConstant) 6406 return SDValue(); 6407 6408 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6409 if (NumElts >= 4) { 6410 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6411 return shuffle; 6412 } 6413 6414 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6415 // know the default expansion would otherwise fall back on something even 6416 // worse. For a vector with one or two non-undef values, that's 6417 // scalar_to_vector for the elements followed by a shuffle (provided the 6418 // shuffle is valid for the target) and materialization element by element 6419 // on the stack followed by a load for everything else. 6420 if (!isConstant && !usesOnlyOneValue) { 6421 SDValue Vec = DAG.getUNDEF(VT); 6422 SDValue Op0 = Op.getOperand(0); 6423 unsigned ElemSize = VT.getVectorElementType().getSizeInBits(); 6424 unsigned i = 0; 6425 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to 6426 // a) Avoid a RMW dependency on the full vector register, and 6427 // b) Allow the register coalescer to fold away the copy if the 6428 // value is already in an S or D register. 6429 // Do not do this for UNDEF/LOAD nodes because we have better patterns 6430 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR. 6431 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD && 6432 (ElemSize == 32 || ElemSize == 64)) { 6433 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub; 6434 MachineSDNode *N = 6435 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0, 6436 DAG.getTargetConstant(SubIdx, dl, MVT::i32)); 6437 Vec = SDValue(N, 0); 6438 ++i; 6439 } 6440 for (; i < NumElts; ++i) { 6441 SDValue V = Op.getOperand(i); 6442 if (V.isUndef()) 6443 continue; 6444 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6445 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6446 } 6447 return Vec; 6448 } 6449 6450 // Just use the default expansion. We failed to find a better alternative. 6451 return SDValue(); 6452 } 6453 6454 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6455 SelectionDAG &DAG) const { 6456 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6457 6458 // Check for non-constant or out of range lane. 6459 EVT VT = Op.getOperand(0).getValueType(); 6460 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6461 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6462 return SDValue(); 6463 6464 6465 // Insertion/extraction are legal for V128 types. 6466 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6467 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6468 VT == MVT::v8f16) 6469 return Op; 6470 6471 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6472 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6473 return SDValue(); 6474 6475 // For V64 types, we perform insertion by expanding the value 6476 // to a V128 type and perform the insertion on that. 6477 SDLoc DL(Op); 6478 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6479 EVT WideTy = WideVec.getValueType(); 6480 6481 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6482 Op.getOperand(1), Op.getOperand(2)); 6483 // Re-narrow the resultant vector. 6484 return NarrowVector(Node, DAG); 6485 } 6486 6487 SDValue 6488 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6489 SelectionDAG &DAG) const { 6490 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6491 6492 // Check for non-constant or out of range lane. 6493 EVT VT = Op.getOperand(0).getValueType(); 6494 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6495 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6496 return SDValue(); 6497 6498 6499 // Insertion/extraction are legal for V128 types. 6500 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6501 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6502 VT == MVT::v8f16) 6503 return Op; 6504 6505 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6506 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6507 return SDValue(); 6508 6509 // For V64 types, we perform extraction by expanding the value 6510 // to a V128 type and perform the extraction on that. 6511 SDLoc DL(Op); 6512 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6513 EVT WideTy = WideVec.getValueType(); 6514 6515 EVT ExtrTy = WideTy.getVectorElementType(); 6516 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 6517 ExtrTy = MVT::i32; 6518 6519 // For extractions, we just return the result directly. 6520 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 6521 Op.getOperand(1)); 6522 } 6523 6524 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 6525 SelectionDAG &DAG) const { 6526 EVT VT = Op.getOperand(0).getValueType(); 6527 SDLoc dl(Op); 6528 // Just in case... 6529 if (!VT.isVector()) 6530 return SDValue(); 6531 6532 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6533 if (!Cst) 6534 return SDValue(); 6535 unsigned Val = Cst->getZExtValue(); 6536 6537 unsigned Size = Op.getValueType().getSizeInBits(); 6538 6539 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 6540 if (Val == 0) 6541 return Op; 6542 6543 // If this is extracting the upper 64-bits of a 128-bit vector, we match 6544 // that directly. 6545 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64) 6546 return Op; 6547 6548 return SDValue(); 6549 } 6550 6551 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6552 EVT VT) const { 6553 if (VT.getVectorNumElements() == 4 && 6554 (VT.is128BitVector() || VT.is64BitVector())) { 6555 unsigned PFIndexes[4]; 6556 for (unsigned i = 0; i != 4; ++i) { 6557 if (M[i] < 0) 6558 PFIndexes[i] = 8; 6559 else 6560 PFIndexes[i] = M[i]; 6561 } 6562 6563 // Compute the index in the perfect shuffle table. 6564 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6565 PFIndexes[2] * 9 + PFIndexes[3]; 6566 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6567 unsigned Cost = (PFEntry >> 30); 6568 6569 if (Cost <= 4) 6570 return true; 6571 } 6572 6573 bool DummyBool; 6574 int DummyInt; 6575 unsigned DummyUnsigned; 6576 6577 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 6578 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 6579 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 6580 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 6581 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 6582 isZIPMask(M, VT, DummyUnsigned) || 6583 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 6584 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 6585 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 6586 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 6587 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 6588 } 6589 6590 /// getVShiftImm - Check if this is a valid build_vector for the immediate 6591 /// operand of a vector shift operation, where all the elements of the 6592 /// build_vector must have the same constant integer value. 6593 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6594 // Ignore bit_converts. 6595 while (Op.getOpcode() == ISD::BITCAST) 6596 Op = Op.getOperand(0); 6597 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6598 APInt SplatBits, SplatUndef; 6599 unsigned SplatBitSize; 6600 bool HasAnyUndefs; 6601 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 6602 HasAnyUndefs, ElementBits) || 6603 SplatBitSize > ElementBits) 6604 return false; 6605 Cnt = SplatBits.getSExtValue(); 6606 return true; 6607 } 6608 6609 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6610 /// operand of a vector shift left operation. That value must be in the range: 6611 /// 0 <= Value < ElementBits for a left shift; or 6612 /// 0 <= Value <= ElementBits for a long left shift. 6613 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6614 assert(VT.isVector() && "vector shift count is not a vector type"); 6615 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 6616 if (!getVShiftImm(Op, ElementBits, Cnt)) 6617 return false; 6618 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6619 } 6620 6621 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6622 /// operand of a vector shift right operation. The value must be in the range: 6623 /// 1 <= Value <= ElementBits for a right shift; or 6624 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 6625 assert(VT.isVector() && "vector shift count is not a vector type"); 6626 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 6627 if (!getVShiftImm(Op, ElementBits, Cnt)) 6628 return false; 6629 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6630 } 6631 6632 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 6633 SelectionDAG &DAG) const { 6634 EVT VT = Op.getValueType(); 6635 SDLoc DL(Op); 6636 int64_t Cnt; 6637 6638 if (!Op.getOperand(1).getValueType().isVector()) 6639 return Op; 6640 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6641 6642 switch (Op.getOpcode()) { 6643 default: 6644 llvm_unreachable("unexpected shift opcode"); 6645 6646 case ISD::SHL: 6647 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 6648 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 6649 DAG.getConstant(Cnt, DL, MVT::i32)); 6650 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6651 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 6652 MVT::i32), 6653 Op.getOperand(0), Op.getOperand(1)); 6654 case ISD::SRA: 6655 case ISD::SRL: 6656 // Right shift immediate 6657 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 6658 unsigned Opc = 6659 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 6660 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 6661 DAG.getConstant(Cnt, DL, MVT::i32)); 6662 } 6663 6664 // Right shift register. Note, there is not a shift right register 6665 // instruction, but the shift left register instruction takes a signed 6666 // value, where negative numbers specify a right shift. 6667 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 6668 : Intrinsic::aarch64_neon_ushl; 6669 // negate the shift amount 6670 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 6671 SDValue NegShiftLeft = 6672 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6673 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 6674 NegShift); 6675 return NegShiftLeft; 6676 } 6677 6678 return SDValue(); 6679 } 6680 6681 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 6682 AArch64CC::CondCode CC, bool NoNans, EVT VT, 6683 SDLoc dl, SelectionDAG &DAG) { 6684 EVT SrcVT = LHS.getValueType(); 6685 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 6686 "function only supposed to emit natural comparisons"); 6687 6688 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 6689 APInt CnstBits(VT.getSizeInBits(), 0); 6690 APInt UndefBits(VT.getSizeInBits(), 0); 6691 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 6692 bool IsZero = IsCnst && (CnstBits == 0); 6693 6694 if (SrcVT.getVectorElementType().isFloatingPoint()) { 6695 switch (CC) { 6696 default: 6697 return SDValue(); 6698 case AArch64CC::NE: { 6699 SDValue Fcmeq; 6700 if (IsZero) 6701 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6702 else 6703 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6704 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 6705 } 6706 case AArch64CC::EQ: 6707 if (IsZero) 6708 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6709 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6710 case AArch64CC::GE: 6711 if (IsZero) 6712 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 6713 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 6714 case AArch64CC::GT: 6715 if (IsZero) 6716 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 6717 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 6718 case AArch64CC::LS: 6719 if (IsZero) 6720 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 6721 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 6722 case AArch64CC::LT: 6723 if (!NoNans) 6724 return SDValue(); 6725 // If we ignore NaNs then we can use to the MI implementation. 6726 // Fallthrough. 6727 case AArch64CC::MI: 6728 if (IsZero) 6729 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 6730 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 6731 } 6732 } 6733 6734 switch (CC) { 6735 default: 6736 return SDValue(); 6737 case AArch64CC::NE: { 6738 SDValue Cmeq; 6739 if (IsZero) 6740 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6741 else 6742 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6743 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 6744 } 6745 case AArch64CC::EQ: 6746 if (IsZero) 6747 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6748 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6749 case AArch64CC::GE: 6750 if (IsZero) 6751 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 6752 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 6753 case AArch64CC::GT: 6754 if (IsZero) 6755 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 6756 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 6757 case AArch64CC::LE: 6758 if (IsZero) 6759 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 6760 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 6761 case AArch64CC::LS: 6762 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 6763 case AArch64CC::LO: 6764 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 6765 case AArch64CC::LT: 6766 if (IsZero) 6767 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 6768 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 6769 case AArch64CC::HI: 6770 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 6771 case AArch64CC::HS: 6772 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 6773 } 6774 } 6775 6776 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 6777 SelectionDAG &DAG) const { 6778 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6779 SDValue LHS = Op.getOperand(0); 6780 SDValue RHS = Op.getOperand(1); 6781 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 6782 SDLoc dl(Op); 6783 6784 if (LHS.getValueType().getVectorElementType().isInteger()) { 6785 assert(LHS.getValueType() == RHS.getValueType()); 6786 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6787 SDValue Cmp = 6788 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 6789 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6790 } 6791 6792 if (LHS.getValueType().getVectorElementType() == MVT::f16) 6793 return SDValue(); 6794 6795 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 6796 LHS.getValueType().getVectorElementType() == MVT::f64); 6797 6798 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6799 // clean. Some of them require two branches to implement. 6800 AArch64CC::CondCode CC1, CC2; 6801 bool ShouldInvert; 6802 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 6803 6804 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 6805 SDValue Cmp = 6806 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 6807 if (!Cmp.getNode()) 6808 return SDValue(); 6809 6810 if (CC2 != AArch64CC::AL) { 6811 SDValue Cmp2 = 6812 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 6813 if (!Cmp2.getNode()) 6814 return SDValue(); 6815 6816 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 6817 } 6818 6819 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6820 6821 if (ShouldInvert) 6822 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 6823 6824 return Cmp; 6825 } 6826 6827 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 6828 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 6829 /// specified in the intrinsic calls. 6830 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 6831 const CallInst &I, 6832 unsigned Intrinsic) const { 6833 auto &DL = I.getModule()->getDataLayout(); 6834 switch (Intrinsic) { 6835 case Intrinsic::aarch64_neon_ld2: 6836 case Intrinsic::aarch64_neon_ld3: 6837 case Intrinsic::aarch64_neon_ld4: 6838 case Intrinsic::aarch64_neon_ld1x2: 6839 case Intrinsic::aarch64_neon_ld1x3: 6840 case Intrinsic::aarch64_neon_ld1x4: 6841 case Intrinsic::aarch64_neon_ld2lane: 6842 case Intrinsic::aarch64_neon_ld3lane: 6843 case Intrinsic::aarch64_neon_ld4lane: 6844 case Intrinsic::aarch64_neon_ld2r: 6845 case Intrinsic::aarch64_neon_ld3r: 6846 case Intrinsic::aarch64_neon_ld4r: { 6847 Info.opc = ISD::INTRINSIC_W_CHAIN; 6848 // Conservatively set memVT to the entire set of vectors loaded. 6849 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 6850 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6851 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6852 Info.offset = 0; 6853 Info.align = 0; 6854 Info.vol = false; // volatile loads with NEON intrinsics not supported 6855 Info.readMem = true; 6856 Info.writeMem = false; 6857 return true; 6858 } 6859 case Intrinsic::aarch64_neon_st2: 6860 case Intrinsic::aarch64_neon_st3: 6861 case Intrinsic::aarch64_neon_st4: 6862 case Intrinsic::aarch64_neon_st1x2: 6863 case Intrinsic::aarch64_neon_st1x3: 6864 case Intrinsic::aarch64_neon_st1x4: 6865 case Intrinsic::aarch64_neon_st2lane: 6866 case Intrinsic::aarch64_neon_st3lane: 6867 case Intrinsic::aarch64_neon_st4lane: { 6868 Info.opc = ISD::INTRINSIC_VOID; 6869 // Conservatively set memVT to the entire set of vectors stored. 6870 unsigned NumElts = 0; 6871 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 6872 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 6873 if (!ArgTy->isVectorTy()) 6874 break; 6875 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 6876 } 6877 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6878 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6879 Info.offset = 0; 6880 Info.align = 0; 6881 Info.vol = false; // volatile stores with NEON intrinsics not supported 6882 Info.readMem = false; 6883 Info.writeMem = true; 6884 return true; 6885 } 6886 case Intrinsic::aarch64_ldaxr: 6887 case Intrinsic::aarch64_ldxr: { 6888 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 6889 Info.opc = ISD::INTRINSIC_W_CHAIN; 6890 Info.memVT = MVT::getVT(PtrTy->getElementType()); 6891 Info.ptrVal = I.getArgOperand(0); 6892 Info.offset = 0; 6893 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 6894 Info.vol = true; 6895 Info.readMem = true; 6896 Info.writeMem = false; 6897 return true; 6898 } 6899 case Intrinsic::aarch64_stlxr: 6900 case Intrinsic::aarch64_stxr: { 6901 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 6902 Info.opc = ISD::INTRINSIC_W_CHAIN; 6903 Info.memVT = MVT::getVT(PtrTy->getElementType()); 6904 Info.ptrVal = I.getArgOperand(1); 6905 Info.offset = 0; 6906 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 6907 Info.vol = true; 6908 Info.readMem = false; 6909 Info.writeMem = true; 6910 return true; 6911 } 6912 case Intrinsic::aarch64_ldaxp: 6913 case Intrinsic::aarch64_ldxp: { 6914 Info.opc = ISD::INTRINSIC_W_CHAIN; 6915 Info.memVT = MVT::i128; 6916 Info.ptrVal = I.getArgOperand(0); 6917 Info.offset = 0; 6918 Info.align = 16; 6919 Info.vol = true; 6920 Info.readMem = true; 6921 Info.writeMem = false; 6922 return true; 6923 } 6924 case Intrinsic::aarch64_stlxp: 6925 case Intrinsic::aarch64_stxp: { 6926 Info.opc = ISD::INTRINSIC_W_CHAIN; 6927 Info.memVT = MVT::i128; 6928 Info.ptrVal = I.getArgOperand(2); 6929 Info.offset = 0; 6930 Info.align = 16; 6931 Info.vol = true; 6932 Info.readMem = false; 6933 Info.writeMem = true; 6934 return true; 6935 } 6936 default: 6937 break; 6938 } 6939 6940 return false; 6941 } 6942 6943 // Truncations from 64-bit GPR to 32-bit GPR is free. 6944 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 6945 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 6946 return false; 6947 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 6948 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 6949 return NumBits1 > NumBits2; 6950 } 6951 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 6952 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 6953 return false; 6954 unsigned NumBits1 = VT1.getSizeInBits(); 6955 unsigned NumBits2 = VT2.getSizeInBits(); 6956 return NumBits1 > NumBits2; 6957 } 6958 6959 /// Check if it is profitable to hoist instruction in then/else to if. 6960 /// Not profitable if I and it's user can form a FMA instruction 6961 /// because we prefer FMSUB/FMADD. 6962 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 6963 if (I->getOpcode() != Instruction::FMul) 6964 return true; 6965 6966 if (I->getNumUses() != 1) 6967 return true; 6968 6969 Instruction *User = I->user_back(); 6970 6971 if (User && 6972 !(User->getOpcode() == Instruction::FSub || 6973 User->getOpcode() == Instruction::FAdd)) 6974 return true; 6975 6976 const TargetOptions &Options = getTargetMachine().Options; 6977 const DataLayout &DL = I->getModule()->getDataLayout(); 6978 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 6979 6980 return !(isFMAFasterThanFMulAndFAdd(VT) && 6981 isOperationLegalOrCustom(ISD::FMA, VT) && 6982 (Options.AllowFPOpFusion == FPOpFusion::Fast || 6983 Options.UnsafeFPMath)); 6984 } 6985 6986 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 6987 // 64-bit GPR. 6988 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 6989 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 6990 return false; 6991 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 6992 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 6993 return NumBits1 == 32 && NumBits2 == 64; 6994 } 6995 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 6996 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 6997 return false; 6998 unsigned NumBits1 = VT1.getSizeInBits(); 6999 unsigned NumBits2 = VT2.getSizeInBits(); 7000 return NumBits1 == 32 && NumBits2 == 64; 7001 } 7002 7003 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7004 EVT VT1 = Val.getValueType(); 7005 if (isZExtFree(VT1, VT2)) { 7006 return true; 7007 } 7008 7009 if (Val.getOpcode() != ISD::LOAD) 7010 return false; 7011 7012 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7013 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7014 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7015 VT1.getSizeInBits() <= 32); 7016 } 7017 7018 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7019 if (isa<FPExtInst>(Ext)) 7020 return false; 7021 7022 // Vector types are next free. 7023 if (Ext->getType()->isVectorTy()) 7024 return false; 7025 7026 for (const Use &U : Ext->uses()) { 7027 // The extension is free if we can fold it with a left shift in an 7028 // addressing mode or an arithmetic operation: add, sub, and cmp. 7029 7030 // Is there a shift? 7031 const Instruction *Instr = cast<Instruction>(U.getUser()); 7032 7033 // Is this a constant shift? 7034 switch (Instr->getOpcode()) { 7035 case Instruction::Shl: 7036 if (!isa<ConstantInt>(Instr->getOperand(1))) 7037 return false; 7038 break; 7039 case Instruction::GetElementPtr: { 7040 gep_type_iterator GTI = gep_type_begin(Instr); 7041 auto &DL = Ext->getModule()->getDataLayout(); 7042 std::advance(GTI, U.getOperandNo()); 7043 Type *IdxTy = *GTI; 7044 // This extension will end up with a shift because of the scaling factor. 7045 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7046 // Get the shift amount based on the scaling factor: 7047 // log2(sizeof(IdxTy)) - log2(8). 7048 uint64_t ShiftAmt = 7049 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7050 // Is the constant foldable in the shift of the addressing mode? 7051 // I.e., shift amount is between 1 and 4 inclusive. 7052 if (ShiftAmt == 0 || ShiftAmt > 4) 7053 return false; 7054 break; 7055 } 7056 case Instruction::Trunc: 7057 // Check if this is a noop. 7058 // trunc(sext ty1 to ty2) to ty1. 7059 if (Instr->getType() == Ext->getOperand(0)->getType()) 7060 continue; 7061 // FALL THROUGH. 7062 default: 7063 return false; 7064 } 7065 7066 // At this point we can use the bfm family, so this extension is free 7067 // for that use. 7068 } 7069 return true; 7070 } 7071 7072 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType, 7073 unsigned &RequiredAligment) const { 7074 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy()) 7075 return false; 7076 // Cyclone supports unaligned accesses. 7077 RequiredAligment = 0; 7078 unsigned NumBits = LoadedType->getPrimitiveSizeInBits(); 7079 return NumBits == 32 || NumBits == 64; 7080 } 7081 7082 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7083 unsigned &RequiredAligment) const { 7084 if (!LoadedType.isSimple() || 7085 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7086 return false; 7087 // Cyclone supports unaligned accesses. 7088 RequiredAligment = 0; 7089 unsigned NumBits = LoadedType.getSizeInBits(); 7090 return NumBits == 32 || NumBits == 64; 7091 } 7092 7093 /// \brief Lower an interleaved load into a ldN intrinsic. 7094 /// 7095 /// E.g. Lower an interleaved load (Factor = 2): 7096 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7097 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7098 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7099 /// 7100 /// Into: 7101 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7102 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7103 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7104 bool AArch64TargetLowering::lowerInterleavedLoad( 7105 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7106 ArrayRef<unsigned> Indices, unsigned Factor) const { 7107 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7108 "Invalid interleave factor"); 7109 assert(!Shuffles.empty() && "Empty shufflevector input"); 7110 assert(Shuffles.size() == Indices.size() && 7111 "Unmatched number of shufflevectors and indices"); 7112 7113 const DataLayout &DL = LI->getModule()->getDataLayout(); 7114 7115 VectorType *VecTy = Shuffles[0]->getType(); 7116 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7117 7118 // Skip if we do not have NEON and skip illegal vector types. 7119 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128)) 7120 return false; 7121 7122 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7123 // load integer vectors first and then convert to pointer vectors. 7124 Type *EltTy = VecTy->getVectorElementType(); 7125 if (EltTy->isPointerTy()) 7126 VecTy = 7127 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7128 7129 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7130 Type *Tys[2] = {VecTy, PtrTy}; 7131 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7132 Intrinsic::aarch64_neon_ld3, 7133 Intrinsic::aarch64_neon_ld4}; 7134 Function *LdNFunc = 7135 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7136 7137 IRBuilder<> Builder(LI); 7138 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy); 7139 7140 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN"); 7141 7142 // Replace uses of each shufflevector with the corresponding vector loaded 7143 // by ldN. 7144 for (unsigned i = 0; i < Shuffles.size(); i++) { 7145 ShuffleVectorInst *SVI = Shuffles[i]; 7146 unsigned Index = Indices[i]; 7147 7148 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7149 7150 // Convert the integer vector to pointer vector if the element is pointer. 7151 if (EltTy->isPointerTy()) 7152 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType()); 7153 7154 SVI->replaceAllUsesWith(SubVec); 7155 } 7156 7157 return true; 7158 } 7159 7160 /// \brief Get a mask consisting of sequential integers starting from \p Start. 7161 /// 7162 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 7163 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 7164 unsigned NumElts) { 7165 SmallVector<Constant *, 16> Mask; 7166 for (unsigned i = 0; i < NumElts; i++) 7167 Mask.push_back(Builder.getInt32(Start + i)); 7168 7169 return ConstantVector::get(Mask); 7170 } 7171 7172 /// \brief Lower an interleaved store into a stN intrinsic. 7173 /// 7174 /// E.g. Lower an interleaved store (Factor = 3): 7175 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7176 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7177 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7178 /// 7179 /// Into: 7180 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7181 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7182 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7183 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7184 /// 7185 /// Note that the new shufflevectors will be removed and we'll only generate one 7186 /// st3 instruction in CodeGen. 7187 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7188 ShuffleVectorInst *SVI, 7189 unsigned Factor) const { 7190 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7191 "Invalid interleave factor"); 7192 7193 VectorType *VecTy = SVI->getType(); 7194 assert(VecTy->getVectorNumElements() % Factor == 0 && 7195 "Invalid interleaved store"); 7196 7197 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 7198 Type *EltTy = VecTy->getVectorElementType(); 7199 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 7200 7201 const DataLayout &DL = SI->getModule()->getDataLayout(); 7202 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 7203 7204 // Skip if we do not have NEON and skip illegal vector types. 7205 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128)) 7206 return false; 7207 7208 Value *Op0 = SVI->getOperand(0); 7209 Value *Op1 = SVI->getOperand(1); 7210 IRBuilder<> Builder(SI); 7211 7212 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7213 // vectors to integer vectors. 7214 if (EltTy->isPointerTy()) { 7215 Type *IntTy = DL.getIntPtrType(EltTy); 7216 unsigned NumOpElts = 7217 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7218 7219 // Convert to the corresponding integer vector. 7220 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7221 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7222 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7223 7224 SubVecTy = VectorType::get(IntTy, NumSubElts); 7225 } 7226 7227 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7228 Type *Tys[2] = {SubVecTy, PtrTy}; 7229 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7230 Intrinsic::aarch64_neon_st3, 7231 Intrinsic::aarch64_neon_st4}; 7232 Function *StNFunc = 7233 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7234 7235 SmallVector<Value *, 5> Ops; 7236 7237 // Split the shufflevector operands into sub vectors for the new stN call. 7238 for (unsigned i = 0; i < Factor; i++) 7239 Ops.push_back(Builder.CreateShuffleVector( 7240 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 7241 7242 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy)); 7243 Builder.CreateCall(StNFunc, Ops); 7244 return true; 7245 } 7246 7247 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7248 unsigned AlignCheck) { 7249 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7250 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7251 } 7252 7253 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7254 unsigned SrcAlign, bool IsMemset, 7255 bool ZeroMemset, 7256 bool MemcpyStrSrc, 7257 MachineFunction &MF) const { 7258 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7259 // instruction to materialize the v2i64 zero and one store (with restrictive 7260 // addressing mode). Just do two i64 store of zero-registers. 7261 bool Fast; 7262 const Function *F = MF.getFunction(); 7263 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7264 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7265 (memOpAlign(SrcAlign, DstAlign, 16) || 7266 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7267 return MVT::f128; 7268 7269 if (Size >= 8 && 7270 (memOpAlign(SrcAlign, DstAlign, 8) || 7271 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7272 return MVT::i64; 7273 7274 if (Size >= 4 && 7275 (memOpAlign(SrcAlign, DstAlign, 4) || 7276 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7277 return MVT::i32; 7278 7279 return MVT::Other; 7280 } 7281 7282 // 12-bit optionally shifted immediates are legal for adds. 7283 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7284 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7285 } 7286 7287 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7288 // immediates is the same as for an add or a sub. 7289 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7290 if (Immed < 0) 7291 Immed *= -1; 7292 return isLegalAddImmediate(Immed); 7293 } 7294 7295 /// isLegalAddressingMode - Return true if the addressing mode represented 7296 /// by AM is legal for this target, for a load/store of the specified type. 7297 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7298 const AddrMode &AM, Type *Ty, 7299 unsigned AS) const { 7300 // AArch64 has five basic addressing modes: 7301 // reg 7302 // reg + 9-bit signed offset 7303 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7304 // reg1 + reg2 7305 // reg + SIZE_IN_BYTES * reg 7306 7307 // No global is ever allowed as a base. 7308 if (AM.BaseGV) 7309 return false; 7310 7311 // No reg+reg+imm addressing. 7312 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7313 return false; 7314 7315 // check reg + imm case: 7316 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7317 uint64_t NumBytes = 0; 7318 if (Ty->isSized()) { 7319 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7320 NumBytes = NumBits / 8; 7321 if (!isPowerOf2_64(NumBits)) 7322 NumBytes = 0; 7323 } 7324 7325 if (!AM.Scale) { 7326 int64_t Offset = AM.BaseOffs; 7327 7328 // 9-bit signed offset 7329 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1) 7330 return true; 7331 7332 // 12-bit unsigned offset 7333 unsigned shift = Log2_64(NumBytes); 7334 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 7335 // Must be a multiple of NumBytes (NumBytes is a power of 2) 7336 (Offset >> shift) << shift == Offset) 7337 return true; 7338 return false; 7339 } 7340 7341 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 7342 7343 return !AM.Scale || AM.Scale == 1 || 7344 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 7345 } 7346 7347 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 7348 const AddrMode &AM, Type *Ty, 7349 unsigned AS) const { 7350 // Scaling factors are not free at all. 7351 // Operands | Rt Latency 7352 // ------------------------------------------- 7353 // Rt, [Xn, Xm] | 4 7354 // ------------------------------------------- 7355 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 7356 // Rt, [Xn, Wm, <extend> #imm] | 7357 if (isLegalAddressingMode(DL, AM, Ty, AS)) 7358 // Scale represents reg2 * scale, thus account for 1 if 7359 // it is not equal to 0 or 1. 7360 return AM.Scale != 0 && AM.Scale != 1; 7361 return -1; 7362 } 7363 7364 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7365 VT = VT.getScalarType(); 7366 7367 if (!VT.isSimple()) 7368 return false; 7369 7370 switch (VT.getSimpleVT().SimpleTy) { 7371 case MVT::f32: 7372 case MVT::f64: 7373 return true; 7374 default: 7375 break; 7376 } 7377 7378 return false; 7379 } 7380 7381 const MCPhysReg * 7382 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 7383 // LR is a callee-save register, but we must treat it as clobbered by any call 7384 // site. Hence we include LR in the scratch registers, which are in turn added 7385 // as implicit-defs for stackmaps and patchpoints. 7386 static const MCPhysReg ScratchRegs[] = { 7387 AArch64::X16, AArch64::X17, AArch64::LR, 0 7388 }; 7389 return ScratchRegs; 7390 } 7391 7392 bool 7393 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 7394 EVT VT = N->getValueType(0); 7395 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 7396 // it with shift to let it be lowered to UBFX. 7397 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 7398 isa<ConstantSDNode>(N->getOperand(1))) { 7399 uint64_t TruncMask = N->getConstantOperandVal(1); 7400 if (isMask_64(TruncMask) && 7401 N->getOperand(0).getOpcode() == ISD::SRL && 7402 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 7403 return false; 7404 } 7405 return true; 7406 } 7407 7408 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 7409 Type *Ty) const { 7410 assert(Ty->isIntegerTy()); 7411 7412 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 7413 if (BitSize == 0) 7414 return false; 7415 7416 int64_t Val = Imm.getSExtValue(); 7417 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 7418 return true; 7419 7420 if ((int64_t)Val < 0) 7421 Val = ~Val; 7422 if (BitSize == 32) 7423 Val &= (1LL << 32) - 1; 7424 7425 unsigned LZ = countLeadingZeros((uint64_t)Val); 7426 unsigned Shift = (63 - LZ) / 16; 7427 // MOVZ is free so return true for one or fewer MOVK. 7428 return Shift < 3; 7429 } 7430 7431 /// Turn vector tests of the signbit in the form of: 7432 /// xor (sra X, elt_size(X)-1), -1 7433 /// into: 7434 /// cmge X, X, #0 7435 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 7436 const AArch64Subtarget *Subtarget) { 7437 EVT VT = N->getValueType(0); 7438 if (!Subtarget->hasNEON() || !VT.isVector()) 7439 return SDValue(); 7440 7441 // There must be a shift right algebraic before the xor, and the xor must be a 7442 // 'not' operation. 7443 SDValue Shift = N->getOperand(0); 7444 SDValue Ones = N->getOperand(1); 7445 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 7446 !ISD::isBuildVectorAllOnes(Ones.getNode())) 7447 return SDValue(); 7448 7449 // The shift should be smearing the sign bit across each vector element. 7450 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7451 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 7452 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 7453 return SDValue(); 7454 7455 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 7456 } 7457 7458 // Generate SUBS and CSEL for integer abs. 7459 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 7460 EVT VT = N->getValueType(0); 7461 7462 SDValue N0 = N->getOperand(0); 7463 SDValue N1 = N->getOperand(1); 7464 SDLoc DL(N); 7465 7466 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 7467 // and change it to SUB and CSEL. 7468 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 7469 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 7470 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 7471 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 7472 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 7473 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7474 N0.getOperand(0)); 7475 // Generate SUBS & CSEL. 7476 SDValue Cmp = 7477 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 7478 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 7479 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 7480 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 7481 SDValue(Cmp.getNode(), 1)); 7482 } 7483 return SDValue(); 7484 } 7485 7486 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 7487 TargetLowering::DAGCombinerInfo &DCI, 7488 const AArch64Subtarget *Subtarget) { 7489 if (DCI.isBeforeLegalizeOps()) 7490 return SDValue(); 7491 7492 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 7493 return Cmp; 7494 7495 return performIntegerAbsCombine(N, DAG); 7496 } 7497 7498 SDValue 7499 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7500 SelectionDAG &DAG, 7501 std::vector<SDNode *> *Created) const { 7502 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 7503 if (isIntDivCheap(N->getValueType(0), Attr)) 7504 return SDValue(N,0); // Lower SDIV as SDIV 7505 7506 // fold (sdiv X, pow2) 7507 EVT VT = N->getValueType(0); 7508 if ((VT != MVT::i32 && VT != MVT::i64) || 7509 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 7510 return SDValue(); 7511 7512 SDLoc DL(N); 7513 SDValue N0 = N->getOperand(0); 7514 unsigned Lg2 = Divisor.countTrailingZeros(); 7515 SDValue Zero = DAG.getConstant(0, DL, VT); 7516 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 7517 7518 // Add (N0 < 0) ? Pow2 - 1 : 0; 7519 SDValue CCVal; 7520 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 7521 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 7522 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 7523 7524 if (Created) { 7525 Created->push_back(Cmp.getNode()); 7526 Created->push_back(Add.getNode()); 7527 Created->push_back(CSel.getNode()); 7528 } 7529 7530 // Divide by pow2. 7531 SDValue SRA = 7532 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 7533 7534 // If we're dividing by a positive value, we're done. Otherwise, we must 7535 // negate the result. 7536 if (Divisor.isNonNegative()) 7537 return SRA; 7538 7539 if (Created) 7540 Created->push_back(SRA.getNode()); 7541 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 7542 } 7543 7544 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 7545 TargetLowering::DAGCombinerInfo &DCI, 7546 const AArch64Subtarget *Subtarget) { 7547 if (DCI.isBeforeLegalizeOps()) 7548 return SDValue(); 7549 7550 // Multiplication of a power of two plus/minus one can be done more 7551 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 7552 // future CPUs have a cheaper MADD instruction, this may need to be 7553 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 7554 // 64-bit is 5 cycles, so this is always a win. 7555 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 7556 APInt Value = C->getAPIntValue(); 7557 EVT VT = N->getValueType(0); 7558 SDLoc DL(N); 7559 if (Value.isNonNegative()) { 7560 // (mul x, 2^N + 1) => (add (shl x, N), x) 7561 APInt VM1 = Value - 1; 7562 if (VM1.isPowerOf2()) { 7563 SDValue ShiftedVal = 7564 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7565 DAG.getConstant(VM1.logBase2(), DL, MVT::i64)); 7566 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, 7567 N->getOperand(0)); 7568 } 7569 // (mul x, 2^N - 1) => (sub (shl x, N), x) 7570 APInt VP1 = Value + 1; 7571 if (VP1.isPowerOf2()) { 7572 SDValue ShiftedVal = 7573 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7574 DAG.getConstant(VP1.logBase2(), DL, MVT::i64)); 7575 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal, 7576 N->getOperand(0)); 7577 } 7578 } else { 7579 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 7580 APInt VNP1 = -Value + 1; 7581 if (VNP1.isPowerOf2()) { 7582 SDValue ShiftedVal = 7583 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7584 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64)); 7585 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), 7586 ShiftedVal); 7587 } 7588 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 7589 APInt VNM1 = -Value - 1; 7590 if (VNM1.isPowerOf2()) { 7591 SDValue ShiftedVal = 7592 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7593 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64)); 7594 SDValue Add = 7595 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0)); 7596 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add); 7597 } 7598 } 7599 } 7600 return SDValue(); 7601 } 7602 7603 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 7604 SelectionDAG &DAG) { 7605 // Take advantage of vector comparisons producing 0 or -1 in each lane to 7606 // optimize away operation when it's from a constant. 7607 // 7608 // The general transformation is: 7609 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 7610 // AND(VECTOR_CMP(x,y), constant2) 7611 // constant2 = UNARYOP(constant) 7612 7613 // Early exit if this isn't a vector operation, the operand of the 7614 // unary operation isn't a bitwise AND, or if the sizes of the operations 7615 // aren't the same. 7616 EVT VT = N->getValueType(0); 7617 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 7618 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 7619 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 7620 return SDValue(); 7621 7622 // Now check that the other operand of the AND is a constant. We could 7623 // make the transformation for non-constant splats as well, but it's unclear 7624 // that would be a benefit as it would not eliminate any operations, just 7625 // perform one more step in scalar code before moving to the vector unit. 7626 if (BuildVectorSDNode *BV = 7627 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 7628 // Bail out if the vector isn't a constant. 7629 if (!BV->isConstant()) 7630 return SDValue(); 7631 7632 // Everything checks out. Build up the new and improved node. 7633 SDLoc DL(N); 7634 EVT IntVT = BV->getValueType(0); 7635 // Create a new constant of the appropriate type for the transformed 7636 // DAG. 7637 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 7638 // The AND node needs bitcasts to/from an integer vector type around it. 7639 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 7640 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 7641 N->getOperand(0)->getOperand(0), MaskConst); 7642 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 7643 return Res; 7644 } 7645 7646 return SDValue(); 7647 } 7648 7649 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 7650 const AArch64Subtarget *Subtarget) { 7651 // First try to optimize away the conversion when it's conditionally from 7652 // a constant. Vectors only. 7653 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 7654 return Res; 7655 7656 EVT VT = N->getValueType(0); 7657 if (VT != MVT::f32 && VT != MVT::f64) 7658 return SDValue(); 7659 7660 // Only optimize when the source and destination types have the same width. 7661 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits()) 7662 return SDValue(); 7663 7664 // If the result of an integer load is only used by an integer-to-float 7665 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 7666 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 7667 SDValue N0 = N->getOperand(0); 7668 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7669 // Do not change the width of a volatile load. 7670 !cast<LoadSDNode>(N0)->isVolatile()) { 7671 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7672 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7673 LN0->getPointerInfo(), LN0->isVolatile(), 7674 LN0->isNonTemporal(), LN0->isInvariant(), 7675 LN0->getAlignment()); 7676 7677 // Make sure successors of the original load stay after it by updating them 7678 // to use the new Chain. 7679 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 7680 7681 unsigned Opcode = 7682 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 7683 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 7684 } 7685 7686 return SDValue(); 7687 } 7688 7689 /// Fold a floating-point multiply by power of two into floating-point to 7690 /// fixed-point conversion. 7691 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 7692 const AArch64Subtarget *Subtarget) { 7693 if (!Subtarget->hasNEON()) 7694 return SDValue(); 7695 7696 SDValue Op = N->getOperand(0); 7697 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 7698 Op.getOpcode() != ISD::FMUL) 7699 return SDValue(); 7700 7701 SDValue ConstVec = Op->getOperand(1); 7702 if (!isa<BuildVectorSDNode>(ConstVec)) 7703 return SDValue(); 7704 7705 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 7706 uint32_t FloatBits = FloatTy.getSizeInBits(); 7707 if (FloatBits != 32 && FloatBits != 64) 7708 return SDValue(); 7709 7710 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 7711 uint32_t IntBits = IntTy.getSizeInBits(); 7712 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7713 return SDValue(); 7714 7715 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 7716 if (IntBits > FloatBits) 7717 return SDValue(); 7718 7719 BitVector UndefElements; 7720 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7721 int32_t Bits = IntBits == 64 ? 64 : 32; 7722 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 7723 if (C == -1 || C == 0 || C > Bits) 7724 return SDValue(); 7725 7726 MVT ResTy; 7727 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7728 switch (NumLanes) { 7729 default: 7730 return SDValue(); 7731 case 2: 7732 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7733 break; 7734 case 4: 7735 ResTy = MVT::v4i32; 7736 break; 7737 } 7738 7739 SDLoc DL(N); 7740 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7741 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 7742 : Intrinsic::aarch64_neon_vcvtfp2fxu; 7743 SDValue FixConv = 7744 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 7745 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 7746 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 7747 // We can handle smaller integers by generating an extra trunc. 7748 if (IntBits < FloatBits) 7749 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 7750 7751 return FixConv; 7752 } 7753 7754 /// Fold a floating-point divide by power of two into fixed-point to 7755 /// floating-point conversion. 7756 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 7757 const AArch64Subtarget *Subtarget) { 7758 if (!Subtarget->hasNEON()) 7759 return SDValue(); 7760 7761 SDValue Op = N->getOperand(0); 7762 unsigned Opc = Op->getOpcode(); 7763 if (!Op.getValueType().isVector() || 7764 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 7765 return SDValue(); 7766 7767 SDValue ConstVec = N->getOperand(1); 7768 if (!isa<BuildVectorSDNode>(ConstVec)) 7769 return SDValue(); 7770 7771 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 7772 int32_t IntBits = IntTy.getSizeInBits(); 7773 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7774 return SDValue(); 7775 7776 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 7777 int32_t FloatBits = FloatTy.getSizeInBits(); 7778 if (FloatBits != 32 && FloatBits != 64) 7779 return SDValue(); 7780 7781 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 7782 if (IntBits > FloatBits) 7783 return SDValue(); 7784 7785 BitVector UndefElements; 7786 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7787 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 7788 if (C == -1 || C == 0 || C > FloatBits) 7789 return SDValue(); 7790 7791 MVT ResTy; 7792 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7793 switch (NumLanes) { 7794 default: 7795 return SDValue(); 7796 case 2: 7797 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7798 break; 7799 case 4: 7800 ResTy = MVT::v4i32; 7801 break; 7802 } 7803 7804 SDLoc DL(N); 7805 SDValue ConvInput = Op.getOperand(0); 7806 bool IsSigned = Opc == ISD::SINT_TO_FP; 7807 if (IntBits < FloatBits) 7808 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 7809 ResTy, ConvInput); 7810 7811 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 7812 : Intrinsic::aarch64_neon_vcvtfxu2fp; 7813 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 7814 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 7815 DAG.getConstant(C, DL, MVT::i32)); 7816 } 7817 7818 /// An EXTR instruction is made up of two shifts, ORed together. This helper 7819 /// searches for and classifies those shifts. 7820 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 7821 bool &FromHi) { 7822 if (N.getOpcode() == ISD::SHL) 7823 FromHi = false; 7824 else if (N.getOpcode() == ISD::SRL) 7825 FromHi = true; 7826 else 7827 return false; 7828 7829 if (!isa<ConstantSDNode>(N.getOperand(1))) 7830 return false; 7831 7832 ShiftAmount = N->getConstantOperandVal(1); 7833 Src = N->getOperand(0); 7834 return true; 7835 } 7836 7837 /// EXTR instruction extracts a contiguous chunk of bits from two existing 7838 /// registers viewed as a high/low pair. This function looks for the pattern: 7839 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an 7840 /// EXTR. Can't quite be done in TableGen because the two immediates aren't 7841 /// independent. 7842 static SDValue tryCombineToEXTR(SDNode *N, 7843 TargetLowering::DAGCombinerInfo &DCI) { 7844 SelectionDAG &DAG = DCI.DAG; 7845 SDLoc DL(N); 7846 EVT VT = N->getValueType(0); 7847 7848 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 7849 7850 if (VT != MVT::i32 && VT != MVT::i64) 7851 return SDValue(); 7852 7853 SDValue LHS; 7854 uint32_t ShiftLHS = 0; 7855 bool LHSFromHi = 0; 7856 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 7857 return SDValue(); 7858 7859 SDValue RHS; 7860 uint32_t ShiftRHS = 0; 7861 bool RHSFromHi = 0; 7862 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 7863 return SDValue(); 7864 7865 // If they're both trying to come from the high part of the register, they're 7866 // not really an EXTR. 7867 if (LHSFromHi == RHSFromHi) 7868 return SDValue(); 7869 7870 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 7871 return SDValue(); 7872 7873 if (LHSFromHi) { 7874 std::swap(LHS, RHS); 7875 std::swap(ShiftLHS, ShiftRHS); 7876 } 7877 7878 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 7879 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 7880 } 7881 7882 static SDValue tryCombineToBSL(SDNode *N, 7883 TargetLowering::DAGCombinerInfo &DCI) { 7884 EVT VT = N->getValueType(0); 7885 SelectionDAG &DAG = DCI.DAG; 7886 SDLoc DL(N); 7887 7888 if (!VT.isVector()) 7889 return SDValue(); 7890 7891 SDValue N0 = N->getOperand(0); 7892 if (N0.getOpcode() != ISD::AND) 7893 return SDValue(); 7894 7895 SDValue N1 = N->getOperand(1); 7896 if (N1.getOpcode() != ISD::AND) 7897 return SDValue(); 7898 7899 // We only have to look for constant vectors here since the general, variable 7900 // case can be handled in TableGen. 7901 unsigned Bits = VT.getVectorElementType().getSizeInBits(); 7902 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 7903 for (int i = 1; i >= 0; --i) 7904 for (int j = 1; j >= 0; --j) { 7905 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 7906 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 7907 if (!BVN0 || !BVN1) 7908 continue; 7909 7910 bool FoundMatch = true; 7911 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 7912 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 7913 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 7914 if (!CN0 || !CN1 || 7915 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 7916 FoundMatch = false; 7917 break; 7918 } 7919 } 7920 7921 if (FoundMatch) 7922 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 7923 N0->getOperand(1 - i), N1->getOperand(1 - j)); 7924 } 7925 7926 return SDValue(); 7927 } 7928 7929 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 7930 const AArch64Subtarget *Subtarget) { 7931 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 7932 if (!EnableAArch64ExtrGeneration) 7933 return SDValue(); 7934 SelectionDAG &DAG = DCI.DAG; 7935 EVT VT = N->getValueType(0); 7936 7937 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 7938 return SDValue(); 7939 7940 if (SDValue Res = tryCombineToEXTR(N, DCI)) 7941 return Res; 7942 7943 if (SDValue Res = tryCombineToBSL(N, DCI)) 7944 return Res; 7945 7946 return SDValue(); 7947 } 7948 7949 static SDValue performBitcastCombine(SDNode *N, 7950 TargetLowering::DAGCombinerInfo &DCI, 7951 SelectionDAG &DAG) { 7952 // Wait 'til after everything is legalized to try this. That way we have 7953 // legal vector types and such. 7954 if (DCI.isBeforeLegalizeOps()) 7955 return SDValue(); 7956 7957 // Remove extraneous bitcasts around an extract_subvector. 7958 // For example, 7959 // (v4i16 (bitconvert 7960 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 7961 // becomes 7962 // (extract_subvector ((v8i16 ...), (i64 4))) 7963 7964 // Only interested in 64-bit vectors as the ultimate result. 7965 EVT VT = N->getValueType(0); 7966 if (!VT.isVector()) 7967 return SDValue(); 7968 if (VT.getSimpleVT().getSizeInBits() != 64) 7969 return SDValue(); 7970 // Is the operand an extract_subvector starting at the beginning or halfway 7971 // point of the vector? A low half may also come through as an 7972 // EXTRACT_SUBREG, so look for that, too. 7973 SDValue Op0 = N->getOperand(0); 7974 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 7975 !(Op0->isMachineOpcode() && 7976 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 7977 return SDValue(); 7978 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 7979 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 7980 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 7981 return SDValue(); 7982 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 7983 if (idx != AArch64::dsub) 7984 return SDValue(); 7985 // The dsub reference is equivalent to a lane zero subvector reference. 7986 idx = 0; 7987 } 7988 // Look through the bitcast of the input to the extract. 7989 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 7990 return SDValue(); 7991 SDValue Source = Op0->getOperand(0)->getOperand(0); 7992 // If the source type has twice the number of elements as our destination 7993 // type, we know this is an extract of the high or low half of the vector. 7994 EVT SVT = Source->getValueType(0); 7995 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 7996 return SDValue(); 7997 7998 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 7999 8000 // Create the simplified form to just extract the low or high half of the 8001 // vector directly rather than bothering with the bitcasts. 8002 SDLoc dl(N); 8003 unsigned NumElements = VT.getVectorNumElements(); 8004 if (idx) { 8005 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8006 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8007 } else { 8008 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8009 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8010 Source, SubReg), 8011 0); 8012 } 8013 } 8014 8015 static SDValue performConcatVectorsCombine(SDNode *N, 8016 TargetLowering::DAGCombinerInfo &DCI, 8017 SelectionDAG &DAG) { 8018 SDLoc dl(N); 8019 EVT VT = N->getValueType(0); 8020 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8021 8022 // Optimize concat_vectors of truncated vectors, where the intermediate 8023 // type is illegal, to avoid said illegality, e.g., 8024 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8025 // (v2i16 (truncate (v2i64))))) 8026 // -> 8027 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8028 // (v4i32 (bitcast (v2i64))), 8029 // <0, 2, 4, 6>))) 8030 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8031 // on both input and result type, so we might generate worse code. 8032 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8033 if (N->getNumOperands() == 2 && 8034 N0->getOpcode() == ISD::TRUNCATE && 8035 N1->getOpcode() == ISD::TRUNCATE) { 8036 SDValue N00 = N0->getOperand(0); 8037 SDValue N10 = N1->getOperand(0); 8038 EVT N00VT = N00.getValueType(); 8039 8040 if (N00VT == N10.getValueType() && 8041 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8042 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8043 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8044 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8045 for (size_t i = 0; i < Mask.size(); ++i) 8046 Mask[i] = i * 2; 8047 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8048 DAG.getVectorShuffle( 8049 MidVT, dl, 8050 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8051 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8052 } 8053 } 8054 8055 // Wait 'til after everything is legalized to try this. That way we have 8056 // legal vector types and such. 8057 if (DCI.isBeforeLegalizeOps()) 8058 return SDValue(); 8059 8060 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8061 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8062 // canonicalise to that. 8063 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8064 assert(VT.getVectorElementType().getSizeInBits() == 64); 8065 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8066 DAG.getConstant(0, dl, MVT::i64)); 8067 } 8068 8069 // Canonicalise concat_vectors so that the right-hand vector has as few 8070 // bit-casts as possible before its real operation. The primary matching 8071 // destination for these operations will be the narrowing "2" instructions, 8072 // which depend on the operation being performed on this right-hand vector. 8073 // For example, 8074 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8075 // becomes 8076 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8077 8078 if (N1->getOpcode() != ISD::BITCAST) 8079 return SDValue(); 8080 SDValue RHS = N1->getOperand(0); 8081 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8082 // If the RHS is not a vector, this is not the pattern we're looking for. 8083 if (!RHSTy.isVector()) 8084 return SDValue(); 8085 8086 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8087 8088 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8089 RHSTy.getVectorNumElements() * 2); 8090 return DAG.getNode(ISD::BITCAST, dl, VT, 8091 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8092 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8093 RHS)); 8094 } 8095 8096 static SDValue tryCombineFixedPointConvert(SDNode *N, 8097 TargetLowering::DAGCombinerInfo &DCI, 8098 SelectionDAG &DAG) { 8099 // Wait 'til after everything is legalized to try this. That way we have 8100 // legal vector types and such. 8101 if (DCI.isBeforeLegalizeOps()) 8102 return SDValue(); 8103 // Transform a scalar conversion of a value from a lane extract into a 8104 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8105 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8106 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8107 // 8108 // The second form interacts better with instruction selection and the 8109 // register allocator to avoid cross-class register copies that aren't 8110 // coalescable due to a lane reference. 8111 8112 // Check the operand and see if it originates from a lane extract. 8113 SDValue Op1 = N->getOperand(1); 8114 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8115 // Yep, no additional predication needed. Perform the transform. 8116 SDValue IID = N->getOperand(0); 8117 SDValue Shift = N->getOperand(2); 8118 SDValue Vec = Op1.getOperand(0); 8119 SDValue Lane = Op1.getOperand(1); 8120 EVT ResTy = N->getValueType(0); 8121 EVT VecResTy; 8122 SDLoc DL(N); 8123 8124 // The vector width should be 128 bits by the time we get here, even 8125 // if it started as 64 bits (the extract_vector handling will have 8126 // done so). 8127 assert(Vec.getValueType().getSizeInBits() == 128 && 8128 "unexpected vector size on extract_vector_elt!"); 8129 if (Vec.getValueType() == MVT::v4i32) 8130 VecResTy = MVT::v4f32; 8131 else if (Vec.getValueType() == MVT::v2i64) 8132 VecResTy = MVT::v2f64; 8133 else 8134 llvm_unreachable("unexpected vector type!"); 8135 8136 SDValue Convert = 8137 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8138 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8139 } 8140 return SDValue(); 8141 } 8142 8143 // AArch64 high-vector "long" operations are formed by performing the non-high 8144 // version on an extract_subvector of each operand which gets the high half: 8145 // 8146 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8147 // 8148 // However, there are cases which don't have an extract_high explicitly, but 8149 // have another operation that can be made compatible with one for free. For 8150 // example: 8151 // 8152 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8153 // 8154 // This routine does the actual conversion of such DUPs, once outer routines 8155 // have determined that everything else is in order. 8156 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8157 // similarly here. 8158 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8159 switch (N.getOpcode()) { 8160 case AArch64ISD::DUP: 8161 case AArch64ISD::DUPLANE8: 8162 case AArch64ISD::DUPLANE16: 8163 case AArch64ISD::DUPLANE32: 8164 case AArch64ISD::DUPLANE64: 8165 case AArch64ISD::MOVI: 8166 case AArch64ISD::MOVIshift: 8167 case AArch64ISD::MOVIedit: 8168 case AArch64ISD::MOVImsl: 8169 case AArch64ISD::MVNIshift: 8170 case AArch64ISD::MVNImsl: 8171 break; 8172 default: 8173 // FMOV could be supported, but isn't very useful, as it would only occur 8174 // if you passed a bitcast' floating point immediate to an eligible long 8175 // integer op (addl, smull, ...). 8176 return SDValue(); 8177 } 8178 8179 MVT NarrowTy = N.getSimpleValueType(); 8180 if (!NarrowTy.is64BitVector()) 8181 return SDValue(); 8182 8183 MVT ElementTy = NarrowTy.getVectorElementType(); 8184 unsigned NumElems = NarrowTy.getVectorNumElements(); 8185 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8186 8187 SDLoc dl(N); 8188 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8189 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8190 DAG.getConstant(NumElems, dl, MVT::i64)); 8191 } 8192 8193 static bool isEssentiallyExtractSubvector(SDValue N) { 8194 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8195 return true; 8196 8197 return N.getOpcode() == ISD::BITCAST && 8198 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8199 } 8200 8201 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8202 struct GenericSetCCInfo { 8203 const SDValue *Opnd0; 8204 const SDValue *Opnd1; 8205 ISD::CondCode CC; 8206 }; 8207 8208 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8209 struct AArch64SetCCInfo { 8210 const SDValue *Cmp; 8211 AArch64CC::CondCode CC; 8212 }; 8213 8214 /// \brief Helper structure to keep track of SetCC information. 8215 union SetCCInfo { 8216 GenericSetCCInfo Generic; 8217 AArch64SetCCInfo AArch64; 8218 }; 8219 8220 /// \brief Helper structure to be able to read SetCC information. If set to 8221 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8222 /// GenericSetCCInfo. 8223 struct SetCCInfoAndKind { 8224 SetCCInfo Info; 8225 bool IsAArch64; 8226 }; 8227 8228 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8229 /// an 8230 /// AArch64 lowered one. 8231 /// \p SetCCInfo is filled accordingly. 8232 /// \post SetCCInfo is meanginfull only when this function returns true. 8233 /// \return True when Op is a kind of SET_CC operation. 8234 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8235 // If this is a setcc, this is straight forward. 8236 if (Op.getOpcode() == ISD::SETCC) { 8237 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8238 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8239 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8240 SetCCInfo.IsAArch64 = false; 8241 return true; 8242 } 8243 // Otherwise, check if this is a matching csel instruction. 8244 // In other words: 8245 // - csel 1, 0, cc 8246 // - csel 0, 1, !cc 8247 if (Op.getOpcode() != AArch64ISD::CSEL) 8248 return false; 8249 // Set the information about the operands. 8250 // TODO: we want the operands of the Cmp not the csel 8251 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8252 SetCCInfo.IsAArch64 = true; 8253 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8254 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8255 8256 // Check that the operands matches the constraints: 8257 // (1) Both operands must be constants. 8258 // (2) One must be 1 and the other must be 0. 8259 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 8260 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8261 8262 // Check (1). 8263 if (!TValue || !FValue) 8264 return false; 8265 8266 // Check (2). 8267 if (!TValue->isOne()) { 8268 // Update the comparison when we are interested in !cc. 8269 std::swap(TValue, FValue); 8270 SetCCInfo.Info.AArch64.CC = 8271 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 8272 } 8273 return TValue->isOne() && FValue->isNullValue(); 8274 } 8275 8276 // Returns true if Op is setcc or zext of setcc. 8277 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 8278 if (isSetCC(Op, Info)) 8279 return true; 8280 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 8281 isSetCC(Op->getOperand(0), Info)); 8282 } 8283 8284 // The folding we want to perform is: 8285 // (add x, [zext] (setcc cc ...) ) 8286 // --> 8287 // (csel x, (add x, 1), !cc ...) 8288 // 8289 // The latter will get matched to a CSINC instruction. 8290 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 8291 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 8292 SDValue LHS = Op->getOperand(0); 8293 SDValue RHS = Op->getOperand(1); 8294 SetCCInfoAndKind InfoAndKind; 8295 8296 // If neither operand is a SET_CC, give up. 8297 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 8298 std::swap(LHS, RHS); 8299 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 8300 return SDValue(); 8301 } 8302 8303 // FIXME: This could be generatized to work for FP comparisons. 8304 EVT CmpVT = InfoAndKind.IsAArch64 8305 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 8306 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 8307 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 8308 return SDValue(); 8309 8310 SDValue CCVal; 8311 SDValue Cmp; 8312 SDLoc dl(Op); 8313 if (InfoAndKind.IsAArch64) { 8314 CCVal = DAG.getConstant( 8315 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 8316 MVT::i32); 8317 Cmp = *InfoAndKind.Info.AArch64.Cmp; 8318 } else 8319 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 8320 *InfoAndKind.Info.Generic.Opnd1, 8321 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 8322 CCVal, DAG, dl); 8323 8324 EVT VT = Op->getValueType(0); 8325 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 8326 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 8327 } 8328 8329 // The basic add/sub long vector instructions have variants with "2" on the end 8330 // which act on the high-half of their inputs. They are normally matched by 8331 // patterns like: 8332 // 8333 // (add (zeroext (extract_high LHS)), 8334 // (zeroext (extract_high RHS))) 8335 // -> uaddl2 vD, vN, vM 8336 // 8337 // However, if one of the extracts is something like a duplicate, this 8338 // instruction can still be used profitably. This function puts the DAG into a 8339 // more appropriate form for those patterns to trigger. 8340 static SDValue performAddSubLongCombine(SDNode *N, 8341 TargetLowering::DAGCombinerInfo &DCI, 8342 SelectionDAG &DAG) { 8343 if (DCI.isBeforeLegalizeOps()) 8344 return SDValue(); 8345 8346 MVT VT = N->getSimpleValueType(0); 8347 if (!VT.is128BitVector()) { 8348 if (N->getOpcode() == ISD::ADD) 8349 return performSetccAddFolding(N, DAG); 8350 return SDValue(); 8351 } 8352 8353 // Make sure both branches are extended in the same way. 8354 SDValue LHS = N->getOperand(0); 8355 SDValue RHS = N->getOperand(1); 8356 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 8357 LHS.getOpcode() != ISD::SIGN_EXTEND) || 8358 LHS.getOpcode() != RHS.getOpcode()) 8359 return SDValue(); 8360 8361 unsigned ExtType = LHS.getOpcode(); 8362 8363 // It's not worth doing if at least one of the inputs isn't already an 8364 // extract, but we don't know which it'll be so we have to try both. 8365 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 8366 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 8367 if (!RHS.getNode()) 8368 return SDValue(); 8369 8370 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 8371 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 8372 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 8373 if (!LHS.getNode()) 8374 return SDValue(); 8375 8376 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 8377 } 8378 8379 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 8380 } 8381 8382 // Massage DAGs which we can use the high-half "long" operations on into 8383 // something isel will recognize better. E.g. 8384 // 8385 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 8386 // (aarch64_neon_umull (extract_high (v2i64 vec))) 8387 // (extract_high (v2i64 (dup128 scalar))))) 8388 // 8389 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 8390 TargetLowering::DAGCombinerInfo &DCI, 8391 SelectionDAG &DAG) { 8392 if (DCI.isBeforeLegalizeOps()) 8393 return SDValue(); 8394 8395 SDValue LHS = N->getOperand(1); 8396 SDValue RHS = N->getOperand(2); 8397 assert(LHS.getValueType().is64BitVector() && 8398 RHS.getValueType().is64BitVector() && 8399 "unexpected shape for long operation"); 8400 8401 // Either node could be a DUP, but it's not worth doing both of them (you'd 8402 // just as well use the non-high version) so look for a corresponding extract 8403 // operation on the other "wing". 8404 if (isEssentiallyExtractSubvector(LHS)) { 8405 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 8406 if (!RHS.getNode()) 8407 return SDValue(); 8408 } else if (isEssentiallyExtractSubvector(RHS)) { 8409 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 8410 if (!LHS.getNode()) 8411 return SDValue(); 8412 } 8413 8414 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 8415 N->getOperand(0), LHS, RHS); 8416 } 8417 8418 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 8419 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 8420 unsigned ElemBits = ElemTy.getSizeInBits(); 8421 8422 int64_t ShiftAmount; 8423 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 8424 APInt SplatValue, SplatUndef; 8425 unsigned SplatBitSize; 8426 bool HasAnyUndefs; 8427 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 8428 HasAnyUndefs, ElemBits) || 8429 SplatBitSize != ElemBits) 8430 return SDValue(); 8431 8432 ShiftAmount = SplatValue.getSExtValue(); 8433 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 8434 ShiftAmount = CVN->getSExtValue(); 8435 } else 8436 return SDValue(); 8437 8438 unsigned Opcode; 8439 bool IsRightShift; 8440 switch (IID) { 8441 default: 8442 llvm_unreachable("Unknown shift intrinsic"); 8443 case Intrinsic::aarch64_neon_sqshl: 8444 Opcode = AArch64ISD::SQSHL_I; 8445 IsRightShift = false; 8446 break; 8447 case Intrinsic::aarch64_neon_uqshl: 8448 Opcode = AArch64ISD::UQSHL_I; 8449 IsRightShift = false; 8450 break; 8451 case Intrinsic::aarch64_neon_srshl: 8452 Opcode = AArch64ISD::SRSHR_I; 8453 IsRightShift = true; 8454 break; 8455 case Intrinsic::aarch64_neon_urshl: 8456 Opcode = AArch64ISD::URSHR_I; 8457 IsRightShift = true; 8458 break; 8459 case Intrinsic::aarch64_neon_sqshlu: 8460 Opcode = AArch64ISD::SQSHLU_I; 8461 IsRightShift = false; 8462 break; 8463 } 8464 8465 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 8466 SDLoc dl(N); 8467 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8468 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 8469 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 8470 SDLoc dl(N); 8471 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8472 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 8473 } 8474 8475 return SDValue(); 8476 } 8477 8478 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 8479 // the intrinsics must be legal and take an i32, this means there's almost 8480 // certainly going to be a zext in the DAG which we can eliminate. 8481 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 8482 SDValue AndN = N->getOperand(2); 8483 if (AndN.getOpcode() != ISD::AND) 8484 return SDValue(); 8485 8486 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 8487 if (!CMask || CMask->getZExtValue() != Mask) 8488 return SDValue(); 8489 8490 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 8491 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 8492 } 8493 8494 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 8495 SelectionDAG &DAG) { 8496 SDLoc dl(N); 8497 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 8498 DAG.getNode(Opc, dl, 8499 N->getOperand(1).getSimpleValueType(), 8500 N->getOperand(1)), 8501 DAG.getConstant(0, dl, MVT::i64)); 8502 } 8503 8504 static SDValue performIntrinsicCombine(SDNode *N, 8505 TargetLowering::DAGCombinerInfo &DCI, 8506 const AArch64Subtarget *Subtarget) { 8507 SelectionDAG &DAG = DCI.DAG; 8508 unsigned IID = getIntrinsicID(N); 8509 switch (IID) { 8510 default: 8511 break; 8512 case Intrinsic::aarch64_neon_vcvtfxs2fp: 8513 case Intrinsic::aarch64_neon_vcvtfxu2fp: 8514 return tryCombineFixedPointConvert(N, DCI, DAG); 8515 case Intrinsic::aarch64_neon_saddv: 8516 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 8517 case Intrinsic::aarch64_neon_uaddv: 8518 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 8519 case Intrinsic::aarch64_neon_sminv: 8520 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 8521 case Intrinsic::aarch64_neon_uminv: 8522 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 8523 case Intrinsic::aarch64_neon_smaxv: 8524 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 8525 case Intrinsic::aarch64_neon_umaxv: 8526 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 8527 case Intrinsic::aarch64_neon_fmax: 8528 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 8529 N->getOperand(1), N->getOperand(2)); 8530 case Intrinsic::aarch64_neon_fmin: 8531 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 8532 N->getOperand(1), N->getOperand(2)); 8533 case Intrinsic::aarch64_neon_fmaxnm: 8534 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 8535 N->getOperand(1), N->getOperand(2)); 8536 case Intrinsic::aarch64_neon_fminnm: 8537 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 8538 N->getOperand(1), N->getOperand(2)); 8539 case Intrinsic::aarch64_neon_smull: 8540 case Intrinsic::aarch64_neon_umull: 8541 case Intrinsic::aarch64_neon_pmull: 8542 case Intrinsic::aarch64_neon_sqdmull: 8543 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 8544 case Intrinsic::aarch64_neon_sqshl: 8545 case Intrinsic::aarch64_neon_uqshl: 8546 case Intrinsic::aarch64_neon_sqshlu: 8547 case Intrinsic::aarch64_neon_srshl: 8548 case Intrinsic::aarch64_neon_urshl: 8549 return tryCombineShiftImm(IID, N, DAG); 8550 case Intrinsic::aarch64_crc32b: 8551 case Intrinsic::aarch64_crc32cb: 8552 return tryCombineCRC32(0xff, N, DAG); 8553 case Intrinsic::aarch64_crc32h: 8554 case Intrinsic::aarch64_crc32ch: 8555 return tryCombineCRC32(0xffff, N, DAG); 8556 } 8557 return SDValue(); 8558 } 8559 8560 static SDValue performExtendCombine(SDNode *N, 8561 TargetLowering::DAGCombinerInfo &DCI, 8562 SelectionDAG &DAG) { 8563 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 8564 // we can convert that DUP into another extract_high (of a bigger DUP), which 8565 // helps the backend to decide that an sabdl2 would be useful, saving a real 8566 // extract_high operation. 8567 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 8568 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 8569 SDNode *ABDNode = N->getOperand(0).getNode(); 8570 unsigned IID = getIntrinsicID(ABDNode); 8571 if (IID == Intrinsic::aarch64_neon_sabd || 8572 IID == Intrinsic::aarch64_neon_uabd) { 8573 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 8574 if (!NewABD.getNode()) 8575 return SDValue(); 8576 8577 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 8578 NewABD); 8579 } 8580 } 8581 8582 // This is effectively a custom type legalization for AArch64. 8583 // 8584 // Type legalization will split an extend of a small, legal, type to a larger 8585 // illegal type by first splitting the destination type, often creating 8586 // illegal source types, which then get legalized in isel-confusing ways, 8587 // leading to really terrible codegen. E.g., 8588 // %result = v8i32 sext v8i8 %value 8589 // becomes 8590 // %losrc = extract_subreg %value, ... 8591 // %hisrc = extract_subreg %value, ... 8592 // %lo = v4i32 sext v4i8 %losrc 8593 // %hi = v4i32 sext v4i8 %hisrc 8594 // Things go rapidly downhill from there. 8595 // 8596 // For AArch64, the [sz]ext vector instructions can only go up one element 8597 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 8598 // take two instructions. 8599 // 8600 // This implies that the most efficient way to do the extend from v8i8 8601 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 8602 // the normal splitting to happen for the v8i16->v8i32. 8603 8604 // This is pre-legalization to catch some cases where the default 8605 // type legalization will create ill-tempered code. 8606 if (!DCI.isBeforeLegalizeOps()) 8607 return SDValue(); 8608 8609 // We're only interested in cleaning things up for non-legal vector types 8610 // here. If both the source and destination are legal, things will just 8611 // work naturally without any fiddling. 8612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8613 EVT ResVT = N->getValueType(0); 8614 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 8615 return SDValue(); 8616 // If the vector type isn't a simple VT, it's beyond the scope of what 8617 // we're worried about here. Let legalization do its thing and hope for 8618 // the best. 8619 SDValue Src = N->getOperand(0); 8620 EVT SrcVT = Src->getValueType(0); 8621 if (!ResVT.isSimple() || !SrcVT.isSimple()) 8622 return SDValue(); 8623 8624 // If the source VT is a 64-bit vector, we can play games and get the 8625 // better results we want. 8626 if (SrcVT.getSizeInBits() != 64) 8627 return SDValue(); 8628 8629 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits(); 8630 unsigned ElementCount = SrcVT.getVectorNumElements(); 8631 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 8632 SDLoc DL(N); 8633 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 8634 8635 // Now split the rest of the operation into two halves, each with a 64 8636 // bit source. 8637 EVT LoVT, HiVT; 8638 SDValue Lo, Hi; 8639 unsigned NumElements = ResVT.getVectorNumElements(); 8640 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 8641 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 8642 ResVT.getVectorElementType(), NumElements / 2); 8643 8644 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 8645 LoVT.getVectorNumElements()); 8646 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8647 DAG.getConstant(0, DL, MVT::i64)); 8648 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8649 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 8650 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 8651 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 8652 8653 // Now combine the parts back together so we still have a single result 8654 // like the combiner expects. 8655 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 8656 } 8657 8658 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 8659 /// value. The load store optimizer pass will merge them to store pair stores. 8660 /// This has better performance than a splat of the scalar followed by a split 8661 /// vector store. Even if the stores are not merged it is four stores vs a dup, 8662 /// followed by an ext.b and two stores. 8663 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) { 8664 SDValue StVal = St->getValue(); 8665 EVT VT = StVal.getValueType(); 8666 8667 // Don't replace floating point stores, they possibly won't be transformed to 8668 // stp because of the store pair suppress pass. 8669 if (VT.isFloatingPoint()) 8670 return SDValue(); 8671 8672 // Check for insert vector elements. 8673 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 8674 return SDValue(); 8675 8676 // We can express a splat as store pair(s) for 2 or 4 elements. 8677 unsigned NumVecElts = VT.getVectorNumElements(); 8678 if (NumVecElts != 4 && NumVecElts != 2) 8679 return SDValue(); 8680 SDValue SplatVal = StVal.getOperand(1); 8681 unsigned RemainInsertElts = NumVecElts - 1; 8682 8683 // Check that this is a splat. 8684 while (--RemainInsertElts) { 8685 SDValue NextInsertElt = StVal.getOperand(0); 8686 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT) 8687 return SDValue(); 8688 if (NextInsertElt.getOperand(1) != SplatVal) 8689 return SDValue(); 8690 StVal = NextInsertElt; 8691 } 8692 unsigned OrigAlignment = St->getAlignment(); 8693 unsigned EltOffset = NumVecElts == 4 ? 4 : 8; 8694 unsigned Alignment = std::min(OrigAlignment, EltOffset); 8695 8696 // Create scalar stores. This is at least as good as the code sequence for a 8697 // split unaligned store which is a dup.s, ext.b, and two stores. 8698 // Most of the time the three stores should be replaced by store pair 8699 // instructions (stp). 8700 SDLoc DL(St); 8701 SDValue BasePtr = St->getBasePtr(); 8702 SDValue NewST1 = 8703 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(), 8704 St->isVolatile(), St->isNonTemporal(), St->getAlignment()); 8705 8706 unsigned Offset = EltOffset; 8707 while (--NumVecElts) { 8708 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8709 DAG.getConstant(Offset, DL, MVT::i64)); 8710 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 8711 St->getPointerInfo(), St->isVolatile(), 8712 St->isNonTemporal(), Alignment); 8713 Offset += EltOffset; 8714 } 8715 return NewST1; 8716 } 8717 8718 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8719 SelectionDAG &DAG, 8720 const AArch64Subtarget *Subtarget) { 8721 if (!DCI.isBeforeLegalize()) 8722 return SDValue(); 8723 8724 StoreSDNode *S = cast<StoreSDNode>(N); 8725 if (S->isVolatile()) 8726 return SDValue(); 8727 8728 // FIXME: The logic for deciding if an unaligned store should be split should 8729 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 8730 // a call to that function here. 8731 8732 // Cyclone has bad performance on unaligned 16B stores when crossing line and 8733 // page boundaries. We want to split such stores. 8734 if (!Subtarget->isCyclone()) 8735 return SDValue(); 8736 8737 // Don't split at -Oz. 8738 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 8739 return SDValue(); 8740 8741 SDValue StVal = S->getValue(); 8742 EVT VT = StVal.getValueType(); 8743 8744 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 8745 // those up regresses performance on micro-benchmarks and olden/bh. 8746 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 8747 return SDValue(); 8748 8749 // Split unaligned 16B stores. They are terrible for performance. 8750 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 8751 // extensions can use this to mark that it does not want splitting to happen 8752 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 8753 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 8754 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 8755 S->getAlignment() <= 2) 8756 return SDValue(); 8757 8758 // If we get a splat of a scalar convert this vector store to a store of 8759 // scalars. They will be merged into store pairs thereby removing two 8760 // instructions. 8761 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S)) 8762 return ReplacedSplat; 8763 8764 SDLoc DL(S); 8765 unsigned NumElts = VT.getVectorNumElements() / 2; 8766 // Split VT into two. 8767 EVT HalfVT = 8768 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 8769 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 8770 DAG.getConstant(0, DL, MVT::i64)); 8771 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 8772 DAG.getConstant(NumElts, DL, MVT::i64)); 8773 SDValue BasePtr = S->getBasePtr(); 8774 SDValue NewST1 = 8775 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 8776 S->isVolatile(), S->isNonTemporal(), S->getAlignment()); 8777 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8778 DAG.getConstant(8, DL, MVT::i64)); 8779 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 8780 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(), 8781 S->getAlignment()); 8782 } 8783 8784 /// Target-specific DAG combine function for post-increment LD1 (lane) and 8785 /// post-increment LD1R. 8786 static SDValue performPostLD1Combine(SDNode *N, 8787 TargetLowering::DAGCombinerInfo &DCI, 8788 bool IsLaneOp) { 8789 if (DCI.isBeforeLegalizeOps()) 8790 return SDValue(); 8791 8792 SelectionDAG &DAG = DCI.DAG; 8793 EVT VT = N->getValueType(0); 8794 8795 unsigned LoadIdx = IsLaneOp ? 1 : 0; 8796 SDNode *LD = N->getOperand(LoadIdx).getNode(); 8797 // If it is not LOAD, can not do such combine. 8798 if (LD->getOpcode() != ISD::LOAD) 8799 return SDValue(); 8800 8801 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 8802 EVT MemVT = LoadSDN->getMemoryVT(); 8803 // Check if memory operand is the same type as the vector element. 8804 if (MemVT != VT.getVectorElementType()) 8805 return SDValue(); 8806 8807 // Check if there are other uses. If so, do not combine as it will introduce 8808 // an extra load. 8809 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 8810 ++UI) { 8811 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 8812 continue; 8813 if (*UI != N) 8814 return SDValue(); 8815 } 8816 8817 SDValue Addr = LD->getOperand(1); 8818 SDValue Vector = N->getOperand(0); 8819 // Search for a use of the address operand that is an increment. 8820 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 8821 Addr.getNode()->use_end(); UI != UE; ++UI) { 8822 SDNode *User = *UI; 8823 if (User->getOpcode() != ISD::ADD 8824 || UI.getUse().getResNo() != Addr.getResNo()) 8825 continue; 8826 8827 // Check that the add is independent of the load. Otherwise, folding it 8828 // would create a cycle. 8829 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 8830 continue; 8831 // Also check that add is not used in the vector operand. This would also 8832 // create a cycle. 8833 if (User->isPredecessorOf(Vector.getNode())) 8834 continue; 8835 8836 // If the increment is a constant, it must match the memory ref size. 8837 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 8838 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 8839 uint32_t IncVal = CInc->getZExtValue(); 8840 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 8841 if (IncVal != NumBytes) 8842 continue; 8843 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 8844 } 8845 8846 // Finally, check that the vector doesn't depend on the load. 8847 // Again, this would create a cycle. 8848 // The load depending on the vector is fine, as that's the case for the 8849 // LD1*post we'll eventually generate anyway. 8850 if (LoadSDN->isPredecessorOf(Vector.getNode())) 8851 continue; 8852 8853 SmallVector<SDValue, 8> Ops; 8854 Ops.push_back(LD->getOperand(0)); // Chain 8855 if (IsLaneOp) { 8856 Ops.push_back(Vector); // The vector to be inserted 8857 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 8858 } 8859 Ops.push_back(Addr); 8860 Ops.push_back(Inc); 8861 8862 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 8863 SDVTList SDTys = DAG.getVTList(Tys); 8864 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 8865 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 8866 MemVT, 8867 LoadSDN->getMemOperand()); 8868 8869 // Update the uses. 8870 SmallVector<SDValue, 2> NewResults; 8871 NewResults.push_back(SDValue(LD, 0)); // The result of load 8872 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain 8873 DCI.CombineTo(LD, NewResults); 8874 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 8875 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 8876 8877 break; 8878 } 8879 return SDValue(); 8880 } 8881 8882 /// Simplify \Addr given that the top byte of it is ignored by HW during 8883 /// address translation. 8884 static bool performTBISimplification(SDValue Addr, 8885 TargetLowering::DAGCombinerInfo &DCI, 8886 SelectionDAG &DAG) { 8887 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 8888 APInt KnownZero, KnownOne; 8889 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 8890 DCI.isBeforeLegalizeOps()); 8891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8892 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) { 8893 DCI.CommitTargetLoweringOpt(TLO); 8894 return true; 8895 } 8896 return false; 8897 } 8898 8899 static SDValue performSTORECombine(SDNode *N, 8900 TargetLowering::DAGCombinerInfo &DCI, 8901 SelectionDAG &DAG, 8902 const AArch64Subtarget *Subtarget) { 8903 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget)) 8904 return Split; 8905 8906 if (Subtarget->supportsAddressTopByteIgnored() && 8907 performTBISimplification(N->getOperand(2), DCI, DAG)) 8908 return SDValue(N, 0); 8909 8910 return SDValue(); 8911 } 8912 8913 /// This function handles the log2-shuffle pattern produced by the 8914 /// LoopVectorizer for the across vector reduction. It consists of 8915 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements 8916 /// are reduced, where s is an induction variable from 0 to 8917 /// log2(NumVectorElements). 8918 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV, 8919 unsigned Op, 8920 SelectionDAG &DAG) { 8921 EVT VTy = OpV->getOperand(0).getValueType(); 8922 if (!VTy.isVector()) 8923 return SDValue(); 8924 8925 int NumVecElts = VTy.getVectorNumElements(); 8926 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 8927 if (NumVecElts != 4) 8928 return SDValue(); 8929 } else { 8930 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16) 8931 return SDValue(); 8932 } 8933 8934 int NumExpectedSteps = APInt(8, NumVecElts).logBase2(); 8935 SDValue PreOp = OpV; 8936 // Iterate over each step of the across vector reduction. 8937 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) { 8938 SDValue CurOp = PreOp.getOperand(0); 8939 SDValue Shuffle = PreOp.getOperand(1); 8940 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) { 8941 // Try to swap the 1st and 2nd operand as add and min/max instructions 8942 // are commutative. 8943 CurOp = PreOp.getOperand(1); 8944 Shuffle = PreOp.getOperand(0); 8945 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) 8946 return SDValue(); 8947 } 8948 8949 // Check if the input vector is fed by the operator we want to handle, 8950 // except the last step; the very first input vector is not necessarily 8951 // the same operator we are handling. 8952 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1))) 8953 return SDValue(); 8954 8955 // Check if it forms one step of the across vector reduction. 8956 // E.g., 8957 // %cur = add %1, %0 8958 // %shuffle = vector_shuffle %cur, <2, 3, u, u> 8959 // %pre = add %cur, %shuffle 8960 if (Shuffle.getOperand(0) != CurOp) 8961 return SDValue(); 8962 8963 int NumMaskElts = 1 << CurStep; 8964 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask(); 8965 // Check mask values in each step. 8966 // We expect the shuffle mask in each step follows a specific pattern 8967 // denoted here by the <M, U> form, where M is a sequence of integers 8968 // starting from NumMaskElts, increasing by 1, and the number integers 8969 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number 8970 // of undef in U should be NumVecElts - NumMaskElts. 8971 // E.g., for <8 x i16>, mask values in each step should be : 8972 // step 0 : <1,u,u,u,u,u,u,u> 8973 // step 1 : <2,3,u,u,u,u,u,u> 8974 // step 2 : <4,5,6,7,u,u,u,u> 8975 for (int i = 0; i < NumVecElts; ++i) 8976 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) || 8977 (i >= NumMaskElts && !(Mask[i] < 0))) 8978 return SDValue(); 8979 8980 PreOp = CurOp; 8981 } 8982 unsigned Opcode; 8983 bool IsIntrinsic = false; 8984 8985 switch (Op) { 8986 default: 8987 llvm_unreachable("Unexpected operator for across vector reduction"); 8988 case ISD::ADD: 8989 Opcode = AArch64ISD::UADDV; 8990 break; 8991 case ISD::SMAX: 8992 Opcode = AArch64ISD::SMAXV; 8993 break; 8994 case ISD::UMAX: 8995 Opcode = AArch64ISD::UMAXV; 8996 break; 8997 case ISD::SMIN: 8998 Opcode = AArch64ISD::SMINV; 8999 break; 9000 case ISD::UMIN: 9001 Opcode = AArch64ISD::UMINV; 9002 break; 9003 case ISD::FMAXNUM: 9004 Opcode = Intrinsic::aarch64_neon_fmaxnmv; 9005 IsIntrinsic = true; 9006 break; 9007 case ISD::FMINNUM: 9008 Opcode = Intrinsic::aarch64_neon_fminnmv; 9009 IsIntrinsic = true; 9010 break; 9011 } 9012 SDLoc DL(N); 9013 9014 return IsIntrinsic 9015 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0), 9016 DAG.getConstant(Opcode, DL, MVT::i32), PreOp) 9017 : DAG.getNode( 9018 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), 9019 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp), 9020 DAG.getConstant(0, DL, MVT::i64)); 9021 } 9022 9023 /// Target-specific DAG combine for the across vector min/max reductions. 9024 /// This function specifically handles the final clean-up step of the vector 9025 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle 9026 /// pattern, which narrows down and finds the final min/max value from all 9027 /// elements of the vector. 9028 /// For example, for a <16 x i8> vector : 9029 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> 9030 /// %smax0 = smax %arr, svn0 9031 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u> 9032 /// %smax1 = smax %smax0, %svn1 9033 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9034 /// %smax2 = smax %smax1, svn2 9035 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9036 /// %sc = setcc %smax2, %svn3, gt 9037 /// %n0 = extract_vector_elt %sc, #0 9038 /// %n1 = extract_vector_elt %smax2, #0 9039 /// %n2 = extract_vector_elt $smax2, #1 9040 /// %result = select %n0, %n1, n2 9041 /// becomes : 9042 /// %1 = smaxv %0 9043 /// %result = extract_vector_elt %1, 0 9044 static SDValue 9045 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG, 9046 const AArch64Subtarget *Subtarget) { 9047 if (!Subtarget->hasNEON()) 9048 return SDValue(); 9049 9050 SDValue N0 = N->getOperand(0); 9051 SDValue IfTrue = N->getOperand(1); 9052 SDValue IfFalse = N->getOperand(2); 9053 9054 // Check if the SELECT merges up the final result of the min/max 9055 // from a vector. 9056 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9057 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9058 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9059 return SDValue(); 9060 9061 // Expect N0 is fed by SETCC. 9062 SDValue SetCC = N0.getOperand(0); 9063 EVT SetCCVT = SetCC.getValueType(); 9064 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() || 9065 SetCCVT.getVectorElementType() != MVT::i1) 9066 return SDValue(); 9067 9068 SDValue VectorOp = SetCC.getOperand(0); 9069 unsigned Op = VectorOp->getOpcode(); 9070 // Check if the input vector is fed by the operator we want to handle. 9071 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN && 9072 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM) 9073 return SDValue(); 9074 9075 EVT VTy = VectorOp.getValueType(); 9076 if (!VTy.isVector()) 9077 return SDValue(); 9078 9079 if (VTy.getSizeInBits() < 64) 9080 return SDValue(); 9081 9082 EVT EltTy = VTy.getVectorElementType(); 9083 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 9084 if (EltTy != MVT::f32) 9085 return SDValue(); 9086 } else { 9087 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9088 return SDValue(); 9089 } 9090 9091 // Check if extracting from the same vector. 9092 // For example, 9093 // %sc = setcc %vector, %svn1, gt 9094 // %n0 = extract_vector_elt %sc, #0 9095 // %n1 = extract_vector_elt %vector, #0 9096 // %n2 = extract_vector_elt $vector, #1 9097 if (!(VectorOp == IfTrue->getOperand(0) && 9098 VectorOp == IfFalse->getOperand(0))) 9099 return SDValue(); 9100 9101 // Check if the condition code is matched with the operator type. 9102 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 9103 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) || 9104 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) || 9105 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) || 9106 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) || 9107 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE && 9108 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT && 9109 CC != ISD::SETGE) || 9110 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE && 9111 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT && 9112 CC != ISD::SETLE)) 9113 return SDValue(); 9114 9115 // Expect to check only lane 0 from the vector SETCC. 9116 if (!isNullConstant(N0.getOperand(1))) 9117 return SDValue(); 9118 9119 // Expect to extract the true value from lane 0. 9120 if (!isNullConstant(IfTrue.getOperand(1))) 9121 return SDValue(); 9122 9123 // Expect to extract the false value from lane 1. 9124 if (!isOneConstant(IfFalse.getOperand(1))) 9125 return SDValue(); 9126 9127 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG); 9128 } 9129 9130 /// Target-specific DAG combine for the across vector add reduction. 9131 /// This function specifically handles the final clean-up step of the vector 9132 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle 9133 /// pattern, which adds all elements of a vector together. 9134 /// For example, for a <4 x i32> vector : 9135 /// %1 = vector_shuffle %0, <2,3,u,u> 9136 /// %2 = add %0, %1 9137 /// %3 = vector_shuffle %2, <1,u,u,u> 9138 /// %4 = add %2, %3 9139 /// %result = extract_vector_elt %4, 0 9140 /// becomes : 9141 /// %0 = uaddv %0 9142 /// %result = extract_vector_elt %0, 0 9143 static SDValue 9144 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG, 9145 const AArch64Subtarget *Subtarget) { 9146 if (!Subtarget->hasNEON()) 9147 return SDValue(); 9148 SDValue N0 = N->getOperand(0); 9149 SDValue N1 = N->getOperand(1); 9150 9151 // Check if the input vector is fed by the ADD. 9152 if (N0->getOpcode() != ISD::ADD) 9153 return SDValue(); 9154 9155 // The vector extract idx must constant zero because we only expect the final 9156 // result of the reduction is placed in lane 0. 9157 if (!isNullConstant(N1)) 9158 return SDValue(); 9159 9160 EVT VTy = N0.getValueType(); 9161 if (!VTy.isVector()) 9162 return SDValue(); 9163 9164 EVT EltTy = VTy.getVectorElementType(); 9165 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9166 return SDValue(); 9167 9168 if (VTy.getSizeInBits() < 64) 9169 return SDValue(); 9170 9171 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG); 9172 } 9173 9174 /// Target-specific DAG combine function for NEON load/store intrinsics 9175 /// to merge base address updates. 9176 static SDValue performNEONPostLDSTCombine(SDNode *N, 9177 TargetLowering::DAGCombinerInfo &DCI, 9178 SelectionDAG &DAG) { 9179 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9180 return SDValue(); 9181 9182 unsigned AddrOpIdx = N->getNumOperands() - 1; 9183 SDValue Addr = N->getOperand(AddrOpIdx); 9184 9185 // Search for a use of the address operand that is an increment. 9186 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9187 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9188 SDNode *User = *UI; 9189 if (User->getOpcode() != ISD::ADD || 9190 UI.getUse().getResNo() != Addr.getResNo()) 9191 continue; 9192 9193 // Check that the add is independent of the load/store. Otherwise, folding 9194 // it would create a cycle. 9195 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9196 continue; 9197 9198 // Find the new opcode for the updating load/store. 9199 bool IsStore = false; 9200 bool IsLaneOp = false; 9201 bool IsDupOp = false; 9202 unsigned NewOpc = 0; 9203 unsigned NumVecs = 0; 9204 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9205 switch (IntNo) { 9206 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9207 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9208 NumVecs = 2; break; 9209 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9210 NumVecs = 3; break; 9211 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9212 NumVecs = 4; break; 9213 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9214 NumVecs = 2; IsStore = true; break; 9215 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9216 NumVecs = 3; IsStore = true; break; 9217 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9218 NumVecs = 4; IsStore = true; break; 9219 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9220 NumVecs = 2; break; 9221 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9222 NumVecs = 3; break; 9223 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9224 NumVecs = 4; break; 9225 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9226 NumVecs = 2; IsStore = true; break; 9227 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9228 NumVecs = 3; IsStore = true; break; 9229 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9230 NumVecs = 4; IsStore = true; break; 9231 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9232 NumVecs = 2; IsDupOp = true; break; 9233 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9234 NumVecs = 3; IsDupOp = true; break; 9235 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9236 NumVecs = 4; IsDupOp = true; break; 9237 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9238 NumVecs = 2; IsLaneOp = true; break; 9239 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9240 NumVecs = 3; IsLaneOp = true; break; 9241 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9242 NumVecs = 4; IsLaneOp = true; break; 9243 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9244 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9245 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9246 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9247 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9248 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9249 } 9250 9251 EVT VecTy; 9252 if (IsStore) 9253 VecTy = N->getOperand(2).getValueType(); 9254 else 9255 VecTy = N->getValueType(0); 9256 9257 // If the increment is a constant, it must match the memory ref size. 9258 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9259 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9260 uint32_t IncVal = CInc->getZExtValue(); 9261 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9262 if (IsLaneOp || IsDupOp) 9263 NumBytes /= VecTy.getVectorNumElements(); 9264 if (IncVal != NumBytes) 9265 continue; 9266 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9267 } 9268 SmallVector<SDValue, 8> Ops; 9269 Ops.push_back(N->getOperand(0)); // Incoming chain 9270 // Load lane and store have vector list as input. 9271 if (IsLaneOp || IsStore) 9272 for (unsigned i = 2; i < AddrOpIdx; ++i) 9273 Ops.push_back(N->getOperand(i)); 9274 Ops.push_back(Addr); // Base register 9275 Ops.push_back(Inc); 9276 9277 // Return Types. 9278 EVT Tys[6]; 9279 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9280 unsigned n; 9281 for (n = 0; n < NumResultVecs; ++n) 9282 Tys[n] = VecTy; 9283 Tys[n++] = MVT::i64; // Type of write back register 9284 Tys[n] = MVT::Other; // Type of the chain 9285 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9286 9287 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9288 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9289 MemInt->getMemoryVT(), 9290 MemInt->getMemOperand()); 9291 9292 // Update the uses. 9293 std::vector<SDValue> NewResults; 9294 for (unsigned i = 0; i < NumResultVecs; ++i) { 9295 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9296 } 9297 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9298 DCI.CombineTo(N, NewResults); 9299 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9300 9301 break; 9302 } 9303 return SDValue(); 9304 } 9305 9306 // Checks to see if the value is the prescribed width and returns information 9307 // about its extension mode. 9308 static 9309 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9310 ExtType = ISD::NON_EXTLOAD; 9311 switch(V.getNode()->getOpcode()) { 9312 default: 9313 return false; 9314 case ISD::LOAD: { 9315 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9316 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9317 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9318 ExtType = LoadNode->getExtensionType(); 9319 return true; 9320 } 9321 return false; 9322 } 9323 case ISD::AssertSext: { 9324 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9325 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9326 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9327 ExtType = ISD::SEXTLOAD; 9328 return true; 9329 } 9330 return false; 9331 } 9332 case ISD::AssertZext: { 9333 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9334 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9335 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9336 ExtType = ISD::ZEXTLOAD; 9337 return true; 9338 } 9339 return false; 9340 } 9341 case ISD::Constant: 9342 case ISD::TargetConstant: { 9343 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9344 1LL << (width - 1); 9345 } 9346 } 9347 9348 return true; 9349 } 9350 9351 // This function does a whole lot of voodoo to determine if the tests are 9352 // equivalent without and with a mask. Essentially what happens is that given a 9353 // DAG resembling: 9354 // 9355 // +-------------+ +-------------+ +-------------+ +-------------+ 9356 // | Input | | AddConstant | | CompConstant| | CC | 9357 // +-------------+ +-------------+ +-------------+ +-------------+ 9358 // | | | | 9359 // V V | +----------+ 9360 // +-------------+ +----+ | | 9361 // | ADD | |0xff| | | 9362 // +-------------+ +----+ | | 9363 // | | | | 9364 // V V | | 9365 // +-------------+ | | 9366 // | AND | | | 9367 // +-------------+ | | 9368 // | | | 9369 // +-----+ | | 9370 // | | | 9371 // V V V 9372 // +-------------+ 9373 // | CMP | 9374 // +-------------+ 9375 // 9376 // The AND node may be safely removed for some combinations of inputs. In 9377 // particular we need to take into account the extension type of the Input, 9378 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9379 // width of the input (this can work for any width inputs, the above graph is 9380 // specific to 8 bits. 9381 // 9382 // The specific equations were worked out by generating output tables for each 9383 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9384 // problem was simplified by working with 4 bit inputs, which means we only 9385 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9386 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9387 // patterns present in both extensions (0,7). For every distinct set of 9388 // AddConstant and CompConstants bit patterns we can consider the masked and 9389 // unmasked versions to be equivalent if the result of this function is true for 9390 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9391 // 9392 // sub w8, w0, w1 9393 // and w10, w8, #0x0f 9394 // cmp w8, w2 9395 // cset w9, AArch64CC 9396 // cmp w10, w2 9397 // cset w11, AArch64CC 9398 // cmp w9, w11 9399 // cset w0, eq 9400 // ret 9401 // 9402 // Since the above function shows when the outputs are equivalent it defines 9403 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9404 // would be expensive to run during compiles. The equations below were written 9405 // in a test harness that confirmed they gave equivalent outputs to the above 9406 // for all inputs function, so they can be used determine if the removal is 9407 // legal instead. 9408 // 9409 // isEquivalentMaskless() is the code for testing if the AND can be removed 9410 // factored out of the DAG recognition as the DAG can take several forms. 9411 9412 static 9413 bool isEquivalentMaskless(unsigned CC, unsigned width, 9414 ISD::LoadExtType ExtType, signed AddConstant, 9415 signed CompConstant) { 9416 // By being careful about our equations and only writing the in term 9417 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 9418 // make them generally applicable to all bit widths. 9419 signed MaxUInt = (1 << width); 9420 9421 // For the purposes of these comparisons sign extending the type is 9422 // equivalent to zero extending the add and displacing it by half the integer 9423 // width. Provided we are careful and make sure our equations are valid over 9424 // the whole range we can just adjust the input and avoid writing equations 9425 // for sign extended inputs. 9426 if (ExtType == ISD::SEXTLOAD) 9427 AddConstant -= (1 << (width-1)); 9428 9429 switch(CC) { 9430 case AArch64CC::LE: 9431 case AArch64CC::GT: { 9432 if ((AddConstant == 0) || 9433 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 9434 (AddConstant >= 0 && CompConstant < 0) || 9435 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 9436 return true; 9437 } break; 9438 case AArch64CC::LT: 9439 case AArch64CC::GE: { 9440 if ((AddConstant == 0) || 9441 (AddConstant >= 0 && CompConstant <= 0) || 9442 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 9443 return true; 9444 } break; 9445 case AArch64CC::HI: 9446 case AArch64CC::LS: { 9447 if ((AddConstant >= 0 && CompConstant < 0) || 9448 (AddConstant <= 0 && CompConstant >= -1 && 9449 CompConstant < AddConstant + MaxUInt)) 9450 return true; 9451 } break; 9452 case AArch64CC::PL: 9453 case AArch64CC::MI: { 9454 if ((AddConstant == 0) || 9455 (AddConstant > 0 && CompConstant <= 0) || 9456 (AddConstant < 0 && CompConstant <= AddConstant)) 9457 return true; 9458 } break; 9459 case AArch64CC::LO: 9460 case AArch64CC::HS: { 9461 if ((AddConstant >= 0 && CompConstant <= 0) || 9462 (AddConstant <= 0 && CompConstant >= 0 && 9463 CompConstant <= AddConstant + MaxUInt)) 9464 return true; 9465 } break; 9466 case AArch64CC::EQ: 9467 case AArch64CC::NE: { 9468 if ((AddConstant > 0 && CompConstant < 0) || 9469 (AddConstant < 0 && CompConstant >= 0 && 9470 CompConstant < AddConstant + MaxUInt) || 9471 (AddConstant >= 0 && CompConstant >= 0 && 9472 CompConstant >= AddConstant) || 9473 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 9474 9475 return true; 9476 } break; 9477 case AArch64CC::VS: 9478 case AArch64CC::VC: 9479 case AArch64CC::AL: 9480 case AArch64CC::NV: 9481 return true; 9482 case AArch64CC::Invalid: 9483 break; 9484 } 9485 9486 return false; 9487 } 9488 9489 static 9490 SDValue performCONDCombine(SDNode *N, 9491 TargetLowering::DAGCombinerInfo &DCI, 9492 SelectionDAG &DAG, unsigned CCIndex, 9493 unsigned CmpIndex) { 9494 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 9495 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 9496 unsigned CondOpcode = SubsNode->getOpcode(); 9497 9498 if (CondOpcode != AArch64ISD::SUBS) 9499 return SDValue(); 9500 9501 // There is a SUBS feeding this condition. Is it fed by a mask we can 9502 // use? 9503 9504 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 9505 unsigned MaskBits = 0; 9506 9507 if (AndNode->getOpcode() != ISD::AND) 9508 return SDValue(); 9509 9510 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 9511 uint32_t CNV = CN->getZExtValue(); 9512 if (CNV == 255) 9513 MaskBits = 8; 9514 else if (CNV == 65535) 9515 MaskBits = 16; 9516 } 9517 9518 if (!MaskBits) 9519 return SDValue(); 9520 9521 SDValue AddValue = AndNode->getOperand(0); 9522 9523 if (AddValue.getOpcode() != ISD::ADD) 9524 return SDValue(); 9525 9526 // The basic dag structure is correct, grab the inputs and validate them. 9527 9528 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 9529 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 9530 SDValue SubsInputValue = SubsNode->getOperand(1); 9531 9532 // The mask is present and the provenance of all the values is a smaller type, 9533 // lets see if the mask is superfluous. 9534 9535 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 9536 !isa<ConstantSDNode>(SubsInputValue.getNode())) 9537 return SDValue(); 9538 9539 ISD::LoadExtType ExtType; 9540 9541 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 9542 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 9543 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 9544 return SDValue(); 9545 9546 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 9547 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 9548 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 9549 return SDValue(); 9550 9551 // The AND is not necessary, remove it. 9552 9553 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 9554 SubsNode->getValueType(1)); 9555 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 9556 9557 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 9558 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 9559 9560 return SDValue(N, 0); 9561 } 9562 9563 // Optimize compare with zero and branch. 9564 static SDValue performBRCONDCombine(SDNode *N, 9565 TargetLowering::DAGCombinerInfo &DCI, 9566 SelectionDAG &DAG) { 9567 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 9568 N = NV.getNode(); 9569 SDValue Chain = N->getOperand(0); 9570 SDValue Dest = N->getOperand(1); 9571 SDValue CCVal = N->getOperand(2); 9572 SDValue Cmp = N->getOperand(3); 9573 9574 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 9575 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 9576 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 9577 return SDValue(); 9578 9579 unsigned CmpOpc = Cmp.getOpcode(); 9580 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 9581 return SDValue(); 9582 9583 // Only attempt folding if there is only one use of the flag and no use of the 9584 // value. 9585 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 9586 return SDValue(); 9587 9588 SDValue LHS = Cmp.getOperand(0); 9589 SDValue RHS = Cmp.getOperand(1); 9590 9591 assert(LHS.getValueType() == RHS.getValueType() && 9592 "Expected the value type to be the same for both operands!"); 9593 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 9594 return SDValue(); 9595 9596 if (isNullConstant(LHS)) 9597 std::swap(LHS, RHS); 9598 9599 if (!isNullConstant(RHS)) 9600 return SDValue(); 9601 9602 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 9603 LHS.getOpcode() == ISD::SRL) 9604 return SDValue(); 9605 9606 // Fold the compare into the branch instruction. 9607 SDValue BR; 9608 if (CC == AArch64CC::EQ) 9609 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9610 else 9611 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9612 9613 // Do not add new nodes to DAG combiner worklist. 9614 DCI.CombineTo(N, BR, false); 9615 9616 return SDValue(); 9617 } 9618 9619 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 9620 // as well as whether the test should be inverted. This code is required to 9621 // catch these cases (as opposed to standard dag combines) because 9622 // AArch64ISD::TBZ is matched during legalization. 9623 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 9624 SelectionDAG &DAG) { 9625 9626 if (!Op->hasOneUse()) 9627 return Op; 9628 9629 // We don't handle undef/constant-fold cases below, as they should have 9630 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 9631 // etc.) 9632 9633 // (tbz (trunc x), b) -> (tbz x, b) 9634 // This case is just here to enable more of the below cases to be caught. 9635 if (Op->getOpcode() == ISD::TRUNCATE && 9636 Bit < Op->getValueType(0).getSizeInBits()) { 9637 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9638 } 9639 9640 if (Op->getNumOperands() != 2) 9641 return Op; 9642 9643 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 9644 if (!C) 9645 return Op; 9646 9647 switch (Op->getOpcode()) { 9648 default: 9649 return Op; 9650 9651 // (tbz (and x, m), b) -> (tbz x, b) 9652 case ISD::AND: 9653 if ((C->getZExtValue() >> Bit) & 1) 9654 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9655 return Op; 9656 9657 // (tbz (shl x, c), b) -> (tbz x, b-c) 9658 case ISD::SHL: 9659 if (C->getZExtValue() <= Bit && 9660 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9661 Bit = Bit - C->getZExtValue(); 9662 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9663 } 9664 return Op; 9665 9666 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 9667 case ISD::SRA: 9668 Bit = Bit + C->getZExtValue(); 9669 if (Bit >= Op->getValueType(0).getSizeInBits()) 9670 Bit = Op->getValueType(0).getSizeInBits() - 1; 9671 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9672 9673 // (tbz (srl x, c), b) -> (tbz x, b+c) 9674 case ISD::SRL: 9675 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9676 Bit = Bit + C->getZExtValue(); 9677 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9678 } 9679 return Op; 9680 9681 // (tbz (xor x, -1), b) -> (tbnz x, b) 9682 case ISD::XOR: 9683 if ((C->getZExtValue() >> Bit) & 1) 9684 Invert = !Invert; 9685 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9686 } 9687 } 9688 9689 // Optimize test single bit zero/non-zero and branch. 9690 static SDValue performTBZCombine(SDNode *N, 9691 TargetLowering::DAGCombinerInfo &DCI, 9692 SelectionDAG &DAG) { 9693 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9694 bool Invert = false; 9695 SDValue TestSrc = N->getOperand(1); 9696 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 9697 9698 if (TestSrc == NewTestSrc) 9699 return SDValue(); 9700 9701 unsigned NewOpc = N->getOpcode(); 9702 if (Invert) { 9703 if (NewOpc == AArch64ISD::TBZ) 9704 NewOpc = AArch64ISD::TBNZ; 9705 else { 9706 assert(NewOpc == AArch64ISD::TBNZ); 9707 NewOpc = AArch64ISD::TBZ; 9708 } 9709 } 9710 9711 SDLoc DL(N); 9712 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 9713 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 9714 } 9715 9716 // vselect (v1i1 setcc) -> 9717 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 9718 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 9719 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 9720 // such VSELECT. 9721 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 9722 SDValue N0 = N->getOperand(0); 9723 EVT CCVT = N0.getValueType(); 9724 9725 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 9726 CCVT.getVectorElementType() != MVT::i1) 9727 return SDValue(); 9728 9729 EVT ResVT = N->getValueType(0); 9730 EVT CmpVT = N0.getOperand(0).getValueType(); 9731 // Only combine when the result type is of the same size as the compared 9732 // operands. 9733 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 9734 return SDValue(); 9735 9736 SDValue IfTrue = N->getOperand(1); 9737 SDValue IfFalse = N->getOperand(2); 9738 SDValue SetCC = 9739 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 9740 N0.getOperand(0), N0.getOperand(1), 9741 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9742 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 9743 IfTrue, IfFalse); 9744 } 9745 9746 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 9747 /// the compare-mask instructions rather than going via NZCV, even if LHS and 9748 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 9749 /// with a vector one followed by a DUP shuffle on the result. 9750 static SDValue performSelectCombine(SDNode *N, 9751 TargetLowering::DAGCombinerInfo &DCI) { 9752 SelectionDAG &DAG = DCI.DAG; 9753 SDValue N0 = N->getOperand(0); 9754 EVT ResVT = N->getValueType(0); 9755 9756 if (N0.getOpcode() != ISD::SETCC) 9757 return SDValue(); 9758 9759 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 9760 // scalar SetCCResultType. We also don't expect vectors, because we assume 9761 // that selects fed by vector SETCCs are canonicalized to VSELECT. 9762 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 9763 "Scalar-SETCC feeding SELECT has unexpected result type!"); 9764 9765 // If NumMaskElts == 0, the comparison is larger than select result. The 9766 // largest real NEON comparison is 64-bits per lane, which means the result is 9767 // at most 32-bits and an illegal vector. Just bail out for now. 9768 EVT SrcVT = N0.getOperand(0).getValueType(); 9769 9770 // Don't try to do this optimization when the setcc itself has i1 operands. 9771 // There are no legal vectors of i1, so this would be pointless. 9772 if (SrcVT == MVT::i1) 9773 return SDValue(); 9774 9775 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 9776 if (!ResVT.isVector() || NumMaskElts == 0) 9777 return SDValue(); 9778 9779 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 9780 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 9781 9782 // Also bail out if the vector CCVT isn't the same size as ResVT. 9783 // This can happen if the SETCC operand size doesn't divide the ResVT size 9784 // (e.g., f64 vs v3f32). 9785 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 9786 return SDValue(); 9787 9788 // Make sure we didn't create illegal types, if we're not supposed to. 9789 assert(DCI.isBeforeLegalize() || 9790 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 9791 9792 // First perform a vector comparison, where lane 0 is the one we're interested 9793 // in. 9794 SDLoc DL(N0); 9795 SDValue LHS = 9796 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 9797 SDValue RHS = 9798 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 9799 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 9800 9801 // Now duplicate the comparison mask we want across all other lanes. 9802 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 9803 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data()); 9804 Mask = DAG.getNode(ISD::BITCAST, DL, 9805 ResVT.changeVectorElementTypeToInteger(), Mask); 9806 9807 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 9808 } 9809 9810 /// Get rid of unnecessary NVCASTs (that don't change the type). 9811 static SDValue performNVCASTCombine(SDNode *N) { 9812 if (N->getValueType(0) == N->getOperand(0).getValueType()) 9813 return N->getOperand(0); 9814 9815 return SDValue(); 9816 } 9817 9818 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 9819 DAGCombinerInfo &DCI) const { 9820 SelectionDAG &DAG = DCI.DAG; 9821 switch (N->getOpcode()) { 9822 default: 9823 break; 9824 case ISD::ADD: 9825 case ISD::SUB: 9826 return performAddSubLongCombine(N, DCI, DAG); 9827 case ISD::XOR: 9828 return performXorCombine(N, DAG, DCI, Subtarget); 9829 case ISD::MUL: 9830 return performMulCombine(N, DAG, DCI, Subtarget); 9831 case ISD::SINT_TO_FP: 9832 case ISD::UINT_TO_FP: 9833 return performIntToFpCombine(N, DAG, Subtarget); 9834 case ISD::FP_TO_SINT: 9835 case ISD::FP_TO_UINT: 9836 return performFpToIntCombine(N, DAG, Subtarget); 9837 case ISD::FDIV: 9838 return performFDivCombine(N, DAG, Subtarget); 9839 case ISD::OR: 9840 return performORCombine(N, DCI, Subtarget); 9841 case ISD::INTRINSIC_WO_CHAIN: 9842 return performIntrinsicCombine(N, DCI, Subtarget); 9843 case ISD::ANY_EXTEND: 9844 case ISD::ZERO_EXTEND: 9845 case ISD::SIGN_EXTEND: 9846 return performExtendCombine(N, DCI, DAG); 9847 case ISD::BITCAST: 9848 return performBitcastCombine(N, DCI, DAG); 9849 case ISD::CONCAT_VECTORS: 9850 return performConcatVectorsCombine(N, DCI, DAG); 9851 case ISD::SELECT: { 9852 SDValue RV = performSelectCombine(N, DCI); 9853 if (!RV.getNode()) 9854 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget); 9855 return RV; 9856 } 9857 case ISD::VSELECT: 9858 return performVSelectCombine(N, DCI.DAG); 9859 case ISD::LOAD: 9860 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 9861 return SDValue(N, 0); 9862 break; 9863 case ISD::STORE: 9864 return performSTORECombine(N, DCI, DAG, Subtarget); 9865 case AArch64ISD::BRCOND: 9866 return performBRCONDCombine(N, DCI, DAG); 9867 case AArch64ISD::TBNZ: 9868 case AArch64ISD::TBZ: 9869 return performTBZCombine(N, DCI, DAG); 9870 case AArch64ISD::CSEL: 9871 return performCONDCombine(N, DCI, DAG, 2, 3); 9872 case AArch64ISD::DUP: 9873 return performPostLD1Combine(N, DCI, false); 9874 case AArch64ISD::NVCAST: 9875 return performNVCASTCombine(N); 9876 case ISD::INSERT_VECTOR_ELT: 9877 return performPostLD1Combine(N, DCI, true); 9878 case ISD::EXTRACT_VECTOR_ELT: 9879 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget); 9880 case ISD::INTRINSIC_VOID: 9881 case ISD::INTRINSIC_W_CHAIN: 9882 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 9883 case Intrinsic::aarch64_neon_ld2: 9884 case Intrinsic::aarch64_neon_ld3: 9885 case Intrinsic::aarch64_neon_ld4: 9886 case Intrinsic::aarch64_neon_ld1x2: 9887 case Intrinsic::aarch64_neon_ld1x3: 9888 case Intrinsic::aarch64_neon_ld1x4: 9889 case Intrinsic::aarch64_neon_ld2lane: 9890 case Intrinsic::aarch64_neon_ld3lane: 9891 case Intrinsic::aarch64_neon_ld4lane: 9892 case Intrinsic::aarch64_neon_ld2r: 9893 case Intrinsic::aarch64_neon_ld3r: 9894 case Intrinsic::aarch64_neon_ld4r: 9895 case Intrinsic::aarch64_neon_st2: 9896 case Intrinsic::aarch64_neon_st3: 9897 case Intrinsic::aarch64_neon_st4: 9898 case Intrinsic::aarch64_neon_st1x2: 9899 case Intrinsic::aarch64_neon_st1x3: 9900 case Intrinsic::aarch64_neon_st1x4: 9901 case Intrinsic::aarch64_neon_st2lane: 9902 case Intrinsic::aarch64_neon_st3lane: 9903 case Intrinsic::aarch64_neon_st4lane: 9904 return performNEONPostLDSTCombine(N, DCI, DAG); 9905 default: 9906 break; 9907 } 9908 } 9909 return SDValue(); 9910 } 9911 9912 // Check if the return value is used as only a return value, as otherwise 9913 // we can't perform a tail-call. In particular, we need to check for 9914 // target ISD nodes that are returns and any other "odd" constructs 9915 // that the generic analysis code won't necessarily catch. 9916 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 9917 SDValue &Chain) const { 9918 if (N->getNumValues() != 1) 9919 return false; 9920 if (!N->hasNUsesOfValue(1, 0)) 9921 return false; 9922 9923 SDValue TCChain = Chain; 9924 SDNode *Copy = *N->use_begin(); 9925 if (Copy->getOpcode() == ISD::CopyToReg) { 9926 // If the copy has a glue operand, we conservatively assume it isn't safe to 9927 // perform a tail call. 9928 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 9929 MVT::Glue) 9930 return false; 9931 TCChain = Copy->getOperand(0); 9932 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 9933 return false; 9934 9935 bool HasRet = false; 9936 for (SDNode *Node : Copy->uses()) { 9937 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 9938 return false; 9939 HasRet = true; 9940 } 9941 9942 if (!HasRet) 9943 return false; 9944 9945 Chain = TCChain; 9946 return true; 9947 } 9948 9949 // Return whether the an instruction can potentially be optimized to a tail 9950 // call. This will cause the optimizers to attempt to move, or duplicate, 9951 // return instructions to help enable tail call optimizations for this 9952 // instruction. 9953 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 9954 return CI->isTailCall(); 9955 } 9956 9957 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 9958 SDValue &Offset, 9959 ISD::MemIndexedMode &AM, 9960 bool &IsInc, 9961 SelectionDAG &DAG) const { 9962 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 9963 return false; 9964 9965 Base = Op->getOperand(0); 9966 // All of the indexed addressing mode instructions take a signed 9967 // 9 bit immediate offset. 9968 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 9969 int64_t RHSC = (int64_t)RHS->getZExtValue(); 9970 if (RHSC >= 256 || RHSC <= -256) 9971 return false; 9972 IsInc = (Op->getOpcode() == ISD::ADD); 9973 Offset = Op->getOperand(1); 9974 return true; 9975 } 9976 return false; 9977 } 9978 9979 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 9980 SDValue &Offset, 9981 ISD::MemIndexedMode &AM, 9982 SelectionDAG &DAG) const { 9983 EVT VT; 9984 SDValue Ptr; 9985 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9986 VT = LD->getMemoryVT(); 9987 Ptr = LD->getBasePtr(); 9988 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9989 VT = ST->getMemoryVT(); 9990 Ptr = ST->getBasePtr(); 9991 } else 9992 return false; 9993 9994 bool IsInc; 9995 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 9996 return false; 9997 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 9998 return true; 9999 } 10000 10001 bool AArch64TargetLowering::getPostIndexedAddressParts( 10002 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10003 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10004 EVT VT; 10005 SDValue Ptr; 10006 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10007 VT = LD->getMemoryVT(); 10008 Ptr = LD->getBasePtr(); 10009 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10010 VT = ST->getMemoryVT(); 10011 Ptr = ST->getBasePtr(); 10012 } else 10013 return false; 10014 10015 bool IsInc; 10016 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10017 return false; 10018 // Post-indexing updates the base, so it's not a valid transform 10019 // if that's not the same as the load's pointer. 10020 if (Ptr != Base) 10021 return false; 10022 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10023 return true; 10024 } 10025 10026 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10027 SelectionDAG &DAG) { 10028 SDLoc DL(N); 10029 SDValue Op = N->getOperand(0); 10030 10031 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10032 return; 10033 10034 Op = SDValue( 10035 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10036 DAG.getUNDEF(MVT::i32), Op, 10037 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10038 0); 10039 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10040 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10041 } 10042 10043 static void ReplaceReductionResults(SDNode *N, 10044 SmallVectorImpl<SDValue> &Results, 10045 SelectionDAG &DAG, unsigned InterOp, 10046 unsigned AcrossOp) { 10047 EVT LoVT, HiVT; 10048 SDValue Lo, Hi; 10049 SDLoc dl(N); 10050 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10051 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10052 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10053 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10054 Results.push_back(SplitVal); 10055 } 10056 10057 static void ReplaceCMP_SWAP_128Results(SDNode *N, 10058 SmallVectorImpl<SDValue> & Results, 10059 SelectionDAG &DAG) { 10060 assert(N->getValueType(0) == MVT::i128 && 10061 "AtomicCmpSwap on types less than 128 should be legal"); 10062 SDValue Ops[] = {N->getOperand(1), 10063 N->getOperand(2)->getOperand(0), 10064 N->getOperand(2)->getOperand(1), 10065 N->getOperand(3)->getOperand(0), 10066 N->getOperand(3)->getOperand(1), 10067 N->getOperand(0)}; 10068 SDNode *CmpSwap = DAG.getMachineNode( 10069 AArch64::CMP_SWAP_128, SDLoc(N), 10070 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 10071 10072 MachineFunction &MF = DAG.getMachineFunction(); 10073 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 10074 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 10075 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 10076 10077 Results.push_back(SDValue(CmpSwap, 0)); 10078 Results.push_back(SDValue(CmpSwap, 1)); 10079 Results.push_back(SDValue(CmpSwap, 3)); 10080 } 10081 10082 void AArch64TargetLowering::ReplaceNodeResults( 10083 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10084 switch (N->getOpcode()) { 10085 default: 10086 llvm_unreachable("Don't know how to custom expand this"); 10087 case ISD::BITCAST: 10088 ReplaceBITCASTResults(N, Results, DAG); 10089 return; 10090 case AArch64ISD::SADDV: 10091 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10092 return; 10093 case AArch64ISD::UADDV: 10094 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10095 return; 10096 case AArch64ISD::SMINV: 10097 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10098 return; 10099 case AArch64ISD::UMINV: 10100 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10101 return; 10102 case AArch64ISD::SMAXV: 10103 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10104 return; 10105 case AArch64ISD::UMAXV: 10106 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10107 return; 10108 case ISD::FP_TO_UINT: 10109 case ISD::FP_TO_SINT: 10110 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10111 // Let normal code take care of it by not adding anything to Results. 10112 return; 10113 case ISD::ATOMIC_CMP_SWAP: 10114 ReplaceCMP_SWAP_128Results(N, Results, DAG); 10115 return; 10116 } 10117 } 10118 10119 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10120 if (!Subtarget->isTargetAndroid()) 10121 return true; 10122 return TargetLowering::useLoadStackGuardNode(); 10123 } 10124 10125 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10126 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10127 // reciprocal if there are three or more FDIVs. 10128 return 3; 10129 } 10130 10131 TargetLoweringBase::LegalizeTypeAction 10132 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10133 MVT SVT = VT.getSimpleVT(); 10134 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10135 // v4i16, v2i32 instead of to promote. 10136 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10137 || SVT == MVT::v1f32) 10138 return TypeWidenVector; 10139 10140 return TargetLoweringBase::getPreferredVectorAction(VT); 10141 } 10142 10143 // Loads and stores less than 128-bits are already atomic; ones above that 10144 // are doomed anyway, so defer to the default libcall and blame the OS when 10145 // things go wrong. 10146 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10147 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10148 return Size == 128; 10149 } 10150 10151 // Loads and stores less than 128-bits are already atomic; ones above that 10152 // are doomed anyway, so defer to the default libcall and blame the OS when 10153 // things go wrong. 10154 TargetLowering::AtomicExpansionKind 10155 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10156 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10157 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10158 } 10159 10160 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10161 TargetLowering::AtomicExpansionKind 10162 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10163 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10164 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10165 } 10166 10167 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10168 AtomicCmpXchgInst *AI) const { 10169 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 10170 // implement cmpxchg without spilling. If the address being exchanged is also 10171 // on the stack and close enough to the spill slot, this can lead to a 10172 // situation where the monitor always gets cleared and the atomic operation 10173 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 10174 return getTargetMachine().getOptLevel() != 0; 10175 } 10176 10177 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10178 AtomicOrdering Ord) const { 10179 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10180 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10181 bool IsAcquire = isAcquireOrStronger(Ord); 10182 10183 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10184 // intrinsic must return {i64, i64} and we have to recombine them into a 10185 // single i128 here. 10186 if (ValTy->getPrimitiveSizeInBits() == 128) { 10187 Intrinsic::ID Int = 10188 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10189 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int); 10190 10191 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10192 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10193 10194 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10195 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10196 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10197 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10198 return Builder.CreateOr( 10199 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10200 } 10201 10202 Type *Tys[] = { Addr->getType() }; 10203 Intrinsic::ID Int = 10204 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10205 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys); 10206 10207 return Builder.CreateTruncOrBitCast( 10208 Builder.CreateCall(Ldxr, Addr), 10209 cast<PointerType>(Addr->getType())->getElementType()); 10210 } 10211 10212 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10213 IRBuilder<> &Builder) const { 10214 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10215 Builder.CreateCall( 10216 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10217 } 10218 10219 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10220 Value *Val, Value *Addr, 10221 AtomicOrdering Ord) const { 10222 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10223 bool IsRelease = isReleaseOrStronger(Ord); 10224 10225 // Since the intrinsics must have legal type, the i128 intrinsics take two 10226 // parameters: "i64, i64". We must marshal Val into the appropriate form 10227 // before the call. 10228 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10229 Intrinsic::ID Int = 10230 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10231 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10232 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10233 10234 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10235 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10236 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10237 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10238 } 10239 10240 Intrinsic::ID Int = 10241 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10242 Type *Tys[] = { Addr->getType() }; 10243 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10244 10245 return Builder.CreateCall(Stxr, 10246 {Builder.CreateZExtOrBitCast( 10247 Val, Stxr->getFunctionType()->getParamType(0)), 10248 Addr}); 10249 } 10250 10251 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10252 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10253 return Ty->isArrayTy(); 10254 } 10255 10256 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10257 EVT) const { 10258 return false; 10259 } 10260 10261 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 10262 if (!Subtarget->isTargetAndroid()) 10263 return TargetLowering::getIRStackGuard(IRB); 10264 10265 // Android provides a fixed TLS slot for the stack cookie. See the definition 10266 // of TLS_SLOT_STACK_GUARD in 10267 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10268 const unsigned TlsOffset = 0x28; 10269 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10270 Function *ThreadPointerFunc = 10271 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10272 return IRB.CreatePointerCast( 10273 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10274 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10275 } 10276 10277 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10278 if (!Subtarget->isTargetAndroid()) 10279 return TargetLowering::getSafeStackPointerLocation(IRB); 10280 10281 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10282 // definition of TLS_SLOT_SAFESTACK in 10283 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10284 const unsigned TlsOffset = 0x48; 10285 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10286 Function *ThreadPointerFunc = 10287 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10288 return IRB.CreatePointerCast( 10289 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10290 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10291 } 10292 10293 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10294 // Update IsSplitCSR in AArch64unctionInfo. 10295 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10296 AFI->setIsSplitCSR(true); 10297 } 10298 10299 void AArch64TargetLowering::insertCopiesSplitCSR( 10300 MachineBasicBlock *Entry, 10301 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10302 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10303 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10304 if (!IStart) 10305 return; 10306 10307 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10308 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10309 MachineBasicBlock::iterator MBBI = Entry->begin(); 10310 for (const MCPhysReg *I = IStart; *I; ++I) { 10311 const TargetRegisterClass *RC = nullptr; 10312 if (AArch64::GPR64RegClass.contains(*I)) 10313 RC = &AArch64::GPR64RegClass; 10314 else if (AArch64::FPR64RegClass.contains(*I)) 10315 RC = &AArch64::FPR64RegClass; 10316 else 10317 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10318 10319 unsigned NewVR = MRI->createVirtualRegister(RC); 10320 // Create copy from CSR to a virtual register. 10321 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10322 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10323 // nounwind. If we want to generalize this later, we may need to emit 10324 // CFI pseudo-instructions. 10325 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10326 Attribute::NoUnwind) && 10327 "Function should be nounwind in insertCopiesSplitCSR!"); 10328 Entry->addLiveIn(*I); 10329 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10330 .addReg(*I); 10331 10332 // Insert the copy-back instructions right before the terminator. 10333 for (auto *Exit : Exits) 10334 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10335 TII->get(TargetOpcode::COPY), *I) 10336 .addReg(NewVR); 10337 } 10338 } 10339 10340 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const { 10341 // Integer division on AArch64 is expensive. However, when aggressively 10342 // optimizing for code size, we prefer to use a div instruction, as it is 10343 // usually smaller than the alternative sequence. 10344 // The exception to this is vector division. Since AArch64 doesn't have vector 10345 // integer division, leaving the division as-is is a loss even in terms of 10346 // size, because it will have to be scalarized, while the alternative code 10347 // sequence can be performed in vector form. 10348 bool OptSize = 10349 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 10350 return OptSize && !VT.isVector(); 10351 } 10352