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 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero 239 // counterparts, which AArch64 supports directly. 240 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand); 241 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand); 242 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 243 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 244 245 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 246 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 247 248 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 249 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 250 for (MVT VT : MVT::vector_valuetypes()) { 251 setOperationAction(ISD::SDIVREM, VT, Expand); 252 setOperationAction(ISD::UDIVREM, VT, Expand); 253 } 254 setOperationAction(ISD::SREM, MVT::i32, Expand); 255 setOperationAction(ISD::SREM, MVT::i64, Expand); 256 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 257 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 258 setOperationAction(ISD::UREM, MVT::i32, Expand); 259 setOperationAction(ISD::UREM, MVT::i64, Expand); 260 261 // Custom lower Add/Sub/Mul with overflow. 262 setOperationAction(ISD::SADDO, MVT::i32, Custom); 263 setOperationAction(ISD::SADDO, MVT::i64, Custom); 264 setOperationAction(ISD::UADDO, MVT::i32, Custom); 265 setOperationAction(ISD::UADDO, MVT::i64, Custom); 266 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 267 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 268 setOperationAction(ISD::USUBO, MVT::i32, Custom); 269 setOperationAction(ISD::USUBO, MVT::i64, Custom); 270 setOperationAction(ISD::SMULO, MVT::i32, Custom); 271 setOperationAction(ISD::SMULO, MVT::i64, Custom); 272 setOperationAction(ISD::UMULO, MVT::i32, Custom); 273 setOperationAction(ISD::UMULO, MVT::i64, Custom); 274 275 setOperationAction(ISD::FSIN, MVT::f32, Expand); 276 setOperationAction(ISD::FSIN, MVT::f64, Expand); 277 setOperationAction(ISD::FCOS, MVT::f32, Expand); 278 setOperationAction(ISD::FCOS, MVT::f64, Expand); 279 setOperationAction(ISD::FPOW, MVT::f32, Expand); 280 setOperationAction(ISD::FPOW, MVT::f64, Expand); 281 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 282 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 283 284 // f16 is a storage-only type, always promote it to f32. 285 setOperationAction(ISD::SETCC, MVT::f16, Promote); 286 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 287 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 288 setOperationAction(ISD::SELECT, MVT::f16, Promote); 289 setOperationAction(ISD::FADD, MVT::f16, Promote); 290 setOperationAction(ISD::FSUB, MVT::f16, Promote); 291 setOperationAction(ISD::FMUL, MVT::f16, Promote); 292 setOperationAction(ISD::FDIV, MVT::f16, Promote); 293 setOperationAction(ISD::FREM, MVT::f16, Promote); 294 setOperationAction(ISD::FMA, MVT::f16, Promote); 295 setOperationAction(ISD::FNEG, MVT::f16, Promote); 296 setOperationAction(ISD::FABS, MVT::f16, Promote); 297 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 298 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 299 setOperationAction(ISD::FCOS, MVT::f16, Promote); 300 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 301 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 302 setOperationAction(ISD::FPOW, MVT::f16, Promote); 303 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 304 setOperationAction(ISD::FRINT, MVT::f16, Promote); 305 setOperationAction(ISD::FSIN, MVT::f16, Promote); 306 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 307 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 308 setOperationAction(ISD::FEXP, MVT::f16, Promote); 309 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 310 setOperationAction(ISD::FLOG, MVT::f16, Promote); 311 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 312 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 313 setOperationAction(ISD::FROUND, MVT::f16, Promote); 314 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 315 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 316 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 317 setOperationAction(ISD::FMINNAN, MVT::f16, Promote); 318 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote); 319 320 // v4f16 is also a storage-only type, so promote it to v4f32 when that is 321 // known to be safe. 322 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 323 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 324 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 325 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 326 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 327 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 328 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 329 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 330 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 331 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 332 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 333 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 334 335 // Expand all other v4f16 operations. 336 // FIXME: We could generate better code by promoting some operations to 337 // a pair of v4f32s 338 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 339 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 340 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 341 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 342 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 343 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 344 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 345 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 346 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 347 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 348 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 349 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 350 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 352 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 353 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 354 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 355 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 356 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 357 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 358 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 359 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 361 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 362 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 363 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 364 365 366 // v8f16 is also a storage-only type, so expand it. 367 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 368 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 369 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 370 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 371 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 372 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 373 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 374 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 375 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 376 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 377 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 378 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 379 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 380 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 381 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 382 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 383 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 384 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 385 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 386 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 387 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 388 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 389 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 390 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 391 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 392 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 393 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 394 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 395 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 396 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 397 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 398 399 // AArch64 has implementations of a lot of rounding-like FP operations. 400 for (MVT Ty : {MVT::f32, MVT::f64}) { 401 setOperationAction(ISD::FFLOOR, Ty, Legal); 402 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 403 setOperationAction(ISD::FCEIL, Ty, Legal); 404 setOperationAction(ISD::FRINT, Ty, Legal); 405 setOperationAction(ISD::FTRUNC, Ty, Legal); 406 setOperationAction(ISD::FROUND, Ty, Legal); 407 setOperationAction(ISD::FMINNUM, Ty, Legal); 408 setOperationAction(ISD::FMAXNUM, Ty, Legal); 409 setOperationAction(ISD::FMINNAN, Ty, Legal); 410 setOperationAction(ISD::FMAXNAN, Ty, Legal); 411 } 412 413 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 414 415 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 416 // This requires the Performance Monitors extension. 417 if (Subtarget->hasPerfMon()) 418 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 419 420 if (Subtarget->isTargetMachO()) { 421 // For iOS, we don't want to the normal expansion of a libcall to 422 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 423 // traffic. 424 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 425 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 426 } else { 427 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 428 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 429 } 430 431 // Make floating-point constants legal for the large code model, so they don't 432 // become loads from the constant pool. 433 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 434 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 435 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 436 } 437 438 // AArch64 does not have floating-point extending loads, i1 sign-extending 439 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 440 for (MVT VT : MVT::fp_valuetypes()) { 441 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 442 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 443 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 444 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 445 } 446 for (MVT VT : MVT::integer_valuetypes()) 447 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 448 449 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 450 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 451 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 452 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 453 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 454 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 455 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 456 457 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 458 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 459 460 // Indexed loads and stores are supported. 461 for (unsigned im = (unsigned)ISD::PRE_INC; 462 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 463 setIndexedLoadAction(im, MVT::i8, Legal); 464 setIndexedLoadAction(im, MVT::i16, Legal); 465 setIndexedLoadAction(im, MVT::i32, Legal); 466 setIndexedLoadAction(im, MVT::i64, Legal); 467 setIndexedLoadAction(im, MVT::f64, Legal); 468 setIndexedLoadAction(im, MVT::f32, Legal); 469 setIndexedLoadAction(im, MVT::f16, Legal); 470 setIndexedStoreAction(im, MVT::i8, Legal); 471 setIndexedStoreAction(im, MVT::i16, Legal); 472 setIndexedStoreAction(im, MVT::i32, Legal); 473 setIndexedStoreAction(im, MVT::i64, Legal); 474 setIndexedStoreAction(im, MVT::f64, Legal); 475 setIndexedStoreAction(im, MVT::f32, Legal); 476 setIndexedStoreAction(im, MVT::f16, Legal); 477 } 478 479 // Trap. 480 setOperationAction(ISD::TRAP, MVT::Other, Legal); 481 482 // We combine OR nodes for bitfield operations. 483 setTargetDAGCombine(ISD::OR); 484 485 // Vector add and sub nodes may conceal a high-half opportunity. 486 // Also, try to fold ADD into CSINC/CSINV.. 487 setTargetDAGCombine(ISD::ADD); 488 setTargetDAGCombine(ISD::SUB); 489 490 setTargetDAGCombine(ISD::XOR); 491 setTargetDAGCombine(ISD::SINT_TO_FP); 492 setTargetDAGCombine(ISD::UINT_TO_FP); 493 494 setTargetDAGCombine(ISD::FP_TO_SINT); 495 setTargetDAGCombine(ISD::FP_TO_UINT); 496 setTargetDAGCombine(ISD::FDIV); 497 498 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 499 500 setTargetDAGCombine(ISD::ANY_EXTEND); 501 setTargetDAGCombine(ISD::ZERO_EXTEND); 502 setTargetDAGCombine(ISD::SIGN_EXTEND); 503 setTargetDAGCombine(ISD::BITCAST); 504 setTargetDAGCombine(ISD::CONCAT_VECTORS); 505 setTargetDAGCombine(ISD::STORE); 506 if (Subtarget->supportsAddressTopByteIgnored()) 507 setTargetDAGCombine(ISD::LOAD); 508 509 setTargetDAGCombine(ISD::MUL); 510 511 setTargetDAGCombine(ISD::SELECT); 512 setTargetDAGCombine(ISD::VSELECT); 513 514 setTargetDAGCombine(ISD::INTRINSIC_VOID); 515 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 516 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 517 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 518 519 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8; 520 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4; 521 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4; 522 523 setStackPointerRegisterToSaveRestore(AArch64::SP); 524 525 setSchedulingPreference(Sched::Hybrid); 526 527 // Enable TBZ/TBNZ 528 MaskAndBranchFoldingIsLegal = true; 529 EnableExtLdPromotion = true; 530 531 setMinFunctionAlignment(2); 532 533 setHasExtractBitsInsn(true); 534 535 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 536 537 if (Subtarget->hasNEON()) { 538 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 539 // silliness like this: 540 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 541 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 542 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 543 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 544 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 545 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 546 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 547 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 548 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 549 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 550 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 551 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 552 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 553 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 554 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 555 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 556 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 557 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 558 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 559 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 560 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 561 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 562 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 563 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 564 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 565 566 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 567 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 568 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 569 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 570 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 571 572 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 573 574 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 575 // elements smaller than i32, so promote the input to i32 first. 576 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote); 577 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote); 578 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote); 579 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote); 580 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16 581 // -> v8f16 conversions. 582 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote); 583 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote); 584 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 585 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote); 586 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 587 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 588 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 589 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 590 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 591 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 592 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 593 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 594 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 595 596 // AArch64 doesn't have MUL.2d: 597 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 598 // Custom handling for some quad-vector types to detect MULL. 599 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 600 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 601 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 602 603 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 604 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 605 // Likewise, narrowing and extending vector loads/stores aren't handled 606 // directly. 607 for (MVT VT : MVT::vector_valuetypes()) { 608 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 609 610 setOperationAction(ISD::MULHS, VT, Expand); 611 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 612 setOperationAction(ISD::MULHU, VT, Expand); 613 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 614 615 setOperationAction(ISD::BSWAP, VT, Expand); 616 617 for (MVT InnerVT : MVT::vector_valuetypes()) { 618 setTruncStoreAction(VT, InnerVT, Expand); 619 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 620 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 621 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 622 } 623 } 624 625 // AArch64 has implementations of a lot of rounding-like FP operations. 626 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 627 setOperationAction(ISD::FFLOOR, Ty, Legal); 628 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 629 setOperationAction(ISD::FCEIL, Ty, Legal); 630 setOperationAction(ISD::FRINT, Ty, Legal); 631 setOperationAction(ISD::FTRUNC, Ty, Legal); 632 setOperationAction(ISD::FROUND, Ty, Legal); 633 } 634 } 635 636 // Prefer likely predicted branches to selects on out-of-order cores. 637 if (Subtarget->isCortexA57() || Subtarget->isKryo()) 638 PredictableSelectIsExpensive = true; 639 } 640 641 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) { 642 if (VT == MVT::v2f32 || VT == MVT::v4f16) { 643 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote); 644 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32); 645 646 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote); 647 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32); 648 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) { 649 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote); 650 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64); 651 652 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote); 653 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64); 654 } 655 656 // Mark vector float intrinsics as expand. 657 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 658 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand); 659 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand); 660 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand); 661 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand); 662 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand); 663 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand); 664 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand); 665 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand); 666 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand); 667 668 // But we do support custom-lowering for FCOPYSIGN. 669 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom); 670 } 671 672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom); 673 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom); 674 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom); 675 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom); 676 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom); 677 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom); 678 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom); 679 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom); 680 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom); 681 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom); 682 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom); 683 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal); 684 685 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand); 686 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand); 687 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand); 688 for (MVT InnerVT : MVT::all_valuetypes()) 689 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand); 690 691 // CNT supports only B element sizes. 692 if (VT != MVT::v8i8 && VT != MVT::v16i8) 693 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand); 694 695 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand); 696 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand); 697 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand); 698 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand); 699 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand); 700 701 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom); 702 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom); 703 704 // [SU][MIN|MAX] are available for all NEON types apart from i64. 705 if (!VT.isFloatingPoint() && 706 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64) 707 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 708 setOperationAction(Opcode, VT.getSimpleVT(), Legal); 709 710 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!). 711 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16) 712 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN, 713 ISD::FMINNUM, ISD::FMAXNUM}) 714 setOperationAction(Opcode, VT.getSimpleVT(), Legal); 715 716 if (Subtarget->isLittleEndian()) { 717 for (unsigned im = (unsigned)ISD::PRE_INC; 718 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 719 setIndexedLoadAction(im, VT.getSimpleVT(), Legal); 720 setIndexedStoreAction(im, VT.getSimpleVT(), Legal); 721 } 722 } 723 } 724 725 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 726 addRegisterClass(VT, &AArch64::FPR64RegClass); 727 addTypeForNEON(VT, MVT::v2i32); 728 } 729 730 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 731 addRegisterClass(VT, &AArch64::FPR128RegClass); 732 addTypeForNEON(VT, MVT::v4i32); 733 } 734 735 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 736 EVT VT) const { 737 if (!VT.isVector()) 738 return MVT::i32; 739 return VT.changeVectorElementTypeToInteger(); 740 } 741 742 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 743 /// Mask are known to be either zero or one and return them in the 744 /// KnownZero/KnownOne bitsets. 745 void AArch64TargetLowering::computeKnownBitsForTargetNode( 746 const SDValue Op, APInt &KnownZero, APInt &KnownOne, 747 const SelectionDAG &DAG, unsigned Depth) const { 748 switch (Op.getOpcode()) { 749 default: 750 break; 751 case AArch64ISD::CSEL: { 752 APInt KnownZero2, KnownOne2; 753 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1); 754 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1); 755 KnownZero &= KnownZero2; 756 KnownOne &= KnownOne2; 757 break; 758 } 759 case ISD::INTRINSIC_W_CHAIN: { 760 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 761 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 762 switch (IntID) { 763 default: return; 764 case Intrinsic::aarch64_ldaxr: 765 case Intrinsic::aarch64_ldxr: { 766 unsigned BitWidth = KnownOne.getBitWidth(); 767 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 768 unsigned MemBits = VT.getScalarType().getSizeInBits(); 769 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 770 return; 771 } 772 } 773 break; 774 } 775 case ISD::INTRINSIC_WO_CHAIN: 776 case ISD::INTRINSIC_VOID: { 777 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 778 switch (IntNo) { 779 default: 780 break; 781 case Intrinsic::aarch64_neon_umaxv: 782 case Intrinsic::aarch64_neon_uminv: { 783 // Figure out the datatype of the vector operand. The UMINV instruction 784 // will zero extend the result, so we can mark as known zero all the 785 // bits larger than the element datatype. 32-bit or larget doesn't need 786 // this as those are legal types and will be handled by isel directly. 787 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 788 unsigned BitWidth = KnownZero.getBitWidth(); 789 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 790 assert(BitWidth >= 8 && "Unexpected width!"); 791 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 792 KnownZero |= Mask; 793 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 794 assert(BitWidth >= 16 && "Unexpected width!"); 795 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 796 KnownZero |= Mask; 797 } 798 break; 799 } break; 800 } 801 } 802 } 803 } 804 805 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 806 EVT) const { 807 return MVT::i64; 808 } 809 810 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 811 unsigned AddrSpace, 812 unsigned Align, 813 bool *Fast) const { 814 if (Subtarget->requiresStrictAlign()) 815 return false; 816 817 // FIXME: This is mostly true for Cyclone, but not necessarily others. 818 if (Fast) { 819 // FIXME: Define an attribute for slow unaligned accesses instead of 820 // relying on the CPU type as a proxy. 821 // On Cyclone, unaligned 128-bit stores are slow. 822 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 || 823 // See comments in performSTORECombine() for more details about 824 // these conditions. 825 826 // Code that uses clang vector extensions can mark that it 827 // wants unaligned accesses to be treated as fast by 828 // underspecifying alignment to be 1 or 2. 829 Align <= 2 || 830 831 // Disregard v2i64. Memcpy lowering produces those and splitting 832 // them regresses performance on micro-benchmarks and olden/bh. 833 VT == MVT::v2i64; 834 } 835 return true; 836 } 837 838 FastISel * 839 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 840 const TargetLibraryInfo *libInfo) const { 841 return AArch64::createFastISel(funcInfo, libInfo); 842 } 843 844 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 845 switch ((AArch64ISD::NodeType)Opcode) { 846 case AArch64ISD::FIRST_NUMBER: break; 847 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 848 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 849 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 850 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 851 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 852 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 853 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 854 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 855 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 856 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 857 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 858 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 859 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 860 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 861 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 862 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 863 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 864 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 865 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 866 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 867 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 868 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 869 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 870 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 871 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 872 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 873 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 874 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 875 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 876 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 877 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 878 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 879 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 880 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 881 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 882 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 883 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 884 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 885 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 886 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 887 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 888 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 889 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 890 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 891 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 892 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 893 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 894 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 895 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 896 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 897 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 898 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 899 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 900 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 901 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 902 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 903 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 904 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 905 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 906 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 907 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 908 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 909 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 910 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 911 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 912 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 913 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 914 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 915 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 916 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 917 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 918 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 919 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 920 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 921 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 922 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 923 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 924 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 925 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 926 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 927 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 928 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 929 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 930 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 931 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 932 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 933 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 934 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 935 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 936 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 937 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 938 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 939 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 940 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 941 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 942 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 943 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 944 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 945 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 946 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 947 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 948 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 949 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 950 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 951 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 952 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 953 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 954 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 955 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 956 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 957 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 958 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 959 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 960 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 961 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 962 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 963 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 964 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 965 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 966 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 967 } 968 return nullptr; 969 } 970 971 MachineBasicBlock * 972 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI, 973 MachineBasicBlock *MBB) const { 974 // We materialise the F128CSEL pseudo-instruction as some control flow and a 975 // phi node: 976 977 // OrigBB: 978 // [... previous instrs leading to comparison ...] 979 // b.ne TrueBB 980 // b EndBB 981 // TrueBB: 982 // ; Fallthrough 983 // EndBB: 984 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 985 986 MachineFunction *MF = MBB->getParent(); 987 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 988 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 989 DebugLoc DL = MI->getDebugLoc(); 990 MachineFunction::iterator It = ++MBB->getIterator(); 991 992 unsigned DestReg = MI->getOperand(0).getReg(); 993 unsigned IfTrueReg = MI->getOperand(1).getReg(); 994 unsigned IfFalseReg = MI->getOperand(2).getReg(); 995 unsigned CondCode = MI->getOperand(3).getImm(); 996 bool NZCVKilled = MI->getOperand(4).isKill(); 997 998 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 999 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1000 MF->insert(It, TrueBB); 1001 MF->insert(It, EndBB); 1002 1003 // Transfer rest of current basic-block to EndBB 1004 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1005 MBB->end()); 1006 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1007 1008 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1009 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1010 MBB->addSuccessor(TrueBB); 1011 MBB->addSuccessor(EndBB); 1012 1013 // TrueBB falls through to the end. 1014 TrueBB->addSuccessor(EndBB); 1015 1016 if (!NZCVKilled) { 1017 TrueBB->addLiveIn(AArch64::NZCV); 1018 EndBB->addLiveIn(AArch64::NZCV); 1019 } 1020 1021 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1022 .addReg(IfTrueReg) 1023 .addMBB(TrueBB) 1024 .addReg(IfFalseReg) 1025 .addMBB(MBB); 1026 1027 MI->eraseFromParent(); 1028 return EndBB; 1029 } 1030 1031 MachineBasicBlock * 1032 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 1033 MachineBasicBlock *BB) const { 1034 switch (MI->getOpcode()) { 1035 default: 1036 #ifndef NDEBUG 1037 MI->dump(); 1038 #endif 1039 llvm_unreachable("Unexpected instruction for custom inserter!"); 1040 1041 case AArch64::F128CSEL: 1042 return EmitF128CSEL(MI, BB); 1043 1044 case TargetOpcode::STACKMAP: 1045 case TargetOpcode::PATCHPOINT: 1046 return emitPatchPoint(MI, BB); 1047 } 1048 } 1049 1050 //===----------------------------------------------------------------------===// 1051 // AArch64 Lowering private implementation. 1052 //===----------------------------------------------------------------------===// 1053 1054 //===----------------------------------------------------------------------===// 1055 // Lowering Code 1056 //===----------------------------------------------------------------------===// 1057 1058 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1059 /// CC 1060 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1061 switch (CC) { 1062 default: 1063 llvm_unreachable("Unknown condition code!"); 1064 case ISD::SETNE: 1065 return AArch64CC::NE; 1066 case ISD::SETEQ: 1067 return AArch64CC::EQ; 1068 case ISD::SETGT: 1069 return AArch64CC::GT; 1070 case ISD::SETGE: 1071 return AArch64CC::GE; 1072 case ISD::SETLT: 1073 return AArch64CC::LT; 1074 case ISD::SETLE: 1075 return AArch64CC::LE; 1076 case ISD::SETUGT: 1077 return AArch64CC::HI; 1078 case ISD::SETUGE: 1079 return AArch64CC::HS; 1080 case ISD::SETULT: 1081 return AArch64CC::LO; 1082 case ISD::SETULE: 1083 return AArch64CC::LS; 1084 } 1085 } 1086 1087 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1088 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1089 AArch64CC::CondCode &CondCode, 1090 AArch64CC::CondCode &CondCode2) { 1091 CondCode2 = AArch64CC::AL; 1092 switch (CC) { 1093 default: 1094 llvm_unreachable("Unknown FP condition!"); 1095 case ISD::SETEQ: 1096 case ISD::SETOEQ: 1097 CondCode = AArch64CC::EQ; 1098 break; 1099 case ISD::SETGT: 1100 case ISD::SETOGT: 1101 CondCode = AArch64CC::GT; 1102 break; 1103 case ISD::SETGE: 1104 case ISD::SETOGE: 1105 CondCode = AArch64CC::GE; 1106 break; 1107 case ISD::SETOLT: 1108 CondCode = AArch64CC::MI; 1109 break; 1110 case ISD::SETOLE: 1111 CondCode = AArch64CC::LS; 1112 break; 1113 case ISD::SETONE: 1114 CondCode = AArch64CC::MI; 1115 CondCode2 = AArch64CC::GT; 1116 break; 1117 case ISD::SETO: 1118 CondCode = AArch64CC::VC; 1119 break; 1120 case ISD::SETUO: 1121 CondCode = AArch64CC::VS; 1122 break; 1123 case ISD::SETUEQ: 1124 CondCode = AArch64CC::EQ; 1125 CondCode2 = AArch64CC::VS; 1126 break; 1127 case ISD::SETUGT: 1128 CondCode = AArch64CC::HI; 1129 break; 1130 case ISD::SETUGE: 1131 CondCode = AArch64CC::PL; 1132 break; 1133 case ISD::SETLT: 1134 case ISD::SETULT: 1135 CondCode = AArch64CC::LT; 1136 break; 1137 case ISD::SETLE: 1138 case ISD::SETULE: 1139 CondCode = AArch64CC::LE; 1140 break; 1141 case ISD::SETNE: 1142 case ISD::SETUNE: 1143 CondCode = AArch64CC::NE; 1144 break; 1145 } 1146 } 1147 1148 /// Convert a DAG fp condition code to an AArch64 CC. 1149 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1150 /// should be AND'ed instead of OR'ed. 1151 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1152 AArch64CC::CondCode &CondCode, 1153 AArch64CC::CondCode &CondCode2) { 1154 CondCode2 = AArch64CC::AL; 1155 switch (CC) { 1156 default: 1157 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1158 assert(CondCode2 == AArch64CC::AL); 1159 break; 1160 case ISD::SETONE: 1161 // (a one b) 1162 // == ((a olt b) || (a ogt b)) 1163 // == ((a ord b) && (a une b)) 1164 CondCode = AArch64CC::VC; 1165 CondCode2 = AArch64CC::NE; 1166 break; 1167 case ISD::SETUEQ: 1168 // (a ueq b) 1169 // == ((a uno b) || (a oeq b)) 1170 // == ((a ule b) && (a uge b)) 1171 CondCode = AArch64CC::PL; 1172 CondCode2 = AArch64CC::LE; 1173 break; 1174 } 1175 } 1176 1177 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1178 /// CC usable with the vector instructions. Fewer operations are available 1179 /// without a real NZCV register, so we have to use less efficient combinations 1180 /// to get the same effect. 1181 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1182 AArch64CC::CondCode &CondCode, 1183 AArch64CC::CondCode &CondCode2, 1184 bool &Invert) { 1185 Invert = false; 1186 switch (CC) { 1187 default: 1188 // Mostly the scalar mappings work fine. 1189 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1190 break; 1191 case ISD::SETUO: 1192 Invert = true; // Fallthrough 1193 case ISD::SETO: 1194 CondCode = AArch64CC::MI; 1195 CondCode2 = AArch64CC::GE; 1196 break; 1197 case ISD::SETUEQ: 1198 case ISD::SETULT: 1199 case ISD::SETULE: 1200 case ISD::SETUGT: 1201 case ISD::SETUGE: 1202 // All of the compare-mask comparisons are ordered, but we can switch 1203 // between the two by a double inversion. E.g. ULE == !OGT. 1204 Invert = true; 1205 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1206 break; 1207 } 1208 } 1209 1210 static bool isLegalArithImmed(uint64_t C) { 1211 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1212 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1213 } 1214 1215 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1216 SDLoc dl, SelectionDAG &DAG) { 1217 EVT VT = LHS.getValueType(); 1218 1219 if (VT.isFloatingPoint()) { 1220 assert(VT != MVT::f128); 1221 if (VT == MVT::f16) { 1222 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1223 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1224 } 1225 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1226 } 1227 1228 // The CMP instruction is just an alias for SUBS, and representing it as 1229 // SUBS means that it's possible to get CSE with subtract operations. 1230 // A later phase can perform the optimization of setting the destination 1231 // register to WZR/XZR if it ends up being unused. 1232 unsigned Opcode = AArch64ISD::SUBS; 1233 1234 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 1235 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1236 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on 1237 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags 1238 // can be set differently by this operation. It comes down to whether 1239 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1240 // everything is fine. If not then the optimization is wrong. Thus general 1241 // comparisons are only valid if op2 != 0. 1242 1243 // So, finally, the only LLVM-native comparisons that don't mention C and V 1244 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1245 // the absence of information about op2. 1246 Opcode = AArch64ISD::ADDS; 1247 RHS = RHS.getOperand(1); 1248 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1249 !isUnsignedIntSetCC(CC)) { 1250 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1251 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1252 // of the signed comparisons. 1253 Opcode = AArch64ISD::ANDS; 1254 RHS = LHS.getOperand(1); 1255 LHS = LHS.getOperand(0); 1256 } 1257 1258 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1259 .getValue(1); 1260 } 1261 1262 /// \defgroup AArch64CCMP CMP;CCMP matching 1263 /// 1264 /// These functions deal with the formation of CMP;CCMP;... sequences. 1265 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1266 /// a comparison. They set the NZCV flags to a predefined value if their 1267 /// predicate is false. This allows to express arbitrary conjunctions, for 1268 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))" 1269 /// expressed as: 1270 /// cmp A 1271 /// ccmp B, inv(CB), CA 1272 /// check for CB flags 1273 /// 1274 /// In general we can create code for arbitrary "... (and (and A B) C)" 1275 /// sequences. We can also implement some "or" expressions, because "(or A B)" 1276 /// is equivalent to "not (and (not A) (not B))" and we can implement some 1277 /// negation operations: 1278 /// We can negate the results of a single comparison by inverting the flags 1279 /// used when the predicate fails and inverting the flags tested in the next 1280 /// instruction; We can also negate the results of the whole previous 1281 /// conditional compare sequence by inverting the flags tested in the next 1282 /// instruction. However there is no way to negate the result of a partial 1283 /// sequence. 1284 /// 1285 /// Therefore on encountering an "or" expression we can negate the subtree on 1286 /// one side and have to be able to push the negate to the leafs of the subtree 1287 /// on the other side (see also the comments in code). As complete example: 1288 /// "or (or (setCA (cmp A)) (setCB (cmp B))) 1289 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1290 /// is transformed to 1291 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D)))) 1292 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1293 /// and implemented as: 1294 /// cmp C 1295 /// ccmp D, inv(CD), CC 1296 /// ccmp A, CA, inv(CD) 1297 /// ccmp B, CB, inv(CA) 1298 /// check for CB flags 1299 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented 1300 /// by conditional compare sequences. 1301 /// @{ 1302 1303 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1304 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1305 ISD::CondCode CC, SDValue CCOp, 1306 AArch64CC::CondCode Predicate, 1307 AArch64CC::CondCode OutCC, 1308 SDLoc DL, SelectionDAG &DAG) { 1309 unsigned Opcode = 0; 1310 if (LHS.getValueType().isFloatingPoint()) { 1311 assert(LHS.getValueType() != MVT::f128); 1312 if (LHS.getValueType() == MVT::f16) { 1313 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1314 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1315 } 1316 Opcode = AArch64ISD::FCCMP; 1317 } else if (RHS.getOpcode() == ISD::SUB) { 1318 SDValue SubOp0 = RHS.getOperand(0); 1319 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1320 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1321 Opcode = AArch64ISD::CCMN; 1322 RHS = RHS.getOperand(1); 1323 } 1324 } 1325 if (Opcode == 0) 1326 Opcode = AArch64ISD::CCMP; 1327 1328 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1329 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1330 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1331 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1332 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1333 } 1334 1335 /// Returns true if @p Val is a tree of AND/OR/SETCC operations. 1336 /// CanPushNegate is set to true if we can push a negate operation through 1337 /// the tree in a was that we are left with AND operations and negate operations 1338 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to 1339 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be 1340 /// brought into such a form. 1341 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate, 1342 unsigned Depth = 0) { 1343 if (!Val.hasOneUse()) 1344 return false; 1345 unsigned Opcode = Val->getOpcode(); 1346 if (Opcode == ISD::SETCC) { 1347 if (Val->getOperand(0).getValueType() == MVT::f128) 1348 return false; 1349 CanNegate = true; 1350 return true; 1351 } 1352 // Protect against exponential runtime and stack overflow. 1353 if (Depth > 6) 1354 return false; 1355 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1356 SDValue O0 = Val->getOperand(0); 1357 SDValue O1 = Val->getOperand(1); 1358 bool CanNegateL; 1359 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1)) 1360 return false; 1361 bool CanNegateR; 1362 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1)) 1363 return false; 1364 1365 if (Opcode == ISD::OR) { 1366 // For an OR expression we need to be able to negate at least one side or 1367 // we cannot do the transformation at all. 1368 if (!CanNegateL && !CanNegateR) 1369 return false; 1370 // We can however change a (not (or x y)) to (and (not x) (not y)) if we 1371 // can negate the x and y subtrees. 1372 CanNegate = CanNegateL && CanNegateR; 1373 } else { 1374 // If the operands are OR expressions then we finally need to negate their 1375 // outputs, we can only do that for the operand with emitted last by 1376 // negating OutCC, not for both operands. 1377 bool NeedsNegOutL = O0->getOpcode() == ISD::OR; 1378 bool NeedsNegOutR = O1->getOpcode() == ISD::OR; 1379 if (NeedsNegOutL && NeedsNegOutR) 1380 return false; 1381 // We cannot negate an AND operation (it would become an OR), 1382 CanNegate = false; 1383 } 1384 return true; 1385 } 1386 return false; 1387 } 1388 1389 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1390 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1391 /// Tries to transform the given i1 producing node @p Val to a series compare 1392 /// and conditional compare operations. @returns an NZCV flags producing node 1393 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1394 /// transformation was not possible. 1395 /// On recursive invocations @p PushNegate may be set to true to have negation 1396 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate 1397 /// for the comparisons in the current subtree; @p Depth limits the search 1398 /// depth to avoid stack overflow. 1399 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val, 1400 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1401 AArch64CC::CondCode Predicate) { 1402 // We're at a tree leaf, produce a conditional comparison operation. 1403 unsigned Opcode = Val->getOpcode(); 1404 if (Opcode == ISD::SETCC) { 1405 SDValue LHS = Val->getOperand(0); 1406 SDValue RHS = Val->getOperand(1); 1407 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1408 bool isInteger = LHS.getValueType().isInteger(); 1409 if (Negate) 1410 CC = getSetCCInverse(CC, isInteger); 1411 SDLoc DL(Val); 1412 // Determine OutCC and handle FP special case. 1413 if (isInteger) { 1414 OutCC = changeIntCCToAArch64CC(CC); 1415 } else { 1416 assert(LHS.getValueType().isFloatingPoint()); 1417 AArch64CC::CondCode ExtraCC; 1418 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1419 // Some floating point conditions can't be tested with a single condition 1420 // code. Construct an additional comparison in this case. 1421 if (ExtraCC != AArch64CC::AL) { 1422 SDValue ExtraCmp; 1423 if (!CCOp.getNode()) 1424 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1425 else 1426 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1427 ExtraCC, DL, DAG); 1428 CCOp = ExtraCmp; 1429 Predicate = ExtraCC; 1430 } 1431 } 1432 1433 // Produce a normal comparison if we are first in the chain 1434 if (!CCOp) 1435 return emitComparison(LHS, RHS, CC, DL, DAG); 1436 // Otherwise produce a ccmp. 1437 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1438 DAG); 1439 } 1440 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) && 1441 "Valid conjunction/disjunction tree"); 1442 1443 // Check if both sides can be transformed. 1444 SDValue LHS = Val->getOperand(0); 1445 SDValue RHS = Val->getOperand(1); 1446 1447 // In case of an OR we need to negate our operands and the result. 1448 // (A v B) <=> not(not(A) ^ not(B)) 1449 bool NegateOpsAndResult = Opcode == ISD::OR; 1450 // We can negate the results of all previous operations by inverting the 1451 // predicate flags giving us a free negation for one side. The other side 1452 // must be negatable by itself. 1453 if (NegateOpsAndResult) { 1454 // See which side we can negate. 1455 bool CanNegateL; 1456 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL); 1457 assert(isValidL && "Valid conjunction/disjunction tree"); 1458 (void)isValidL; 1459 1460 #ifndef NDEBUG 1461 bool CanNegateR; 1462 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR); 1463 assert(isValidR && "Valid conjunction/disjunction tree"); 1464 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree"); 1465 #endif 1466 1467 // Order the side which we cannot negate to RHS so we can emit it first. 1468 if (!CanNegateL) 1469 std::swap(LHS, RHS); 1470 } else { 1471 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR; 1472 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) && 1473 "Valid conjunction/disjunction tree"); 1474 // Order the side where we need to negate the output flags to RHS so it 1475 // gets emitted first. 1476 if (NeedsNegOutL) 1477 std::swap(LHS, RHS); 1478 } 1479 1480 // Emit RHS. If we want to negate the tree we only need to push a negate 1481 // through if we are already in a PushNegate case, otherwise we can negate 1482 // the "flags to test" afterwards. 1483 AArch64CC::CondCode RHSCC; 1484 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate, 1485 CCOp, Predicate); 1486 if (NegateOpsAndResult && !Negate) 1487 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1488 // Emit LHS. We may need to negate it. 1489 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC, 1490 NegateOpsAndResult, CmpR, 1491 RHSCC); 1492 // If we transformed an OR to and AND then we have to negate the result 1493 // (or absorb the Negate parameter). 1494 if (NegateOpsAndResult && !Negate) 1495 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1496 return CmpL; 1497 } 1498 1499 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1500 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1501 /// \see emitConjunctionDisjunctionTreeRec(). 1502 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val, 1503 AArch64CC::CondCode &OutCC) { 1504 bool CanNegate; 1505 if (!isConjunctionDisjunctionTree(Val, CanNegate)) 1506 return SDValue(); 1507 1508 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(), 1509 AArch64CC::AL); 1510 } 1511 1512 /// @} 1513 1514 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1515 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) { 1516 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1517 EVT VT = RHS.getValueType(); 1518 uint64_t C = RHSC->getZExtValue(); 1519 if (!isLegalArithImmed(C)) { 1520 // Constant does not fit, try adjusting it by one? 1521 switch (CC) { 1522 default: 1523 break; 1524 case ISD::SETLT: 1525 case ISD::SETGE: 1526 if ((VT == MVT::i32 && C != 0x80000000 && 1527 isLegalArithImmed((uint32_t)(C - 1))) || 1528 (VT == MVT::i64 && C != 0x80000000ULL && 1529 isLegalArithImmed(C - 1ULL))) { 1530 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1531 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1532 RHS = DAG.getConstant(C, dl, VT); 1533 } 1534 break; 1535 case ISD::SETULT: 1536 case ISD::SETUGE: 1537 if ((VT == MVT::i32 && C != 0 && 1538 isLegalArithImmed((uint32_t)(C - 1))) || 1539 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1540 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1541 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1542 RHS = DAG.getConstant(C, dl, VT); 1543 } 1544 break; 1545 case ISD::SETLE: 1546 case ISD::SETGT: 1547 if ((VT == MVT::i32 && C != INT32_MAX && 1548 isLegalArithImmed((uint32_t)(C + 1))) || 1549 (VT == MVT::i64 && C != INT64_MAX && 1550 isLegalArithImmed(C + 1ULL))) { 1551 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1552 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1553 RHS = DAG.getConstant(C, dl, VT); 1554 } 1555 break; 1556 case ISD::SETULE: 1557 case ISD::SETUGT: 1558 if ((VT == MVT::i32 && C != UINT32_MAX && 1559 isLegalArithImmed((uint32_t)(C + 1))) || 1560 (VT == MVT::i64 && C != UINT64_MAX && 1561 isLegalArithImmed(C + 1ULL))) { 1562 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1563 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1564 RHS = DAG.getConstant(C, dl, VT); 1565 } 1566 break; 1567 } 1568 } 1569 } 1570 SDValue Cmp; 1571 AArch64CC::CondCode AArch64CC; 1572 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1573 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1574 1575 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1576 // For the i8 operand, the largest immediate is 255, so this can be easily 1577 // encoded in the compare instruction. For the i16 operand, however, the 1578 // largest immediate cannot be encoded in the compare. 1579 // Therefore, use a sign extending load and cmn to avoid materializing the 1580 // -1 constant. For example, 1581 // movz w1, #65535 1582 // ldrh w0, [x0, #0] 1583 // cmp w0, w1 1584 // > 1585 // ldrsh w0, [x0, #0] 1586 // cmn w0, #1 1587 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1588 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1589 // ensure both the LHS and RHS are truly zero extended and to make sure the 1590 // transformation is profitable. 1591 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1592 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1593 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1594 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1595 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1596 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1597 SDValue SExt = 1598 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1599 DAG.getValueType(MVT::i16)); 1600 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1601 RHS.getValueType()), 1602 CC, dl, DAG); 1603 AArch64CC = changeIntCCToAArch64CC(CC); 1604 } 1605 } 1606 1607 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 1608 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) { 1609 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 1610 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 1611 } 1612 } 1613 } 1614 1615 if (!Cmp) { 1616 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 1617 AArch64CC = changeIntCCToAArch64CC(CC); 1618 } 1619 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 1620 return Cmp; 1621 } 1622 1623 // Attempt to form conditional compare sequences for and/or trees 1624 // with setcc leafs. 1625 static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) { 1626 SDValue LHS = Op.getOperand(0); 1627 SDValue RHS = Op.getOperand(1); 1628 if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC)) 1629 return Op; 1630 1631 bool CanNegate; 1632 if (!isConjunctionDisjunctionTree(Op, CanNegate)) 1633 return SDValue(); 1634 1635 EVT VT = Op.getValueType(); 1636 SDLoc DL(Op); 1637 SDValue TVal = DAG.getConstant(1, DL, VT); 1638 SDValue FVal = DAG.getConstant(0, DL, VT); 1639 SDValue CCVal; 1640 SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL); 1641 return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp); 1642 } 1643 1644 static std::pair<SDValue, SDValue> 1645 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 1646 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 1647 "Unsupported value type"); 1648 SDValue Value, Overflow; 1649 SDLoc DL(Op); 1650 SDValue LHS = Op.getOperand(0); 1651 SDValue RHS = Op.getOperand(1); 1652 unsigned Opc = 0; 1653 switch (Op.getOpcode()) { 1654 default: 1655 llvm_unreachable("Unknown overflow instruction!"); 1656 case ISD::SADDO: 1657 Opc = AArch64ISD::ADDS; 1658 CC = AArch64CC::VS; 1659 break; 1660 case ISD::UADDO: 1661 Opc = AArch64ISD::ADDS; 1662 CC = AArch64CC::HS; 1663 break; 1664 case ISD::SSUBO: 1665 Opc = AArch64ISD::SUBS; 1666 CC = AArch64CC::VS; 1667 break; 1668 case ISD::USUBO: 1669 Opc = AArch64ISD::SUBS; 1670 CC = AArch64CC::LO; 1671 break; 1672 // Multiply needs a little bit extra work. 1673 case ISD::SMULO: 1674 case ISD::UMULO: { 1675 CC = AArch64CC::NE; 1676 bool IsSigned = Op.getOpcode() == ISD::SMULO; 1677 if (Op.getValueType() == MVT::i32) { 1678 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1679 // For a 32 bit multiply with overflow check we want the instruction 1680 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 1681 // need to generate the following pattern: 1682 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 1683 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 1684 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 1685 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1686 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 1687 DAG.getConstant(0, DL, MVT::i64)); 1688 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 1689 // operation. We need to clear out the upper 32 bits, because we used a 1690 // widening multiply that wrote all 64 bits. In the end this should be a 1691 // noop. 1692 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 1693 if (IsSigned) { 1694 // The signed overflow check requires more than just a simple check for 1695 // any bit set in the upper 32 bits of the result. These bits could be 1696 // just the sign bits of a negative number. To perform the overflow 1697 // check we have to arithmetic shift right the 32nd bit of the result by 1698 // 31 bits. Then we compare the result to the upper 32 bits. 1699 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 1700 DAG.getConstant(32, DL, MVT::i64)); 1701 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 1702 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 1703 DAG.getConstant(31, DL, MVT::i64)); 1704 // It is important that LowerBits is last, otherwise the arithmetic 1705 // shift will not be folded into the compare (SUBS). 1706 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 1707 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1708 .getValue(1); 1709 } else { 1710 // The overflow check for unsigned multiply is easy. We only need to 1711 // check if any of the upper 32 bits are set. This can be done with a 1712 // CMP (shifted register). For that we need to generate the following 1713 // pattern: 1714 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 1715 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 1716 DAG.getConstant(32, DL, MVT::i64)); 1717 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1718 Overflow = 1719 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1720 DAG.getConstant(0, DL, MVT::i64), 1721 UpperBits).getValue(1); 1722 } 1723 break; 1724 } 1725 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 1726 // For the 64 bit multiply 1727 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1728 if (IsSigned) { 1729 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 1730 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 1731 DAG.getConstant(63, DL, MVT::i64)); 1732 // It is important that LowerBits is last, otherwise the arithmetic 1733 // shift will not be folded into the compare (SUBS). 1734 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1735 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1736 .getValue(1); 1737 } else { 1738 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 1739 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1740 Overflow = 1741 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1742 DAG.getConstant(0, DL, MVT::i64), 1743 UpperBits).getValue(1); 1744 } 1745 break; 1746 } 1747 } // switch (...) 1748 1749 if (Opc) { 1750 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 1751 1752 // Emit the AArch64 operation with overflow check. 1753 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 1754 Overflow = Value.getValue(1); 1755 } 1756 return std::make_pair(Value, Overflow); 1757 } 1758 1759 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 1760 RTLIB::Libcall Call) const { 1761 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1762 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 1763 } 1764 1765 SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const { 1766 if (Op.getValueType().isVector()) 1767 return LowerVectorAND(Op, DAG); 1768 return tryLowerToAArch64Cmp(Op, DAG); 1769 } 1770 1771 SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const { 1772 if (Op.getValueType().isVector()) 1773 return LowerVectorOR(Op, DAG); 1774 return tryLowerToAArch64Cmp(Op, DAG); 1775 } 1776 1777 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1778 SDValue Sel = Op.getOperand(0); 1779 SDValue Other = Op.getOperand(1); 1780 1781 // If neither operand is a SELECT_CC, give up. 1782 if (Sel.getOpcode() != ISD::SELECT_CC) 1783 std::swap(Sel, Other); 1784 if (Sel.getOpcode() != ISD::SELECT_CC) 1785 return Op; 1786 1787 // The folding we want to perform is: 1788 // (xor x, (select_cc a, b, cc, 0, -1) ) 1789 // --> 1790 // (csel x, (xor x, -1), cc ...) 1791 // 1792 // The latter will get matched to a CSINV instruction. 1793 1794 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 1795 SDValue LHS = Sel.getOperand(0); 1796 SDValue RHS = Sel.getOperand(1); 1797 SDValue TVal = Sel.getOperand(2); 1798 SDValue FVal = Sel.getOperand(3); 1799 SDLoc dl(Sel); 1800 1801 // FIXME: This could be generalized to non-integer comparisons. 1802 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 1803 return Op; 1804 1805 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 1806 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 1807 1808 // The values aren't constants, this isn't the pattern we're looking for. 1809 if (!CFVal || !CTVal) 1810 return Op; 1811 1812 // We can commute the SELECT_CC by inverting the condition. This 1813 // might be needed to make this fit into a CSINV pattern. 1814 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 1815 std::swap(TVal, FVal); 1816 std::swap(CTVal, CFVal); 1817 CC = ISD::getSetCCInverse(CC, true); 1818 } 1819 1820 // If the constants line up, perform the transform! 1821 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 1822 SDValue CCVal; 1823 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 1824 1825 FVal = Other; 1826 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 1827 DAG.getConstant(-1ULL, dl, Other.getValueType())); 1828 1829 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 1830 CCVal, Cmp); 1831 } 1832 1833 return Op; 1834 } 1835 1836 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 1837 EVT VT = Op.getValueType(); 1838 1839 // Let legalize expand this if it isn't a legal type yet. 1840 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 1841 return SDValue(); 1842 1843 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 1844 1845 unsigned Opc; 1846 bool ExtraOp = false; 1847 switch (Op.getOpcode()) { 1848 default: 1849 llvm_unreachable("Invalid code"); 1850 case ISD::ADDC: 1851 Opc = AArch64ISD::ADDS; 1852 break; 1853 case ISD::SUBC: 1854 Opc = AArch64ISD::SUBS; 1855 break; 1856 case ISD::ADDE: 1857 Opc = AArch64ISD::ADCS; 1858 ExtraOp = true; 1859 break; 1860 case ISD::SUBE: 1861 Opc = AArch64ISD::SBCS; 1862 ExtraOp = true; 1863 break; 1864 } 1865 1866 if (!ExtraOp) 1867 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 1868 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 1869 Op.getOperand(2)); 1870 } 1871 1872 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 1873 // Let legalize expand this if it isn't a legal type yet. 1874 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 1875 return SDValue(); 1876 1877 SDLoc dl(Op); 1878 AArch64CC::CondCode CC; 1879 // The actual operation that sets the overflow or carry flag. 1880 SDValue Value, Overflow; 1881 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 1882 1883 // We use 0 and 1 as false and true values. 1884 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 1885 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 1886 1887 // We use an inverted condition, because the conditional select is inverted 1888 // too. This will allow it to be selected to a single instruction: 1889 // CSINC Wd, WZR, WZR, invert(cond). 1890 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 1891 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 1892 CCVal, Overflow); 1893 1894 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 1895 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 1896 } 1897 1898 // Prefetch operands are: 1899 // 1: Address to prefetch 1900 // 2: bool isWrite 1901 // 3: int locality (0 = no locality ... 3 = extreme locality) 1902 // 4: bool isDataCache 1903 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 1904 SDLoc DL(Op); 1905 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 1906 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 1907 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 1908 1909 bool IsStream = !Locality; 1910 // When the locality number is set 1911 if (Locality) { 1912 // The front-end should have filtered out the out-of-range values 1913 assert(Locality <= 3 && "Prefetch locality out-of-range"); 1914 // The locality degree is the opposite of the cache speed. 1915 // Put the number the other way around. 1916 // The encoding starts at 0 for level 1 1917 Locality = 3 - Locality; 1918 } 1919 1920 // built the mask value encoding the expected behavior. 1921 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 1922 (!IsData << 3) | // IsDataCache bit 1923 (Locality << 1) | // Cache level bits 1924 (unsigned)IsStream; // Stream bit 1925 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 1926 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 1927 } 1928 1929 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 1930 SelectionDAG &DAG) const { 1931 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 1932 1933 RTLIB::Libcall LC; 1934 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 1935 1936 return LowerF128Call(Op, DAG, LC); 1937 } 1938 1939 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 1940 SelectionDAG &DAG) const { 1941 if (Op.getOperand(0).getValueType() != MVT::f128) { 1942 // It's legal except when f128 is involved 1943 return Op; 1944 } 1945 1946 RTLIB::Libcall LC; 1947 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 1948 1949 // FP_ROUND node has a second operand indicating whether it is known to be 1950 // precise. That doesn't take part in the LibCall so we can't directly use 1951 // LowerF128Call. 1952 SDValue SrcVal = Op.getOperand(0); 1953 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 1954 SDLoc(Op)).first; 1955 } 1956 1957 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 1958 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 1959 // Any additional optimization in this function should be recorded 1960 // in the cost tables. 1961 EVT InVT = Op.getOperand(0).getValueType(); 1962 EVT VT = Op.getValueType(); 1963 unsigned NumElts = InVT.getVectorNumElements(); 1964 1965 // f16 vectors are promoted to f32 before a conversion. 1966 if (InVT.getVectorElementType() == MVT::f16) { 1967 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 1968 SDLoc dl(Op); 1969 return DAG.getNode( 1970 Op.getOpcode(), dl, Op.getValueType(), 1971 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 1972 } 1973 1974 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 1975 SDLoc dl(Op); 1976 SDValue Cv = 1977 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 1978 Op.getOperand(0)); 1979 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 1980 } 1981 1982 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 1983 SDLoc dl(Op); 1984 MVT ExtVT = 1985 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 1986 VT.getVectorNumElements()); 1987 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 1988 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 1989 } 1990 1991 // Type changing conversions are illegal. 1992 return Op; 1993 } 1994 1995 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 1996 SelectionDAG &DAG) const { 1997 if (Op.getOperand(0).getValueType().isVector()) 1998 return LowerVectorFP_TO_INT(Op, DAG); 1999 2000 // f16 conversions are promoted to f32. 2001 if (Op.getOperand(0).getValueType() == MVT::f16) { 2002 SDLoc dl(Op); 2003 return DAG.getNode( 2004 Op.getOpcode(), dl, Op.getValueType(), 2005 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2006 } 2007 2008 if (Op.getOperand(0).getValueType() != MVT::f128) { 2009 // It's legal except when f128 is involved 2010 return Op; 2011 } 2012 2013 RTLIB::Libcall LC; 2014 if (Op.getOpcode() == ISD::FP_TO_SINT) 2015 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2016 else 2017 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2018 2019 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2020 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2021 } 2022 2023 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2024 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2025 // Any additional optimization in this function should be recorded 2026 // in the cost tables. 2027 EVT VT = Op.getValueType(); 2028 SDLoc dl(Op); 2029 SDValue In = Op.getOperand(0); 2030 EVT InVT = In.getValueType(); 2031 2032 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2033 MVT CastVT = 2034 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2035 InVT.getVectorNumElements()); 2036 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2037 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2038 } 2039 2040 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2041 unsigned CastOpc = 2042 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2043 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2044 In = DAG.getNode(CastOpc, dl, CastVT, In); 2045 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2046 } 2047 2048 return Op; 2049 } 2050 2051 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2052 SelectionDAG &DAG) const { 2053 if (Op.getValueType().isVector()) 2054 return LowerVectorINT_TO_FP(Op, DAG); 2055 2056 // f16 conversions are promoted to f32. 2057 if (Op.getValueType() == MVT::f16) { 2058 SDLoc dl(Op); 2059 return DAG.getNode( 2060 ISD::FP_ROUND, dl, MVT::f16, 2061 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2062 DAG.getIntPtrConstant(0, dl)); 2063 } 2064 2065 // i128 conversions are libcalls. 2066 if (Op.getOperand(0).getValueType() == MVT::i128) 2067 return SDValue(); 2068 2069 // Other conversions are legal, unless it's to the completely software-based 2070 // fp128. 2071 if (Op.getValueType() != MVT::f128) 2072 return Op; 2073 2074 RTLIB::Libcall LC; 2075 if (Op.getOpcode() == ISD::SINT_TO_FP) 2076 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2077 else 2078 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2079 2080 return LowerF128Call(Op, DAG, LC); 2081 } 2082 2083 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2084 SelectionDAG &DAG) const { 2085 // For iOS, we want to call an alternative entry point: __sincos_stret, 2086 // which returns the values in two S / D registers. 2087 SDLoc dl(Op); 2088 SDValue Arg = Op.getOperand(0); 2089 EVT ArgVT = Arg.getValueType(); 2090 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2091 2092 ArgListTy Args; 2093 ArgListEntry Entry; 2094 2095 Entry.Node = Arg; 2096 Entry.Ty = ArgTy; 2097 Entry.isSExt = false; 2098 Entry.isZExt = false; 2099 Args.push_back(Entry); 2100 2101 const char *LibcallName = 2102 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2103 SDValue Callee = 2104 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2105 2106 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 2107 TargetLowering::CallLoweringInfo CLI(DAG); 2108 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 2109 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0); 2110 2111 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2112 return CallResult.first; 2113 } 2114 2115 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2116 if (Op.getValueType() != MVT::f16) 2117 return SDValue(); 2118 2119 assert(Op.getOperand(0).getValueType() == MVT::i16); 2120 SDLoc DL(Op); 2121 2122 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2123 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2124 return SDValue( 2125 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2126 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2127 0); 2128 } 2129 2130 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2131 if (OrigVT.getSizeInBits() >= 64) 2132 return OrigVT; 2133 2134 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2135 2136 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2137 switch (OrigSimpleTy) { 2138 default: llvm_unreachable("Unexpected Vector Type"); 2139 case MVT::v2i8: 2140 case MVT::v2i16: 2141 return MVT::v2i32; 2142 case MVT::v4i8: 2143 return MVT::v4i16; 2144 } 2145 } 2146 2147 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2148 const EVT &OrigTy, 2149 const EVT &ExtTy, 2150 unsigned ExtOpcode) { 2151 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2152 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2153 // 64-bits we need to insert a new extension so that it will be 64-bits. 2154 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2155 if (OrigTy.getSizeInBits() >= 64) 2156 return N; 2157 2158 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2159 EVT NewVT = getExtensionTo64Bits(OrigTy); 2160 2161 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2162 } 2163 2164 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2165 bool isSigned) { 2166 EVT VT = N->getValueType(0); 2167 2168 if (N->getOpcode() != ISD::BUILD_VECTOR) 2169 return false; 2170 2171 for (const SDValue &Elt : N->op_values()) { 2172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2173 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 2174 unsigned HalfSize = EltSize / 2; 2175 if (isSigned) { 2176 if (!isIntN(HalfSize, C->getSExtValue())) 2177 return false; 2178 } else { 2179 if (!isUIntN(HalfSize, C->getZExtValue())) 2180 return false; 2181 } 2182 continue; 2183 } 2184 return false; 2185 } 2186 2187 return true; 2188 } 2189 2190 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2191 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2192 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2193 N->getOperand(0)->getValueType(0), 2194 N->getValueType(0), 2195 N->getOpcode()); 2196 2197 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2198 EVT VT = N->getValueType(0); 2199 SDLoc dl(N); 2200 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 2201 unsigned NumElts = VT.getVectorNumElements(); 2202 MVT TruncVT = MVT::getIntegerVT(EltSize); 2203 SmallVector<SDValue, 8> Ops; 2204 for (unsigned i = 0; i != NumElts; ++i) { 2205 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2206 const APInt &CInt = C->getAPIntValue(); 2207 // Element types smaller than 32 bits are not legal, so use i32 elements. 2208 // The values are implicitly truncated so sext vs. zext doesn't matter. 2209 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2210 } 2211 return DAG.getNode(ISD::BUILD_VECTOR, dl, 2212 MVT::getVectorVT(TruncVT, NumElts), Ops); 2213 } 2214 2215 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2216 if (N->getOpcode() == ISD::SIGN_EXTEND) 2217 return true; 2218 if (isExtendedBUILD_VECTOR(N, DAG, true)) 2219 return true; 2220 return false; 2221 } 2222 2223 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2224 if (N->getOpcode() == ISD::ZERO_EXTEND) 2225 return true; 2226 if (isExtendedBUILD_VECTOR(N, DAG, false)) 2227 return true; 2228 return false; 2229 } 2230 2231 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2232 unsigned Opcode = N->getOpcode(); 2233 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2234 SDNode *N0 = N->getOperand(0).getNode(); 2235 SDNode *N1 = N->getOperand(1).getNode(); 2236 return N0->hasOneUse() && N1->hasOneUse() && 2237 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2238 } 2239 return false; 2240 } 2241 2242 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2243 unsigned Opcode = N->getOpcode(); 2244 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2245 SDNode *N0 = N->getOperand(0).getNode(); 2246 SDNode *N1 = N->getOperand(1).getNode(); 2247 return N0->hasOneUse() && N1->hasOneUse() && 2248 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2249 } 2250 return false; 2251 } 2252 2253 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2254 // Multiplications are only custom-lowered for 128-bit vectors so that 2255 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2256 EVT VT = Op.getValueType(); 2257 assert(VT.is128BitVector() && VT.isInteger() && 2258 "unexpected type for custom-lowering ISD::MUL"); 2259 SDNode *N0 = Op.getOperand(0).getNode(); 2260 SDNode *N1 = Op.getOperand(1).getNode(); 2261 unsigned NewOpc = 0; 2262 bool isMLA = false; 2263 bool isN0SExt = isSignExtended(N0, DAG); 2264 bool isN1SExt = isSignExtended(N1, DAG); 2265 if (isN0SExt && isN1SExt) 2266 NewOpc = AArch64ISD::SMULL; 2267 else { 2268 bool isN0ZExt = isZeroExtended(N0, DAG); 2269 bool isN1ZExt = isZeroExtended(N1, DAG); 2270 if (isN0ZExt && isN1ZExt) 2271 NewOpc = AArch64ISD::UMULL; 2272 else if (isN1SExt || isN1ZExt) { 2273 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2274 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2275 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2276 NewOpc = AArch64ISD::SMULL; 2277 isMLA = true; 2278 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2279 NewOpc = AArch64ISD::UMULL; 2280 isMLA = true; 2281 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2282 std::swap(N0, N1); 2283 NewOpc = AArch64ISD::UMULL; 2284 isMLA = true; 2285 } 2286 } 2287 2288 if (!NewOpc) { 2289 if (VT == MVT::v2i64) 2290 // Fall through to expand this. It is not legal. 2291 return SDValue(); 2292 else 2293 // Other vector multiplications are legal. 2294 return Op; 2295 } 2296 } 2297 2298 // Legalize to a S/UMULL instruction 2299 SDLoc DL(Op); 2300 SDValue Op0; 2301 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2302 if (!isMLA) { 2303 Op0 = skipExtensionForVectorMULL(N0, DAG); 2304 assert(Op0.getValueType().is64BitVector() && 2305 Op1.getValueType().is64BitVector() && 2306 "unexpected types for extended operands to VMULL"); 2307 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2308 } 2309 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2310 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2311 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2312 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2313 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2314 EVT Op1VT = Op1.getValueType(); 2315 return DAG.getNode(N0->getOpcode(), DL, VT, 2316 DAG.getNode(NewOpc, DL, VT, 2317 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2318 DAG.getNode(NewOpc, DL, VT, 2319 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2320 } 2321 2322 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2323 SelectionDAG &DAG) const { 2324 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2325 SDLoc dl(Op); 2326 switch (IntNo) { 2327 default: return SDValue(); // Don't custom lower most intrinsics. 2328 case Intrinsic::aarch64_thread_pointer: { 2329 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2330 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2331 } 2332 case Intrinsic::aarch64_neon_smax: 2333 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2334 Op.getOperand(1), Op.getOperand(2)); 2335 case Intrinsic::aarch64_neon_umax: 2336 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2337 Op.getOperand(1), Op.getOperand(2)); 2338 case Intrinsic::aarch64_neon_smin: 2339 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2340 Op.getOperand(1), Op.getOperand(2)); 2341 case Intrinsic::aarch64_neon_umin: 2342 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2343 Op.getOperand(1), Op.getOperand(2)); 2344 } 2345 } 2346 2347 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2348 SelectionDAG &DAG) const { 2349 switch (Op.getOpcode()) { 2350 default: 2351 llvm_unreachable("unimplemented operand"); 2352 return SDValue(); 2353 case ISD::BITCAST: 2354 return LowerBITCAST(Op, DAG); 2355 case ISD::GlobalAddress: 2356 return LowerGlobalAddress(Op, DAG); 2357 case ISD::GlobalTLSAddress: 2358 return LowerGlobalTLSAddress(Op, DAG); 2359 case ISD::SETCC: 2360 return LowerSETCC(Op, DAG); 2361 case ISD::BR_CC: 2362 return LowerBR_CC(Op, DAG); 2363 case ISD::SELECT: 2364 return LowerSELECT(Op, DAG); 2365 case ISD::SELECT_CC: 2366 return LowerSELECT_CC(Op, DAG); 2367 case ISD::JumpTable: 2368 return LowerJumpTable(Op, DAG); 2369 case ISD::ConstantPool: 2370 return LowerConstantPool(Op, DAG); 2371 case ISD::BlockAddress: 2372 return LowerBlockAddress(Op, DAG); 2373 case ISD::VASTART: 2374 return LowerVASTART(Op, DAG); 2375 case ISD::VACOPY: 2376 return LowerVACOPY(Op, DAG); 2377 case ISD::VAARG: 2378 return LowerVAARG(Op, DAG); 2379 case ISD::ADDC: 2380 case ISD::ADDE: 2381 case ISD::SUBC: 2382 case ISD::SUBE: 2383 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2384 case ISD::SADDO: 2385 case ISD::UADDO: 2386 case ISD::SSUBO: 2387 case ISD::USUBO: 2388 case ISD::SMULO: 2389 case ISD::UMULO: 2390 return LowerXALUO(Op, DAG); 2391 case ISD::FADD: 2392 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2393 case ISD::FSUB: 2394 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2395 case ISD::FMUL: 2396 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2397 case ISD::FDIV: 2398 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2399 case ISD::FP_ROUND: 2400 return LowerFP_ROUND(Op, DAG); 2401 case ISD::FP_EXTEND: 2402 return LowerFP_EXTEND(Op, DAG); 2403 case ISD::FRAMEADDR: 2404 return LowerFRAMEADDR(Op, DAG); 2405 case ISD::RETURNADDR: 2406 return LowerRETURNADDR(Op, DAG); 2407 case ISD::INSERT_VECTOR_ELT: 2408 return LowerINSERT_VECTOR_ELT(Op, DAG); 2409 case ISD::EXTRACT_VECTOR_ELT: 2410 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2411 case ISD::BUILD_VECTOR: 2412 return LowerBUILD_VECTOR(Op, DAG); 2413 case ISD::VECTOR_SHUFFLE: 2414 return LowerVECTOR_SHUFFLE(Op, DAG); 2415 case ISD::EXTRACT_SUBVECTOR: 2416 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2417 case ISD::SRA: 2418 case ISD::SRL: 2419 case ISD::SHL: 2420 return LowerVectorSRA_SRL_SHL(Op, DAG); 2421 case ISD::SHL_PARTS: 2422 return LowerShiftLeftParts(Op, DAG); 2423 case ISD::SRL_PARTS: 2424 case ISD::SRA_PARTS: 2425 return LowerShiftRightParts(Op, DAG); 2426 case ISD::CTPOP: 2427 return LowerCTPOP(Op, DAG); 2428 case ISD::FCOPYSIGN: 2429 return LowerFCOPYSIGN(Op, DAG); 2430 case ISD::AND: 2431 return LowerAND(Op, DAG); 2432 case ISD::OR: 2433 return LowerOR(Op, DAG); 2434 case ISD::XOR: 2435 return LowerXOR(Op, DAG); 2436 case ISD::PREFETCH: 2437 return LowerPREFETCH(Op, DAG); 2438 case ISD::SINT_TO_FP: 2439 case ISD::UINT_TO_FP: 2440 return LowerINT_TO_FP(Op, DAG); 2441 case ISD::FP_TO_SINT: 2442 case ISD::FP_TO_UINT: 2443 return LowerFP_TO_INT(Op, DAG); 2444 case ISD::FSINCOS: 2445 return LowerFSINCOS(Op, DAG); 2446 case ISD::MUL: 2447 return LowerMUL(Op, DAG); 2448 case ISD::INTRINSIC_WO_CHAIN: 2449 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2450 } 2451 } 2452 2453 //===----------------------------------------------------------------------===// 2454 // Calling Convention Implementation 2455 //===----------------------------------------------------------------------===// 2456 2457 #include "AArch64GenCallingConv.inc" 2458 2459 /// Selects the correct CCAssignFn for a given CallingConvention value. 2460 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2461 bool IsVarArg) const { 2462 switch (CC) { 2463 default: 2464 llvm_unreachable("Unsupported calling convention."); 2465 case CallingConv::WebKit_JS: 2466 return CC_AArch64_WebKit_JS; 2467 case CallingConv::GHC: 2468 return CC_AArch64_GHC; 2469 case CallingConv::C: 2470 case CallingConv::Fast: 2471 case CallingConv::PreserveMost: 2472 case CallingConv::CXX_FAST_TLS: 2473 if (!Subtarget->isTargetDarwin()) 2474 return CC_AArch64_AAPCS; 2475 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2476 } 2477 } 2478 2479 SDValue AArch64TargetLowering::LowerFormalArguments( 2480 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2481 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG, 2482 SmallVectorImpl<SDValue> &InVals) const { 2483 MachineFunction &MF = DAG.getMachineFunction(); 2484 MachineFrameInfo *MFI = MF.getFrameInfo(); 2485 2486 // Assign locations to all of the incoming arguments. 2487 SmallVector<CCValAssign, 16> ArgLocs; 2488 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2489 *DAG.getContext()); 2490 2491 // At this point, Ins[].VT may already be promoted to i32. To correctly 2492 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2493 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2494 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2495 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2496 // LocVT. 2497 unsigned NumArgs = Ins.size(); 2498 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2499 unsigned CurArgIdx = 0; 2500 for (unsigned i = 0; i != NumArgs; ++i) { 2501 MVT ValVT = Ins[i].VT; 2502 if (Ins[i].isOrigArg()) { 2503 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2504 CurArgIdx = Ins[i].getOrigArgIndex(); 2505 2506 // Get type of the original argument. 2507 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2508 /*AllowUnknown*/ true); 2509 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2510 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2511 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2512 ValVT = MVT::i8; 2513 else if (ActualMVT == MVT::i16) 2514 ValVT = MVT::i16; 2515 } 2516 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2517 bool Res = 2518 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2519 assert(!Res && "Call operand has unhandled type"); 2520 (void)Res; 2521 } 2522 assert(ArgLocs.size() == Ins.size()); 2523 SmallVector<SDValue, 16> ArgValues; 2524 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2525 CCValAssign &VA = ArgLocs[i]; 2526 2527 if (Ins[i].Flags.isByVal()) { 2528 // Byval is used for HFAs in the PCS, but the system should work in a 2529 // non-compliant manner for larger structs. 2530 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2531 int Size = Ins[i].Flags.getByValSize(); 2532 unsigned NumRegs = (Size + 7) / 8; 2533 2534 // FIXME: This works on big-endian for composite byvals, which are the common 2535 // case. It should also work for fundamental types too. 2536 unsigned FrameIdx = 2537 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2538 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2539 InVals.push_back(FrameIdxN); 2540 2541 continue; 2542 } 2543 2544 if (VA.isRegLoc()) { 2545 // Arguments stored in registers. 2546 EVT RegVT = VA.getLocVT(); 2547 2548 SDValue ArgValue; 2549 const TargetRegisterClass *RC; 2550 2551 if (RegVT == MVT::i32) 2552 RC = &AArch64::GPR32RegClass; 2553 else if (RegVT == MVT::i64) 2554 RC = &AArch64::GPR64RegClass; 2555 else if (RegVT == MVT::f16) 2556 RC = &AArch64::FPR16RegClass; 2557 else if (RegVT == MVT::f32) 2558 RC = &AArch64::FPR32RegClass; 2559 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2560 RC = &AArch64::FPR64RegClass; 2561 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2562 RC = &AArch64::FPR128RegClass; 2563 else 2564 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2565 2566 // Transform the arguments in physical registers into virtual ones. 2567 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2568 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2569 2570 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2571 // to 64 bits. Insert an assert[sz]ext to capture this, then 2572 // truncate to the right size. 2573 switch (VA.getLocInfo()) { 2574 default: 2575 llvm_unreachable("Unknown loc info!"); 2576 case CCValAssign::Full: 2577 break; 2578 case CCValAssign::BCvt: 2579 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2580 break; 2581 case CCValAssign::AExt: 2582 case CCValAssign::SExt: 2583 case CCValAssign::ZExt: 2584 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2585 // nodes after our lowering. 2586 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2587 break; 2588 } 2589 2590 InVals.push_back(ArgValue); 2591 2592 } else { // VA.isRegLoc() 2593 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2594 unsigned ArgOffset = VA.getLocMemOffset(); 2595 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2596 2597 uint32_t BEAlign = 0; 2598 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2599 !Ins[i].Flags.isInConsecutiveRegs()) 2600 BEAlign = 8 - ArgSize; 2601 2602 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2603 2604 // Create load nodes to retrieve arguments from the stack. 2605 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2606 SDValue ArgValue; 2607 2608 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2609 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2610 MVT MemVT = VA.getValVT(); 2611 2612 switch (VA.getLocInfo()) { 2613 default: 2614 break; 2615 case CCValAssign::BCvt: 2616 MemVT = VA.getLocVT(); 2617 break; 2618 case CCValAssign::SExt: 2619 ExtType = ISD::SEXTLOAD; 2620 break; 2621 case CCValAssign::ZExt: 2622 ExtType = ISD::ZEXTLOAD; 2623 break; 2624 case CCValAssign::AExt: 2625 ExtType = ISD::EXTLOAD; 2626 break; 2627 } 2628 2629 ArgValue = DAG.getExtLoad( 2630 ExtType, DL, VA.getLocVT(), Chain, FIN, 2631 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2632 MemVT, false, false, false, 0); 2633 2634 InVals.push_back(ArgValue); 2635 } 2636 } 2637 2638 // varargs 2639 if (isVarArg) { 2640 if (!Subtarget->isTargetDarwin()) { 2641 // The AAPCS variadic function ABI is identical to the non-variadic 2642 // one. As a result there may be more arguments in registers and we should 2643 // save them for future reference. 2644 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2645 } 2646 2647 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 2648 // This will point to the next argument passed via stack. 2649 unsigned StackOffset = CCInfo.getNextStackOffset(); 2650 // We currently pass all varargs at 8-byte alignment. 2651 StackOffset = ((StackOffset + 7) & ~7); 2652 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true)); 2653 } 2654 2655 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2656 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2657 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2658 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2659 // This is a non-standard ABI so by fiat I say we're allowed to make full 2660 // use of the stack area to be popped, which must be aligned to 16 bytes in 2661 // any case: 2662 StackArgSize = alignTo(StackArgSize, 16); 2663 2664 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2665 // a multiple of 16. 2666 FuncInfo->setArgumentStackToRestore(StackArgSize); 2667 2668 // This realignment carries over to the available bytes below. Our own 2669 // callers will guarantee the space is free by giving an aligned value to 2670 // CALLSEQ_START. 2671 } 2672 // Even if we're not expected to free up the space, it's useful to know how 2673 // much is there while considering tail calls (because we can reuse it). 2674 FuncInfo->setBytesInStackArgArea(StackArgSize); 2675 2676 return Chain; 2677 } 2678 2679 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2680 SelectionDAG &DAG, SDLoc DL, 2681 SDValue &Chain) const { 2682 MachineFunction &MF = DAG.getMachineFunction(); 2683 MachineFrameInfo *MFI = MF.getFrameInfo(); 2684 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2685 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2686 2687 SmallVector<SDValue, 8> MemOps; 2688 2689 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2690 AArch64::X3, AArch64::X4, AArch64::X5, 2691 AArch64::X6, AArch64::X7 }; 2692 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2693 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2694 2695 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2696 int GPRIdx = 0; 2697 if (GPRSaveSize != 0) { 2698 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false); 2699 2700 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2701 2702 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2703 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2704 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2705 SDValue Store = DAG.getStore( 2706 Val.getValue(1), DL, Val, FIN, 2707 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false, 2708 false, 0); 2709 MemOps.push_back(Store); 2710 FIN = 2711 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2712 } 2713 } 2714 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2715 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2716 2717 if (Subtarget->hasFPARMv8()) { 2718 static const MCPhysReg FPRArgRegs[] = { 2719 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2720 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2721 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2722 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2723 2724 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2725 int FPRIdx = 0; 2726 if (FPRSaveSize != 0) { 2727 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false); 2728 2729 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2730 2731 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2732 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2733 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2734 2735 SDValue Store = DAG.getStore( 2736 Val.getValue(1), DL, Val, FIN, 2737 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16), 2738 false, false, 0); 2739 MemOps.push_back(Store); 2740 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 2741 DAG.getConstant(16, DL, PtrVT)); 2742 } 2743 } 2744 FuncInfo->setVarArgsFPRIndex(FPRIdx); 2745 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 2746 } 2747 2748 if (!MemOps.empty()) { 2749 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2750 } 2751 } 2752 2753 /// LowerCallResult - Lower the result values of a call into the 2754 /// appropriate copies out of appropriate physical registers. 2755 SDValue AArch64TargetLowering::LowerCallResult( 2756 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2757 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG, 2758 SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2759 SDValue ThisVal) const { 2760 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 2761 ? RetCC_AArch64_WebKit_JS 2762 : RetCC_AArch64_AAPCS; 2763 // Assign locations to each value returned by this call. 2764 SmallVector<CCValAssign, 16> RVLocs; 2765 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2766 *DAG.getContext()); 2767 CCInfo.AnalyzeCallResult(Ins, RetCC); 2768 2769 // Copy all of the result registers out of their specified physreg. 2770 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2771 CCValAssign VA = RVLocs[i]; 2772 2773 // Pass 'this' value directly from the argument to return value, to avoid 2774 // reg unit interference 2775 if (i == 0 && isThisReturn) { 2776 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 2777 "unexpected return calling convention register assignment"); 2778 InVals.push_back(ThisVal); 2779 continue; 2780 } 2781 2782 SDValue Val = 2783 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2784 Chain = Val.getValue(1); 2785 InFlag = Val.getValue(2); 2786 2787 switch (VA.getLocInfo()) { 2788 default: 2789 llvm_unreachable("Unknown loc info!"); 2790 case CCValAssign::Full: 2791 break; 2792 case CCValAssign::BCvt: 2793 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2794 break; 2795 } 2796 2797 InVals.push_back(Val); 2798 } 2799 2800 return Chain; 2801 } 2802 2803 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 2804 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2805 bool isCalleeStructRet, bool isCallerStructRet, 2806 const SmallVectorImpl<ISD::OutputArg> &Outs, 2807 const SmallVectorImpl<SDValue> &OutVals, 2808 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2809 // For CallingConv::C this function knows whether the ABI needs 2810 // changing. That's not true for other conventions so they will have to opt in 2811 // manually. 2812 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 2813 return false; 2814 2815 const MachineFunction &MF = DAG.getMachineFunction(); 2816 const Function *CallerF = MF.getFunction(); 2817 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2818 bool CCMatch = CallerCC == CalleeCC; 2819 2820 // Disable tailcall for CXX_FAST_TLS when callee and caller have different 2821 // calling conventions, given that CXX_FAST_TLS has a bigger CSR set. 2822 if (!CCMatch && 2823 (CallerCC == CallingConv::CXX_FAST_TLS || 2824 CalleeCC == CallingConv::CXX_FAST_TLS)) 2825 return false; 2826 2827 // Byval parameters hand the function a pointer directly into the stack area 2828 // we want to reuse during a tail call. Working around this *is* possible (see 2829 // X86) but less efficient and uglier in LowerCall. 2830 for (Function::const_arg_iterator i = CallerF->arg_begin(), 2831 e = CallerF->arg_end(); 2832 i != e; ++i) 2833 if (i->hasByValAttr()) 2834 return false; 2835 2836 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2837 return IsTailCallConvention(CalleeCC) && CCMatch; 2838 } 2839 2840 // Externally-defined functions with weak linkage should not be 2841 // tail-called on AArch64 when the OS does not support dynamic 2842 // pre-emption of symbols, as the AAELF spec requires normal calls 2843 // to undefined weak functions to be replaced with a NOP or jump to the 2844 // next instruction. The behaviour of branch instructions in this 2845 // situation (as used for tail calls) is implementation-defined, so we 2846 // cannot rely on the linker replacing the tail call with a return. 2847 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2848 const GlobalValue *GV = G->getGlobal(); 2849 const Triple &TT = getTargetMachine().getTargetTriple(); 2850 if (GV->hasExternalWeakLinkage() && 2851 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2852 return false; 2853 } 2854 2855 // Now we search for cases where we can use a tail call without changing the 2856 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 2857 // concept. 2858 2859 // I want anyone implementing a new calling convention to think long and hard 2860 // about this assert. 2861 assert((!isVarArg || CalleeCC == CallingConv::C) && 2862 "Unexpected variadic calling convention"); 2863 2864 if (isVarArg && !Outs.empty()) { 2865 // At least two cases here: if caller is fastcc then we can't have any 2866 // memory arguments (we'd be expected to clean up the stack afterwards). If 2867 // caller is C then we could potentially use its argument area. 2868 2869 // FIXME: for now we take the most conservative of these in both cases: 2870 // disallow all variadic memory operands. 2871 SmallVector<CCValAssign, 16> ArgLocs; 2872 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2873 *DAG.getContext()); 2874 2875 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 2876 for (const CCValAssign &ArgLoc : ArgLocs) 2877 if (!ArgLoc.isRegLoc()) 2878 return false; 2879 } 2880 2881 // If the calling conventions do not match, then we'd better make sure the 2882 // results are returned in the same way as what the caller expects. 2883 if (!CCMatch) { 2884 SmallVector<CCValAssign, 16> RVLocs1; 2885 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1, 2886 *DAG.getContext()); 2887 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg)); 2888 2889 SmallVector<CCValAssign, 16> RVLocs2; 2890 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2, 2891 *DAG.getContext()); 2892 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg)); 2893 2894 if (RVLocs1.size() != RVLocs2.size()) 2895 return false; 2896 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2897 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2898 return false; 2899 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2900 return false; 2901 if (RVLocs1[i].isRegLoc()) { 2902 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2903 return false; 2904 } else { 2905 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2906 return false; 2907 } 2908 } 2909 } 2910 2911 // Nothing more to check if the callee is taking no arguments 2912 if (Outs.empty()) 2913 return true; 2914 2915 SmallVector<CCValAssign, 16> ArgLocs; 2916 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs, 2917 *DAG.getContext()); 2918 2919 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2920 2921 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2922 2923 // If the stack arguments for this call would fit into our own save area then 2924 // the call can be made tail. 2925 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea(); 2926 } 2927 2928 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 2929 SelectionDAG &DAG, 2930 MachineFrameInfo *MFI, 2931 int ClobberedFI) const { 2932 SmallVector<SDValue, 8> ArgChains; 2933 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI); 2934 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1; 2935 2936 // Include the original chain at the beginning of the list. When this is 2937 // used by target LowerCall hooks, this helps legalize find the 2938 // CALLSEQ_BEGIN node. 2939 ArgChains.push_back(Chain); 2940 2941 // Add a chain value for each stack argument corresponding 2942 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 2943 UE = DAG.getEntryNode().getNode()->use_end(); 2944 U != UE; ++U) 2945 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 2946 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 2947 if (FI->getIndex() < 0) { 2948 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex()); 2949 int64_t InLastByte = InFirstByte; 2950 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1; 2951 2952 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 2953 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 2954 ArgChains.push_back(SDValue(L, 1)); 2955 } 2956 2957 // Build a tokenfactor for all the chains. 2958 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 2959 } 2960 2961 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 2962 bool TailCallOpt) const { 2963 return CallCC == CallingConv::Fast && TailCallOpt; 2964 } 2965 2966 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const { 2967 return CallCC == CallingConv::Fast || 2968 CallCC == CallingConv::PreserveMost; 2969 } 2970 2971 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 2972 /// and add input and output parameter nodes. 2973 SDValue 2974 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 2975 SmallVectorImpl<SDValue> &InVals) const { 2976 SelectionDAG &DAG = CLI.DAG; 2977 SDLoc &DL = CLI.DL; 2978 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2979 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2980 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2981 SDValue Chain = CLI.Chain; 2982 SDValue Callee = CLI.Callee; 2983 bool &IsTailCall = CLI.IsTailCall; 2984 CallingConv::ID CallConv = CLI.CallConv; 2985 bool IsVarArg = CLI.IsVarArg; 2986 2987 MachineFunction &MF = DAG.getMachineFunction(); 2988 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 2989 bool IsThisReturn = false; 2990 2991 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2992 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2993 bool IsSibCall = false; 2994 2995 if (IsTailCall) { 2996 // Check if it's really possible to do a tail call. 2997 IsTailCall = isEligibleForTailCallOptimization( 2998 Callee, CallConv, IsVarArg, IsStructRet, 2999 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG); 3000 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall()) 3001 report_fatal_error("failed to perform tail call elimination on a call " 3002 "site marked musttail"); 3003 3004 // A sibling call is one where we're under the usual C ABI and not planning 3005 // to change that but can still do a tail call: 3006 if (!TailCallOpt && IsTailCall) 3007 IsSibCall = true; 3008 3009 if (IsTailCall) 3010 ++NumTailCalls; 3011 } 3012 3013 // Analyze operands of the call, assigning locations to each operand. 3014 SmallVector<CCValAssign, 16> ArgLocs; 3015 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3016 *DAG.getContext()); 3017 3018 if (IsVarArg) { 3019 // Handle fixed and variable vector arguments differently. 3020 // Variable vector arguments always go into memory. 3021 unsigned NumArgs = Outs.size(); 3022 3023 for (unsigned i = 0; i != NumArgs; ++i) { 3024 MVT ArgVT = Outs[i].VT; 3025 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3026 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3027 /*IsVarArg=*/ !Outs[i].IsFixed); 3028 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3029 assert(!Res && "Call operand has unhandled type"); 3030 (void)Res; 3031 } 3032 } else { 3033 // At this point, Outs[].VT may already be promoted to i32. To correctly 3034 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3035 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3036 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3037 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3038 // LocVT. 3039 unsigned NumArgs = Outs.size(); 3040 for (unsigned i = 0; i != NumArgs; ++i) { 3041 MVT ValVT = Outs[i].VT; 3042 // Get type of the original argument. 3043 EVT ActualVT = getValueType(DAG.getDataLayout(), 3044 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3045 /*AllowUnknown*/ true); 3046 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3047 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3048 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3049 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3050 ValVT = MVT::i8; 3051 else if (ActualMVT == MVT::i16) 3052 ValVT = MVT::i16; 3053 3054 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3055 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3056 assert(!Res && "Call operand has unhandled type"); 3057 (void)Res; 3058 } 3059 } 3060 3061 // Get a count of how many bytes are to be pushed on the stack. 3062 unsigned NumBytes = CCInfo.getNextStackOffset(); 3063 3064 if (IsSibCall) { 3065 // Since we're not changing the ABI to make this a tail call, the memory 3066 // operands are already available in the caller's incoming argument space. 3067 NumBytes = 0; 3068 } 3069 3070 // FPDiff is the byte offset of the call's argument area from the callee's. 3071 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3072 // by this amount for a tail call. In a sibling call it must be 0 because the 3073 // caller will deallocate the entire stack and the callee still expects its 3074 // arguments to begin at SP+0. Completely unused for non-tail calls. 3075 int FPDiff = 0; 3076 3077 if (IsTailCall && !IsSibCall) { 3078 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3079 3080 // Since callee will pop argument stack as a tail call, we must keep the 3081 // popped size 16-byte aligned. 3082 NumBytes = alignTo(NumBytes, 16); 3083 3084 // FPDiff will be negative if this tail call requires more space than we 3085 // would automatically have in our incoming argument space. Positive if we 3086 // can actually shrink the stack. 3087 FPDiff = NumReusableBytes - NumBytes; 3088 3089 // The stack pointer must be 16-byte aligned at all times it's used for a 3090 // memory operation, which in practice means at *all* times and in 3091 // particular across call boundaries. Therefore our own arguments started at 3092 // a 16-byte aligned SP and the delta applied for the tail call should 3093 // satisfy the same constraint. 3094 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3095 } 3096 3097 // Adjust the stack pointer for the new arguments... 3098 // These operations are automatically eliminated by the prolog/epilog pass 3099 if (!IsSibCall) 3100 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, 3101 true), 3102 DL); 3103 3104 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3105 getPointerTy(DAG.getDataLayout())); 3106 3107 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3108 SmallVector<SDValue, 8> MemOpChains; 3109 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3110 3111 // Walk the register/memloc assignments, inserting copies/loads. 3112 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3113 ++i, ++realArgIdx) { 3114 CCValAssign &VA = ArgLocs[i]; 3115 SDValue Arg = OutVals[realArgIdx]; 3116 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3117 3118 // Promote the value if needed. 3119 switch (VA.getLocInfo()) { 3120 default: 3121 llvm_unreachable("Unknown loc info!"); 3122 case CCValAssign::Full: 3123 break; 3124 case CCValAssign::SExt: 3125 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3126 break; 3127 case CCValAssign::ZExt: 3128 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3129 break; 3130 case CCValAssign::AExt: 3131 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3132 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3133 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3134 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3135 } 3136 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3137 break; 3138 case CCValAssign::BCvt: 3139 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3140 break; 3141 case CCValAssign::FPExt: 3142 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3143 break; 3144 } 3145 3146 if (VA.isRegLoc()) { 3147 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) { 3148 assert(VA.getLocVT() == MVT::i64 && 3149 "unexpected calling convention register assignment"); 3150 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3151 "unexpected use of 'returned'"); 3152 IsThisReturn = true; 3153 } 3154 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3155 } else { 3156 assert(VA.isMemLoc()); 3157 3158 SDValue DstAddr; 3159 MachinePointerInfo DstInfo; 3160 3161 // FIXME: This works on big-endian for composite byvals, which are the 3162 // common case. It should also work for fundamental types too. 3163 uint32_t BEAlign = 0; 3164 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3165 : VA.getValVT().getSizeInBits(); 3166 OpSize = (OpSize + 7) / 8; 3167 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3168 !Flags.isInConsecutiveRegs()) { 3169 if (OpSize < 8) 3170 BEAlign = 8 - OpSize; 3171 } 3172 unsigned LocMemOffset = VA.getLocMemOffset(); 3173 int32_t Offset = LocMemOffset + BEAlign; 3174 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3175 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3176 3177 if (IsTailCall) { 3178 Offset = Offset + FPDiff; 3179 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 3180 3181 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3182 DstInfo = 3183 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3184 3185 // Make sure any stack arguments overlapping with where we're storing 3186 // are loaded before this eventual operation. Otherwise they'll be 3187 // clobbered. 3188 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3189 } else { 3190 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3191 3192 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3193 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3194 LocMemOffset); 3195 } 3196 3197 if (Outs[i].Flags.isByVal()) { 3198 SDValue SizeNode = 3199 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3200 SDValue Cpy = DAG.getMemcpy( 3201 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3202 /*isVol = */ false, /*AlwaysInline = */ false, 3203 /*isTailCall = */ false, 3204 DstInfo, MachinePointerInfo()); 3205 3206 MemOpChains.push_back(Cpy); 3207 } else { 3208 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3209 // promoted to a legal register type i32, we should truncate Arg back to 3210 // i1/i8/i16. 3211 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3212 VA.getValVT() == MVT::i16) 3213 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3214 3215 SDValue Store = 3216 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0); 3217 MemOpChains.push_back(Store); 3218 } 3219 } 3220 } 3221 3222 if (!MemOpChains.empty()) 3223 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3224 3225 // Build a sequence of copy-to-reg nodes chained together with token chain 3226 // and flag operands which copy the outgoing args into the appropriate regs. 3227 SDValue InFlag; 3228 for (auto &RegToPass : RegsToPass) { 3229 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3230 RegToPass.second, InFlag); 3231 InFlag = Chain.getValue(1); 3232 } 3233 3234 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3235 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3236 // node so that legalize doesn't hack it. 3237 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3238 Subtarget->isTargetMachO()) { 3239 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3240 const GlobalValue *GV = G->getGlobal(); 3241 bool InternalLinkage = GV->hasInternalLinkage(); 3242 if (InternalLinkage) 3243 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3244 else { 3245 Callee = 3246 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3247 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3248 } 3249 } else if (ExternalSymbolSDNode *S = 3250 dyn_cast<ExternalSymbolSDNode>(Callee)) { 3251 const char *Sym = S->getSymbol(); 3252 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3253 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3254 } 3255 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3256 const GlobalValue *GV = G->getGlobal(); 3257 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3258 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3259 const char *Sym = S->getSymbol(); 3260 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3261 } 3262 3263 // We don't usually want to end the call-sequence here because we would tidy 3264 // the frame up *after* the call, however in the ABI-changing tail-call case 3265 // we've carefully laid out the parameters so that when sp is reset they'll be 3266 // in the correct location. 3267 if (IsTailCall && !IsSibCall) { 3268 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3269 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3270 InFlag = Chain.getValue(1); 3271 } 3272 3273 std::vector<SDValue> Ops; 3274 Ops.push_back(Chain); 3275 Ops.push_back(Callee); 3276 3277 if (IsTailCall) { 3278 // Each tail call may have to adjust the stack by a different amount, so 3279 // this information must travel along with the operation for eventual 3280 // consumption by emitEpilogue. 3281 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3282 } 3283 3284 // Add argument registers to the end of the list so that they are known live 3285 // into the call. 3286 for (auto &RegToPass : RegsToPass) 3287 Ops.push_back(DAG.getRegister(RegToPass.first, 3288 RegToPass.second.getValueType())); 3289 3290 // Add a register mask operand representing the call-preserved registers. 3291 const uint32_t *Mask; 3292 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3293 if (IsThisReturn) { 3294 // For 'this' returns, use the X0-preserving mask if applicable 3295 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3296 if (!Mask) { 3297 IsThisReturn = false; 3298 Mask = TRI->getCallPreservedMask(MF, CallConv); 3299 } 3300 } else 3301 Mask = TRI->getCallPreservedMask(MF, CallConv); 3302 3303 assert(Mask && "Missing call preserved mask for calling convention"); 3304 Ops.push_back(DAG.getRegisterMask(Mask)); 3305 3306 if (InFlag.getNode()) 3307 Ops.push_back(InFlag); 3308 3309 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3310 3311 // If we're doing a tall call, use a TC_RETURN here rather than an 3312 // actual call instruction. 3313 if (IsTailCall) { 3314 MF.getFrameInfo()->setHasTailCall(); 3315 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3316 } 3317 3318 // Returns a chain and a flag for retval copy to use. 3319 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3320 InFlag = Chain.getValue(1); 3321 3322 uint64_t CalleePopBytes = 3323 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3324 3325 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3326 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3327 InFlag, DL); 3328 if (!Ins.empty()) 3329 InFlag = Chain.getValue(1); 3330 3331 // Handle result values, copying them out of physregs into vregs that we 3332 // return. 3333 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3334 InVals, IsThisReturn, 3335 IsThisReturn ? OutVals[0] : SDValue()); 3336 } 3337 3338 bool AArch64TargetLowering::CanLowerReturn( 3339 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3340 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3341 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3342 ? RetCC_AArch64_WebKit_JS 3343 : RetCC_AArch64_AAPCS; 3344 SmallVector<CCValAssign, 16> RVLocs; 3345 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3346 return CCInfo.CheckReturn(Outs, RetCC); 3347 } 3348 3349 SDValue 3350 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3351 bool isVarArg, 3352 const SmallVectorImpl<ISD::OutputArg> &Outs, 3353 const SmallVectorImpl<SDValue> &OutVals, 3354 SDLoc DL, SelectionDAG &DAG) const { 3355 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3356 ? RetCC_AArch64_WebKit_JS 3357 : RetCC_AArch64_AAPCS; 3358 SmallVector<CCValAssign, 16> RVLocs; 3359 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3360 *DAG.getContext()); 3361 CCInfo.AnalyzeReturn(Outs, RetCC); 3362 3363 // Copy the result values into the output registers. 3364 SDValue Flag; 3365 SmallVector<SDValue, 4> RetOps(1, Chain); 3366 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3367 ++i, ++realRVLocIdx) { 3368 CCValAssign &VA = RVLocs[i]; 3369 assert(VA.isRegLoc() && "Can only return in registers!"); 3370 SDValue Arg = OutVals[realRVLocIdx]; 3371 3372 switch (VA.getLocInfo()) { 3373 default: 3374 llvm_unreachable("Unknown loc info!"); 3375 case CCValAssign::Full: 3376 if (Outs[i].ArgVT == MVT::i1) { 3377 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3378 // value. This is strictly redundant on Darwin (which uses "zeroext 3379 // i1"), but will be optimised out before ISel. 3380 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3381 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3382 } 3383 break; 3384 case CCValAssign::BCvt: 3385 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3386 break; 3387 } 3388 3389 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3390 Flag = Chain.getValue(1); 3391 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3392 } 3393 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3394 const MCPhysReg *I = 3395 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3396 if (I) { 3397 for (; *I; ++I) { 3398 if (AArch64::GPR64RegClass.contains(*I)) 3399 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3400 else if (AArch64::FPR64RegClass.contains(*I)) 3401 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3402 else 3403 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3404 } 3405 } 3406 3407 RetOps[0] = Chain; // Update chain. 3408 3409 // Add the flag if we have it. 3410 if (Flag.getNode()) 3411 RetOps.push_back(Flag); 3412 3413 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3414 } 3415 3416 //===----------------------------------------------------------------------===// 3417 // Other Lowering Code 3418 //===----------------------------------------------------------------------===// 3419 3420 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3421 SelectionDAG &DAG) const { 3422 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3423 SDLoc DL(Op); 3424 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3425 const GlobalValue *GV = GN->getGlobal(); 3426 unsigned char OpFlags = 3427 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3428 3429 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3430 "unexpected offset in global node"); 3431 3432 // This also catched the large code model case for Darwin. 3433 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3434 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 3435 // FIXME: Once remat is capable of dealing with instructions with register 3436 // operands, expand this into two nodes instead of using a wrapper node. 3437 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 3438 } 3439 3440 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) { 3441 assert(getTargetMachine().getCodeModel() == CodeModel::Small && 3442 "use of MO_CONSTPOOL only supported on small model"); 3443 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE); 3444 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 3445 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC; 3446 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags); 3447 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 3448 SDValue GlobalAddr = DAG.getLoad( 3449 PtrVT, DL, DAG.getEntryNode(), PoolAddr, 3450 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 3451 /*isVolatile=*/false, 3452 /*isNonTemporal=*/true, 3453 /*isInvariant=*/true, 8); 3454 if (GN->getOffset() != 0) 3455 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr, 3456 DAG.getConstant(GN->getOffset(), DL, PtrVT)); 3457 return GlobalAddr; 3458 } 3459 3460 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3461 const unsigned char MO_NC = AArch64II::MO_NC; 3462 return DAG.getNode( 3463 AArch64ISD::WrapperLarge, DL, PtrVT, 3464 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3), 3465 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 3466 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 3467 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 3468 } else { 3469 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and 3470 // the only correct model on Darwin. 3471 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 3472 OpFlags | AArch64II::MO_PAGE); 3473 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC; 3474 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags); 3475 3476 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 3477 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 3478 } 3479 } 3480 3481 /// \brief Convert a TLS address reference into the correct sequence of loads 3482 /// and calls to compute the variable's address (for Darwin, currently) and 3483 /// return an SDValue containing the final node. 3484 3485 /// Darwin only has one TLS scheme which must be capable of dealing with the 3486 /// fully general situation, in the worst case. This means: 3487 /// + "extern __thread" declaration. 3488 /// + Defined in a possibly unknown dynamic library. 3489 /// 3490 /// The general system is that each __thread variable has a [3 x i64] descriptor 3491 /// which contains information used by the runtime to calculate the address. The 3492 /// only part of this the compiler needs to know about is the first xword, which 3493 /// contains a function pointer that must be called with the address of the 3494 /// entire descriptor in "x0". 3495 /// 3496 /// Since this descriptor may be in a different unit, in general even the 3497 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3498 /// is: 3499 /// adrp x0, _var@TLVPPAGE 3500 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3501 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3502 /// ; the function pointer 3503 /// blr x1 ; Uses descriptor address in x0 3504 /// ; Address of _var is now in x0. 3505 /// 3506 /// If the address of _var's descriptor *is* known to the linker, then it can 3507 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3508 /// a slight efficiency gain. 3509 SDValue 3510 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3511 SelectionDAG &DAG) const { 3512 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3513 3514 SDLoc DL(Op); 3515 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3516 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3517 3518 SDValue TLVPAddr = 3519 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3520 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3521 3522 // The first entry in the descriptor is a function pointer that we must call 3523 // to obtain the address of the variable. 3524 SDValue Chain = DAG.getEntryNode(); 3525 SDValue FuncTLVGet = 3526 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, 3527 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, 3528 true, true, 8); 3529 Chain = FuncTLVGet.getValue(1); 3530 3531 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3532 MFI->setAdjustsStack(true); 3533 3534 // TLS calls preserve all registers except those that absolutely must be 3535 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3536 // silly). 3537 const uint32_t *Mask = 3538 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3539 3540 // Finally, we can make the call. This is just a degenerate version of a 3541 // normal AArch64 call node: x0 takes the address of the descriptor, and 3542 // returns the address of the variable in this thread. 3543 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3544 Chain = 3545 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3546 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3547 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3548 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3549 } 3550 3551 /// When accessing thread-local variables under either the general-dynamic or 3552 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3553 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3554 /// is a function pointer to carry out the resolution. 3555 /// 3556 /// The sequence is: 3557 /// adrp x0, :tlsdesc:var 3558 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3559 /// add x0, x0, #:tlsdesc_lo12:var 3560 /// .tlsdesccall var 3561 /// blr x1 3562 /// (TPIDR_EL0 offset now in x0) 3563 /// 3564 /// The above sequence must be produced unscheduled, to enable the linker to 3565 /// optimize/relax this sequence. 3566 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3567 /// above sequence, and expanded really late in the compilation flow, to ensure 3568 /// the sequence is produced as per above. 3569 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL, 3570 SelectionDAG &DAG) const { 3571 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3572 3573 SDValue Chain = DAG.getEntryNode(); 3574 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3575 3576 SmallVector<SDValue, 2> Ops; 3577 Ops.push_back(Chain); 3578 Ops.push_back(SymAddr); 3579 3580 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops); 3581 SDValue Glue = Chain.getValue(1); 3582 3583 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3584 } 3585 3586 SDValue 3587 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3588 SelectionDAG &DAG) const { 3589 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3590 assert(getTargetMachine().getCodeModel() == CodeModel::Small && 3591 "ELF TLS only supported in small memory model"); 3592 // Different choices can be made for the maximum size of the TLS area for a 3593 // module. For the small address model, the default TLS size is 16MiB and the 3594 // maximum TLS size is 4GiB. 3595 // FIXME: add -mtls-size command line option and make it control the 16MiB 3596 // vs. 4GiB code sequence generation. 3597 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3598 3599 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3600 3601 if (DAG.getTarget().Options.EmulatedTLS) 3602 return LowerToTLSEmulatedModel(GA, DAG); 3603 3604 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3605 if (Model == TLSModel::LocalDynamic) 3606 Model = TLSModel::GeneralDynamic; 3607 } 3608 3609 SDValue TPOff; 3610 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3611 SDLoc DL(Op); 3612 const GlobalValue *GV = GA->getGlobal(); 3613 3614 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3615 3616 if (Model == TLSModel::LocalExec) { 3617 SDValue HiVar = DAG.getTargetGlobalAddress( 3618 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3619 SDValue LoVar = DAG.getTargetGlobalAddress( 3620 GV, DL, PtrVT, 0, 3621 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3622 3623 SDValue TPWithOff_lo = 3624 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3625 HiVar, 3626 DAG.getTargetConstant(0, DL, MVT::i32)), 3627 0); 3628 SDValue TPWithOff = 3629 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3630 LoVar, 3631 DAG.getTargetConstant(0, DL, MVT::i32)), 3632 0); 3633 return TPWithOff; 3634 } else if (Model == TLSModel::InitialExec) { 3635 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3636 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3637 } else if (Model == TLSModel::LocalDynamic) { 3638 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3639 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3640 // the beginning of the module's TLS region, followed by a DTPREL offset 3641 // calculation. 3642 3643 // These accesses will need deduplicating if there's more than one. 3644 AArch64FunctionInfo *MFI = 3645 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3646 MFI->incNumLocalDynamicTLSAccesses(); 3647 3648 // The call needs a relocation too for linker relaxation. It doesn't make 3649 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3650 // the address. 3651 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3652 AArch64II::MO_TLS); 3653 3654 // Now we can calculate the offset from TPIDR_EL0 to this module's 3655 // thread-local area. 3656 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3657 3658 // Now use :dtprel_whatever: operations to calculate this variable's offset 3659 // in its thread-storage area. 3660 SDValue HiVar = DAG.getTargetGlobalAddress( 3661 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3662 SDValue LoVar = DAG.getTargetGlobalAddress( 3663 GV, DL, MVT::i64, 0, 3664 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3665 3666 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3667 DAG.getTargetConstant(0, DL, MVT::i32)), 3668 0); 3669 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3670 DAG.getTargetConstant(0, DL, MVT::i32)), 3671 0); 3672 } else if (Model == TLSModel::GeneralDynamic) { 3673 // The call needs a relocation too for linker relaxation. It doesn't make 3674 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3675 // the address. 3676 SDValue SymAddr = 3677 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3678 3679 // Finally we can make a call to calculate the offset from tpidr_el0. 3680 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3681 } else 3682 llvm_unreachable("Unsupported ELF TLS access model"); 3683 3684 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3685 } 3686 3687 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3688 SelectionDAG &DAG) const { 3689 if (Subtarget->isTargetDarwin()) 3690 return LowerDarwinGlobalTLSAddress(Op, DAG); 3691 else if (Subtarget->isTargetELF()) 3692 return LowerELFGlobalTLSAddress(Op, DAG); 3693 3694 llvm_unreachable("Unexpected platform trying to use TLS"); 3695 } 3696 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3697 SDValue Chain = Op.getOperand(0); 3698 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3699 SDValue LHS = Op.getOperand(2); 3700 SDValue RHS = Op.getOperand(3); 3701 SDValue Dest = Op.getOperand(4); 3702 SDLoc dl(Op); 3703 3704 // Handle f128 first, since lowering it will result in comparing the return 3705 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3706 // is expecting to deal with. 3707 if (LHS.getValueType() == MVT::f128) { 3708 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3709 3710 // If softenSetCCOperands returned a scalar, we need to compare the result 3711 // against zero to select between true and false values. 3712 if (!RHS.getNode()) { 3713 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3714 CC = ISD::SETNE; 3715 } 3716 } 3717 3718 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 3719 // instruction. 3720 unsigned Opc = LHS.getOpcode(); 3721 if (LHS.getResNo() == 1 && isOneConstant(RHS) && 3722 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3723 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 3724 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 3725 "Unexpected condition code."); 3726 // Only lower legal XALUO ops. 3727 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 3728 return SDValue(); 3729 3730 // The actual operation with overflow check. 3731 AArch64CC::CondCode OFCC; 3732 SDValue Value, Overflow; 3733 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 3734 3735 if (CC == ISD::SETNE) 3736 OFCC = getInvertedCondCode(OFCC); 3737 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 3738 3739 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3740 Overflow); 3741 } 3742 3743 if (LHS.getValueType().isInteger()) { 3744 assert((LHS.getValueType() == RHS.getValueType()) && 3745 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3746 3747 // If the RHS of the comparison is zero, we can potentially fold this 3748 // to a specialized branch. 3749 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 3750 if (RHSC && RHSC->getZExtValue() == 0) { 3751 if (CC == ISD::SETEQ) { 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::TBZ, dl, MVT::Other, Chain, Test, 3762 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3763 Dest); 3764 } 3765 3766 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 3767 } else if (CC == ISD::SETNE) { 3768 // See if we can use a TBZ to fold in an AND as well. 3769 // TBZ has a smaller branch displacement than CBZ. If the offset is 3770 // out of bounds, a late MI-layer pass rewrites branches. 3771 // 403.gcc is an example that hits this case. 3772 if (LHS.getOpcode() == ISD::AND && 3773 isa<ConstantSDNode>(LHS.getOperand(1)) && 3774 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3775 SDValue Test = LHS.getOperand(0); 3776 uint64_t Mask = LHS.getConstantOperandVal(1); 3777 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 3778 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3779 Dest); 3780 } 3781 3782 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 3783 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 3784 // Don't combine AND since emitComparison converts the AND to an ANDS 3785 // (a.k.a. TST) and the test in the test bit and branch instruction 3786 // becomes redundant. This would also increase register pressure. 3787 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1; 3788 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 3789 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3790 } 3791 } 3792 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 3793 LHS.getOpcode() != ISD::AND) { 3794 // Don't combine AND since emitComparison converts the AND to an ANDS 3795 // (a.k.a. TST) and the test in the test bit and branch instruction 3796 // becomes redundant. This would also increase register pressure. 3797 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1; 3798 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 3799 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3800 } 3801 3802 SDValue CCVal; 3803 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 3804 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3805 Cmp); 3806 } 3807 3808 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3809 3810 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 3811 // clean. Some of them require two branches to implement. 3812 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3813 AArch64CC::CondCode CC1, CC2; 3814 changeFPCCToAArch64CC(CC, CC1, CC2); 3815 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3816 SDValue BR1 = 3817 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 3818 if (CC2 != AArch64CC::AL) { 3819 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3820 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 3821 Cmp); 3822 } 3823 3824 return BR1; 3825 } 3826 3827 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 3828 SelectionDAG &DAG) const { 3829 EVT VT = Op.getValueType(); 3830 SDLoc DL(Op); 3831 3832 SDValue In1 = Op.getOperand(0); 3833 SDValue In2 = Op.getOperand(1); 3834 EVT SrcVT = In2.getValueType(); 3835 3836 if (SrcVT.bitsLT(VT)) 3837 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 3838 else if (SrcVT.bitsGT(VT)) 3839 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 3840 3841 EVT VecVT; 3842 EVT EltVT; 3843 uint64_t EltMask; 3844 SDValue VecVal1, VecVal2; 3845 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 3846 EltVT = MVT::i32; 3847 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 3848 EltMask = 0x80000000ULL; 3849 3850 if (!VT.isVector()) { 3851 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3852 DAG.getUNDEF(VecVT), In1); 3853 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3854 DAG.getUNDEF(VecVT), In2); 3855 } else { 3856 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3857 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3858 } 3859 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 3860 EltVT = MVT::i64; 3861 VecVT = MVT::v2i64; 3862 3863 // We want to materialize a mask with the high bit set, but the AdvSIMD 3864 // immediate moves cannot materialize that in a single instruction for 3865 // 64-bit elements. Instead, materialize zero and then negate it. 3866 EltMask = 0; 3867 3868 if (!VT.isVector()) { 3869 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3870 DAG.getUNDEF(VecVT), In1); 3871 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3872 DAG.getUNDEF(VecVT), In2); 3873 } else { 3874 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3875 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3876 } 3877 } else { 3878 llvm_unreachable("Invalid type for copysign!"); 3879 } 3880 3881 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 3882 3883 // If we couldn't materialize the mask above, then the mask vector will be 3884 // the zero vector, and we need to negate it here. 3885 if (VT == MVT::f64 || VT == MVT::v2f64) { 3886 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 3887 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 3888 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 3889 } 3890 3891 SDValue Sel = 3892 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 3893 3894 if (VT == MVT::f32) 3895 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 3896 else if (VT == MVT::f64) 3897 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 3898 else 3899 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 3900 } 3901 3902 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 3903 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 3904 Attribute::NoImplicitFloat)) 3905 return SDValue(); 3906 3907 if (!Subtarget->hasNEON()) 3908 return SDValue(); 3909 3910 // While there is no integer popcount instruction, it can 3911 // be more efficiently lowered to the following sequence that uses 3912 // AdvSIMD registers/instructions as long as the copies to/from 3913 // the AdvSIMD registers are cheap. 3914 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 3915 // CNT V0.8B, V0.8B // 8xbyte pop-counts 3916 // ADDV B0, V0.8B // sum 8xbyte pop-counts 3917 // UMOV X0, V0.B[0] // copy byte result back to integer reg 3918 SDValue Val = Op.getOperand(0); 3919 SDLoc DL(Op); 3920 EVT VT = Op.getValueType(); 3921 3922 if (VT == MVT::i32) 3923 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 3924 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 3925 3926 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 3927 SDValue UaddLV = DAG.getNode( 3928 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 3929 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 3930 3931 if (VT == MVT::i64) 3932 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 3933 return UaddLV; 3934 } 3935 3936 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3937 3938 if (Op.getValueType().isVector()) 3939 return LowerVSETCC(Op, DAG); 3940 3941 SDValue LHS = Op.getOperand(0); 3942 SDValue RHS = Op.getOperand(1); 3943 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3944 SDLoc dl(Op); 3945 3946 // We chose ZeroOrOneBooleanContents, so use zero and one. 3947 EVT VT = Op.getValueType(); 3948 SDValue TVal = DAG.getConstant(1, dl, VT); 3949 SDValue FVal = DAG.getConstant(0, dl, VT); 3950 3951 // Handle f128 first, since one possible outcome is a normal integer 3952 // comparison which gets picked up by the next if statement. 3953 if (LHS.getValueType() == MVT::f128) { 3954 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3955 3956 // If softenSetCCOperands returned a scalar, use it. 3957 if (!RHS.getNode()) { 3958 assert(LHS.getValueType() == Op.getValueType() && 3959 "Unexpected setcc expansion!"); 3960 return LHS; 3961 } 3962 } 3963 3964 if (LHS.getValueType().isInteger()) { 3965 SDValue CCVal; 3966 SDValue Cmp = 3967 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 3968 3969 // Note that we inverted the condition above, so we reverse the order of 3970 // the true and false operands here. This will allow the setcc to be 3971 // matched to a single CSINC instruction. 3972 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 3973 } 3974 3975 // Now we know we're dealing with FP values. 3976 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3977 3978 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 3979 // and do the comparison. 3980 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3981 3982 AArch64CC::CondCode CC1, CC2; 3983 changeFPCCToAArch64CC(CC, CC1, CC2); 3984 if (CC2 == AArch64CC::AL) { 3985 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 3986 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3987 3988 // Note that we inverted the condition above, so we reverse the order of 3989 // the true and false operands here. This will allow the setcc to be 3990 // matched to a single CSINC instruction. 3991 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 3992 } else { 3993 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 3994 // totally clean. Some of them require two CSELs to implement. As is in 3995 // this case, we emit the first CSEL and then emit a second using the output 3996 // of the first as the RHS. We're effectively OR'ing the two CC's together. 3997 3998 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 3999 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4000 SDValue CS1 = 4001 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4002 4003 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4004 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4005 } 4006 } 4007 4008 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 4009 SDValue RHS, SDValue TVal, 4010 SDValue FVal, SDLoc dl, 4011 SelectionDAG &DAG) const { 4012 // Handle f128 first, because it will result in a comparison of some RTLIB 4013 // call result against zero. 4014 if (LHS.getValueType() == MVT::f128) { 4015 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4016 4017 // If softenSetCCOperands returned a scalar, we need to compare the result 4018 // against zero to select between true and false values. 4019 if (!RHS.getNode()) { 4020 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4021 CC = ISD::SETNE; 4022 } 4023 } 4024 4025 // Also handle f16, for which we need to do a f32 comparison. 4026 if (LHS.getValueType() == MVT::f16) { 4027 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 4028 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 4029 } 4030 4031 // Next, handle integers. 4032 if (LHS.getValueType().isInteger()) { 4033 assert((LHS.getValueType() == RHS.getValueType()) && 4034 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4035 4036 unsigned Opcode = AArch64ISD::CSEL; 4037 4038 // If both the TVal and the FVal are constants, see if we can swap them in 4039 // order to for a CSINV or CSINC out of them. 4040 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4041 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4042 4043 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4044 std::swap(TVal, FVal); 4045 std::swap(CTVal, CFVal); 4046 CC = ISD::getSetCCInverse(CC, true); 4047 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4048 std::swap(TVal, FVal); 4049 std::swap(CTVal, CFVal); 4050 CC = ISD::getSetCCInverse(CC, true); 4051 } else if (TVal.getOpcode() == ISD::XOR) { 4052 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4053 // with a CSINV rather than a CSEL. 4054 if (isAllOnesConstant(TVal.getOperand(1))) { 4055 std::swap(TVal, FVal); 4056 std::swap(CTVal, CFVal); 4057 CC = ISD::getSetCCInverse(CC, true); 4058 } 4059 } else if (TVal.getOpcode() == ISD::SUB) { 4060 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4061 // that we can match with a CSNEG rather than a CSEL. 4062 if (isNullConstant(TVal.getOperand(0))) { 4063 std::swap(TVal, FVal); 4064 std::swap(CTVal, CFVal); 4065 CC = ISD::getSetCCInverse(CC, true); 4066 } 4067 } else if (CTVal && CFVal) { 4068 const int64_t TrueVal = CTVal->getSExtValue(); 4069 const int64_t FalseVal = CFVal->getSExtValue(); 4070 bool Swap = false; 4071 4072 // If both TVal and FVal are constants, see if FVal is the 4073 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4074 // instead of a CSEL in that case. 4075 if (TrueVal == ~FalseVal) { 4076 Opcode = AArch64ISD::CSINV; 4077 } else if (TrueVal == -FalseVal) { 4078 Opcode = AArch64ISD::CSNEG; 4079 } else if (TVal.getValueType() == MVT::i32) { 4080 // If our operands are only 32-bit wide, make sure we use 32-bit 4081 // arithmetic for the check whether we can use CSINC. This ensures that 4082 // the addition in the check will wrap around properly in case there is 4083 // an overflow (which would not be the case if we do the check with 4084 // 64-bit arithmetic). 4085 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4086 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4087 4088 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4089 Opcode = AArch64ISD::CSINC; 4090 4091 if (TrueVal32 > FalseVal32) { 4092 Swap = true; 4093 } 4094 } 4095 // 64-bit check whether we can use CSINC. 4096 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4097 Opcode = AArch64ISD::CSINC; 4098 4099 if (TrueVal > FalseVal) { 4100 Swap = true; 4101 } 4102 } 4103 4104 // Swap TVal and FVal if necessary. 4105 if (Swap) { 4106 std::swap(TVal, FVal); 4107 std::swap(CTVal, CFVal); 4108 CC = ISD::getSetCCInverse(CC, true); 4109 } 4110 4111 if (Opcode != AArch64ISD::CSEL) { 4112 // Drop FVal since we can get its value by simply inverting/negating 4113 // TVal. 4114 FVal = TVal; 4115 } 4116 } 4117 4118 SDValue CCVal; 4119 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4120 4121 EVT VT = TVal.getValueType(); 4122 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4123 } 4124 4125 // Now we know we're dealing with FP values. 4126 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4127 assert(LHS.getValueType() == RHS.getValueType()); 4128 EVT VT = TVal.getValueType(); 4129 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4130 4131 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4132 // clean. Some of them require two CSELs to implement. 4133 AArch64CC::CondCode CC1, CC2; 4134 changeFPCCToAArch64CC(CC, CC1, CC2); 4135 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4136 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4137 4138 // If we need a second CSEL, emit it, using the output of the first as the 4139 // RHS. We're effectively OR'ing the two CC's together. 4140 if (CC2 != AArch64CC::AL) { 4141 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4142 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4143 } 4144 4145 // Otherwise, return the output of the first CSEL. 4146 return CS1; 4147 } 4148 4149 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4150 SelectionDAG &DAG) const { 4151 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4152 SDValue LHS = Op.getOperand(0); 4153 SDValue RHS = Op.getOperand(1); 4154 SDValue TVal = Op.getOperand(2); 4155 SDValue FVal = Op.getOperand(3); 4156 SDLoc DL(Op); 4157 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4158 } 4159 4160 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4161 SelectionDAG &DAG) const { 4162 SDValue CCVal = Op->getOperand(0); 4163 SDValue TVal = Op->getOperand(1); 4164 SDValue FVal = Op->getOperand(2); 4165 SDLoc DL(Op); 4166 4167 unsigned Opc = CCVal.getOpcode(); 4168 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4169 // instruction. 4170 if (CCVal.getResNo() == 1 && 4171 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4172 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4173 // Only lower legal XALUO ops. 4174 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4175 return SDValue(); 4176 4177 AArch64CC::CondCode OFCC; 4178 SDValue Value, Overflow; 4179 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4180 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4181 4182 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4183 CCVal, Overflow); 4184 } 4185 4186 // Lower it the same way as we would lower a SELECT_CC node. 4187 ISD::CondCode CC; 4188 SDValue LHS, RHS; 4189 if (CCVal.getOpcode() == ISD::SETCC) { 4190 LHS = CCVal.getOperand(0); 4191 RHS = CCVal.getOperand(1); 4192 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4193 } else { 4194 LHS = CCVal; 4195 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4196 CC = ISD::SETNE; 4197 } 4198 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4199 } 4200 4201 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4202 SelectionDAG &DAG) const { 4203 // Jump table entries as PC relative offsets. No additional tweaking 4204 // is necessary here. Just get the address of the jump table. 4205 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4206 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4207 SDLoc DL(Op); 4208 4209 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4210 !Subtarget->isTargetMachO()) { 4211 const unsigned char MO_NC = AArch64II::MO_NC; 4212 return DAG.getNode( 4213 AArch64ISD::WrapperLarge, DL, PtrVT, 4214 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3), 4215 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC), 4216 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC), 4217 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4218 AArch64II::MO_G0 | MO_NC)); 4219 } 4220 4221 SDValue Hi = 4222 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE); 4223 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4224 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4225 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4226 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4227 } 4228 4229 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4230 SelectionDAG &DAG) const { 4231 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4232 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4233 SDLoc DL(Op); 4234 4235 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4236 // Use the GOT for the large code model on iOS. 4237 if (Subtarget->isTargetMachO()) { 4238 SDValue GotAddr = DAG.getTargetConstantPool( 4239 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4240 AArch64II::MO_GOT); 4241 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 4242 } 4243 4244 const unsigned char MO_NC = AArch64II::MO_NC; 4245 return DAG.getNode( 4246 AArch64ISD::WrapperLarge, DL, PtrVT, 4247 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4248 CP->getOffset(), AArch64II::MO_G3), 4249 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4250 CP->getOffset(), AArch64II::MO_G2 | MO_NC), 4251 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4252 CP->getOffset(), AArch64II::MO_G1 | MO_NC), 4253 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4254 CP->getOffset(), AArch64II::MO_G0 | MO_NC)); 4255 } else { 4256 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on 4257 // ELF, the only valid one on Darwin. 4258 SDValue Hi = 4259 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4260 CP->getOffset(), AArch64II::MO_PAGE); 4261 SDValue Lo = DAG.getTargetConstantPool( 4262 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4263 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4264 4265 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4266 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4267 } 4268 } 4269 4270 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4271 SelectionDAG &DAG) const { 4272 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 4273 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4274 SDLoc DL(Op); 4275 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4276 !Subtarget->isTargetMachO()) { 4277 const unsigned char MO_NC = AArch64II::MO_NC; 4278 return DAG.getNode( 4279 AArch64ISD::WrapperLarge, DL, PtrVT, 4280 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3), 4281 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 4282 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 4283 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 4284 } else { 4285 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE); 4286 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF | 4287 AArch64II::MO_NC); 4288 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4289 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4290 } 4291 } 4292 4293 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4294 SelectionDAG &DAG) const { 4295 AArch64FunctionInfo *FuncInfo = 4296 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4297 4298 SDLoc DL(Op); 4299 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4300 getPointerTy(DAG.getDataLayout())); 4301 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4302 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4303 MachinePointerInfo(SV), false, false, 0); 4304 } 4305 4306 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4307 SelectionDAG &DAG) const { 4308 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4309 // Standard, section B.3. 4310 MachineFunction &MF = DAG.getMachineFunction(); 4311 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4312 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4313 SDLoc DL(Op); 4314 4315 SDValue Chain = Op.getOperand(0); 4316 SDValue VAList = Op.getOperand(1); 4317 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4318 SmallVector<SDValue, 4> MemOps; 4319 4320 // void *__stack at offset 0 4321 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4322 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4323 MachinePointerInfo(SV), false, false, 8)); 4324 4325 // void *__gr_top at offset 8 4326 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4327 if (GPRSize > 0) { 4328 SDValue GRTop, GRTopAddr; 4329 4330 GRTopAddr = 4331 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4332 4333 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4334 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4335 DAG.getConstant(GPRSize, DL, PtrVT)); 4336 4337 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4338 MachinePointerInfo(SV, 8), false, false, 8)); 4339 } 4340 4341 // void *__vr_top at offset 16 4342 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4343 if (FPRSize > 0) { 4344 SDValue VRTop, VRTopAddr; 4345 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4346 DAG.getConstant(16, DL, PtrVT)); 4347 4348 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4349 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4350 DAG.getConstant(FPRSize, DL, PtrVT)); 4351 4352 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4353 MachinePointerInfo(SV, 16), false, false, 8)); 4354 } 4355 4356 // int __gr_offs at offset 24 4357 SDValue GROffsAddr = 4358 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4359 MemOps.push_back(DAG.getStore(Chain, DL, 4360 DAG.getConstant(-GPRSize, DL, MVT::i32), 4361 GROffsAddr, MachinePointerInfo(SV, 24), false, 4362 false, 4)); 4363 4364 // int __vr_offs at offset 28 4365 SDValue VROffsAddr = 4366 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4367 MemOps.push_back(DAG.getStore(Chain, DL, 4368 DAG.getConstant(-FPRSize, DL, MVT::i32), 4369 VROffsAddr, MachinePointerInfo(SV, 28), false, 4370 false, 4)); 4371 4372 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4373 } 4374 4375 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4376 SelectionDAG &DAG) const { 4377 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG) 4378 : LowerAAPCS_VASTART(Op, DAG); 4379 } 4380 4381 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4382 SelectionDAG &DAG) const { 4383 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4384 // pointer. 4385 SDLoc DL(Op); 4386 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32; 4387 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4388 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4389 4390 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4391 Op.getOperand(2), 4392 DAG.getConstant(VaListSize, DL, MVT::i32), 4393 8, false, false, false, MachinePointerInfo(DestSV), 4394 MachinePointerInfo(SrcSV)); 4395 } 4396 4397 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4398 assert(Subtarget->isTargetDarwin() && 4399 "automatic va_arg instruction only works on Darwin"); 4400 4401 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4402 EVT VT = Op.getValueType(); 4403 SDLoc DL(Op); 4404 SDValue Chain = Op.getOperand(0); 4405 SDValue Addr = Op.getOperand(1); 4406 unsigned Align = Op.getConstantOperandVal(3); 4407 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4408 4409 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V), 4410 false, false, false, 0); 4411 Chain = VAList.getValue(1); 4412 4413 if (Align > 8) { 4414 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4415 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4416 DAG.getConstant(Align - 1, DL, PtrVT)); 4417 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4418 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4419 } 4420 4421 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4422 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4423 4424 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4425 // up to 64 bits. At the very least, we have to increase the striding of the 4426 // vaargs list to match this, and for FP values we need to introduce 4427 // FP_ROUND nodes as well. 4428 if (VT.isInteger() && !VT.isVector()) 4429 ArgSize = 8; 4430 bool NeedFPTrunc = false; 4431 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4432 ArgSize = 8; 4433 NeedFPTrunc = true; 4434 } 4435 4436 // Increment the pointer, VAList, to the next vaarg 4437 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4438 DAG.getConstant(ArgSize, DL, PtrVT)); 4439 // Store the incremented VAList to the legalized pointer 4440 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V), 4441 false, false, 0); 4442 4443 // Load the actual argument out of the pointer VAList 4444 if (NeedFPTrunc) { 4445 // Load the value as an f64. 4446 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList, 4447 MachinePointerInfo(), false, false, false, 0); 4448 // Round the value down to an f32. 4449 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4450 DAG.getIntPtrConstant(1, DL)); 4451 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4452 // Merge the rounded value with the chain output of the load. 4453 return DAG.getMergeValues(Ops, DL); 4454 } 4455 4456 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false, 4457 false, false, 0); 4458 } 4459 4460 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4461 SelectionDAG &DAG) const { 4462 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4463 MFI->setFrameAddressIsTaken(true); 4464 4465 EVT VT = Op.getValueType(); 4466 SDLoc DL(Op); 4467 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4468 SDValue FrameAddr = 4469 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4470 while (Depth--) 4471 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4472 MachinePointerInfo(), false, false, false, 0); 4473 return FrameAddr; 4474 } 4475 4476 // FIXME? Maybe this could be a TableGen attribute on some registers and 4477 // this table could be generated automatically from RegInfo. 4478 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4479 SelectionDAG &DAG) const { 4480 unsigned Reg = StringSwitch<unsigned>(RegName) 4481 .Case("sp", AArch64::SP) 4482 .Default(0); 4483 if (Reg) 4484 return Reg; 4485 report_fatal_error(Twine("Invalid register name \"" 4486 + StringRef(RegName) + "\".")); 4487 } 4488 4489 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4490 SelectionDAG &DAG) const { 4491 MachineFunction &MF = DAG.getMachineFunction(); 4492 MachineFrameInfo *MFI = MF.getFrameInfo(); 4493 MFI->setReturnAddressIsTaken(true); 4494 4495 EVT VT = Op.getValueType(); 4496 SDLoc DL(Op); 4497 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4498 if (Depth) { 4499 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4500 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4501 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4502 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4503 MachinePointerInfo(), false, false, false, 0); 4504 } 4505 4506 // Return LR, which contains the return address. Mark it an implicit live-in. 4507 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4508 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4509 } 4510 4511 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4512 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4513 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4514 SelectionDAG &DAG) const { 4515 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4516 EVT VT = Op.getValueType(); 4517 unsigned VTBits = VT.getSizeInBits(); 4518 SDLoc dl(Op); 4519 SDValue ShOpLo = Op.getOperand(0); 4520 SDValue ShOpHi = Op.getOperand(1); 4521 SDValue ShAmt = Op.getOperand(2); 4522 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4523 4524 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4525 4526 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4527 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4528 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4529 4530 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4531 // is "undef". We wanted 0, so CSEL it directly. 4532 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4533 ISD::SETEQ, dl, DAG); 4534 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4535 HiBitsForLo = 4536 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4537 HiBitsForLo, CCVal, Cmp); 4538 4539 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4540 DAG.getConstant(VTBits, dl, MVT::i64)); 4541 4542 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4543 SDValue LoForNormalShift = 4544 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4545 4546 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4547 dl, DAG); 4548 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4549 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4550 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4551 LoForNormalShift, CCVal, Cmp); 4552 4553 // AArch64 shifts larger than the register width are wrapped rather than 4554 // clamped, so we can't just emit "hi >> x". 4555 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4556 SDValue HiForBigShift = 4557 Opc == ISD::SRA 4558 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4559 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4560 : DAG.getConstant(0, dl, VT); 4561 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4562 HiForNormalShift, CCVal, Cmp); 4563 4564 SDValue Ops[2] = { Lo, Hi }; 4565 return DAG.getMergeValues(Ops, dl); 4566 } 4567 4568 4569 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4570 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4571 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4572 SelectionDAG &DAG) const { 4573 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4574 EVT VT = Op.getValueType(); 4575 unsigned VTBits = VT.getSizeInBits(); 4576 SDLoc dl(Op); 4577 SDValue ShOpLo = Op.getOperand(0); 4578 SDValue ShOpHi = Op.getOperand(1); 4579 SDValue ShAmt = Op.getOperand(2); 4580 4581 assert(Op.getOpcode() == ISD::SHL_PARTS); 4582 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4583 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4584 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4585 4586 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4587 // is "undef". We wanted 0, so CSEL it directly. 4588 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4589 ISD::SETEQ, dl, DAG); 4590 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4591 LoBitsForHi = 4592 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4593 LoBitsForHi, CCVal, Cmp); 4594 4595 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4596 DAG.getConstant(VTBits, dl, MVT::i64)); 4597 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4598 SDValue HiForNormalShift = 4599 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4600 4601 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4602 4603 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4604 dl, DAG); 4605 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4606 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4607 HiForNormalShift, CCVal, Cmp); 4608 4609 // AArch64 shifts of larger than register sizes are wrapped rather than 4610 // clamped, so we can't just emit "lo << a" if a is too big. 4611 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4612 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4613 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4614 LoForNormalShift, CCVal, Cmp); 4615 4616 SDValue Ops[2] = { Lo, Hi }; 4617 return DAG.getMergeValues(Ops, dl); 4618 } 4619 4620 bool AArch64TargetLowering::isOffsetFoldingLegal( 4621 const GlobalAddressSDNode *GA) const { 4622 // The AArch64 target doesn't support folding offsets into global addresses. 4623 return false; 4624 } 4625 4626 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4627 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4628 // FIXME: We should be able to handle f128 as well with a clever lowering. 4629 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32)) 4630 return true; 4631 4632 if (VT == MVT::f64) 4633 return AArch64_AM::getFP64Imm(Imm) != -1; 4634 else if (VT == MVT::f32) 4635 return AArch64_AM::getFP32Imm(Imm) != -1; 4636 return false; 4637 } 4638 4639 //===----------------------------------------------------------------------===// 4640 // AArch64 Optimization Hooks 4641 //===----------------------------------------------------------------------===// 4642 4643 //===----------------------------------------------------------------------===// 4644 // AArch64 Inline Assembly Support 4645 //===----------------------------------------------------------------------===// 4646 4647 // Table of Constraints 4648 // TODO: This is the current set of constraints supported by ARM for the 4649 // compiler, not all of them may make sense, e.g. S may be difficult to support. 4650 // 4651 // r - A general register 4652 // w - An FP/SIMD register of some size in the range v0-v31 4653 // x - An FP/SIMD register of some size in the range v0-v15 4654 // I - Constant that can be used with an ADD instruction 4655 // J - Constant that can be used with a SUB instruction 4656 // K - Constant that can be used with a 32-bit logical instruction 4657 // L - Constant that can be used with a 64-bit logical instruction 4658 // M - Constant that can be used as a 32-bit MOV immediate 4659 // N - Constant that can be used as a 64-bit MOV immediate 4660 // Q - A memory reference with base register and no offset 4661 // S - A symbolic address 4662 // Y - Floating point constant zero 4663 // Z - Integer constant zero 4664 // 4665 // Note that general register operands will be output using their 64-bit x 4666 // register name, whatever the size of the variable, unless the asm operand 4667 // is prefixed by the %w modifier. Floating-point and SIMD register operands 4668 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 4669 // %q modifier. 4670 4671 /// getConstraintType - Given a constraint letter, return the type of 4672 /// constraint it is for this target. 4673 AArch64TargetLowering::ConstraintType 4674 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 4675 if (Constraint.size() == 1) { 4676 switch (Constraint[0]) { 4677 default: 4678 break; 4679 case 'z': 4680 return C_Other; 4681 case 'x': 4682 case 'w': 4683 return C_RegisterClass; 4684 // An address with a single base register. Due to the way we 4685 // currently handle addresses it is the same as 'r'. 4686 case 'Q': 4687 return C_Memory; 4688 } 4689 } 4690 return TargetLowering::getConstraintType(Constraint); 4691 } 4692 4693 /// Examine constraint type and operand type and determine a weight value. 4694 /// This object must already have been set up with the operand type 4695 /// and the current alternative constraint selected. 4696 TargetLowering::ConstraintWeight 4697 AArch64TargetLowering::getSingleConstraintMatchWeight( 4698 AsmOperandInfo &info, const char *constraint) const { 4699 ConstraintWeight weight = CW_Invalid; 4700 Value *CallOperandVal = info.CallOperandVal; 4701 // If we don't have a value, we can't do a match, 4702 // but allow it at the lowest weight. 4703 if (!CallOperandVal) 4704 return CW_Default; 4705 Type *type = CallOperandVal->getType(); 4706 // Look at the constraint type. 4707 switch (*constraint) { 4708 default: 4709 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 4710 break; 4711 case 'x': 4712 case 'w': 4713 if (type->isFloatingPointTy() || type->isVectorTy()) 4714 weight = CW_Register; 4715 break; 4716 case 'z': 4717 weight = CW_Constant; 4718 break; 4719 } 4720 return weight; 4721 } 4722 4723 std::pair<unsigned, const TargetRegisterClass *> 4724 AArch64TargetLowering::getRegForInlineAsmConstraint( 4725 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 4726 if (Constraint.size() == 1) { 4727 switch (Constraint[0]) { 4728 case 'r': 4729 if (VT.getSizeInBits() == 64) 4730 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 4731 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 4732 case 'w': 4733 if (VT == MVT::f32) 4734 return std::make_pair(0U, &AArch64::FPR32RegClass); 4735 if (VT.getSizeInBits() == 64) 4736 return std::make_pair(0U, &AArch64::FPR64RegClass); 4737 if (VT.getSizeInBits() == 128) 4738 return std::make_pair(0U, &AArch64::FPR128RegClass); 4739 break; 4740 // The instructions that this constraint is designed for can 4741 // only take 128-bit registers so just use that regclass. 4742 case 'x': 4743 if (VT.getSizeInBits() == 128) 4744 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 4745 break; 4746 } 4747 } 4748 if (StringRef("{cc}").equals_lower(Constraint)) 4749 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 4750 4751 // Use the default implementation in TargetLowering to convert the register 4752 // constraint into a member of a register class. 4753 std::pair<unsigned, const TargetRegisterClass *> Res; 4754 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4755 4756 // Not found as a standard register? 4757 if (!Res.second) { 4758 unsigned Size = Constraint.size(); 4759 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 4760 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 4761 int RegNo; 4762 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 4763 if (!Failed && RegNo >= 0 && RegNo <= 31) { 4764 // v0 - v31 are aliases of q0 - q31. 4765 // By default we'll emit v0-v31 for this unless there's a modifier where 4766 // we'll emit the correct register as well. 4767 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 4768 Res.second = &AArch64::FPR128RegClass; 4769 } 4770 } 4771 } 4772 4773 return Res; 4774 } 4775 4776 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 4777 /// vector. If it is invalid, don't add anything to Ops. 4778 void AArch64TargetLowering::LowerAsmOperandForConstraint( 4779 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 4780 SelectionDAG &DAG) const { 4781 SDValue Result; 4782 4783 // Currently only support length 1 constraints. 4784 if (Constraint.length() != 1) 4785 return; 4786 4787 char ConstraintLetter = Constraint[0]; 4788 switch (ConstraintLetter) { 4789 default: 4790 break; 4791 4792 // This set of constraints deal with valid constants for various instructions. 4793 // Validate and return a target constant for them if we can. 4794 case 'z': { 4795 // 'z' maps to xzr or wzr so it needs an input of 0. 4796 if (!isNullConstant(Op)) 4797 return; 4798 4799 if (Op.getValueType() == MVT::i64) 4800 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 4801 else 4802 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 4803 break; 4804 } 4805 4806 case 'I': 4807 case 'J': 4808 case 'K': 4809 case 'L': 4810 case 'M': 4811 case 'N': 4812 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4813 if (!C) 4814 return; 4815 4816 // Grab the value and do some validation. 4817 uint64_t CVal = C->getZExtValue(); 4818 switch (ConstraintLetter) { 4819 // The I constraint applies only to simple ADD or SUB immediate operands: 4820 // i.e. 0 to 4095 with optional shift by 12 4821 // The J constraint applies only to ADD or SUB immediates that would be 4822 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 4823 // instruction [or vice versa], in other words -1 to -4095 with optional 4824 // left shift by 12. 4825 case 'I': 4826 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 4827 break; 4828 return; 4829 case 'J': { 4830 uint64_t NVal = -C->getSExtValue(); 4831 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 4832 CVal = C->getSExtValue(); 4833 break; 4834 } 4835 return; 4836 } 4837 // The K and L constraints apply *only* to logical immediates, including 4838 // what used to be the MOVI alias for ORR (though the MOVI alias has now 4839 // been removed and MOV should be used). So these constraints have to 4840 // distinguish between bit patterns that are valid 32-bit or 64-bit 4841 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 4842 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 4843 // versa. 4844 case 'K': 4845 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4846 break; 4847 return; 4848 case 'L': 4849 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4850 break; 4851 return; 4852 // The M and N constraints are a superset of K and L respectively, for use 4853 // with the MOV (immediate) alias. As well as the logical immediates they 4854 // also match 32 or 64-bit immediates that can be loaded either using a 4855 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 4856 // (M) or 64-bit 0x1234000000000000 (N) etc. 4857 // As a note some of this code is liberally stolen from the asm parser. 4858 case 'M': { 4859 if (!isUInt<32>(CVal)) 4860 return; 4861 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4862 break; 4863 if ((CVal & 0xFFFF) == CVal) 4864 break; 4865 if ((CVal & 0xFFFF0000ULL) == CVal) 4866 break; 4867 uint64_t NCVal = ~(uint32_t)CVal; 4868 if ((NCVal & 0xFFFFULL) == NCVal) 4869 break; 4870 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4871 break; 4872 return; 4873 } 4874 case 'N': { 4875 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4876 break; 4877 if ((CVal & 0xFFFFULL) == CVal) 4878 break; 4879 if ((CVal & 0xFFFF0000ULL) == CVal) 4880 break; 4881 if ((CVal & 0xFFFF00000000ULL) == CVal) 4882 break; 4883 if ((CVal & 0xFFFF000000000000ULL) == CVal) 4884 break; 4885 uint64_t NCVal = ~CVal; 4886 if ((NCVal & 0xFFFFULL) == NCVal) 4887 break; 4888 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4889 break; 4890 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 4891 break; 4892 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 4893 break; 4894 return; 4895 } 4896 default: 4897 return; 4898 } 4899 4900 // All assembler immediates are 64-bit integers. 4901 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 4902 break; 4903 } 4904 4905 if (Result.getNode()) { 4906 Ops.push_back(Result); 4907 return; 4908 } 4909 4910 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 4911 } 4912 4913 //===----------------------------------------------------------------------===// 4914 // AArch64 Advanced SIMD Support 4915 //===----------------------------------------------------------------------===// 4916 4917 /// WidenVector - Given a value in the V64 register class, produce the 4918 /// equivalent value in the V128 register class. 4919 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 4920 EVT VT = V64Reg.getValueType(); 4921 unsigned NarrowSize = VT.getVectorNumElements(); 4922 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 4923 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 4924 SDLoc DL(V64Reg); 4925 4926 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 4927 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 4928 } 4929 4930 /// getExtFactor - Determine the adjustment factor for the position when 4931 /// generating an "extract from vector registers" instruction. 4932 static unsigned getExtFactor(SDValue &V) { 4933 EVT EltType = V.getValueType().getVectorElementType(); 4934 return EltType.getSizeInBits() / 8; 4935 } 4936 4937 /// NarrowVector - Given a value in the V128 register class, produce the 4938 /// equivalent value in the V64 register class. 4939 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 4940 EVT VT = V128Reg.getValueType(); 4941 unsigned WideSize = VT.getVectorNumElements(); 4942 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 4943 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 4944 SDLoc DL(V128Reg); 4945 4946 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 4947 } 4948 4949 // Gather data to see if the operation can be modelled as a 4950 // shuffle in combination with VEXTs. 4951 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 4952 SelectionDAG &DAG) const { 4953 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 4954 SDLoc dl(Op); 4955 EVT VT = Op.getValueType(); 4956 unsigned NumElts = VT.getVectorNumElements(); 4957 4958 struct ShuffleSourceInfo { 4959 SDValue Vec; 4960 unsigned MinElt; 4961 unsigned MaxElt; 4962 4963 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 4964 // be compatible with the shuffle we intend to construct. As a result 4965 // ShuffleVec will be some sliding window into the original Vec. 4966 SDValue ShuffleVec; 4967 4968 // Code should guarantee that element i in Vec starts at element "WindowBase 4969 // + i * WindowScale in ShuffleVec". 4970 int WindowBase; 4971 int WindowScale; 4972 4973 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 4974 ShuffleSourceInfo(SDValue Vec) 4975 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 4976 WindowScale(1) {} 4977 }; 4978 4979 // First gather all vectors used as an immediate source for this BUILD_VECTOR 4980 // node. 4981 SmallVector<ShuffleSourceInfo, 2> Sources; 4982 for (unsigned i = 0; i < NumElts; ++i) { 4983 SDValue V = Op.getOperand(i); 4984 if (V.isUndef()) 4985 continue; 4986 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4987 !isa<ConstantSDNode>(V.getOperand(1))) { 4988 // A shuffle can only come from building a vector from various 4989 // elements of other vectors, provided their indices are constant. 4990 return SDValue(); 4991 } 4992 4993 // Add this element source to the list if it's not already there. 4994 SDValue SourceVec = V.getOperand(0); 4995 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 4996 if (Source == Sources.end()) 4997 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 4998 4999 // Update the minimum and maximum lane number seen. 5000 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5001 Source->MinElt = std::min(Source->MinElt, EltNo); 5002 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5003 } 5004 5005 // Currently only do something sane when at most two source vectors 5006 // are involved. 5007 if (Sources.size() > 2) 5008 return SDValue(); 5009 5010 // Find out the smallest element size among result and two sources, and use 5011 // it as element size to build the shuffle_vector. 5012 EVT SmallestEltTy = VT.getVectorElementType(); 5013 for (auto &Source : Sources) { 5014 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5015 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5016 SmallestEltTy = SrcEltTy; 5017 } 5018 } 5019 unsigned ResMultiplier = 5020 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5021 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5022 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5023 5024 // If the source vector is too wide or too narrow, we may nevertheless be able 5025 // to construct a compatible shuffle either by concatenating it with UNDEF or 5026 // extracting a suitable range of elements. 5027 for (auto &Src : Sources) { 5028 EVT SrcVT = Src.ShuffleVec.getValueType(); 5029 5030 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5031 continue; 5032 5033 // This stage of the search produces a source with the same element type as 5034 // the original, but with a total width matching the BUILD_VECTOR output. 5035 EVT EltVT = SrcVT.getVectorElementType(); 5036 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5037 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5038 5039 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5040 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5041 // We can pad out the smaller vector for free, so if it's part of a 5042 // shuffle... 5043 Src.ShuffleVec = 5044 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5045 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5046 continue; 5047 } 5048 5049 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5050 5051 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5052 // Span too large for a VEXT to cope 5053 return SDValue(); 5054 } 5055 5056 if (Src.MinElt >= NumSrcElts) { 5057 // The extraction can just take the second half 5058 Src.ShuffleVec = 5059 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5060 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5061 Src.WindowBase = -NumSrcElts; 5062 } else if (Src.MaxElt < NumSrcElts) { 5063 // The extraction can just take the first half 5064 Src.ShuffleVec = 5065 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5066 DAG.getConstant(0, dl, MVT::i64)); 5067 } else { 5068 // An actual VEXT is needed 5069 SDValue VEXTSrc1 = 5070 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5071 DAG.getConstant(0, dl, MVT::i64)); 5072 SDValue VEXTSrc2 = 5073 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5074 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5075 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5076 5077 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5078 VEXTSrc2, 5079 DAG.getConstant(Imm, dl, MVT::i32)); 5080 Src.WindowBase = -Src.MinElt; 5081 } 5082 } 5083 5084 // Another possible incompatibility occurs from the vector element types. We 5085 // can fix this by bitcasting the source vectors to the same type we intend 5086 // for the shuffle. 5087 for (auto &Src : Sources) { 5088 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5089 if (SrcEltTy == SmallestEltTy) 5090 continue; 5091 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5092 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5093 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5094 Src.WindowBase *= Src.WindowScale; 5095 } 5096 5097 // Final sanity check before we try to actually produce a shuffle. 5098 DEBUG( 5099 for (auto Src : Sources) 5100 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5101 ); 5102 5103 // The stars all align, our next step is to produce the mask for the shuffle. 5104 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5105 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5106 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5107 SDValue Entry = Op.getOperand(i); 5108 if (Entry.isUndef()) 5109 continue; 5110 5111 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5112 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5113 5114 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5115 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5116 // segment. 5117 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5118 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5119 VT.getVectorElementType().getSizeInBits()); 5120 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5121 5122 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5123 // starting at the appropriate offset. 5124 int *LaneMask = &Mask[i * ResMultiplier]; 5125 5126 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5127 ExtractBase += NumElts * (Src - Sources.begin()); 5128 for (int j = 0; j < LanesDefined; ++j) 5129 LaneMask[j] = ExtractBase + j; 5130 } 5131 5132 // Final check before we try to produce nonsense... 5133 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5134 return SDValue(); 5135 5136 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5137 for (unsigned i = 0; i < Sources.size(); ++i) 5138 ShuffleOps[i] = Sources[i].ShuffleVec; 5139 5140 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5141 ShuffleOps[1], &Mask[0]); 5142 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5143 } 5144 5145 // check if an EXT instruction can handle the shuffle mask when the 5146 // vector sources of the shuffle are the same. 5147 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5148 unsigned NumElts = VT.getVectorNumElements(); 5149 5150 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5151 if (M[0] < 0) 5152 return false; 5153 5154 Imm = M[0]; 5155 5156 // If this is a VEXT shuffle, the immediate value is the index of the first 5157 // element. The other shuffle indices must be the successive elements after 5158 // the first one. 5159 unsigned ExpectedElt = Imm; 5160 for (unsigned i = 1; i < NumElts; ++i) { 5161 // Increment the expected index. If it wraps around, just follow it 5162 // back to index zero and keep going. 5163 ++ExpectedElt; 5164 if (ExpectedElt == NumElts) 5165 ExpectedElt = 0; 5166 5167 if (M[i] < 0) 5168 continue; // ignore UNDEF indices 5169 if (ExpectedElt != static_cast<unsigned>(M[i])) 5170 return false; 5171 } 5172 5173 return true; 5174 } 5175 5176 // check if an EXT instruction can handle the shuffle mask when the 5177 // vector sources of the shuffle are different. 5178 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5179 unsigned &Imm) { 5180 // Look for the first non-undef element. 5181 const int *FirstRealElt = std::find_if(M.begin(), M.end(), 5182 [](int Elt) {return Elt >= 0;}); 5183 5184 // Benefit form APInt to handle overflow when calculating expected element. 5185 unsigned NumElts = VT.getVectorNumElements(); 5186 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5187 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5188 // The following shuffle indices must be the successive elements after the 5189 // first real element. 5190 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5191 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5192 if (FirstWrongElt != M.end()) 5193 return false; 5194 5195 // The index of an EXT is the first element if it is not UNDEF. 5196 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5197 // value of the first element. E.g. 5198 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5199 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5200 // ExpectedElt is the last mask index plus 1. 5201 Imm = ExpectedElt.getZExtValue(); 5202 5203 // There are two difference cases requiring to reverse input vectors. 5204 // For example, for vector <4 x i32> we have the following cases, 5205 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5206 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5207 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5208 // to reverse two input vectors. 5209 if (Imm < NumElts) 5210 ReverseEXT = true; 5211 else 5212 Imm -= NumElts; 5213 5214 return true; 5215 } 5216 5217 /// isREVMask - Check if a vector shuffle corresponds to a REV 5218 /// instruction with the specified blocksize. (The order of the elements 5219 /// within each block of the vector is reversed.) 5220 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5221 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5222 "Only possible block sizes for REV are: 16, 32, 64"); 5223 5224 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5225 if (EltSz == 64) 5226 return false; 5227 5228 unsigned NumElts = VT.getVectorNumElements(); 5229 unsigned BlockElts = M[0] + 1; 5230 // If the first shuffle index is UNDEF, be optimistic. 5231 if (M[0] < 0) 5232 BlockElts = BlockSize / EltSz; 5233 5234 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5235 return false; 5236 5237 for (unsigned i = 0; i < NumElts; ++i) { 5238 if (M[i] < 0) 5239 continue; // ignore UNDEF indices 5240 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5241 return false; 5242 } 5243 5244 return true; 5245 } 5246 5247 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5248 unsigned NumElts = VT.getVectorNumElements(); 5249 WhichResult = (M[0] == 0 ? 0 : 1); 5250 unsigned Idx = WhichResult * NumElts / 2; 5251 for (unsigned i = 0; i != NumElts; i += 2) { 5252 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5253 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5254 return false; 5255 Idx += 1; 5256 } 5257 5258 return true; 5259 } 5260 5261 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5262 unsigned NumElts = VT.getVectorNumElements(); 5263 WhichResult = (M[0] == 0 ? 0 : 1); 5264 for (unsigned i = 0; i != NumElts; ++i) { 5265 if (M[i] < 0) 5266 continue; // ignore UNDEF indices 5267 if ((unsigned)M[i] != 2 * i + WhichResult) 5268 return false; 5269 } 5270 5271 return true; 5272 } 5273 5274 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5275 unsigned NumElts = VT.getVectorNumElements(); 5276 WhichResult = (M[0] == 0 ? 0 : 1); 5277 for (unsigned i = 0; i < NumElts; i += 2) { 5278 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5279 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5280 return false; 5281 } 5282 return true; 5283 } 5284 5285 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5286 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5287 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5288 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5289 unsigned NumElts = VT.getVectorNumElements(); 5290 WhichResult = (M[0] == 0 ? 0 : 1); 5291 unsigned Idx = WhichResult * NumElts / 2; 5292 for (unsigned i = 0; i != NumElts; i += 2) { 5293 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5294 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5295 return false; 5296 Idx += 1; 5297 } 5298 5299 return true; 5300 } 5301 5302 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5303 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5304 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5305 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5306 unsigned Half = VT.getVectorNumElements() / 2; 5307 WhichResult = (M[0] == 0 ? 0 : 1); 5308 for (unsigned j = 0; j != 2; ++j) { 5309 unsigned Idx = WhichResult; 5310 for (unsigned i = 0; i != Half; ++i) { 5311 int MIdx = M[i + j * Half]; 5312 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5313 return false; 5314 Idx += 2; 5315 } 5316 } 5317 5318 return true; 5319 } 5320 5321 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5322 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5323 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5324 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5325 unsigned NumElts = VT.getVectorNumElements(); 5326 WhichResult = (M[0] == 0 ? 0 : 1); 5327 for (unsigned i = 0; i < NumElts; i += 2) { 5328 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5329 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5330 return false; 5331 } 5332 return true; 5333 } 5334 5335 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5336 bool &DstIsLeft, int &Anomaly) { 5337 if (M.size() != static_cast<size_t>(NumInputElements)) 5338 return false; 5339 5340 int NumLHSMatch = 0, NumRHSMatch = 0; 5341 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5342 5343 for (int i = 0; i < NumInputElements; ++i) { 5344 if (M[i] == -1) { 5345 ++NumLHSMatch; 5346 ++NumRHSMatch; 5347 continue; 5348 } 5349 5350 if (M[i] == i) 5351 ++NumLHSMatch; 5352 else 5353 LastLHSMismatch = i; 5354 5355 if (M[i] == i + NumInputElements) 5356 ++NumRHSMatch; 5357 else 5358 LastRHSMismatch = i; 5359 } 5360 5361 if (NumLHSMatch == NumInputElements - 1) { 5362 DstIsLeft = true; 5363 Anomaly = LastLHSMismatch; 5364 return true; 5365 } else if (NumRHSMatch == NumInputElements - 1) { 5366 DstIsLeft = false; 5367 Anomaly = LastRHSMismatch; 5368 return true; 5369 } 5370 5371 return false; 5372 } 5373 5374 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5375 if (VT.getSizeInBits() != 128) 5376 return false; 5377 5378 unsigned NumElts = VT.getVectorNumElements(); 5379 5380 for (int I = 0, E = NumElts / 2; I != E; I++) { 5381 if (Mask[I] != I) 5382 return false; 5383 } 5384 5385 int Offset = NumElts / 2; 5386 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5387 if (Mask[I] != I + SplitLHS * Offset) 5388 return false; 5389 } 5390 5391 return true; 5392 } 5393 5394 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5395 SDLoc DL(Op); 5396 EVT VT = Op.getValueType(); 5397 SDValue V0 = Op.getOperand(0); 5398 SDValue V1 = Op.getOperand(1); 5399 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5400 5401 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5402 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5403 return SDValue(); 5404 5405 bool SplitV0 = V0.getValueType().getSizeInBits() == 128; 5406 5407 if (!isConcatMask(Mask, VT, SplitV0)) 5408 return SDValue(); 5409 5410 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5411 VT.getVectorNumElements() / 2); 5412 if (SplitV0) { 5413 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5414 DAG.getConstant(0, DL, MVT::i64)); 5415 } 5416 if (V1.getValueType().getSizeInBits() == 128) { 5417 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5418 DAG.getConstant(0, DL, MVT::i64)); 5419 } 5420 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5421 } 5422 5423 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5424 /// the specified operations to build the shuffle. 5425 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5426 SDValue RHS, SelectionDAG &DAG, 5427 SDLoc dl) { 5428 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5429 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5430 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5431 5432 enum { 5433 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5434 OP_VREV, 5435 OP_VDUP0, 5436 OP_VDUP1, 5437 OP_VDUP2, 5438 OP_VDUP3, 5439 OP_VEXT1, 5440 OP_VEXT2, 5441 OP_VEXT3, 5442 OP_VUZPL, // VUZP, left result 5443 OP_VUZPR, // VUZP, right result 5444 OP_VZIPL, // VZIP, left result 5445 OP_VZIPR, // VZIP, right result 5446 OP_VTRNL, // VTRN, left result 5447 OP_VTRNR // VTRN, right result 5448 }; 5449 5450 if (OpNum == OP_COPY) { 5451 if (LHSID == (1 * 9 + 2) * 9 + 3) 5452 return LHS; 5453 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5454 return RHS; 5455 } 5456 5457 SDValue OpLHS, OpRHS; 5458 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5459 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5460 EVT VT = OpLHS.getValueType(); 5461 5462 switch (OpNum) { 5463 default: 5464 llvm_unreachable("Unknown shuffle opcode!"); 5465 case OP_VREV: 5466 // VREV divides the vector in half and swaps within the half. 5467 if (VT.getVectorElementType() == MVT::i32 || 5468 VT.getVectorElementType() == MVT::f32) 5469 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5470 // vrev <4 x i16> -> REV32 5471 if (VT.getVectorElementType() == MVT::i16 || 5472 VT.getVectorElementType() == MVT::f16) 5473 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5474 // vrev <4 x i8> -> REV16 5475 assert(VT.getVectorElementType() == MVT::i8); 5476 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5477 case OP_VDUP0: 5478 case OP_VDUP1: 5479 case OP_VDUP2: 5480 case OP_VDUP3: { 5481 EVT EltTy = VT.getVectorElementType(); 5482 unsigned Opcode; 5483 if (EltTy == MVT::i8) 5484 Opcode = AArch64ISD::DUPLANE8; 5485 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5486 Opcode = AArch64ISD::DUPLANE16; 5487 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5488 Opcode = AArch64ISD::DUPLANE32; 5489 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5490 Opcode = AArch64ISD::DUPLANE64; 5491 else 5492 llvm_unreachable("Invalid vector element type?"); 5493 5494 if (VT.getSizeInBits() == 64) 5495 OpLHS = WidenVector(OpLHS, DAG); 5496 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5497 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5498 } 5499 case OP_VEXT1: 5500 case OP_VEXT2: 5501 case OP_VEXT3: { 5502 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5503 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5504 DAG.getConstant(Imm, dl, MVT::i32)); 5505 } 5506 case OP_VUZPL: 5507 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5508 OpRHS); 5509 case OP_VUZPR: 5510 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5511 OpRHS); 5512 case OP_VZIPL: 5513 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5514 OpRHS); 5515 case OP_VZIPR: 5516 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5517 OpRHS); 5518 case OP_VTRNL: 5519 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5520 OpRHS); 5521 case OP_VTRNR: 5522 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5523 OpRHS); 5524 } 5525 } 5526 5527 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5528 SelectionDAG &DAG) { 5529 // Check to see if we can use the TBL instruction. 5530 SDValue V1 = Op.getOperand(0); 5531 SDValue V2 = Op.getOperand(1); 5532 SDLoc DL(Op); 5533 5534 EVT EltVT = Op.getValueType().getVectorElementType(); 5535 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5536 5537 SmallVector<SDValue, 8> TBLMask; 5538 for (int Val : ShuffleMask) { 5539 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 5540 unsigned Offset = Byte + Val * BytesPerElt; 5541 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 5542 } 5543 } 5544 5545 MVT IndexVT = MVT::v8i8; 5546 unsigned IndexLen = 8; 5547 if (Op.getValueType().getSizeInBits() == 128) { 5548 IndexVT = MVT::v16i8; 5549 IndexLen = 16; 5550 } 5551 5552 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 5553 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 5554 5555 SDValue Shuffle; 5556 if (V2.getNode()->isUndef()) { 5557 if (IndexLen == 8) 5558 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 5559 Shuffle = DAG.getNode( 5560 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5561 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5562 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, 5563 makeArrayRef(TBLMask.data(), IndexLen))); 5564 } else { 5565 if (IndexLen == 8) { 5566 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 5567 Shuffle = DAG.getNode( 5568 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5569 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5570 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, 5571 makeArrayRef(TBLMask.data(), IndexLen))); 5572 } else { 5573 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 5574 // cannot currently represent the register constraints on the input 5575 // table registers. 5576 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 5577 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, 5578 // &TBLMask[0], IndexLen)); 5579 Shuffle = DAG.getNode( 5580 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5581 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), 5582 V1Cst, V2Cst, 5583 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, 5584 makeArrayRef(TBLMask.data(), IndexLen))); 5585 } 5586 } 5587 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 5588 } 5589 5590 static unsigned getDUPLANEOp(EVT EltType) { 5591 if (EltType == MVT::i8) 5592 return AArch64ISD::DUPLANE8; 5593 if (EltType == MVT::i16 || EltType == MVT::f16) 5594 return AArch64ISD::DUPLANE16; 5595 if (EltType == MVT::i32 || EltType == MVT::f32) 5596 return AArch64ISD::DUPLANE32; 5597 if (EltType == MVT::i64 || EltType == MVT::f64) 5598 return AArch64ISD::DUPLANE64; 5599 5600 llvm_unreachable("Invalid vector element type?"); 5601 } 5602 5603 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 5604 SelectionDAG &DAG) const { 5605 SDLoc dl(Op); 5606 EVT VT = Op.getValueType(); 5607 5608 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5609 5610 // Convert shuffles that are directly supported on NEON to target-specific 5611 // DAG nodes, instead of keeping them as shuffles and matching them again 5612 // during code selection. This is more efficient and avoids the possibility 5613 // of inconsistencies between legalization and selection. 5614 ArrayRef<int> ShuffleMask = SVN->getMask(); 5615 5616 SDValue V1 = Op.getOperand(0); 5617 SDValue V2 = Op.getOperand(1); 5618 5619 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], 5620 V1.getValueType().getSimpleVT())) { 5621 int Lane = SVN->getSplatIndex(); 5622 // If this is undef splat, generate it via "just" vdup, if possible. 5623 if (Lane == -1) 5624 Lane = 0; 5625 5626 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 5627 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 5628 V1.getOperand(0)); 5629 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 5630 // constant. If so, we can just reference the lane's definition directly. 5631 if (V1.getOpcode() == ISD::BUILD_VECTOR && 5632 !isa<ConstantSDNode>(V1.getOperand(Lane))) 5633 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 5634 5635 // Otherwise, duplicate from the lane of the input vector. 5636 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 5637 5638 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 5639 // to make a vector of the same size as this SHUFFLE. We can ignore the 5640 // extract entirely, and canonicalise the concat using WidenVector. 5641 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 5642 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 5643 V1 = V1.getOperand(0); 5644 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 5645 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 5646 Lane -= Idx * VT.getVectorNumElements() / 2; 5647 V1 = WidenVector(V1.getOperand(Idx), DAG); 5648 } else if (VT.getSizeInBits() == 64) 5649 V1 = WidenVector(V1, DAG); 5650 5651 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 5652 } 5653 5654 if (isREVMask(ShuffleMask, VT, 64)) 5655 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 5656 if (isREVMask(ShuffleMask, VT, 32)) 5657 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 5658 if (isREVMask(ShuffleMask, VT, 16)) 5659 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 5660 5661 bool ReverseEXT = false; 5662 unsigned Imm; 5663 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 5664 if (ReverseEXT) 5665 std::swap(V1, V2); 5666 Imm *= getExtFactor(V1); 5667 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 5668 DAG.getConstant(Imm, dl, MVT::i32)); 5669 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 5670 Imm *= getExtFactor(V1); 5671 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 5672 DAG.getConstant(Imm, dl, MVT::i32)); 5673 } 5674 5675 unsigned WhichResult; 5676 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 5677 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5678 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5679 } 5680 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 5681 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5682 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5683 } 5684 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 5685 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5686 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5687 } 5688 5689 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5690 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5691 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5692 } 5693 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5694 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5695 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5696 } 5697 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5698 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5699 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5700 } 5701 5702 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 5703 return Concat; 5704 5705 bool DstIsLeft; 5706 int Anomaly; 5707 int NumInputElements = V1.getValueType().getVectorNumElements(); 5708 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 5709 SDValue DstVec = DstIsLeft ? V1 : V2; 5710 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 5711 5712 SDValue SrcVec = V1; 5713 int SrcLane = ShuffleMask[Anomaly]; 5714 if (SrcLane >= NumInputElements) { 5715 SrcVec = V2; 5716 SrcLane -= VT.getVectorNumElements(); 5717 } 5718 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 5719 5720 EVT ScalarVT = VT.getVectorElementType(); 5721 5722 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 5723 ScalarVT = MVT::i32; 5724 5725 return DAG.getNode( 5726 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 5727 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 5728 DstLaneV); 5729 } 5730 5731 // If the shuffle is not directly supported and it has 4 elements, use 5732 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5733 unsigned NumElts = VT.getVectorNumElements(); 5734 if (NumElts == 4) { 5735 unsigned PFIndexes[4]; 5736 for (unsigned i = 0; i != 4; ++i) { 5737 if (ShuffleMask[i] < 0) 5738 PFIndexes[i] = 8; 5739 else 5740 PFIndexes[i] = ShuffleMask[i]; 5741 } 5742 5743 // Compute the index in the perfect shuffle table. 5744 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 5745 PFIndexes[2] * 9 + PFIndexes[3]; 5746 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5747 unsigned Cost = (PFEntry >> 30); 5748 5749 if (Cost <= 4) 5750 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5751 } 5752 5753 return GenerateTBL(Op, ShuffleMask, DAG); 5754 } 5755 5756 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 5757 APInt &UndefBits) { 5758 EVT VT = BVN->getValueType(0); 5759 APInt SplatBits, SplatUndef; 5760 unsigned SplatBitSize; 5761 bool HasAnyUndefs; 5762 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5763 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 5764 5765 for (unsigned i = 0; i < NumSplats; ++i) { 5766 CnstBits <<= SplatBitSize; 5767 UndefBits <<= SplatBitSize; 5768 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 5769 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 5770 } 5771 5772 return true; 5773 } 5774 5775 return false; 5776 } 5777 5778 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 5779 SelectionDAG &DAG) const { 5780 BuildVectorSDNode *BVN = 5781 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 5782 SDValue LHS = Op.getOperand(0); 5783 SDLoc dl(Op); 5784 EVT VT = Op.getValueType(); 5785 5786 if (!BVN) 5787 return Op; 5788 5789 APInt CnstBits(VT.getSizeInBits(), 0); 5790 APInt UndefBits(VT.getSizeInBits(), 0); 5791 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 5792 // We only have BIC vector immediate instruction, which is and-not. 5793 CnstBits = ~CnstBits; 5794 5795 // We make use of a little bit of goto ickiness in order to avoid having to 5796 // duplicate the immediate matching logic for the undef toggled case. 5797 bool SecondTry = false; 5798 AttemptModImm: 5799 5800 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 5801 CnstBits = CnstBits.zextOrTrunc(64); 5802 uint64_t CnstVal = CnstBits.getZExtValue(); 5803 5804 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 5805 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 5806 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5807 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5808 DAG.getConstant(CnstVal, dl, MVT::i32), 5809 DAG.getConstant(0, dl, MVT::i32)); 5810 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5811 } 5812 5813 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 5814 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 5815 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5816 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5817 DAG.getConstant(CnstVal, dl, MVT::i32), 5818 DAG.getConstant(8, dl, MVT::i32)); 5819 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5820 } 5821 5822 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 5823 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 5824 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5825 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5826 DAG.getConstant(CnstVal, dl, MVT::i32), 5827 DAG.getConstant(16, dl, MVT::i32)); 5828 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5829 } 5830 5831 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 5832 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 5833 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5834 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5835 DAG.getConstant(CnstVal, dl, MVT::i32), 5836 DAG.getConstant(24, dl, MVT::i32)); 5837 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5838 } 5839 5840 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 5841 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 5842 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5843 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5844 DAG.getConstant(CnstVal, dl, MVT::i32), 5845 DAG.getConstant(0, dl, MVT::i32)); 5846 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5847 } 5848 5849 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 5850 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 5851 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5852 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5853 DAG.getConstant(CnstVal, dl, MVT::i32), 5854 DAG.getConstant(8, dl, MVT::i32)); 5855 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5856 } 5857 } 5858 5859 if (SecondTry) 5860 goto FailedModImm; 5861 SecondTry = true; 5862 CnstBits = ~UndefBits; 5863 goto AttemptModImm; 5864 } 5865 5866 // We can always fall back to a non-immediate AND. 5867 FailedModImm: 5868 return Op; 5869 } 5870 5871 // Specialized code to quickly find if PotentialBVec is a BuildVector that 5872 // consists of only the same constant int value, returned in reference arg 5873 // ConstVal 5874 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 5875 uint64_t &ConstVal) { 5876 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 5877 if (!Bvec) 5878 return false; 5879 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 5880 if (!FirstElt) 5881 return false; 5882 EVT VT = Bvec->getValueType(0); 5883 unsigned NumElts = VT.getVectorNumElements(); 5884 for (unsigned i = 1; i < NumElts; ++i) 5885 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 5886 return false; 5887 ConstVal = FirstElt->getZExtValue(); 5888 return true; 5889 } 5890 5891 static unsigned getIntrinsicID(const SDNode *N) { 5892 unsigned Opcode = N->getOpcode(); 5893 switch (Opcode) { 5894 default: 5895 return Intrinsic::not_intrinsic; 5896 case ISD::INTRINSIC_WO_CHAIN: { 5897 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5898 if (IID < Intrinsic::num_intrinsics) 5899 return IID; 5900 return Intrinsic::not_intrinsic; 5901 } 5902 } 5903 } 5904 5905 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 5906 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 5907 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 5908 // Also, logical shift right -> sri, with the same structure. 5909 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 5910 EVT VT = N->getValueType(0); 5911 5912 if (!VT.isVector()) 5913 return SDValue(); 5914 5915 SDLoc DL(N); 5916 5917 // Is the first op an AND? 5918 const SDValue And = N->getOperand(0); 5919 if (And.getOpcode() != ISD::AND) 5920 return SDValue(); 5921 5922 // Is the second op an shl or lshr? 5923 SDValue Shift = N->getOperand(1); 5924 // This will have been turned into: AArch64ISD::VSHL vector, #shift 5925 // or AArch64ISD::VLSHR vector, #shift 5926 unsigned ShiftOpc = Shift.getOpcode(); 5927 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 5928 return SDValue(); 5929 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 5930 5931 // Is the shift amount constant? 5932 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 5933 if (!C2node) 5934 return SDValue(); 5935 5936 // Is the and mask vector all constant? 5937 uint64_t C1; 5938 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 5939 return SDValue(); 5940 5941 // Is C1 == ~C2, taking into account how much one can shift elements of a 5942 // particular size? 5943 uint64_t C2 = C2node->getZExtValue(); 5944 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits(); 5945 if (C2 > ElemSizeInBits) 5946 return SDValue(); 5947 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 5948 if ((C1 & ElemMask) != (~C2 & ElemMask)) 5949 return SDValue(); 5950 5951 SDValue X = And.getOperand(0); 5952 SDValue Y = Shift.getOperand(0); 5953 5954 unsigned Intrin = 5955 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 5956 SDValue ResultSLI = 5957 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 5958 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 5959 Shift.getOperand(1)); 5960 5961 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 5962 DEBUG(N->dump(&DAG)); 5963 DEBUG(dbgs() << "into: \n"); 5964 DEBUG(ResultSLI->dump(&DAG)); 5965 5966 ++NumShiftInserts; 5967 return ResultSLI; 5968 } 5969 5970 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 5971 SelectionDAG &DAG) const { 5972 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 5973 if (EnableAArch64SlrGeneration) { 5974 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 5975 return Res; 5976 } 5977 5978 BuildVectorSDNode *BVN = 5979 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 5980 SDValue LHS = Op.getOperand(1); 5981 SDLoc dl(Op); 5982 EVT VT = Op.getValueType(); 5983 5984 // OR commutes, so try swapping the operands. 5985 if (!BVN) { 5986 LHS = Op.getOperand(0); 5987 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 5988 } 5989 if (!BVN) 5990 return Op; 5991 5992 APInt CnstBits(VT.getSizeInBits(), 0); 5993 APInt UndefBits(VT.getSizeInBits(), 0); 5994 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 5995 // We make use of a little bit of goto ickiness in order to avoid having to 5996 // duplicate the immediate matching logic for the undef toggled case. 5997 bool SecondTry = false; 5998 AttemptModImm: 5999 6000 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6001 CnstBits = CnstBits.zextOrTrunc(64); 6002 uint64_t CnstVal = CnstBits.getZExtValue(); 6003 6004 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6005 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6006 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6007 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6008 DAG.getConstant(CnstVal, dl, MVT::i32), 6009 DAG.getConstant(0, dl, MVT::i32)); 6010 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6011 } 6012 6013 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6014 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6015 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6016 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6017 DAG.getConstant(CnstVal, dl, MVT::i32), 6018 DAG.getConstant(8, dl, MVT::i32)); 6019 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6020 } 6021 6022 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6023 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6024 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6025 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6026 DAG.getConstant(CnstVal, dl, MVT::i32), 6027 DAG.getConstant(16, dl, MVT::i32)); 6028 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6029 } 6030 6031 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6032 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6033 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6034 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6035 DAG.getConstant(CnstVal, dl, MVT::i32), 6036 DAG.getConstant(24, dl, MVT::i32)); 6037 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6038 } 6039 6040 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6041 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6042 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6043 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6044 DAG.getConstant(CnstVal, dl, MVT::i32), 6045 DAG.getConstant(0, dl, MVT::i32)); 6046 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6047 } 6048 6049 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6050 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6051 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6052 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6053 DAG.getConstant(CnstVal, dl, MVT::i32), 6054 DAG.getConstant(8, dl, MVT::i32)); 6055 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6056 } 6057 } 6058 6059 if (SecondTry) 6060 goto FailedModImm; 6061 SecondTry = true; 6062 CnstBits = UndefBits; 6063 goto AttemptModImm; 6064 } 6065 6066 // We can always fall back to a non-immediate OR. 6067 FailedModImm: 6068 return Op; 6069 } 6070 6071 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6072 // be truncated to fit element width. 6073 static SDValue NormalizeBuildVector(SDValue Op, 6074 SelectionDAG &DAG) { 6075 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6076 SDLoc dl(Op); 6077 EVT VT = Op.getValueType(); 6078 EVT EltTy= VT.getVectorElementType(); 6079 6080 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6081 return Op; 6082 6083 SmallVector<SDValue, 16> Ops; 6084 for (SDValue Lane : Op->ops()) { 6085 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6086 APInt LowBits(EltTy.getSizeInBits(), 6087 CstLane->getZExtValue()); 6088 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6089 } 6090 Ops.push_back(Lane); 6091 } 6092 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 6093 } 6094 6095 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6096 SelectionDAG &DAG) const { 6097 SDLoc dl(Op); 6098 EVT VT = Op.getValueType(); 6099 Op = NormalizeBuildVector(Op, DAG); 6100 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6101 6102 APInt CnstBits(VT.getSizeInBits(), 0); 6103 APInt UndefBits(VT.getSizeInBits(), 0); 6104 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6105 // We make use of a little bit of goto ickiness in order to avoid having to 6106 // duplicate the immediate matching logic for the undef toggled case. 6107 bool SecondTry = false; 6108 AttemptModImm: 6109 6110 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6111 CnstBits = CnstBits.zextOrTrunc(64); 6112 uint64_t CnstVal = CnstBits.getZExtValue(); 6113 6114 // Certain magic vector constants (used to express things like NOT 6115 // and NEG) are passed through unmodified. This allows codegen patterns 6116 // for these operations to match. Special-purpose patterns will lower 6117 // these immediates to MOVIs if it proves necessary. 6118 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6119 return Op; 6120 6121 // The many faces of MOVI... 6122 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6123 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6124 if (VT.getSizeInBits() == 128) { 6125 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6126 DAG.getConstant(CnstVal, dl, MVT::i32)); 6127 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6128 } 6129 6130 // Support the V64 version via subregister insertion. 6131 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6132 DAG.getConstant(CnstVal, dl, MVT::i32)); 6133 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6134 } 6135 6136 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6137 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6138 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6139 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6140 DAG.getConstant(CnstVal, dl, MVT::i32), 6141 DAG.getConstant(0, dl, MVT::i32)); 6142 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6143 } 6144 6145 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6146 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6147 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6148 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6149 DAG.getConstant(CnstVal, dl, MVT::i32), 6150 DAG.getConstant(8, dl, MVT::i32)); 6151 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6152 } 6153 6154 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6155 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6156 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6157 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6158 DAG.getConstant(CnstVal, dl, MVT::i32), 6159 DAG.getConstant(16, dl, MVT::i32)); 6160 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6161 } 6162 6163 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6164 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6165 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6166 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6167 DAG.getConstant(CnstVal, dl, MVT::i32), 6168 DAG.getConstant(24, dl, MVT::i32)); 6169 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6170 } 6171 6172 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6173 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6174 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6175 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6176 DAG.getConstant(CnstVal, dl, MVT::i32), 6177 DAG.getConstant(0, dl, MVT::i32)); 6178 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6179 } 6180 6181 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6182 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6183 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6184 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6185 DAG.getConstant(CnstVal, dl, MVT::i32), 6186 DAG.getConstant(8, dl, MVT::i32)); 6187 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6188 } 6189 6190 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6191 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6192 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6193 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6194 DAG.getConstant(CnstVal, dl, MVT::i32), 6195 DAG.getConstant(264, dl, MVT::i32)); 6196 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6197 } 6198 6199 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6200 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6201 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6202 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6203 DAG.getConstant(CnstVal, dl, MVT::i32), 6204 DAG.getConstant(272, dl, MVT::i32)); 6205 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6206 } 6207 6208 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6209 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6210 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6211 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6212 DAG.getConstant(CnstVal, dl, MVT::i32)); 6213 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6214 } 6215 6216 // The few faces of FMOV... 6217 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6218 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6219 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6220 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6221 DAG.getConstant(CnstVal, dl, MVT::i32)); 6222 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6223 } 6224 6225 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6226 VT.getSizeInBits() == 128) { 6227 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6228 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6229 DAG.getConstant(CnstVal, dl, MVT::i32)); 6230 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6231 } 6232 6233 // The many faces of MVNI... 6234 CnstVal = ~CnstVal; 6235 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6236 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6237 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6238 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6239 DAG.getConstant(CnstVal, dl, MVT::i32), 6240 DAG.getConstant(0, dl, MVT::i32)); 6241 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6242 } 6243 6244 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6245 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6246 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6247 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6248 DAG.getConstant(CnstVal, dl, MVT::i32), 6249 DAG.getConstant(8, dl, MVT::i32)); 6250 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6251 } 6252 6253 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6254 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6255 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6256 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6257 DAG.getConstant(CnstVal, dl, MVT::i32), 6258 DAG.getConstant(16, dl, MVT::i32)); 6259 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6260 } 6261 6262 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6263 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6264 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6265 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6266 DAG.getConstant(CnstVal, dl, MVT::i32), 6267 DAG.getConstant(24, dl, MVT::i32)); 6268 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6269 } 6270 6271 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6272 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6273 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6274 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6275 DAG.getConstant(CnstVal, dl, MVT::i32), 6276 DAG.getConstant(0, dl, MVT::i32)); 6277 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6278 } 6279 6280 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6281 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6282 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6283 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6284 DAG.getConstant(CnstVal, dl, MVT::i32), 6285 DAG.getConstant(8, dl, MVT::i32)); 6286 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6287 } 6288 6289 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6290 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6291 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6292 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6293 DAG.getConstant(CnstVal, dl, MVT::i32), 6294 DAG.getConstant(264, dl, MVT::i32)); 6295 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6296 } 6297 6298 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6299 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6300 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6301 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6302 DAG.getConstant(CnstVal, dl, MVT::i32), 6303 DAG.getConstant(272, dl, MVT::i32)); 6304 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6305 } 6306 } 6307 6308 if (SecondTry) 6309 goto FailedModImm; 6310 SecondTry = true; 6311 CnstBits = UndefBits; 6312 goto AttemptModImm; 6313 } 6314 FailedModImm: 6315 6316 // Scan through the operands to find some interesting properties we can 6317 // exploit: 6318 // 1) If only one value is used, we can use a DUP, or 6319 // 2) if only the low element is not undef, we can just insert that, or 6320 // 3) if only one constant value is used (w/ some non-constant lanes), 6321 // we can splat the constant value into the whole vector then fill 6322 // in the non-constant lanes. 6323 // 4) FIXME: If different constant values are used, but we can intelligently 6324 // select the values we'll be overwriting for the non-constant 6325 // lanes such that we can directly materialize the vector 6326 // some other way (MOVI, e.g.), we can be sneaky. 6327 unsigned NumElts = VT.getVectorNumElements(); 6328 bool isOnlyLowElement = true; 6329 bool usesOnlyOneValue = true; 6330 bool usesOnlyOneConstantValue = true; 6331 bool isConstant = true; 6332 unsigned NumConstantLanes = 0; 6333 SDValue Value; 6334 SDValue ConstantValue; 6335 for (unsigned i = 0; i < NumElts; ++i) { 6336 SDValue V = Op.getOperand(i); 6337 if (V.isUndef()) 6338 continue; 6339 if (i > 0) 6340 isOnlyLowElement = false; 6341 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6342 isConstant = false; 6343 6344 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6345 ++NumConstantLanes; 6346 if (!ConstantValue.getNode()) 6347 ConstantValue = V; 6348 else if (ConstantValue != V) 6349 usesOnlyOneConstantValue = false; 6350 } 6351 6352 if (!Value.getNode()) 6353 Value = V; 6354 else if (V != Value) 6355 usesOnlyOneValue = false; 6356 } 6357 6358 if (!Value.getNode()) 6359 return DAG.getUNDEF(VT); 6360 6361 if (isOnlyLowElement) 6362 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6363 6364 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6365 // i32 and try again. 6366 if (usesOnlyOneValue) { 6367 if (!isConstant) { 6368 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6369 Value.getValueType() != VT) 6370 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6371 6372 // This is actually a DUPLANExx operation, which keeps everything vectory. 6373 6374 // DUPLANE works on 128-bit vectors, widen it if necessary. 6375 SDValue Lane = Value.getOperand(1); 6376 Value = Value.getOperand(0); 6377 if (Value.getValueType().getSizeInBits() == 64) 6378 Value = WidenVector(Value, DAG); 6379 6380 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6381 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6382 } 6383 6384 if (VT.getVectorElementType().isFloatingPoint()) { 6385 SmallVector<SDValue, 8> Ops; 6386 EVT EltTy = VT.getVectorElementType(); 6387 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6388 "Unsupported floating-point vector type"); 6389 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6390 for (unsigned i = 0; i < NumElts; ++i) 6391 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6392 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6393 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 6394 Val = LowerBUILD_VECTOR(Val, DAG); 6395 if (Val.getNode()) 6396 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6397 } 6398 } 6399 6400 // If there was only one constant value used and for more than one lane, 6401 // start by splatting that value, then replace the non-constant lanes. This 6402 // is better than the default, which will perform a separate initialization 6403 // for each lane. 6404 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6405 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6406 // Now insert the non-constant lanes. 6407 for (unsigned i = 0; i < NumElts; ++i) { 6408 SDValue V = Op.getOperand(i); 6409 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6410 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6411 // Note that type legalization likely mucked about with the VT of the 6412 // source operand, so we may have to convert it here before inserting. 6413 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6414 } 6415 } 6416 return Val; 6417 } 6418 6419 // If all elements are constants and the case above didn't get hit, fall back 6420 // to the default expansion, which will generate a load from the constant 6421 // pool. 6422 if (isConstant) 6423 return SDValue(); 6424 6425 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6426 if (NumElts >= 4) { 6427 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6428 return shuffle; 6429 } 6430 6431 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6432 // know the default expansion would otherwise fall back on something even 6433 // worse. For a vector with one or two non-undef values, that's 6434 // scalar_to_vector for the elements followed by a shuffle (provided the 6435 // shuffle is valid for the target) and materialization element by element 6436 // on the stack followed by a load for everything else. 6437 if (!isConstant && !usesOnlyOneValue) { 6438 SDValue Vec = DAG.getUNDEF(VT); 6439 SDValue Op0 = Op.getOperand(0); 6440 unsigned ElemSize = VT.getVectorElementType().getSizeInBits(); 6441 unsigned i = 0; 6442 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to 6443 // a) Avoid a RMW dependency on the full vector register, and 6444 // b) Allow the register coalescer to fold away the copy if the 6445 // value is already in an S or D register. 6446 // Do not do this for UNDEF/LOAD nodes because we have better patterns 6447 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR. 6448 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD && 6449 (ElemSize == 32 || ElemSize == 64)) { 6450 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub; 6451 MachineSDNode *N = 6452 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0, 6453 DAG.getTargetConstant(SubIdx, dl, MVT::i32)); 6454 Vec = SDValue(N, 0); 6455 ++i; 6456 } 6457 for (; i < NumElts; ++i) { 6458 SDValue V = Op.getOperand(i); 6459 if (V.isUndef()) 6460 continue; 6461 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6462 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6463 } 6464 return Vec; 6465 } 6466 6467 // Just use the default expansion. We failed to find a better alternative. 6468 return SDValue(); 6469 } 6470 6471 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6472 SelectionDAG &DAG) const { 6473 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6474 6475 // Check for non-constant or out of range lane. 6476 EVT VT = Op.getOperand(0).getValueType(); 6477 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6478 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6479 return SDValue(); 6480 6481 6482 // Insertion/extraction are legal for V128 types. 6483 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6484 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6485 VT == MVT::v8f16) 6486 return Op; 6487 6488 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6489 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6490 return SDValue(); 6491 6492 // For V64 types, we perform insertion by expanding the value 6493 // to a V128 type and perform the insertion on that. 6494 SDLoc DL(Op); 6495 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6496 EVT WideTy = WideVec.getValueType(); 6497 6498 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6499 Op.getOperand(1), Op.getOperand(2)); 6500 // Re-narrow the resultant vector. 6501 return NarrowVector(Node, DAG); 6502 } 6503 6504 SDValue 6505 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6506 SelectionDAG &DAG) const { 6507 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6508 6509 // Check for non-constant or out of range lane. 6510 EVT VT = Op.getOperand(0).getValueType(); 6511 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6512 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6513 return SDValue(); 6514 6515 6516 // Insertion/extraction are legal for V128 types. 6517 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6518 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6519 VT == MVT::v8f16) 6520 return Op; 6521 6522 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6523 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6524 return SDValue(); 6525 6526 // For V64 types, we perform extraction by expanding the value 6527 // to a V128 type and perform the extraction on that. 6528 SDLoc DL(Op); 6529 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6530 EVT WideTy = WideVec.getValueType(); 6531 6532 EVT ExtrTy = WideTy.getVectorElementType(); 6533 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 6534 ExtrTy = MVT::i32; 6535 6536 // For extractions, we just return the result directly. 6537 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 6538 Op.getOperand(1)); 6539 } 6540 6541 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 6542 SelectionDAG &DAG) const { 6543 EVT VT = Op.getOperand(0).getValueType(); 6544 SDLoc dl(Op); 6545 // Just in case... 6546 if (!VT.isVector()) 6547 return SDValue(); 6548 6549 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6550 if (!Cst) 6551 return SDValue(); 6552 unsigned Val = Cst->getZExtValue(); 6553 6554 unsigned Size = Op.getValueType().getSizeInBits(); 6555 6556 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 6557 if (Val == 0) 6558 return Op; 6559 6560 // If this is extracting the upper 64-bits of a 128-bit vector, we match 6561 // that directly. 6562 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64) 6563 return Op; 6564 6565 return SDValue(); 6566 } 6567 6568 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6569 EVT VT) const { 6570 if (VT.getVectorNumElements() == 4 && 6571 (VT.is128BitVector() || VT.is64BitVector())) { 6572 unsigned PFIndexes[4]; 6573 for (unsigned i = 0; i != 4; ++i) { 6574 if (M[i] < 0) 6575 PFIndexes[i] = 8; 6576 else 6577 PFIndexes[i] = M[i]; 6578 } 6579 6580 // Compute the index in the perfect shuffle table. 6581 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6582 PFIndexes[2] * 9 + PFIndexes[3]; 6583 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6584 unsigned Cost = (PFEntry >> 30); 6585 6586 if (Cost <= 4) 6587 return true; 6588 } 6589 6590 bool DummyBool; 6591 int DummyInt; 6592 unsigned DummyUnsigned; 6593 6594 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 6595 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 6596 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 6597 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 6598 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 6599 isZIPMask(M, VT, DummyUnsigned) || 6600 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 6601 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 6602 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 6603 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 6604 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 6605 } 6606 6607 /// getVShiftImm - Check if this is a valid build_vector for the immediate 6608 /// operand of a vector shift operation, where all the elements of the 6609 /// build_vector must have the same constant integer value. 6610 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6611 // Ignore bit_converts. 6612 while (Op.getOpcode() == ISD::BITCAST) 6613 Op = Op.getOperand(0); 6614 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6615 APInt SplatBits, SplatUndef; 6616 unsigned SplatBitSize; 6617 bool HasAnyUndefs; 6618 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 6619 HasAnyUndefs, ElementBits) || 6620 SplatBitSize > ElementBits) 6621 return false; 6622 Cnt = SplatBits.getSExtValue(); 6623 return true; 6624 } 6625 6626 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6627 /// operand of a vector shift left operation. That value must be in the range: 6628 /// 0 <= Value < ElementBits for a left shift; or 6629 /// 0 <= Value <= ElementBits for a long left shift. 6630 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6631 assert(VT.isVector() && "vector shift count is not a vector type"); 6632 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 6633 if (!getVShiftImm(Op, ElementBits, Cnt)) 6634 return false; 6635 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6636 } 6637 6638 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6639 /// operand of a vector shift right operation. The value must be in the range: 6640 /// 1 <= Value <= ElementBits for a right shift; or 6641 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 6642 assert(VT.isVector() && "vector shift count is not a vector type"); 6643 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 6644 if (!getVShiftImm(Op, ElementBits, Cnt)) 6645 return false; 6646 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6647 } 6648 6649 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 6650 SelectionDAG &DAG) const { 6651 EVT VT = Op.getValueType(); 6652 SDLoc DL(Op); 6653 int64_t Cnt; 6654 6655 if (!Op.getOperand(1).getValueType().isVector()) 6656 return Op; 6657 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6658 6659 switch (Op.getOpcode()) { 6660 default: 6661 llvm_unreachable("unexpected shift opcode"); 6662 6663 case ISD::SHL: 6664 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 6665 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 6666 DAG.getConstant(Cnt, DL, MVT::i32)); 6667 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6668 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 6669 MVT::i32), 6670 Op.getOperand(0), Op.getOperand(1)); 6671 case ISD::SRA: 6672 case ISD::SRL: 6673 // Right shift immediate 6674 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 6675 unsigned Opc = 6676 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 6677 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 6678 DAG.getConstant(Cnt, DL, MVT::i32)); 6679 } 6680 6681 // Right shift register. Note, there is not a shift right register 6682 // instruction, but the shift left register instruction takes a signed 6683 // value, where negative numbers specify a right shift. 6684 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 6685 : Intrinsic::aarch64_neon_ushl; 6686 // negate the shift amount 6687 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 6688 SDValue NegShiftLeft = 6689 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6690 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 6691 NegShift); 6692 return NegShiftLeft; 6693 } 6694 6695 return SDValue(); 6696 } 6697 6698 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 6699 AArch64CC::CondCode CC, bool NoNans, EVT VT, 6700 SDLoc dl, SelectionDAG &DAG) { 6701 EVT SrcVT = LHS.getValueType(); 6702 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 6703 "function only supposed to emit natural comparisons"); 6704 6705 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 6706 APInt CnstBits(VT.getSizeInBits(), 0); 6707 APInt UndefBits(VT.getSizeInBits(), 0); 6708 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 6709 bool IsZero = IsCnst && (CnstBits == 0); 6710 6711 if (SrcVT.getVectorElementType().isFloatingPoint()) { 6712 switch (CC) { 6713 default: 6714 return SDValue(); 6715 case AArch64CC::NE: { 6716 SDValue Fcmeq; 6717 if (IsZero) 6718 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6719 else 6720 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6721 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 6722 } 6723 case AArch64CC::EQ: 6724 if (IsZero) 6725 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6726 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6727 case AArch64CC::GE: 6728 if (IsZero) 6729 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 6730 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 6731 case AArch64CC::GT: 6732 if (IsZero) 6733 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 6734 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 6735 case AArch64CC::LS: 6736 if (IsZero) 6737 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 6738 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 6739 case AArch64CC::LT: 6740 if (!NoNans) 6741 return SDValue(); 6742 // If we ignore NaNs then we can use to the MI implementation. 6743 // Fallthrough. 6744 case AArch64CC::MI: 6745 if (IsZero) 6746 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 6747 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 6748 } 6749 } 6750 6751 switch (CC) { 6752 default: 6753 return SDValue(); 6754 case AArch64CC::NE: { 6755 SDValue Cmeq; 6756 if (IsZero) 6757 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6758 else 6759 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6760 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 6761 } 6762 case AArch64CC::EQ: 6763 if (IsZero) 6764 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6765 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6766 case AArch64CC::GE: 6767 if (IsZero) 6768 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 6769 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 6770 case AArch64CC::GT: 6771 if (IsZero) 6772 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 6773 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 6774 case AArch64CC::LE: 6775 if (IsZero) 6776 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 6777 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 6778 case AArch64CC::LS: 6779 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 6780 case AArch64CC::LO: 6781 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 6782 case AArch64CC::LT: 6783 if (IsZero) 6784 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 6785 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 6786 case AArch64CC::HI: 6787 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 6788 case AArch64CC::HS: 6789 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 6790 } 6791 } 6792 6793 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 6794 SelectionDAG &DAG) const { 6795 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6796 SDValue LHS = Op.getOperand(0); 6797 SDValue RHS = Op.getOperand(1); 6798 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 6799 SDLoc dl(Op); 6800 6801 if (LHS.getValueType().getVectorElementType().isInteger()) { 6802 assert(LHS.getValueType() == RHS.getValueType()); 6803 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6804 SDValue Cmp = 6805 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 6806 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6807 } 6808 6809 if (LHS.getValueType().getVectorElementType() == MVT::f16) 6810 return SDValue(); 6811 6812 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 6813 LHS.getValueType().getVectorElementType() == MVT::f64); 6814 6815 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6816 // clean. Some of them require two branches to implement. 6817 AArch64CC::CondCode CC1, CC2; 6818 bool ShouldInvert; 6819 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 6820 6821 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 6822 SDValue Cmp = 6823 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 6824 if (!Cmp.getNode()) 6825 return SDValue(); 6826 6827 if (CC2 != AArch64CC::AL) { 6828 SDValue Cmp2 = 6829 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 6830 if (!Cmp2.getNode()) 6831 return SDValue(); 6832 6833 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 6834 } 6835 6836 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6837 6838 if (ShouldInvert) 6839 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 6840 6841 return Cmp; 6842 } 6843 6844 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 6845 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 6846 /// specified in the intrinsic calls. 6847 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 6848 const CallInst &I, 6849 unsigned Intrinsic) const { 6850 auto &DL = I.getModule()->getDataLayout(); 6851 switch (Intrinsic) { 6852 case Intrinsic::aarch64_neon_ld2: 6853 case Intrinsic::aarch64_neon_ld3: 6854 case Intrinsic::aarch64_neon_ld4: 6855 case Intrinsic::aarch64_neon_ld1x2: 6856 case Intrinsic::aarch64_neon_ld1x3: 6857 case Intrinsic::aarch64_neon_ld1x4: 6858 case Intrinsic::aarch64_neon_ld2lane: 6859 case Intrinsic::aarch64_neon_ld3lane: 6860 case Intrinsic::aarch64_neon_ld4lane: 6861 case Intrinsic::aarch64_neon_ld2r: 6862 case Intrinsic::aarch64_neon_ld3r: 6863 case Intrinsic::aarch64_neon_ld4r: { 6864 Info.opc = ISD::INTRINSIC_W_CHAIN; 6865 // Conservatively set memVT to the entire set of vectors loaded. 6866 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 6867 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6868 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6869 Info.offset = 0; 6870 Info.align = 0; 6871 Info.vol = false; // volatile loads with NEON intrinsics not supported 6872 Info.readMem = true; 6873 Info.writeMem = false; 6874 return true; 6875 } 6876 case Intrinsic::aarch64_neon_st2: 6877 case Intrinsic::aarch64_neon_st3: 6878 case Intrinsic::aarch64_neon_st4: 6879 case Intrinsic::aarch64_neon_st1x2: 6880 case Intrinsic::aarch64_neon_st1x3: 6881 case Intrinsic::aarch64_neon_st1x4: 6882 case Intrinsic::aarch64_neon_st2lane: 6883 case Intrinsic::aarch64_neon_st3lane: 6884 case Intrinsic::aarch64_neon_st4lane: { 6885 Info.opc = ISD::INTRINSIC_VOID; 6886 // Conservatively set memVT to the entire set of vectors stored. 6887 unsigned NumElts = 0; 6888 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 6889 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 6890 if (!ArgTy->isVectorTy()) 6891 break; 6892 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 6893 } 6894 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6895 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6896 Info.offset = 0; 6897 Info.align = 0; 6898 Info.vol = false; // volatile stores with NEON intrinsics not supported 6899 Info.readMem = false; 6900 Info.writeMem = true; 6901 return true; 6902 } 6903 case Intrinsic::aarch64_ldaxr: 6904 case Intrinsic::aarch64_ldxr: { 6905 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 6906 Info.opc = ISD::INTRINSIC_W_CHAIN; 6907 Info.memVT = MVT::getVT(PtrTy->getElementType()); 6908 Info.ptrVal = I.getArgOperand(0); 6909 Info.offset = 0; 6910 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 6911 Info.vol = true; 6912 Info.readMem = true; 6913 Info.writeMem = false; 6914 return true; 6915 } 6916 case Intrinsic::aarch64_stlxr: 6917 case Intrinsic::aarch64_stxr: { 6918 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 6919 Info.opc = ISD::INTRINSIC_W_CHAIN; 6920 Info.memVT = MVT::getVT(PtrTy->getElementType()); 6921 Info.ptrVal = I.getArgOperand(1); 6922 Info.offset = 0; 6923 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 6924 Info.vol = true; 6925 Info.readMem = false; 6926 Info.writeMem = true; 6927 return true; 6928 } 6929 case Intrinsic::aarch64_ldaxp: 6930 case Intrinsic::aarch64_ldxp: { 6931 Info.opc = ISD::INTRINSIC_W_CHAIN; 6932 Info.memVT = MVT::i128; 6933 Info.ptrVal = I.getArgOperand(0); 6934 Info.offset = 0; 6935 Info.align = 16; 6936 Info.vol = true; 6937 Info.readMem = true; 6938 Info.writeMem = false; 6939 return true; 6940 } 6941 case Intrinsic::aarch64_stlxp: 6942 case Intrinsic::aarch64_stxp: { 6943 Info.opc = ISD::INTRINSIC_W_CHAIN; 6944 Info.memVT = MVT::i128; 6945 Info.ptrVal = I.getArgOperand(2); 6946 Info.offset = 0; 6947 Info.align = 16; 6948 Info.vol = true; 6949 Info.readMem = false; 6950 Info.writeMem = true; 6951 return true; 6952 } 6953 default: 6954 break; 6955 } 6956 6957 return false; 6958 } 6959 6960 // Truncations from 64-bit GPR to 32-bit GPR is free. 6961 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 6962 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 6963 return false; 6964 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 6965 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 6966 return NumBits1 > NumBits2; 6967 } 6968 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 6969 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 6970 return false; 6971 unsigned NumBits1 = VT1.getSizeInBits(); 6972 unsigned NumBits2 = VT2.getSizeInBits(); 6973 return NumBits1 > NumBits2; 6974 } 6975 6976 /// Check if it is profitable to hoist instruction in then/else to if. 6977 /// Not profitable if I and it's user can form a FMA instruction 6978 /// because we prefer FMSUB/FMADD. 6979 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 6980 if (I->getOpcode() != Instruction::FMul) 6981 return true; 6982 6983 if (I->getNumUses() != 1) 6984 return true; 6985 6986 Instruction *User = I->user_back(); 6987 6988 if (User && 6989 !(User->getOpcode() == Instruction::FSub || 6990 User->getOpcode() == Instruction::FAdd)) 6991 return true; 6992 6993 const TargetOptions &Options = getTargetMachine().Options; 6994 const DataLayout &DL = I->getModule()->getDataLayout(); 6995 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 6996 6997 return !(isFMAFasterThanFMulAndFAdd(VT) && 6998 isOperationLegalOrCustom(ISD::FMA, VT) && 6999 (Options.AllowFPOpFusion == FPOpFusion::Fast || 7000 Options.UnsafeFPMath)); 7001 } 7002 7003 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 7004 // 64-bit GPR. 7005 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 7006 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7007 return false; 7008 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7009 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7010 return NumBits1 == 32 && NumBits2 == 64; 7011 } 7012 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 7013 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7014 return false; 7015 unsigned NumBits1 = VT1.getSizeInBits(); 7016 unsigned NumBits2 = VT2.getSizeInBits(); 7017 return NumBits1 == 32 && NumBits2 == 64; 7018 } 7019 7020 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7021 EVT VT1 = Val.getValueType(); 7022 if (isZExtFree(VT1, VT2)) { 7023 return true; 7024 } 7025 7026 if (Val.getOpcode() != ISD::LOAD) 7027 return false; 7028 7029 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7030 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7031 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7032 VT1.getSizeInBits() <= 32); 7033 } 7034 7035 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7036 if (isa<FPExtInst>(Ext)) 7037 return false; 7038 7039 // Vector types are next free. 7040 if (Ext->getType()->isVectorTy()) 7041 return false; 7042 7043 for (const Use &U : Ext->uses()) { 7044 // The extension is free if we can fold it with a left shift in an 7045 // addressing mode or an arithmetic operation: add, sub, and cmp. 7046 7047 // Is there a shift? 7048 const Instruction *Instr = cast<Instruction>(U.getUser()); 7049 7050 // Is this a constant shift? 7051 switch (Instr->getOpcode()) { 7052 case Instruction::Shl: 7053 if (!isa<ConstantInt>(Instr->getOperand(1))) 7054 return false; 7055 break; 7056 case Instruction::GetElementPtr: { 7057 gep_type_iterator GTI = gep_type_begin(Instr); 7058 auto &DL = Ext->getModule()->getDataLayout(); 7059 std::advance(GTI, U.getOperandNo()); 7060 Type *IdxTy = *GTI; 7061 // This extension will end up with a shift because of the scaling factor. 7062 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7063 // Get the shift amount based on the scaling factor: 7064 // log2(sizeof(IdxTy)) - log2(8). 7065 uint64_t ShiftAmt = 7066 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7067 // Is the constant foldable in the shift of the addressing mode? 7068 // I.e., shift amount is between 1 and 4 inclusive. 7069 if (ShiftAmt == 0 || ShiftAmt > 4) 7070 return false; 7071 break; 7072 } 7073 case Instruction::Trunc: 7074 // Check if this is a noop. 7075 // trunc(sext ty1 to ty2) to ty1. 7076 if (Instr->getType() == Ext->getOperand(0)->getType()) 7077 continue; 7078 // FALL THROUGH. 7079 default: 7080 return false; 7081 } 7082 7083 // At this point we can use the bfm family, so this extension is free 7084 // for that use. 7085 } 7086 return true; 7087 } 7088 7089 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType, 7090 unsigned &RequiredAligment) const { 7091 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy()) 7092 return false; 7093 // Cyclone supports unaligned accesses. 7094 RequiredAligment = 0; 7095 unsigned NumBits = LoadedType->getPrimitiveSizeInBits(); 7096 return NumBits == 32 || NumBits == 64; 7097 } 7098 7099 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7100 unsigned &RequiredAligment) const { 7101 if (!LoadedType.isSimple() || 7102 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7103 return false; 7104 // Cyclone supports unaligned accesses. 7105 RequiredAligment = 0; 7106 unsigned NumBits = LoadedType.getSizeInBits(); 7107 return NumBits == 32 || NumBits == 64; 7108 } 7109 7110 /// \brief Lower an interleaved load into a ldN intrinsic. 7111 /// 7112 /// E.g. Lower an interleaved load (Factor = 2): 7113 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7114 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7115 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7116 /// 7117 /// Into: 7118 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7119 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7120 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7121 bool AArch64TargetLowering::lowerInterleavedLoad( 7122 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7123 ArrayRef<unsigned> Indices, unsigned Factor) const { 7124 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7125 "Invalid interleave factor"); 7126 assert(!Shuffles.empty() && "Empty shufflevector input"); 7127 assert(Shuffles.size() == Indices.size() && 7128 "Unmatched number of shufflevectors and indices"); 7129 7130 const DataLayout &DL = LI->getModule()->getDataLayout(); 7131 7132 VectorType *VecTy = Shuffles[0]->getType(); 7133 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7134 7135 // Skip if we do not have NEON and skip illegal vector types. 7136 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128)) 7137 return false; 7138 7139 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7140 // load integer vectors first and then convert to pointer vectors. 7141 Type *EltTy = VecTy->getVectorElementType(); 7142 if (EltTy->isPointerTy()) 7143 VecTy = 7144 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7145 7146 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7147 Type *Tys[2] = {VecTy, PtrTy}; 7148 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7149 Intrinsic::aarch64_neon_ld3, 7150 Intrinsic::aarch64_neon_ld4}; 7151 Function *LdNFunc = 7152 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7153 7154 IRBuilder<> Builder(LI); 7155 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy); 7156 7157 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN"); 7158 7159 // Replace uses of each shufflevector with the corresponding vector loaded 7160 // by ldN. 7161 for (unsigned i = 0; i < Shuffles.size(); i++) { 7162 ShuffleVectorInst *SVI = Shuffles[i]; 7163 unsigned Index = Indices[i]; 7164 7165 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7166 7167 // Convert the integer vector to pointer vector if the element is pointer. 7168 if (EltTy->isPointerTy()) 7169 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType()); 7170 7171 SVI->replaceAllUsesWith(SubVec); 7172 } 7173 7174 return true; 7175 } 7176 7177 /// \brief Get a mask consisting of sequential integers starting from \p Start. 7178 /// 7179 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 7180 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 7181 unsigned NumElts) { 7182 SmallVector<Constant *, 16> Mask; 7183 for (unsigned i = 0; i < NumElts; i++) 7184 Mask.push_back(Builder.getInt32(Start + i)); 7185 7186 return ConstantVector::get(Mask); 7187 } 7188 7189 /// \brief Lower an interleaved store into a stN intrinsic. 7190 /// 7191 /// E.g. Lower an interleaved store (Factor = 3): 7192 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7193 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7194 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7195 /// 7196 /// Into: 7197 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7198 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7199 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7200 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7201 /// 7202 /// Note that the new shufflevectors will be removed and we'll only generate one 7203 /// st3 instruction in CodeGen. 7204 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7205 ShuffleVectorInst *SVI, 7206 unsigned Factor) const { 7207 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7208 "Invalid interleave factor"); 7209 7210 VectorType *VecTy = SVI->getType(); 7211 assert(VecTy->getVectorNumElements() % Factor == 0 && 7212 "Invalid interleaved store"); 7213 7214 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 7215 Type *EltTy = VecTy->getVectorElementType(); 7216 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 7217 7218 const DataLayout &DL = SI->getModule()->getDataLayout(); 7219 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 7220 7221 // Skip if we do not have NEON and skip illegal vector types. 7222 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128)) 7223 return false; 7224 7225 Value *Op0 = SVI->getOperand(0); 7226 Value *Op1 = SVI->getOperand(1); 7227 IRBuilder<> Builder(SI); 7228 7229 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7230 // vectors to integer vectors. 7231 if (EltTy->isPointerTy()) { 7232 Type *IntTy = DL.getIntPtrType(EltTy); 7233 unsigned NumOpElts = 7234 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7235 7236 // Convert to the corresponding integer vector. 7237 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7238 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7239 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7240 7241 SubVecTy = VectorType::get(IntTy, NumSubElts); 7242 } 7243 7244 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7245 Type *Tys[2] = {SubVecTy, PtrTy}; 7246 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7247 Intrinsic::aarch64_neon_st3, 7248 Intrinsic::aarch64_neon_st4}; 7249 Function *StNFunc = 7250 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7251 7252 SmallVector<Value *, 5> Ops; 7253 7254 // Split the shufflevector operands into sub vectors for the new stN call. 7255 for (unsigned i = 0; i < Factor; i++) 7256 Ops.push_back(Builder.CreateShuffleVector( 7257 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 7258 7259 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy)); 7260 Builder.CreateCall(StNFunc, Ops); 7261 return true; 7262 } 7263 7264 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7265 unsigned AlignCheck) { 7266 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7267 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7268 } 7269 7270 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7271 unsigned SrcAlign, bool IsMemset, 7272 bool ZeroMemset, 7273 bool MemcpyStrSrc, 7274 MachineFunction &MF) const { 7275 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7276 // instruction to materialize the v2i64 zero and one store (with restrictive 7277 // addressing mode). Just do two i64 store of zero-registers. 7278 bool Fast; 7279 const Function *F = MF.getFunction(); 7280 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7281 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7282 (memOpAlign(SrcAlign, DstAlign, 16) || 7283 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7284 return MVT::f128; 7285 7286 if (Size >= 8 && 7287 (memOpAlign(SrcAlign, DstAlign, 8) || 7288 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7289 return MVT::i64; 7290 7291 if (Size >= 4 && 7292 (memOpAlign(SrcAlign, DstAlign, 4) || 7293 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7294 return MVT::i32; 7295 7296 return MVT::Other; 7297 } 7298 7299 // 12-bit optionally shifted immediates are legal for adds. 7300 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7301 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7302 } 7303 7304 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7305 // immediates is the same as for an add or a sub. 7306 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7307 if (Immed < 0) 7308 Immed *= -1; 7309 return isLegalAddImmediate(Immed); 7310 } 7311 7312 /// isLegalAddressingMode - Return true if the addressing mode represented 7313 /// by AM is legal for this target, for a load/store of the specified type. 7314 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7315 const AddrMode &AM, Type *Ty, 7316 unsigned AS) const { 7317 // AArch64 has five basic addressing modes: 7318 // reg 7319 // reg + 9-bit signed offset 7320 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7321 // reg1 + reg2 7322 // reg + SIZE_IN_BYTES * reg 7323 7324 // No global is ever allowed as a base. 7325 if (AM.BaseGV) 7326 return false; 7327 7328 // No reg+reg+imm addressing. 7329 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7330 return false; 7331 7332 // check reg + imm case: 7333 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7334 uint64_t NumBytes = 0; 7335 if (Ty->isSized()) { 7336 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7337 NumBytes = NumBits / 8; 7338 if (!isPowerOf2_64(NumBits)) 7339 NumBytes = 0; 7340 } 7341 7342 if (!AM.Scale) { 7343 int64_t Offset = AM.BaseOffs; 7344 7345 // 9-bit signed offset 7346 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1) 7347 return true; 7348 7349 // 12-bit unsigned offset 7350 unsigned shift = Log2_64(NumBytes); 7351 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 7352 // Must be a multiple of NumBytes (NumBytes is a power of 2) 7353 (Offset >> shift) << shift == Offset) 7354 return true; 7355 return false; 7356 } 7357 7358 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 7359 7360 return !AM.Scale || AM.Scale == 1 || 7361 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 7362 } 7363 7364 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 7365 const AddrMode &AM, Type *Ty, 7366 unsigned AS) const { 7367 // Scaling factors are not free at all. 7368 // Operands | Rt Latency 7369 // ------------------------------------------- 7370 // Rt, [Xn, Xm] | 4 7371 // ------------------------------------------- 7372 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 7373 // Rt, [Xn, Wm, <extend> #imm] | 7374 if (isLegalAddressingMode(DL, AM, Ty, AS)) 7375 // Scale represents reg2 * scale, thus account for 1 if 7376 // it is not equal to 0 or 1. 7377 return AM.Scale != 0 && AM.Scale != 1; 7378 return -1; 7379 } 7380 7381 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7382 VT = VT.getScalarType(); 7383 7384 if (!VT.isSimple()) 7385 return false; 7386 7387 switch (VT.getSimpleVT().SimpleTy) { 7388 case MVT::f32: 7389 case MVT::f64: 7390 return true; 7391 default: 7392 break; 7393 } 7394 7395 return false; 7396 } 7397 7398 const MCPhysReg * 7399 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 7400 // LR is a callee-save register, but we must treat it as clobbered by any call 7401 // site. Hence we include LR in the scratch registers, which are in turn added 7402 // as implicit-defs for stackmaps and patchpoints. 7403 static const MCPhysReg ScratchRegs[] = { 7404 AArch64::X16, AArch64::X17, AArch64::LR, 0 7405 }; 7406 return ScratchRegs; 7407 } 7408 7409 bool 7410 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 7411 EVT VT = N->getValueType(0); 7412 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 7413 // it with shift to let it be lowered to UBFX. 7414 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 7415 isa<ConstantSDNode>(N->getOperand(1))) { 7416 uint64_t TruncMask = N->getConstantOperandVal(1); 7417 if (isMask_64(TruncMask) && 7418 N->getOperand(0).getOpcode() == ISD::SRL && 7419 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 7420 return false; 7421 } 7422 return true; 7423 } 7424 7425 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 7426 Type *Ty) const { 7427 assert(Ty->isIntegerTy()); 7428 7429 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 7430 if (BitSize == 0) 7431 return false; 7432 7433 int64_t Val = Imm.getSExtValue(); 7434 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 7435 return true; 7436 7437 if ((int64_t)Val < 0) 7438 Val = ~Val; 7439 if (BitSize == 32) 7440 Val &= (1LL << 32) - 1; 7441 7442 unsigned LZ = countLeadingZeros((uint64_t)Val); 7443 unsigned Shift = (63 - LZ) / 16; 7444 // MOVZ is free so return true for one or fewer MOVK. 7445 return Shift < 3; 7446 } 7447 7448 /// Turn vector tests of the signbit in the form of: 7449 /// xor (sra X, elt_size(X)-1), -1 7450 /// into: 7451 /// cmge X, X, #0 7452 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 7453 const AArch64Subtarget *Subtarget) { 7454 EVT VT = N->getValueType(0); 7455 if (!Subtarget->hasNEON() || !VT.isVector()) 7456 return SDValue(); 7457 7458 // There must be a shift right algebraic before the xor, and the xor must be a 7459 // 'not' operation. 7460 SDValue Shift = N->getOperand(0); 7461 SDValue Ones = N->getOperand(1); 7462 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 7463 !ISD::isBuildVectorAllOnes(Ones.getNode())) 7464 return SDValue(); 7465 7466 // The shift should be smearing the sign bit across each vector element. 7467 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7468 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 7469 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 7470 return SDValue(); 7471 7472 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 7473 } 7474 7475 // Generate SUBS and CSEL for integer abs. 7476 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 7477 EVT VT = N->getValueType(0); 7478 7479 SDValue N0 = N->getOperand(0); 7480 SDValue N1 = N->getOperand(1); 7481 SDLoc DL(N); 7482 7483 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 7484 // and change it to SUB and CSEL. 7485 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 7486 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 7487 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 7488 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 7489 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 7490 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7491 N0.getOperand(0)); 7492 // Generate SUBS & CSEL. 7493 SDValue Cmp = 7494 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 7495 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 7496 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 7497 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 7498 SDValue(Cmp.getNode(), 1)); 7499 } 7500 return SDValue(); 7501 } 7502 7503 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 7504 TargetLowering::DAGCombinerInfo &DCI, 7505 const AArch64Subtarget *Subtarget) { 7506 if (DCI.isBeforeLegalizeOps()) 7507 return SDValue(); 7508 7509 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 7510 return Cmp; 7511 7512 return performIntegerAbsCombine(N, DAG); 7513 } 7514 7515 SDValue 7516 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7517 SelectionDAG &DAG, 7518 std::vector<SDNode *> *Created) const { 7519 // fold (sdiv X, pow2) 7520 EVT VT = N->getValueType(0); 7521 if ((VT != MVT::i32 && VT != MVT::i64) || 7522 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 7523 return SDValue(); 7524 7525 SDLoc DL(N); 7526 SDValue N0 = N->getOperand(0); 7527 unsigned Lg2 = Divisor.countTrailingZeros(); 7528 SDValue Zero = DAG.getConstant(0, DL, VT); 7529 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 7530 7531 // Add (N0 < 0) ? Pow2 - 1 : 0; 7532 SDValue CCVal; 7533 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 7534 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 7535 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 7536 7537 if (Created) { 7538 Created->push_back(Cmp.getNode()); 7539 Created->push_back(Add.getNode()); 7540 Created->push_back(CSel.getNode()); 7541 } 7542 7543 // Divide by pow2. 7544 SDValue SRA = 7545 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 7546 7547 // If we're dividing by a positive value, we're done. Otherwise, we must 7548 // negate the result. 7549 if (Divisor.isNonNegative()) 7550 return SRA; 7551 7552 if (Created) 7553 Created->push_back(SRA.getNode()); 7554 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 7555 } 7556 7557 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 7558 TargetLowering::DAGCombinerInfo &DCI, 7559 const AArch64Subtarget *Subtarget) { 7560 if (DCI.isBeforeLegalizeOps()) 7561 return SDValue(); 7562 7563 // Multiplication of a power of two plus/minus one can be done more 7564 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 7565 // future CPUs have a cheaper MADD instruction, this may need to be 7566 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 7567 // 64-bit is 5 cycles, so this is always a win. 7568 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 7569 APInt Value = C->getAPIntValue(); 7570 EVT VT = N->getValueType(0); 7571 SDLoc DL(N); 7572 if (Value.isNonNegative()) { 7573 // (mul x, 2^N + 1) => (add (shl x, N), x) 7574 APInt VM1 = Value - 1; 7575 if (VM1.isPowerOf2()) { 7576 SDValue ShiftedVal = 7577 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7578 DAG.getConstant(VM1.logBase2(), DL, MVT::i64)); 7579 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, 7580 N->getOperand(0)); 7581 } 7582 // (mul x, 2^N - 1) => (sub (shl x, N), x) 7583 APInt VP1 = Value + 1; 7584 if (VP1.isPowerOf2()) { 7585 SDValue ShiftedVal = 7586 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7587 DAG.getConstant(VP1.logBase2(), DL, MVT::i64)); 7588 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal, 7589 N->getOperand(0)); 7590 } 7591 } else { 7592 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 7593 APInt VNP1 = -Value + 1; 7594 if (VNP1.isPowerOf2()) { 7595 SDValue ShiftedVal = 7596 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7597 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64)); 7598 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), 7599 ShiftedVal); 7600 } 7601 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 7602 APInt VNM1 = -Value - 1; 7603 if (VNM1.isPowerOf2()) { 7604 SDValue ShiftedVal = 7605 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7606 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64)); 7607 SDValue Add = 7608 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0)); 7609 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add); 7610 } 7611 } 7612 } 7613 return SDValue(); 7614 } 7615 7616 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 7617 SelectionDAG &DAG) { 7618 // Take advantage of vector comparisons producing 0 or -1 in each lane to 7619 // optimize away operation when it's from a constant. 7620 // 7621 // The general transformation is: 7622 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 7623 // AND(VECTOR_CMP(x,y), constant2) 7624 // constant2 = UNARYOP(constant) 7625 7626 // Early exit if this isn't a vector operation, the operand of the 7627 // unary operation isn't a bitwise AND, or if the sizes of the operations 7628 // aren't the same. 7629 EVT VT = N->getValueType(0); 7630 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 7631 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 7632 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 7633 return SDValue(); 7634 7635 // Now check that the other operand of the AND is a constant. We could 7636 // make the transformation for non-constant splats as well, but it's unclear 7637 // that would be a benefit as it would not eliminate any operations, just 7638 // perform one more step in scalar code before moving to the vector unit. 7639 if (BuildVectorSDNode *BV = 7640 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 7641 // Bail out if the vector isn't a constant. 7642 if (!BV->isConstant()) 7643 return SDValue(); 7644 7645 // Everything checks out. Build up the new and improved node. 7646 SDLoc DL(N); 7647 EVT IntVT = BV->getValueType(0); 7648 // Create a new constant of the appropriate type for the transformed 7649 // DAG. 7650 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 7651 // The AND node needs bitcasts to/from an integer vector type around it. 7652 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 7653 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 7654 N->getOperand(0)->getOperand(0), MaskConst); 7655 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 7656 return Res; 7657 } 7658 7659 return SDValue(); 7660 } 7661 7662 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 7663 const AArch64Subtarget *Subtarget) { 7664 // First try to optimize away the conversion when it's conditionally from 7665 // a constant. Vectors only. 7666 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 7667 return Res; 7668 7669 EVT VT = N->getValueType(0); 7670 if (VT != MVT::f32 && VT != MVT::f64) 7671 return SDValue(); 7672 7673 // Only optimize when the source and destination types have the same width. 7674 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits()) 7675 return SDValue(); 7676 7677 // If the result of an integer load is only used by an integer-to-float 7678 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 7679 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 7680 SDValue N0 = N->getOperand(0); 7681 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7682 // Do not change the width of a volatile load. 7683 !cast<LoadSDNode>(N0)->isVolatile()) { 7684 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7685 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7686 LN0->getPointerInfo(), LN0->isVolatile(), 7687 LN0->isNonTemporal(), LN0->isInvariant(), 7688 LN0->getAlignment()); 7689 7690 // Make sure successors of the original load stay after it by updating them 7691 // to use the new Chain. 7692 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 7693 7694 unsigned Opcode = 7695 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 7696 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 7697 } 7698 7699 return SDValue(); 7700 } 7701 7702 /// Fold a floating-point multiply by power of two into floating-point to 7703 /// fixed-point conversion. 7704 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 7705 const AArch64Subtarget *Subtarget) { 7706 if (!Subtarget->hasNEON()) 7707 return SDValue(); 7708 7709 SDValue Op = N->getOperand(0); 7710 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 7711 Op.getOpcode() != ISD::FMUL) 7712 return SDValue(); 7713 7714 SDValue ConstVec = Op->getOperand(1); 7715 if (!isa<BuildVectorSDNode>(ConstVec)) 7716 return SDValue(); 7717 7718 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 7719 uint32_t FloatBits = FloatTy.getSizeInBits(); 7720 if (FloatBits != 32 && FloatBits != 64) 7721 return SDValue(); 7722 7723 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 7724 uint32_t IntBits = IntTy.getSizeInBits(); 7725 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7726 return SDValue(); 7727 7728 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 7729 if (IntBits > FloatBits) 7730 return SDValue(); 7731 7732 BitVector UndefElements; 7733 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7734 int32_t Bits = IntBits == 64 ? 64 : 32; 7735 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 7736 if (C == -1 || C == 0 || C > Bits) 7737 return SDValue(); 7738 7739 MVT ResTy; 7740 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7741 switch (NumLanes) { 7742 default: 7743 return SDValue(); 7744 case 2: 7745 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7746 break; 7747 case 4: 7748 ResTy = MVT::v4i32; 7749 break; 7750 } 7751 7752 SDLoc DL(N); 7753 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7754 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 7755 : Intrinsic::aarch64_neon_vcvtfp2fxu; 7756 SDValue FixConv = 7757 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 7758 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 7759 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 7760 // We can handle smaller integers by generating an extra trunc. 7761 if (IntBits < FloatBits) 7762 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 7763 7764 return FixConv; 7765 } 7766 7767 /// Fold a floating-point divide by power of two into fixed-point to 7768 /// floating-point conversion. 7769 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 7770 const AArch64Subtarget *Subtarget) { 7771 if (!Subtarget->hasNEON()) 7772 return SDValue(); 7773 7774 SDValue Op = N->getOperand(0); 7775 unsigned Opc = Op->getOpcode(); 7776 if (!Op.getValueType().isVector() || 7777 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 7778 return SDValue(); 7779 7780 SDValue ConstVec = N->getOperand(1); 7781 if (!isa<BuildVectorSDNode>(ConstVec)) 7782 return SDValue(); 7783 7784 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 7785 int32_t IntBits = IntTy.getSizeInBits(); 7786 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7787 return SDValue(); 7788 7789 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 7790 int32_t FloatBits = FloatTy.getSizeInBits(); 7791 if (FloatBits != 32 && FloatBits != 64) 7792 return SDValue(); 7793 7794 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 7795 if (IntBits > FloatBits) 7796 return SDValue(); 7797 7798 BitVector UndefElements; 7799 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7800 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 7801 if (C == -1 || C == 0 || C > FloatBits) 7802 return SDValue(); 7803 7804 MVT ResTy; 7805 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7806 switch (NumLanes) { 7807 default: 7808 return SDValue(); 7809 case 2: 7810 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7811 break; 7812 case 4: 7813 ResTy = MVT::v4i32; 7814 break; 7815 } 7816 7817 SDLoc DL(N); 7818 SDValue ConvInput = Op.getOperand(0); 7819 bool IsSigned = Opc == ISD::SINT_TO_FP; 7820 if (IntBits < FloatBits) 7821 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 7822 ResTy, ConvInput); 7823 7824 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 7825 : Intrinsic::aarch64_neon_vcvtfxu2fp; 7826 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 7827 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 7828 DAG.getConstant(C, DL, MVT::i32)); 7829 } 7830 7831 /// An EXTR instruction is made up of two shifts, ORed together. This helper 7832 /// searches for and classifies those shifts. 7833 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 7834 bool &FromHi) { 7835 if (N.getOpcode() == ISD::SHL) 7836 FromHi = false; 7837 else if (N.getOpcode() == ISD::SRL) 7838 FromHi = true; 7839 else 7840 return false; 7841 7842 if (!isa<ConstantSDNode>(N.getOperand(1))) 7843 return false; 7844 7845 ShiftAmount = N->getConstantOperandVal(1); 7846 Src = N->getOperand(0); 7847 return true; 7848 } 7849 7850 /// EXTR instruction extracts a contiguous chunk of bits from two existing 7851 /// registers viewed as a high/low pair. This function looks for the pattern: 7852 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an 7853 /// EXTR. Can't quite be done in TableGen because the two immediates aren't 7854 /// independent. 7855 static SDValue tryCombineToEXTR(SDNode *N, 7856 TargetLowering::DAGCombinerInfo &DCI) { 7857 SelectionDAG &DAG = DCI.DAG; 7858 SDLoc DL(N); 7859 EVT VT = N->getValueType(0); 7860 7861 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 7862 7863 if (VT != MVT::i32 && VT != MVT::i64) 7864 return SDValue(); 7865 7866 SDValue LHS; 7867 uint32_t ShiftLHS = 0; 7868 bool LHSFromHi = 0; 7869 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 7870 return SDValue(); 7871 7872 SDValue RHS; 7873 uint32_t ShiftRHS = 0; 7874 bool RHSFromHi = 0; 7875 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 7876 return SDValue(); 7877 7878 // If they're both trying to come from the high part of the register, they're 7879 // not really an EXTR. 7880 if (LHSFromHi == RHSFromHi) 7881 return SDValue(); 7882 7883 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 7884 return SDValue(); 7885 7886 if (LHSFromHi) { 7887 std::swap(LHS, RHS); 7888 std::swap(ShiftLHS, ShiftRHS); 7889 } 7890 7891 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 7892 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 7893 } 7894 7895 static SDValue tryCombineToBSL(SDNode *N, 7896 TargetLowering::DAGCombinerInfo &DCI) { 7897 EVT VT = N->getValueType(0); 7898 SelectionDAG &DAG = DCI.DAG; 7899 SDLoc DL(N); 7900 7901 if (!VT.isVector()) 7902 return SDValue(); 7903 7904 SDValue N0 = N->getOperand(0); 7905 if (N0.getOpcode() != ISD::AND) 7906 return SDValue(); 7907 7908 SDValue N1 = N->getOperand(1); 7909 if (N1.getOpcode() != ISD::AND) 7910 return SDValue(); 7911 7912 // We only have to look for constant vectors here since the general, variable 7913 // case can be handled in TableGen. 7914 unsigned Bits = VT.getVectorElementType().getSizeInBits(); 7915 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 7916 for (int i = 1; i >= 0; --i) 7917 for (int j = 1; j >= 0; --j) { 7918 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 7919 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 7920 if (!BVN0 || !BVN1) 7921 continue; 7922 7923 bool FoundMatch = true; 7924 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 7925 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 7926 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 7927 if (!CN0 || !CN1 || 7928 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 7929 FoundMatch = false; 7930 break; 7931 } 7932 } 7933 7934 if (FoundMatch) 7935 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 7936 N0->getOperand(1 - i), N1->getOperand(1 - j)); 7937 } 7938 7939 return SDValue(); 7940 } 7941 7942 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 7943 const AArch64Subtarget *Subtarget) { 7944 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 7945 if (!EnableAArch64ExtrGeneration) 7946 return SDValue(); 7947 SelectionDAG &DAG = DCI.DAG; 7948 EVT VT = N->getValueType(0); 7949 7950 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 7951 return SDValue(); 7952 7953 if (SDValue Res = tryCombineToEXTR(N, DCI)) 7954 return Res; 7955 7956 if (SDValue Res = tryCombineToBSL(N, DCI)) 7957 return Res; 7958 7959 return SDValue(); 7960 } 7961 7962 static SDValue performBitcastCombine(SDNode *N, 7963 TargetLowering::DAGCombinerInfo &DCI, 7964 SelectionDAG &DAG) { 7965 // Wait 'til after everything is legalized to try this. That way we have 7966 // legal vector types and such. 7967 if (DCI.isBeforeLegalizeOps()) 7968 return SDValue(); 7969 7970 // Remove extraneous bitcasts around an extract_subvector. 7971 // For example, 7972 // (v4i16 (bitconvert 7973 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 7974 // becomes 7975 // (extract_subvector ((v8i16 ...), (i64 4))) 7976 7977 // Only interested in 64-bit vectors as the ultimate result. 7978 EVT VT = N->getValueType(0); 7979 if (!VT.isVector()) 7980 return SDValue(); 7981 if (VT.getSimpleVT().getSizeInBits() != 64) 7982 return SDValue(); 7983 // Is the operand an extract_subvector starting at the beginning or halfway 7984 // point of the vector? A low half may also come through as an 7985 // EXTRACT_SUBREG, so look for that, too. 7986 SDValue Op0 = N->getOperand(0); 7987 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 7988 !(Op0->isMachineOpcode() && 7989 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 7990 return SDValue(); 7991 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 7992 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 7993 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 7994 return SDValue(); 7995 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 7996 if (idx != AArch64::dsub) 7997 return SDValue(); 7998 // The dsub reference is equivalent to a lane zero subvector reference. 7999 idx = 0; 8000 } 8001 // Look through the bitcast of the input to the extract. 8002 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 8003 return SDValue(); 8004 SDValue Source = Op0->getOperand(0)->getOperand(0); 8005 // If the source type has twice the number of elements as our destination 8006 // type, we know this is an extract of the high or low half of the vector. 8007 EVT SVT = Source->getValueType(0); 8008 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 8009 return SDValue(); 8010 8011 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 8012 8013 // Create the simplified form to just extract the low or high half of the 8014 // vector directly rather than bothering with the bitcasts. 8015 SDLoc dl(N); 8016 unsigned NumElements = VT.getVectorNumElements(); 8017 if (idx) { 8018 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8019 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8020 } else { 8021 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8022 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8023 Source, SubReg), 8024 0); 8025 } 8026 } 8027 8028 static SDValue performConcatVectorsCombine(SDNode *N, 8029 TargetLowering::DAGCombinerInfo &DCI, 8030 SelectionDAG &DAG) { 8031 SDLoc dl(N); 8032 EVT VT = N->getValueType(0); 8033 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8034 8035 // Optimize concat_vectors of truncated vectors, where the intermediate 8036 // type is illegal, to avoid said illegality, e.g., 8037 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8038 // (v2i16 (truncate (v2i64))))) 8039 // -> 8040 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8041 // (v4i32 (bitcast (v2i64))), 8042 // <0, 2, 4, 6>))) 8043 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8044 // on both input and result type, so we might generate worse code. 8045 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8046 if (N->getNumOperands() == 2 && 8047 N0->getOpcode() == ISD::TRUNCATE && 8048 N1->getOpcode() == ISD::TRUNCATE) { 8049 SDValue N00 = N0->getOperand(0); 8050 SDValue N10 = N1->getOperand(0); 8051 EVT N00VT = N00.getValueType(); 8052 8053 if (N00VT == N10.getValueType() && 8054 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8055 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8056 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8057 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8058 for (size_t i = 0; i < Mask.size(); ++i) 8059 Mask[i] = i * 2; 8060 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8061 DAG.getVectorShuffle( 8062 MidVT, dl, 8063 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8064 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8065 } 8066 } 8067 8068 // Wait 'til after everything is legalized to try this. That way we have 8069 // legal vector types and such. 8070 if (DCI.isBeforeLegalizeOps()) 8071 return SDValue(); 8072 8073 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8074 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8075 // canonicalise to that. 8076 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8077 assert(VT.getVectorElementType().getSizeInBits() == 64); 8078 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8079 DAG.getConstant(0, dl, MVT::i64)); 8080 } 8081 8082 // Canonicalise concat_vectors so that the right-hand vector has as few 8083 // bit-casts as possible before its real operation. The primary matching 8084 // destination for these operations will be the narrowing "2" instructions, 8085 // which depend on the operation being performed on this right-hand vector. 8086 // For example, 8087 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8088 // becomes 8089 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8090 8091 if (N1->getOpcode() != ISD::BITCAST) 8092 return SDValue(); 8093 SDValue RHS = N1->getOperand(0); 8094 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8095 // If the RHS is not a vector, this is not the pattern we're looking for. 8096 if (!RHSTy.isVector()) 8097 return SDValue(); 8098 8099 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8100 8101 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8102 RHSTy.getVectorNumElements() * 2); 8103 return DAG.getNode(ISD::BITCAST, dl, VT, 8104 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8105 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8106 RHS)); 8107 } 8108 8109 static SDValue tryCombineFixedPointConvert(SDNode *N, 8110 TargetLowering::DAGCombinerInfo &DCI, 8111 SelectionDAG &DAG) { 8112 // Wait 'til after everything is legalized to try this. That way we have 8113 // legal vector types and such. 8114 if (DCI.isBeforeLegalizeOps()) 8115 return SDValue(); 8116 // Transform a scalar conversion of a value from a lane extract into a 8117 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8118 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8119 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8120 // 8121 // The second form interacts better with instruction selection and the 8122 // register allocator to avoid cross-class register copies that aren't 8123 // coalescable due to a lane reference. 8124 8125 // Check the operand and see if it originates from a lane extract. 8126 SDValue Op1 = N->getOperand(1); 8127 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8128 // Yep, no additional predication needed. Perform the transform. 8129 SDValue IID = N->getOperand(0); 8130 SDValue Shift = N->getOperand(2); 8131 SDValue Vec = Op1.getOperand(0); 8132 SDValue Lane = Op1.getOperand(1); 8133 EVT ResTy = N->getValueType(0); 8134 EVT VecResTy; 8135 SDLoc DL(N); 8136 8137 // The vector width should be 128 bits by the time we get here, even 8138 // if it started as 64 bits (the extract_vector handling will have 8139 // done so). 8140 assert(Vec.getValueType().getSizeInBits() == 128 && 8141 "unexpected vector size on extract_vector_elt!"); 8142 if (Vec.getValueType() == MVT::v4i32) 8143 VecResTy = MVT::v4f32; 8144 else if (Vec.getValueType() == MVT::v2i64) 8145 VecResTy = MVT::v2f64; 8146 else 8147 llvm_unreachable("unexpected vector type!"); 8148 8149 SDValue Convert = 8150 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8151 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8152 } 8153 return SDValue(); 8154 } 8155 8156 // AArch64 high-vector "long" operations are formed by performing the non-high 8157 // version on an extract_subvector of each operand which gets the high half: 8158 // 8159 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8160 // 8161 // However, there are cases which don't have an extract_high explicitly, but 8162 // have another operation that can be made compatible with one for free. For 8163 // example: 8164 // 8165 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8166 // 8167 // This routine does the actual conversion of such DUPs, once outer routines 8168 // have determined that everything else is in order. 8169 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8170 // similarly here. 8171 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8172 switch (N.getOpcode()) { 8173 case AArch64ISD::DUP: 8174 case AArch64ISD::DUPLANE8: 8175 case AArch64ISD::DUPLANE16: 8176 case AArch64ISD::DUPLANE32: 8177 case AArch64ISD::DUPLANE64: 8178 case AArch64ISD::MOVI: 8179 case AArch64ISD::MOVIshift: 8180 case AArch64ISD::MOVIedit: 8181 case AArch64ISD::MOVImsl: 8182 case AArch64ISD::MVNIshift: 8183 case AArch64ISD::MVNImsl: 8184 break; 8185 default: 8186 // FMOV could be supported, but isn't very useful, as it would only occur 8187 // if you passed a bitcast' floating point immediate to an eligible long 8188 // integer op (addl, smull, ...). 8189 return SDValue(); 8190 } 8191 8192 MVT NarrowTy = N.getSimpleValueType(); 8193 if (!NarrowTy.is64BitVector()) 8194 return SDValue(); 8195 8196 MVT ElementTy = NarrowTy.getVectorElementType(); 8197 unsigned NumElems = NarrowTy.getVectorNumElements(); 8198 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8199 8200 SDLoc dl(N); 8201 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8202 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8203 DAG.getConstant(NumElems, dl, MVT::i64)); 8204 } 8205 8206 static bool isEssentiallyExtractSubvector(SDValue N) { 8207 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8208 return true; 8209 8210 return N.getOpcode() == ISD::BITCAST && 8211 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8212 } 8213 8214 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8215 struct GenericSetCCInfo { 8216 const SDValue *Opnd0; 8217 const SDValue *Opnd1; 8218 ISD::CondCode CC; 8219 }; 8220 8221 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8222 struct AArch64SetCCInfo { 8223 const SDValue *Cmp; 8224 AArch64CC::CondCode CC; 8225 }; 8226 8227 /// \brief Helper structure to keep track of SetCC information. 8228 union SetCCInfo { 8229 GenericSetCCInfo Generic; 8230 AArch64SetCCInfo AArch64; 8231 }; 8232 8233 /// \brief Helper structure to be able to read SetCC information. If set to 8234 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8235 /// GenericSetCCInfo. 8236 struct SetCCInfoAndKind { 8237 SetCCInfo Info; 8238 bool IsAArch64; 8239 }; 8240 8241 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8242 /// an 8243 /// AArch64 lowered one. 8244 /// \p SetCCInfo is filled accordingly. 8245 /// \post SetCCInfo is meanginfull only when this function returns true. 8246 /// \return True when Op is a kind of SET_CC operation. 8247 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8248 // If this is a setcc, this is straight forward. 8249 if (Op.getOpcode() == ISD::SETCC) { 8250 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8251 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8252 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8253 SetCCInfo.IsAArch64 = false; 8254 return true; 8255 } 8256 // Otherwise, check if this is a matching csel instruction. 8257 // In other words: 8258 // - csel 1, 0, cc 8259 // - csel 0, 1, !cc 8260 if (Op.getOpcode() != AArch64ISD::CSEL) 8261 return false; 8262 // Set the information about the operands. 8263 // TODO: we want the operands of the Cmp not the csel 8264 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8265 SetCCInfo.IsAArch64 = true; 8266 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8267 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8268 8269 // Check that the operands matches the constraints: 8270 // (1) Both operands must be constants. 8271 // (2) One must be 1 and the other must be 0. 8272 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 8273 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8274 8275 // Check (1). 8276 if (!TValue || !FValue) 8277 return false; 8278 8279 // Check (2). 8280 if (!TValue->isOne()) { 8281 // Update the comparison when we are interested in !cc. 8282 std::swap(TValue, FValue); 8283 SetCCInfo.Info.AArch64.CC = 8284 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 8285 } 8286 return TValue->isOne() && FValue->isNullValue(); 8287 } 8288 8289 // Returns true if Op is setcc or zext of setcc. 8290 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 8291 if (isSetCC(Op, Info)) 8292 return true; 8293 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 8294 isSetCC(Op->getOperand(0), Info)); 8295 } 8296 8297 // The folding we want to perform is: 8298 // (add x, [zext] (setcc cc ...) ) 8299 // --> 8300 // (csel x, (add x, 1), !cc ...) 8301 // 8302 // The latter will get matched to a CSINC instruction. 8303 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 8304 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 8305 SDValue LHS = Op->getOperand(0); 8306 SDValue RHS = Op->getOperand(1); 8307 SetCCInfoAndKind InfoAndKind; 8308 8309 // If neither operand is a SET_CC, give up. 8310 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 8311 std::swap(LHS, RHS); 8312 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 8313 return SDValue(); 8314 } 8315 8316 // FIXME: This could be generatized to work for FP comparisons. 8317 EVT CmpVT = InfoAndKind.IsAArch64 8318 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 8319 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 8320 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 8321 return SDValue(); 8322 8323 SDValue CCVal; 8324 SDValue Cmp; 8325 SDLoc dl(Op); 8326 if (InfoAndKind.IsAArch64) { 8327 CCVal = DAG.getConstant( 8328 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 8329 MVT::i32); 8330 Cmp = *InfoAndKind.Info.AArch64.Cmp; 8331 } else 8332 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 8333 *InfoAndKind.Info.Generic.Opnd1, 8334 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 8335 CCVal, DAG, dl); 8336 8337 EVT VT = Op->getValueType(0); 8338 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 8339 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 8340 } 8341 8342 // The basic add/sub long vector instructions have variants with "2" on the end 8343 // which act on the high-half of their inputs. They are normally matched by 8344 // patterns like: 8345 // 8346 // (add (zeroext (extract_high LHS)), 8347 // (zeroext (extract_high RHS))) 8348 // -> uaddl2 vD, vN, vM 8349 // 8350 // However, if one of the extracts is something like a duplicate, this 8351 // instruction can still be used profitably. This function puts the DAG into a 8352 // more appropriate form for those patterns to trigger. 8353 static SDValue performAddSubLongCombine(SDNode *N, 8354 TargetLowering::DAGCombinerInfo &DCI, 8355 SelectionDAG &DAG) { 8356 if (DCI.isBeforeLegalizeOps()) 8357 return SDValue(); 8358 8359 MVT VT = N->getSimpleValueType(0); 8360 if (!VT.is128BitVector()) { 8361 if (N->getOpcode() == ISD::ADD) 8362 return performSetccAddFolding(N, DAG); 8363 return SDValue(); 8364 } 8365 8366 // Make sure both branches are extended in the same way. 8367 SDValue LHS = N->getOperand(0); 8368 SDValue RHS = N->getOperand(1); 8369 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 8370 LHS.getOpcode() != ISD::SIGN_EXTEND) || 8371 LHS.getOpcode() != RHS.getOpcode()) 8372 return SDValue(); 8373 8374 unsigned ExtType = LHS.getOpcode(); 8375 8376 // It's not worth doing if at least one of the inputs isn't already an 8377 // extract, but we don't know which it'll be so we have to try both. 8378 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 8379 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 8380 if (!RHS.getNode()) 8381 return SDValue(); 8382 8383 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 8384 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 8385 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 8386 if (!LHS.getNode()) 8387 return SDValue(); 8388 8389 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 8390 } 8391 8392 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 8393 } 8394 8395 // Massage DAGs which we can use the high-half "long" operations on into 8396 // something isel will recognize better. E.g. 8397 // 8398 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 8399 // (aarch64_neon_umull (extract_high (v2i64 vec))) 8400 // (extract_high (v2i64 (dup128 scalar))))) 8401 // 8402 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 8403 TargetLowering::DAGCombinerInfo &DCI, 8404 SelectionDAG &DAG) { 8405 if (DCI.isBeforeLegalizeOps()) 8406 return SDValue(); 8407 8408 SDValue LHS = N->getOperand(1); 8409 SDValue RHS = N->getOperand(2); 8410 assert(LHS.getValueType().is64BitVector() && 8411 RHS.getValueType().is64BitVector() && 8412 "unexpected shape for long operation"); 8413 8414 // Either node could be a DUP, but it's not worth doing both of them (you'd 8415 // just as well use the non-high version) so look for a corresponding extract 8416 // operation on the other "wing". 8417 if (isEssentiallyExtractSubvector(LHS)) { 8418 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 8419 if (!RHS.getNode()) 8420 return SDValue(); 8421 } else if (isEssentiallyExtractSubvector(RHS)) { 8422 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 8423 if (!LHS.getNode()) 8424 return SDValue(); 8425 } 8426 8427 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 8428 N->getOperand(0), LHS, RHS); 8429 } 8430 8431 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 8432 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 8433 unsigned ElemBits = ElemTy.getSizeInBits(); 8434 8435 int64_t ShiftAmount; 8436 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 8437 APInt SplatValue, SplatUndef; 8438 unsigned SplatBitSize; 8439 bool HasAnyUndefs; 8440 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 8441 HasAnyUndefs, ElemBits) || 8442 SplatBitSize != ElemBits) 8443 return SDValue(); 8444 8445 ShiftAmount = SplatValue.getSExtValue(); 8446 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 8447 ShiftAmount = CVN->getSExtValue(); 8448 } else 8449 return SDValue(); 8450 8451 unsigned Opcode; 8452 bool IsRightShift; 8453 switch (IID) { 8454 default: 8455 llvm_unreachable("Unknown shift intrinsic"); 8456 case Intrinsic::aarch64_neon_sqshl: 8457 Opcode = AArch64ISD::SQSHL_I; 8458 IsRightShift = false; 8459 break; 8460 case Intrinsic::aarch64_neon_uqshl: 8461 Opcode = AArch64ISD::UQSHL_I; 8462 IsRightShift = false; 8463 break; 8464 case Intrinsic::aarch64_neon_srshl: 8465 Opcode = AArch64ISD::SRSHR_I; 8466 IsRightShift = true; 8467 break; 8468 case Intrinsic::aarch64_neon_urshl: 8469 Opcode = AArch64ISD::URSHR_I; 8470 IsRightShift = true; 8471 break; 8472 case Intrinsic::aarch64_neon_sqshlu: 8473 Opcode = AArch64ISD::SQSHLU_I; 8474 IsRightShift = false; 8475 break; 8476 } 8477 8478 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 8479 SDLoc dl(N); 8480 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8481 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 8482 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 8483 SDLoc dl(N); 8484 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8485 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 8486 } 8487 8488 return SDValue(); 8489 } 8490 8491 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 8492 // the intrinsics must be legal and take an i32, this means there's almost 8493 // certainly going to be a zext in the DAG which we can eliminate. 8494 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 8495 SDValue AndN = N->getOperand(2); 8496 if (AndN.getOpcode() != ISD::AND) 8497 return SDValue(); 8498 8499 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 8500 if (!CMask || CMask->getZExtValue() != Mask) 8501 return SDValue(); 8502 8503 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 8504 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 8505 } 8506 8507 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 8508 SelectionDAG &DAG) { 8509 SDLoc dl(N); 8510 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 8511 DAG.getNode(Opc, dl, 8512 N->getOperand(1).getSimpleValueType(), 8513 N->getOperand(1)), 8514 DAG.getConstant(0, dl, MVT::i64)); 8515 } 8516 8517 static SDValue performIntrinsicCombine(SDNode *N, 8518 TargetLowering::DAGCombinerInfo &DCI, 8519 const AArch64Subtarget *Subtarget) { 8520 SelectionDAG &DAG = DCI.DAG; 8521 unsigned IID = getIntrinsicID(N); 8522 switch (IID) { 8523 default: 8524 break; 8525 case Intrinsic::aarch64_neon_vcvtfxs2fp: 8526 case Intrinsic::aarch64_neon_vcvtfxu2fp: 8527 return tryCombineFixedPointConvert(N, DCI, DAG); 8528 case Intrinsic::aarch64_neon_saddv: 8529 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 8530 case Intrinsic::aarch64_neon_uaddv: 8531 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 8532 case Intrinsic::aarch64_neon_sminv: 8533 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 8534 case Intrinsic::aarch64_neon_uminv: 8535 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 8536 case Intrinsic::aarch64_neon_smaxv: 8537 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 8538 case Intrinsic::aarch64_neon_umaxv: 8539 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 8540 case Intrinsic::aarch64_neon_fmax: 8541 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 8542 N->getOperand(1), N->getOperand(2)); 8543 case Intrinsic::aarch64_neon_fmin: 8544 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 8545 N->getOperand(1), N->getOperand(2)); 8546 case Intrinsic::aarch64_neon_fmaxnm: 8547 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 8548 N->getOperand(1), N->getOperand(2)); 8549 case Intrinsic::aarch64_neon_fminnm: 8550 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 8551 N->getOperand(1), N->getOperand(2)); 8552 case Intrinsic::aarch64_neon_smull: 8553 case Intrinsic::aarch64_neon_umull: 8554 case Intrinsic::aarch64_neon_pmull: 8555 case Intrinsic::aarch64_neon_sqdmull: 8556 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 8557 case Intrinsic::aarch64_neon_sqshl: 8558 case Intrinsic::aarch64_neon_uqshl: 8559 case Intrinsic::aarch64_neon_sqshlu: 8560 case Intrinsic::aarch64_neon_srshl: 8561 case Intrinsic::aarch64_neon_urshl: 8562 return tryCombineShiftImm(IID, N, DAG); 8563 case Intrinsic::aarch64_crc32b: 8564 case Intrinsic::aarch64_crc32cb: 8565 return tryCombineCRC32(0xff, N, DAG); 8566 case Intrinsic::aarch64_crc32h: 8567 case Intrinsic::aarch64_crc32ch: 8568 return tryCombineCRC32(0xffff, N, DAG); 8569 } 8570 return SDValue(); 8571 } 8572 8573 static SDValue performExtendCombine(SDNode *N, 8574 TargetLowering::DAGCombinerInfo &DCI, 8575 SelectionDAG &DAG) { 8576 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 8577 // we can convert that DUP into another extract_high (of a bigger DUP), which 8578 // helps the backend to decide that an sabdl2 would be useful, saving a real 8579 // extract_high operation. 8580 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 8581 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 8582 SDNode *ABDNode = N->getOperand(0).getNode(); 8583 unsigned IID = getIntrinsicID(ABDNode); 8584 if (IID == Intrinsic::aarch64_neon_sabd || 8585 IID == Intrinsic::aarch64_neon_uabd) { 8586 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 8587 if (!NewABD.getNode()) 8588 return SDValue(); 8589 8590 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 8591 NewABD); 8592 } 8593 } 8594 8595 // This is effectively a custom type legalization for AArch64. 8596 // 8597 // Type legalization will split an extend of a small, legal, type to a larger 8598 // illegal type by first splitting the destination type, often creating 8599 // illegal source types, which then get legalized in isel-confusing ways, 8600 // leading to really terrible codegen. E.g., 8601 // %result = v8i32 sext v8i8 %value 8602 // becomes 8603 // %losrc = extract_subreg %value, ... 8604 // %hisrc = extract_subreg %value, ... 8605 // %lo = v4i32 sext v4i8 %losrc 8606 // %hi = v4i32 sext v4i8 %hisrc 8607 // Things go rapidly downhill from there. 8608 // 8609 // For AArch64, the [sz]ext vector instructions can only go up one element 8610 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 8611 // take two instructions. 8612 // 8613 // This implies that the most efficient way to do the extend from v8i8 8614 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 8615 // the normal splitting to happen for the v8i16->v8i32. 8616 8617 // This is pre-legalization to catch some cases where the default 8618 // type legalization will create ill-tempered code. 8619 if (!DCI.isBeforeLegalizeOps()) 8620 return SDValue(); 8621 8622 // We're only interested in cleaning things up for non-legal vector types 8623 // here. If both the source and destination are legal, things will just 8624 // work naturally without any fiddling. 8625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8626 EVT ResVT = N->getValueType(0); 8627 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 8628 return SDValue(); 8629 // If the vector type isn't a simple VT, it's beyond the scope of what 8630 // we're worried about here. Let legalization do its thing and hope for 8631 // the best. 8632 SDValue Src = N->getOperand(0); 8633 EVT SrcVT = Src->getValueType(0); 8634 if (!ResVT.isSimple() || !SrcVT.isSimple()) 8635 return SDValue(); 8636 8637 // If the source VT is a 64-bit vector, we can play games and get the 8638 // better results we want. 8639 if (SrcVT.getSizeInBits() != 64) 8640 return SDValue(); 8641 8642 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits(); 8643 unsigned ElementCount = SrcVT.getVectorNumElements(); 8644 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 8645 SDLoc DL(N); 8646 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 8647 8648 // Now split the rest of the operation into two halves, each with a 64 8649 // bit source. 8650 EVT LoVT, HiVT; 8651 SDValue Lo, Hi; 8652 unsigned NumElements = ResVT.getVectorNumElements(); 8653 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 8654 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 8655 ResVT.getVectorElementType(), NumElements / 2); 8656 8657 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 8658 LoVT.getVectorNumElements()); 8659 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8660 DAG.getConstant(0, DL, MVT::i64)); 8661 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8662 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 8663 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 8664 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 8665 8666 // Now combine the parts back together so we still have a single result 8667 // like the combiner expects. 8668 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 8669 } 8670 8671 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 8672 /// value. The load store optimizer pass will merge them to store pair stores. 8673 /// This has better performance than a splat of the scalar followed by a split 8674 /// vector store. Even if the stores are not merged it is four stores vs a dup, 8675 /// followed by an ext.b and two stores. 8676 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) { 8677 SDValue StVal = St->getValue(); 8678 EVT VT = StVal.getValueType(); 8679 8680 // Don't replace floating point stores, they possibly won't be transformed to 8681 // stp because of the store pair suppress pass. 8682 if (VT.isFloatingPoint()) 8683 return SDValue(); 8684 8685 // Check for insert vector elements. 8686 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 8687 return SDValue(); 8688 8689 // We can express a splat as store pair(s) for 2 or 4 elements. 8690 unsigned NumVecElts = VT.getVectorNumElements(); 8691 if (NumVecElts != 4 && NumVecElts != 2) 8692 return SDValue(); 8693 SDValue SplatVal = StVal.getOperand(1); 8694 unsigned RemainInsertElts = NumVecElts - 1; 8695 8696 // Check that this is a splat. 8697 while (--RemainInsertElts) { 8698 SDValue NextInsertElt = StVal.getOperand(0); 8699 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT) 8700 return SDValue(); 8701 if (NextInsertElt.getOperand(1) != SplatVal) 8702 return SDValue(); 8703 StVal = NextInsertElt; 8704 } 8705 unsigned OrigAlignment = St->getAlignment(); 8706 unsigned EltOffset = NumVecElts == 4 ? 4 : 8; 8707 unsigned Alignment = std::min(OrigAlignment, EltOffset); 8708 8709 // Create scalar stores. This is at least as good as the code sequence for a 8710 // split unaligned store which is a dup.s, ext.b, and two stores. 8711 // Most of the time the three stores should be replaced by store pair 8712 // instructions (stp). 8713 SDLoc DL(St); 8714 SDValue BasePtr = St->getBasePtr(); 8715 SDValue NewST1 = 8716 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(), 8717 St->isVolatile(), St->isNonTemporal(), St->getAlignment()); 8718 8719 unsigned Offset = EltOffset; 8720 while (--NumVecElts) { 8721 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8722 DAG.getConstant(Offset, DL, MVT::i64)); 8723 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 8724 St->getPointerInfo(), St->isVolatile(), 8725 St->isNonTemporal(), Alignment); 8726 Offset += EltOffset; 8727 } 8728 return NewST1; 8729 } 8730 8731 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8732 SelectionDAG &DAG, 8733 const AArch64Subtarget *Subtarget) { 8734 if (!DCI.isBeforeLegalize()) 8735 return SDValue(); 8736 8737 StoreSDNode *S = cast<StoreSDNode>(N); 8738 if (S->isVolatile()) 8739 return SDValue(); 8740 8741 // FIXME: The logic for deciding if an unaligned store should be split should 8742 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 8743 // a call to that function here. 8744 8745 // Cyclone has bad performance on unaligned 16B stores when crossing line and 8746 // page boundaries. We want to split such stores. 8747 if (!Subtarget->isCyclone()) 8748 return SDValue(); 8749 8750 // Don't split at -Oz. 8751 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 8752 return SDValue(); 8753 8754 SDValue StVal = S->getValue(); 8755 EVT VT = StVal.getValueType(); 8756 8757 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 8758 // those up regresses performance on micro-benchmarks and olden/bh. 8759 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 8760 return SDValue(); 8761 8762 // Split unaligned 16B stores. They are terrible for performance. 8763 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 8764 // extensions can use this to mark that it does not want splitting to happen 8765 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 8766 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 8767 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 8768 S->getAlignment() <= 2) 8769 return SDValue(); 8770 8771 // If we get a splat of a scalar convert this vector store to a store of 8772 // scalars. They will be merged into store pairs thereby removing two 8773 // instructions. 8774 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S)) 8775 return ReplacedSplat; 8776 8777 SDLoc DL(S); 8778 unsigned NumElts = VT.getVectorNumElements() / 2; 8779 // Split VT into two. 8780 EVT HalfVT = 8781 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 8782 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 8783 DAG.getConstant(0, DL, MVT::i64)); 8784 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 8785 DAG.getConstant(NumElts, DL, MVT::i64)); 8786 SDValue BasePtr = S->getBasePtr(); 8787 SDValue NewST1 = 8788 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 8789 S->isVolatile(), S->isNonTemporal(), S->getAlignment()); 8790 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8791 DAG.getConstant(8, DL, MVT::i64)); 8792 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 8793 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(), 8794 S->getAlignment()); 8795 } 8796 8797 /// Target-specific DAG combine function for post-increment LD1 (lane) and 8798 /// post-increment LD1R. 8799 static SDValue performPostLD1Combine(SDNode *N, 8800 TargetLowering::DAGCombinerInfo &DCI, 8801 bool IsLaneOp) { 8802 if (DCI.isBeforeLegalizeOps()) 8803 return SDValue(); 8804 8805 SelectionDAG &DAG = DCI.DAG; 8806 EVT VT = N->getValueType(0); 8807 8808 unsigned LoadIdx = IsLaneOp ? 1 : 0; 8809 SDNode *LD = N->getOperand(LoadIdx).getNode(); 8810 // If it is not LOAD, can not do such combine. 8811 if (LD->getOpcode() != ISD::LOAD) 8812 return SDValue(); 8813 8814 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 8815 EVT MemVT = LoadSDN->getMemoryVT(); 8816 // Check if memory operand is the same type as the vector element. 8817 if (MemVT != VT.getVectorElementType()) 8818 return SDValue(); 8819 8820 // Check if there are other uses. If so, do not combine as it will introduce 8821 // an extra load. 8822 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 8823 ++UI) { 8824 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 8825 continue; 8826 if (*UI != N) 8827 return SDValue(); 8828 } 8829 8830 SDValue Addr = LD->getOperand(1); 8831 SDValue Vector = N->getOperand(0); 8832 // Search for a use of the address operand that is an increment. 8833 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 8834 Addr.getNode()->use_end(); UI != UE; ++UI) { 8835 SDNode *User = *UI; 8836 if (User->getOpcode() != ISD::ADD 8837 || UI.getUse().getResNo() != Addr.getResNo()) 8838 continue; 8839 8840 // Check that the add is independent of the load. Otherwise, folding it 8841 // would create a cycle. 8842 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 8843 continue; 8844 // Also check that add is not used in the vector operand. This would also 8845 // create a cycle. 8846 if (User->isPredecessorOf(Vector.getNode())) 8847 continue; 8848 8849 // If the increment is a constant, it must match the memory ref size. 8850 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 8851 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 8852 uint32_t IncVal = CInc->getZExtValue(); 8853 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 8854 if (IncVal != NumBytes) 8855 continue; 8856 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 8857 } 8858 8859 // Finally, check that the vector doesn't depend on the load. 8860 // Again, this would create a cycle. 8861 // The load depending on the vector is fine, as that's the case for the 8862 // LD1*post we'll eventually generate anyway. 8863 if (LoadSDN->isPredecessorOf(Vector.getNode())) 8864 continue; 8865 8866 SmallVector<SDValue, 8> Ops; 8867 Ops.push_back(LD->getOperand(0)); // Chain 8868 if (IsLaneOp) { 8869 Ops.push_back(Vector); // The vector to be inserted 8870 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 8871 } 8872 Ops.push_back(Addr); 8873 Ops.push_back(Inc); 8874 8875 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 8876 SDVTList SDTys = DAG.getVTList(Tys); 8877 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 8878 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 8879 MemVT, 8880 LoadSDN->getMemOperand()); 8881 8882 // Update the uses. 8883 SmallVector<SDValue, 2> NewResults; 8884 NewResults.push_back(SDValue(LD, 0)); // The result of load 8885 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain 8886 DCI.CombineTo(LD, NewResults); 8887 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 8888 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 8889 8890 break; 8891 } 8892 return SDValue(); 8893 } 8894 8895 /// Simplify \Addr given that the top byte of it is ignored by HW during 8896 /// address translation. 8897 static bool performTBISimplification(SDValue Addr, 8898 TargetLowering::DAGCombinerInfo &DCI, 8899 SelectionDAG &DAG) { 8900 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 8901 APInt KnownZero, KnownOne; 8902 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 8903 DCI.isBeforeLegalizeOps()); 8904 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8905 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) { 8906 DCI.CommitTargetLoweringOpt(TLO); 8907 return true; 8908 } 8909 return false; 8910 } 8911 8912 static SDValue performSTORECombine(SDNode *N, 8913 TargetLowering::DAGCombinerInfo &DCI, 8914 SelectionDAG &DAG, 8915 const AArch64Subtarget *Subtarget) { 8916 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget)) 8917 return Split; 8918 8919 if (Subtarget->supportsAddressTopByteIgnored() && 8920 performTBISimplification(N->getOperand(2), DCI, DAG)) 8921 return SDValue(N, 0); 8922 8923 return SDValue(); 8924 } 8925 8926 /// This function handles the log2-shuffle pattern produced by the 8927 /// LoopVectorizer for the across vector reduction. It consists of 8928 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements 8929 /// are reduced, where s is an induction variable from 0 to 8930 /// log2(NumVectorElements). 8931 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV, 8932 unsigned Op, 8933 SelectionDAG &DAG) { 8934 EVT VTy = OpV->getOperand(0).getValueType(); 8935 if (!VTy.isVector()) 8936 return SDValue(); 8937 8938 int NumVecElts = VTy.getVectorNumElements(); 8939 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 8940 if (NumVecElts != 4) 8941 return SDValue(); 8942 } else { 8943 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16) 8944 return SDValue(); 8945 } 8946 8947 int NumExpectedSteps = APInt(8, NumVecElts).logBase2(); 8948 SDValue PreOp = OpV; 8949 // Iterate over each step of the across vector reduction. 8950 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) { 8951 SDValue CurOp = PreOp.getOperand(0); 8952 SDValue Shuffle = PreOp.getOperand(1); 8953 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) { 8954 // Try to swap the 1st and 2nd operand as add and min/max instructions 8955 // are commutative. 8956 CurOp = PreOp.getOperand(1); 8957 Shuffle = PreOp.getOperand(0); 8958 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) 8959 return SDValue(); 8960 } 8961 8962 // Check if the input vector is fed by the operator we want to handle, 8963 // except the last step; the very first input vector is not necessarily 8964 // the same operator we are handling. 8965 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1))) 8966 return SDValue(); 8967 8968 // Check if it forms one step of the across vector reduction. 8969 // E.g., 8970 // %cur = add %1, %0 8971 // %shuffle = vector_shuffle %cur, <2, 3, u, u> 8972 // %pre = add %cur, %shuffle 8973 if (Shuffle.getOperand(0) != CurOp) 8974 return SDValue(); 8975 8976 int NumMaskElts = 1 << CurStep; 8977 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask(); 8978 // Check mask values in each step. 8979 // We expect the shuffle mask in each step follows a specific pattern 8980 // denoted here by the <M, U> form, where M is a sequence of integers 8981 // starting from NumMaskElts, increasing by 1, and the number integers 8982 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number 8983 // of undef in U should be NumVecElts - NumMaskElts. 8984 // E.g., for <8 x i16>, mask values in each step should be : 8985 // step 0 : <1,u,u,u,u,u,u,u> 8986 // step 1 : <2,3,u,u,u,u,u,u> 8987 // step 2 : <4,5,6,7,u,u,u,u> 8988 for (int i = 0; i < NumVecElts; ++i) 8989 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) || 8990 (i >= NumMaskElts && !(Mask[i] < 0))) 8991 return SDValue(); 8992 8993 PreOp = CurOp; 8994 } 8995 unsigned Opcode; 8996 bool IsIntrinsic = false; 8997 8998 switch (Op) { 8999 default: 9000 llvm_unreachable("Unexpected operator for across vector reduction"); 9001 case ISD::ADD: 9002 Opcode = AArch64ISD::UADDV; 9003 break; 9004 case ISD::SMAX: 9005 Opcode = AArch64ISD::SMAXV; 9006 break; 9007 case ISD::UMAX: 9008 Opcode = AArch64ISD::UMAXV; 9009 break; 9010 case ISD::SMIN: 9011 Opcode = AArch64ISD::SMINV; 9012 break; 9013 case ISD::UMIN: 9014 Opcode = AArch64ISD::UMINV; 9015 break; 9016 case ISD::FMAXNUM: 9017 Opcode = Intrinsic::aarch64_neon_fmaxnmv; 9018 IsIntrinsic = true; 9019 break; 9020 case ISD::FMINNUM: 9021 Opcode = Intrinsic::aarch64_neon_fminnmv; 9022 IsIntrinsic = true; 9023 break; 9024 } 9025 SDLoc DL(N); 9026 9027 return IsIntrinsic 9028 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0), 9029 DAG.getConstant(Opcode, DL, MVT::i32), PreOp) 9030 : DAG.getNode( 9031 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), 9032 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp), 9033 DAG.getConstant(0, DL, MVT::i64)); 9034 } 9035 9036 /// Target-specific DAG combine for the across vector min/max reductions. 9037 /// This function specifically handles the final clean-up step of the vector 9038 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle 9039 /// pattern, which narrows down and finds the final min/max value from all 9040 /// elements of the vector. 9041 /// For example, for a <16 x i8> vector : 9042 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> 9043 /// %smax0 = smax %arr, svn0 9044 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u> 9045 /// %smax1 = smax %smax0, %svn1 9046 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9047 /// %smax2 = smax %smax1, svn2 9048 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9049 /// %sc = setcc %smax2, %svn3, gt 9050 /// %n0 = extract_vector_elt %sc, #0 9051 /// %n1 = extract_vector_elt %smax2, #0 9052 /// %n2 = extract_vector_elt $smax2, #1 9053 /// %result = select %n0, %n1, n2 9054 /// becomes : 9055 /// %1 = smaxv %0 9056 /// %result = extract_vector_elt %1, 0 9057 static SDValue 9058 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG, 9059 const AArch64Subtarget *Subtarget) { 9060 if (!Subtarget->hasNEON()) 9061 return SDValue(); 9062 9063 SDValue N0 = N->getOperand(0); 9064 SDValue IfTrue = N->getOperand(1); 9065 SDValue IfFalse = N->getOperand(2); 9066 9067 // Check if the SELECT merges up the final result of the min/max 9068 // from a vector. 9069 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9070 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9071 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9072 return SDValue(); 9073 9074 // Expect N0 is fed by SETCC. 9075 SDValue SetCC = N0.getOperand(0); 9076 EVT SetCCVT = SetCC.getValueType(); 9077 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() || 9078 SetCCVT.getVectorElementType() != MVT::i1) 9079 return SDValue(); 9080 9081 SDValue VectorOp = SetCC.getOperand(0); 9082 unsigned Op = VectorOp->getOpcode(); 9083 // Check if the input vector is fed by the operator we want to handle. 9084 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN && 9085 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM) 9086 return SDValue(); 9087 9088 EVT VTy = VectorOp.getValueType(); 9089 if (!VTy.isVector()) 9090 return SDValue(); 9091 9092 if (VTy.getSizeInBits() < 64) 9093 return SDValue(); 9094 9095 EVT EltTy = VTy.getVectorElementType(); 9096 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 9097 if (EltTy != MVT::f32) 9098 return SDValue(); 9099 } else { 9100 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9101 return SDValue(); 9102 } 9103 9104 // Check if extracting from the same vector. 9105 // For example, 9106 // %sc = setcc %vector, %svn1, gt 9107 // %n0 = extract_vector_elt %sc, #0 9108 // %n1 = extract_vector_elt %vector, #0 9109 // %n2 = extract_vector_elt $vector, #1 9110 if (!(VectorOp == IfTrue->getOperand(0) && 9111 VectorOp == IfFalse->getOperand(0))) 9112 return SDValue(); 9113 9114 // Check if the condition code is matched with the operator type. 9115 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 9116 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) || 9117 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) || 9118 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) || 9119 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) || 9120 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE && 9121 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT && 9122 CC != ISD::SETGE) || 9123 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE && 9124 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT && 9125 CC != ISD::SETLE)) 9126 return SDValue(); 9127 9128 // Expect to check only lane 0 from the vector SETCC. 9129 if (!isNullConstant(N0.getOperand(1))) 9130 return SDValue(); 9131 9132 // Expect to extract the true value from lane 0. 9133 if (!isNullConstant(IfTrue.getOperand(1))) 9134 return SDValue(); 9135 9136 // Expect to extract the false value from lane 1. 9137 if (!isOneConstant(IfFalse.getOperand(1))) 9138 return SDValue(); 9139 9140 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG); 9141 } 9142 9143 /// Target-specific DAG combine for the across vector add reduction. 9144 /// This function specifically handles the final clean-up step of the vector 9145 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle 9146 /// pattern, which adds all elements of a vector together. 9147 /// For example, for a <4 x i32> vector : 9148 /// %1 = vector_shuffle %0, <2,3,u,u> 9149 /// %2 = add %0, %1 9150 /// %3 = vector_shuffle %2, <1,u,u,u> 9151 /// %4 = add %2, %3 9152 /// %result = extract_vector_elt %4, 0 9153 /// becomes : 9154 /// %0 = uaddv %0 9155 /// %result = extract_vector_elt %0, 0 9156 static SDValue 9157 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG, 9158 const AArch64Subtarget *Subtarget) { 9159 if (!Subtarget->hasNEON()) 9160 return SDValue(); 9161 SDValue N0 = N->getOperand(0); 9162 SDValue N1 = N->getOperand(1); 9163 9164 // Check if the input vector is fed by the ADD. 9165 if (N0->getOpcode() != ISD::ADD) 9166 return SDValue(); 9167 9168 // The vector extract idx must constant zero because we only expect the final 9169 // result of the reduction is placed in lane 0. 9170 if (!isNullConstant(N1)) 9171 return SDValue(); 9172 9173 EVT VTy = N0.getValueType(); 9174 if (!VTy.isVector()) 9175 return SDValue(); 9176 9177 EVT EltTy = VTy.getVectorElementType(); 9178 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9179 return SDValue(); 9180 9181 if (VTy.getSizeInBits() < 64) 9182 return SDValue(); 9183 9184 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG); 9185 } 9186 9187 /// Target-specific DAG combine function for NEON load/store intrinsics 9188 /// to merge base address updates. 9189 static SDValue performNEONPostLDSTCombine(SDNode *N, 9190 TargetLowering::DAGCombinerInfo &DCI, 9191 SelectionDAG &DAG) { 9192 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9193 return SDValue(); 9194 9195 unsigned AddrOpIdx = N->getNumOperands() - 1; 9196 SDValue Addr = N->getOperand(AddrOpIdx); 9197 9198 // Search for a use of the address operand that is an increment. 9199 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9200 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9201 SDNode *User = *UI; 9202 if (User->getOpcode() != ISD::ADD || 9203 UI.getUse().getResNo() != Addr.getResNo()) 9204 continue; 9205 9206 // Check that the add is independent of the load/store. Otherwise, folding 9207 // it would create a cycle. 9208 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9209 continue; 9210 9211 // Find the new opcode for the updating load/store. 9212 bool IsStore = false; 9213 bool IsLaneOp = false; 9214 bool IsDupOp = false; 9215 unsigned NewOpc = 0; 9216 unsigned NumVecs = 0; 9217 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9218 switch (IntNo) { 9219 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9220 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9221 NumVecs = 2; break; 9222 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9223 NumVecs = 3; break; 9224 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9225 NumVecs = 4; break; 9226 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9227 NumVecs = 2; IsStore = true; break; 9228 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9229 NumVecs = 3; IsStore = true; break; 9230 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9231 NumVecs = 4; IsStore = true; break; 9232 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9233 NumVecs = 2; break; 9234 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9235 NumVecs = 3; break; 9236 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9237 NumVecs = 4; break; 9238 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9239 NumVecs = 2; IsStore = true; break; 9240 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9241 NumVecs = 3; IsStore = true; break; 9242 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9243 NumVecs = 4; IsStore = true; break; 9244 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9245 NumVecs = 2; IsDupOp = true; break; 9246 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9247 NumVecs = 3; IsDupOp = true; break; 9248 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9249 NumVecs = 4; IsDupOp = true; break; 9250 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9251 NumVecs = 2; IsLaneOp = true; break; 9252 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9253 NumVecs = 3; IsLaneOp = true; break; 9254 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9255 NumVecs = 4; IsLaneOp = true; break; 9256 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9257 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9258 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9259 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9260 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9261 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9262 } 9263 9264 EVT VecTy; 9265 if (IsStore) 9266 VecTy = N->getOperand(2).getValueType(); 9267 else 9268 VecTy = N->getValueType(0); 9269 9270 // If the increment is a constant, it must match the memory ref size. 9271 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9272 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9273 uint32_t IncVal = CInc->getZExtValue(); 9274 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9275 if (IsLaneOp || IsDupOp) 9276 NumBytes /= VecTy.getVectorNumElements(); 9277 if (IncVal != NumBytes) 9278 continue; 9279 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9280 } 9281 SmallVector<SDValue, 8> Ops; 9282 Ops.push_back(N->getOperand(0)); // Incoming chain 9283 // Load lane and store have vector list as input. 9284 if (IsLaneOp || IsStore) 9285 for (unsigned i = 2; i < AddrOpIdx; ++i) 9286 Ops.push_back(N->getOperand(i)); 9287 Ops.push_back(Addr); // Base register 9288 Ops.push_back(Inc); 9289 9290 // Return Types. 9291 EVT Tys[6]; 9292 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9293 unsigned n; 9294 for (n = 0; n < NumResultVecs; ++n) 9295 Tys[n] = VecTy; 9296 Tys[n++] = MVT::i64; // Type of write back register 9297 Tys[n] = MVT::Other; // Type of the chain 9298 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9299 9300 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9301 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9302 MemInt->getMemoryVT(), 9303 MemInt->getMemOperand()); 9304 9305 // Update the uses. 9306 std::vector<SDValue> NewResults; 9307 for (unsigned i = 0; i < NumResultVecs; ++i) { 9308 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9309 } 9310 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9311 DCI.CombineTo(N, NewResults); 9312 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9313 9314 break; 9315 } 9316 return SDValue(); 9317 } 9318 9319 // Checks to see if the value is the prescribed width and returns information 9320 // about its extension mode. 9321 static 9322 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9323 ExtType = ISD::NON_EXTLOAD; 9324 switch(V.getNode()->getOpcode()) { 9325 default: 9326 return false; 9327 case ISD::LOAD: { 9328 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9329 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9330 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9331 ExtType = LoadNode->getExtensionType(); 9332 return true; 9333 } 9334 return false; 9335 } 9336 case ISD::AssertSext: { 9337 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9338 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9339 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9340 ExtType = ISD::SEXTLOAD; 9341 return true; 9342 } 9343 return false; 9344 } 9345 case ISD::AssertZext: { 9346 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9347 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9348 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9349 ExtType = ISD::ZEXTLOAD; 9350 return true; 9351 } 9352 return false; 9353 } 9354 case ISD::Constant: 9355 case ISD::TargetConstant: { 9356 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9357 1LL << (width - 1); 9358 } 9359 } 9360 9361 return true; 9362 } 9363 9364 // This function does a whole lot of voodoo to determine if the tests are 9365 // equivalent without and with a mask. Essentially what happens is that given a 9366 // DAG resembling: 9367 // 9368 // +-------------+ +-------------+ +-------------+ +-------------+ 9369 // | Input | | AddConstant | | CompConstant| | CC | 9370 // +-------------+ +-------------+ +-------------+ +-------------+ 9371 // | | | | 9372 // V V | +----------+ 9373 // +-------------+ +----+ | | 9374 // | ADD | |0xff| | | 9375 // +-------------+ +----+ | | 9376 // | | | | 9377 // V V | | 9378 // +-------------+ | | 9379 // | AND | | | 9380 // +-------------+ | | 9381 // | | | 9382 // +-----+ | | 9383 // | | | 9384 // V V V 9385 // +-------------+ 9386 // | CMP | 9387 // +-------------+ 9388 // 9389 // The AND node may be safely removed for some combinations of inputs. In 9390 // particular we need to take into account the extension type of the Input, 9391 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9392 // width of the input (this can work for any width inputs, the above graph is 9393 // specific to 8 bits. 9394 // 9395 // The specific equations were worked out by generating output tables for each 9396 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9397 // problem was simplified by working with 4 bit inputs, which means we only 9398 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9399 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9400 // patterns present in both extensions (0,7). For every distinct set of 9401 // AddConstant and CompConstants bit patterns we can consider the masked and 9402 // unmasked versions to be equivalent if the result of this function is true for 9403 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9404 // 9405 // sub w8, w0, w1 9406 // and w10, w8, #0x0f 9407 // cmp w8, w2 9408 // cset w9, AArch64CC 9409 // cmp w10, w2 9410 // cset w11, AArch64CC 9411 // cmp w9, w11 9412 // cset w0, eq 9413 // ret 9414 // 9415 // Since the above function shows when the outputs are equivalent it defines 9416 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9417 // would be expensive to run during compiles. The equations below were written 9418 // in a test harness that confirmed they gave equivalent outputs to the above 9419 // for all inputs function, so they can be used determine if the removal is 9420 // legal instead. 9421 // 9422 // isEquivalentMaskless() is the code for testing if the AND can be removed 9423 // factored out of the DAG recognition as the DAG can take several forms. 9424 9425 static 9426 bool isEquivalentMaskless(unsigned CC, unsigned width, 9427 ISD::LoadExtType ExtType, signed AddConstant, 9428 signed CompConstant) { 9429 // By being careful about our equations and only writing the in term 9430 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 9431 // make them generally applicable to all bit widths. 9432 signed MaxUInt = (1 << width); 9433 9434 // For the purposes of these comparisons sign extending the type is 9435 // equivalent to zero extending the add and displacing it by half the integer 9436 // width. Provided we are careful and make sure our equations are valid over 9437 // the whole range we can just adjust the input and avoid writing equations 9438 // for sign extended inputs. 9439 if (ExtType == ISD::SEXTLOAD) 9440 AddConstant -= (1 << (width-1)); 9441 9442 switch(CC) { 9443 case AArch64CC::LE: 9444 case AArch64CC::GT: { 9445 if ((AddConstant == 0) || 9446 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 9447 (AddConstant >= 0 && CompConstant < 0) || 9448 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 9449 return true; 9450 } break; 9451 case AArch64CC::LT: 9452 case AArch64CC::GE: { 9453 if ((AddConstant == 0) || 9454 (AddConstant >= 0 && CompConstant <= 0) || 9455 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 9456 return true; 9457 } break; 9458 case AArch64CC::HI: 9459 case AArch64CC::LS: { 9460 if ((AddConstant >= 0 && CompConstant < 0) || 9461 (AddConstant <= 0 && CompConstant >= -1 && 9462 CompConstant < AddConstant + MaxUInt)) 9463 return true; 9464 } break; 9465 case AArch64CC::PL: 9466 case AArch64CC::MI: { 9467 if ((AddConstant == 0) || 9468 (AddConstant > 0 && CompConstant <= 0) || 9469 (AddConstant < 0 && CompConstant <= AddConstant)) 9470 return true; 9471 } break; 9472 case AArch64CC::LO: 9473 case AArch64CC::HS: { 9474 if ((AddConstant >= 0 && CompConstant <= 0) || 9475 (AddConstant <= 0 && CompConstant >= 0 && 9476 CompConstant <= AddConstant + MaxUInt)) 9477 return true; 9478 } break; 9479 case AArch64CC::EQ: 9480 case AArch64CC::NE: { 9481 if ((AddConstant > 0 && CompConstant < 0) || 9482 (AddConstant < 0 && CompConstant >= 0 && 9483 CompConstant < AddConstant + MaxUInt) || 9484 (AddConstant >= 0 && CompConstant >= 0 && 9485 CompConstant >= AddConstant) || 9486 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 9487 9488 return true; 9489 } break; 9490 case AArch64CC::VS: 9491 case AArch64CC::VC: 9492 case AArch64CC::AL: 9493 case AArch64CC::NV: 9494 return true; 9495 case AArch64CC::Invalid: 9496 break; 9497 } 9498 9499 return false; 9500 } 9501 9502 static 9503 SDValue performCONDCombine(SDNode *N, 9504 TargetLowering::DAGCombinerInfo &DCI, 9505 SelectionDAG &DAG, unsigned CCIndex, 9506 unsigned CmpIndex) { 9507 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 9508 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 9509 unsigned CondOpcode = SubsNode->getOpcode(); 9510 9511 if (CondOpcode != AArch64ISD::SUBS) 9512 return SDValue(); 9513 9514 // There is a SUBS feeding this condition. Is it fed by a mask we can 9515 // use? 9516 9517 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 9518 unsigned MaskBits = 0; 9519 9520 if (AndNode->getOpcode() != ISD::AND) 9521 return SDValue(); 9522 9523 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 9524 uint32_t CNV = CN->getZExtValue(); 9525 if (CNV == 255) 9526 MaskBits = 8; 9527 else if (CNV == 65535) 9528 MaskBits = 16; 9529 } 9530 9531 if (!MaskBits) 9532 return SDValue(); 9533 9534 SDValue AddValue = AndNode->getOperand(0); 9535 9536 if (AddValue.getOpcode() != ISD::ADD) 9537 return SDValue(); 9538 9539 // The basic dag structure is correct, grab the inputs and validate them. 9540 9541 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 9542 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 9543 SDValue SubsInputValue = SubsNode->getOperand(1); 9544 9545 // The mask is present and the provenance of all the values is a smaller type, 9546 // lets see if the mask is superfluous. 9547 9548 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 9549 !isa<ConstantSDNode>(SubsInputValue.getNode())) 9550 return SDValue(); 9551 9552 ISD::LoadExtType ExtType; 9553 9554 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 9555 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 9556 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 9557 return SDValue(); 9558 9559 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 9560 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 9561 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 9562 return SDValue(); 9563 9564 // The AND is not necessary, remove it. 9565 9566 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 9567 SubsNode->getValueType(1)); 9568 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 9569 9570 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 9571 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 9572 9573 return SDValue(N, 0); 9574 } 9575 9576 // Optimize compare with zero and branch. 9577 static SDValue performBRCONDCombine(SDNode *N, 9578 TargetLowering::DAGCombinerInfo &DCI, 9579 SelectionDAG &DAG) { 9580 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 9581 N = NV.getNode(); 9582 SDValue Chain = N->getOperand(0); 9583 SDValue Dest = N->getOperand(1); 9584 SDValue CCVal = N->getOperand(2); 9585 SDValue Cmp = N->getOperand(3); 9586 9587 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 9588 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 9589 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 9590 return SDValue(); 9591 9592 unsigned CmpOpc = Cmp.getOpcode(); 9593 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 9594 return SDValue(); 9595 9596 // Only attempt folding if there is only one use of the flag and no use of the 9597 // value. 9598 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 9599 return SDValue(); 9600 9601 SDValue LHS = Cmp.getOperand(0); 9602 SDValue RHS = Cmp.getOperand(1); 9603 9604 assert(LHS.getValueType() == RHS.getValueType() && 9605 "Expected the value type to be the same for both operands!"); 9606 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 9607 return SDValue(); 9608 9609 if (isNullConstant(LHS)) 9610 std::swap(LHS, RHS); 9611 9612 if (!isNullConstant(RHS)) 9613 return SDValue(); 9614 9615 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 9616 LHS.getOpcode() == ISD::SRL) 9617 return SDValue(); 9618 9619 // Fold the compare into the branch instruction. 9620 SDValue BR; 9621 if (CC == AArch64CC::EQ) 9622 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9623 else 9624 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9625 9626 // Do not add new nodes to DAG combiner worklist. 9627 DCI.CombineTo(N, BR, false); 9628 9629 return SDValue(); 9630 } 9631 9632 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 9633 // as well as whether the test should be inverted. This code is required to 9634 // catch these cases (as opposed to standard dag combines) because 9635 // AArch64ISD::TBZ is matched during legalization. 9636 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 9637 SelectionDAG &DAG) { 9638 9639 if (!Op->hasOneUse()) 9640 return Op; 9641 9642 // We don't handle undef/constant-fold cases below, as they should have 9643 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 9644 // etc.) 9645 9646 // (tbz (trunc x), b) -> (tbz x, b) 9647 // This case is just here to enable more of the below cases to be caught. 9648 if (Op->getOpcode() == ISD::TRUNCATE && 9649 Bit < Op->getValueType(0).getSizeInBits()) { 9650 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9651 } 9652 9653 if (Op->getNumOperands() != 2) 9654 return Op; 9655 9656 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 9657 if (!C) 9658 return Op; 9659 9660 switch (Op->getOpcode()) { 9661 default: 9662 return Op; 9663 9664 // (tbz (and x, m), b) -> (tbz x, b) 9665 case ISD::AND: 9666 if ((C->getZExtValue() >> Bit) & 1) 9667 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9668 return Op; 9669 9670 // (tbz (shl x, c), b) -> (tbz x, b-c) 9671 case ISD::SHL: 9672 if (C->getZExtValue() <= Bit && 9673 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9674 Bit = Bit - C->getZExtValue(); 9675 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9676 } 9677 return Op; 9678 9679 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 9680 case ISD::SRA: 9681 Bit = Bit + C->getZExtValue(); 9682 if (Bit >= Op->getValueType(0).getSizeInBits()) 9683 Bit = Op->getValueType(0).getSizeInBits() - 1; 9684 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9685 9686 // (tbz (srl x, c), b) -> (tbz x, b+c) 9687 case ISD::SRL: 9688 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9689 Bit = Bit + C->getZExtValue(); 9690 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9691 } 9692 return Op; 9693 9694 // (tbz (xor x, -1), b) -> (tbnz x, b) 9695 case ISD::XOR: 9696 if ((C->getZExtValue() >> Bit) & 1) 9697 Invert = !Invert; 9698 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9699 } 9700 } 9701 9702 // Optimize test single bit zero/non-zero and branch. 9703 static SDValue performTBZCombine(SDNode *N, 9704 TargetLowering::DAGCombinerInfo &DCI, 9705 SelectionDAG &DAG) { 9706 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9707 bool Invert = false; 9708 SDValue TestSrc = N->getOperand(1); 9709 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 9710 9711 if (TestSrc == NewTestSrc) 9712 return SDValue(); 9713 9714 unsigned NewOpc = N->getOpcode(); 9715 if (Invert) { 9716 if (NewOpc == AArch64ISD::TBZ) 9717 NewOpc = AArch64ISD::TBNZ; 9718 else { 9719 assert(NewOpc == AArch64ISD::TBNZ); 9720 NewOpc = AArch64ISD::TBZ; 9721 } 9722 } 9723 9724 SDLoc DL(N); 9725 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 9726 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 9727 } 9728 9729 // vselect (v1i1 setcc) -> 9730 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 9731 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 9732 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 9733 // such VSELECT. 9734 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 9735 SDValue N0 = N->getOperand(0); 9736 EVT CCVT = N0.getValueType(); 9737 9738 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 9739 CCVT.getVectorElementType() != MVT::i1) 9740 return SDValue(); 9741 9742 EVT ResVT = N->getValueType(0); 9743 EVT CmpVT = N0.getOperand(0).getValueType(); 9744 // Only combine when the result type is of the same size as the compared 9745 // operands. 9746 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 9747 return SDValue(); 9748 9749 SDValue IfTrue = N->getOperand(1); 9750 SDValue IfFalse = N->getOperand(2); 9751 SDValue SetCC = 9752 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 9753 N0.getOperand(0), N0.getOperand(1), 9754 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9755 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 9756 IfTrue, IfFalse); 9757 } 9758 9759 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 9760 /// the compare-mask instructions rather than going via NZCV, even if LHS and 9761 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 9762 /// with a vector one followed by a DUP shuffle on the result. 9763 static SDValue performSelectCombine(SDNode *N, 9764 TargetLowering::DAGCombinerInfo &DCI) { 9765 SelectionDAG &DAG = DCI.DAG; 9766 SDValue N0 = N->getOperand(0); 9767 EVT ResVT = N->getValueType(0); 9768 9769 if (N0.getOpcode() != ISD::SETCC) 9770 return SDValue(); 9771 9772 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 9773 // scalar SetCCResultType. We also don't expect vectors, because we assume 9774 // that selects fed by vector SETCCs are canonicalized to VSELECT. 9775 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 9776 "Scalar-SETCC feeding SELECT has unexpected result type!"); 9777 9778 // If NumMaskElts == 0, the comparison is larger than select result. The 9779 // largest real NEON comparison is 64-bits per lane, which means the result is 9780 // at most 32-bits and an illegal vector. Just bail out for now. 9781 EVT SrcVT = N0.getOperand(0).getValueType(); 9782 9783 // Don't try to do this optimization when the setcc itself has i1 operands. 9784 // There are no legal vectors of i1, so this would be pointless. 9785 if (SrcVT == MVT::i1) 9786 return SDValue(); 9787 9788 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 9789 if (!ResVT.isVector() || NumMaskElts == 0) 9790 return SDValue(); 9791 9792 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 9793 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 9794 9795 // Also bail out if the vector CCVT isn't the same size as ResVT. 9796 // This can happen if the SETCC operand size doesn't divide the ResVT size 9797 // (e.g., f64 vs v3f32). 9798 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 9799 return SDValue(); 9800 9801 // Make sure we didn't create illegal types, if we're not supposed to. 9802 assert(DCI.isBeforeLegalize() || 9803 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 9804 9805 // First perform a vector comparison, where lane 0 is the one we're interested 9806 // in. 9807 SDLoc DL(N0); 9808 SDValue LHS = 9809 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 9810 SDValue RHS = 9811 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 9812 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 9813 9814 // Now duplicate the comparison mask we want across all other lanes. 9815 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 9816 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data()); 9817 Mask = DAG.getNode(ISD::BITCAST, DL, 9818 ResVT.changeVectorElementTypeToInteger(), Mask); 9819 9820 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 9821 } 9822 9823 /// Get rid of unnecessary NVCASTs (that don't change the type). 9824 static SDValue performNVCASTCombine(SDNode *N) { 9825 if (N->getValueType(0) == N->getOperand(0).getValueType()) 9826 return N->getOperand(0); 9827 9828 return SDValue(); 9829 } 9830 9831 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 9832 DAGCombinerInfo &DCI) const { 9833 SelectionDAG &DAG = DCI.DAG; 9834 switch (N->getOpcode()) { 9835 default: 9836 break; 9837 case ISD::ADD: 9838 case ISD::SUB: 9839 return performAddSubLongCombine(N, DCI, DAG); 9840 case ISD::XOR: 9841 return performXorCombine(N, DAG, DCI, Subtarget); 9842 case ISD::MUL: 9843 return performMulCombine(N, DAG, DCI, Subtarget); 9844 case ISD::SINT_TO_FP: 9845 case ISD::UINT_TO_FP: 9846 return performIntToFpCombine(N, DAG, Subtarget); 9847 case ISD::FP_TO_SINT: 9848 case ISD::FP_TO_UINT: 9849 return performFpToIntCombine(N, DAG, Subtarget); 9850 case ISD::FDIV: 9851 return performFDivCombine(N, DAG, Subtarget); 9852 case ISD::OR: 9853 return performORCombine(N, DCI, Subtarget); 9854 case ISD::INTRINSIC_WO_CHAIN: 9855 return performIntrinsicCombine(N, DCI, Subtarget); 9856 case ISD::ANY_EXTEND: 9857 case ISD::ZERO_EXTEND: 9858 case ISD::SIGN_EXTEND: 9859 return performExtendCombine(N, DCI, DAG); 9860 case ISD::BITCAST: 9861 return performBitcastCombine(N, DCI, DAG); 9862 case ISD::CONCAT_VECTORS: 9863 return performConcatVectorsCombine(N, DCI, DAG); 9864 case ISD::SELECT: { 9865 SDValue RV = performSelectCombine(N, DCI); 9866 if (!RV.getNode()) 9867 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget); 9868 return RV; 9869 } 9870 case ISD::VSELECT: 9871 return performVSelectCombine(N, DCI.DAG); 9872 case ISD::LOAD: 9873 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 9874 return SDValue(N, 0); 9875 break; 9876 case ISD::STORE: 9877 return performSTORECombine(N, DCI, DAG, Subtarget); 9878 case AArch64ISD::BRCOND: 9879 return performBRCONDCombine(N, DCI, DAG); 9880 case AArch64ISD::TBNZ: 9881 case AArch64ISD::TBZ: 9882 return performTBZCombine(N, DCI, DAG); 9883 case AArch64ISD::CSEL: 9884 return performCONDCombine(N, DCI, DAG, 2, 3); 9885 case AArch64ISD::DUP: 9886 return performPostLD1Combine(N, DCI, false); 9887 case AArch64ISD::NVCAST: 9888 return performNVCASTCombine(N); 9889 case ISD::INSERT_VECTOR_ELT: 9890 return performPostLD1Combine(N, DCI, true); 9891 case ISD::EXTRACT_VECTOR_ELT: 9892 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget); 9893 case ISD::INTRINSIC_VOID: 9894 case ISD::INTRINSIC_W_CHAIN: 9895 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 9896 case Intrinsic::aarch64_neon_ld2: 9897 case Intrinsic::aarch64_neon_ld3: 9898 case Intrinsic::aarch64_neon_ld4: 9899 case Intrinsic::aarch64_neon_ld1x2: 9900 case Intrinsic::aarch64_neon_ld1x3: 9901 case Intrinsic::aarch64_neon_ld1x4: 9902 case Intrinsic::aarch64_neon_ld2lane: 9903 case Intrinsic::aarch64_neon_ld3lane: 9904 case Intrinsic::aarch64_neon_ld4lane: 9905 case Intrinsic::aarch64_neon_ld2r: 9906 case Intrinsic::aarch64_neon_ld3r: 9907 case Intrinsic::aarch64_neon_ld4r: 9908 case Intrinsic::aarch64_neon_st2: 9909 case Intrinsic::aarch64_neon_st3: 9910 case Intrinsic::aarch64_neon_st4: 9911 case Intrinsic::aarch64_neon_st1x2: 9912 case Intrinsic::aarch64_neon_st1x3: 9913 case Intrinsic::aarch64_neon_st1x4: 9914 case Intrinsic::aarch64_neon_st2lane: 9915 case Intrinsic::aarch64_neon_st3lane: 9916 case Intrinsic::aarch64_neon_st4lane: 9917 return performNEONPostLDSTCombine(N, DCI, DAG); 9918 default: 9919 break; 9920 } 9921 } 9922 return SDValue(); 9923 } 9924 9925 // Check if the return value is used as only a return value, as otherwise 9926 // we can't perform a tail-call. In particular, we need to check for 9927 // target ISD nodes that are returns and any other "odd" constructs 9928 // that the generic analysis code won't necessarily catch. 9929 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 9930 SDValue &Chain) const { 9931 if (N->getNumValues() != 1) 9932 return false; 9933 if (!N->hasNUsesOfValue(1, 0)) 9934 return false; 9935 9936 SDValue TCChain = Chain; 9937 SDNode *Copy = *N->use_begin(); 9938 if (Copy->getOpcode() == ISD::CopyToReg) { 9939 // If the copy has a glue operand, we conservatively assume it isn't safe to 9940 // perform a tail call. 9941 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 9942 MVT::Glue) 9943 return false; 9944 TCChain = Copy->getOperand(0); 9945 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 9946 return false; 9947 9948 bool HasRet = false; 9949 for (SDNode *Node : Copy->uses()) { 9950 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 9951 return false; 9952 HasRet = true; 9953 } 9954 9955 if (!HasRet) 9956 return false; 9957 9958 Chain = TCChain; 9959 return true; 9960 } 9961 9962 // Return whether the an instruction can potentially be optimized to a tail 9963 // call. This will cause the optimizers to attempt to move, or duplicate, 9964 // return instructions to help enable tail call optimizations for this 9965 // instruction. 9966 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 9967 return CI->isTailCall(); 9968 } 9969 9970 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 9971 SDValue &Offset, 9972 ISD::MemIndexedMode &AM, 9973 bool &IsInc, 9974 SelectionDAG &DAG) const { 9975 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 9976 return false; 9977 9978 Base = Op->getOperand(0); 9979 // All of the indexed addressing mode instructions take a signed 9980 // 9 bit immediate offset. 9981 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 9982 int64_t RHSC = (int64_t)RHS->getZExtValue(); 9983 if (RHSC >= 256 || RHSC <= -256) 9984 return false; 9985 IsInc = (Op->getOpcode() == ISD::ADD); 9986 Offset = Op->getOperand(1); 9987 return true; 9988 } 9989 return false; 9990 } 9991 9992 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 9993 SDValue &Offset, 9994 ISD::MemIndexedMode &AM, 9995 SelectionDAG &DAG) const { 9996 EVT VT; 9997 SDValue Ptr; 9998 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9999 VT = LD->getMemoryVT(); 10000 Ptr = LD->getBasePtr(); 10001 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10002 VT = ST->getMemoryVT(); 10003 Ptr = ST->getBasePtr(); 10004 } else 10005 return false; 10006 10007 bool IsInc; 10008 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 10009 return false; 10010 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 10011 return true; 10012 } 10013 10014 bool AArch64TargetLowering::getPostIndexedAddressParts( 10015 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10016 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10017 EVT VT; 10018 SDValue Ptr; 10019 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10020 VT = LD->getMemoryVT(); 10021 Ptr = LD->getBasePtr(); 10022 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10023 VT = ST->getMemoryVT(); 10024 Ptr = ST->getBasePtr(); 10025 } else 10026 return false; 10027 10028 bool IsInc; 10029 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10030 return false; 10031 // Post-indexing updates the base, so it's not a valid transform 10032 // if that's not the same as the load's pointer. 10033 if (Ptr != Base) 10034 return false; 10035 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10036 return true; 10037 } 10038 10039 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10040 SelectionDAG &DAG) { 10041 SDLoc DL(N); 10042 SDValue Op = N->getOperand(0); 10043 10044 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10045 return; 10046 10047 Op = SDValue( 10048 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10049 DAG.getUNDEF(MVT::i32), Op, 10050 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10051 0); 10052 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10053 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10054 } 10055 10056 static void ReplaceReductionResults(SDNode *N, 10057 SmallVectorImpl<SDValue> &Results, 10058 SelectionDAG &DAG, unsigned InterOp, 10059 unsigned AcrossOp) { 10060 EVT LoVT, HiVT; 10061 SDValue Lo, Hi; 10062 SDLoc dl(N); 10063 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10064 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10065 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10066 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10067 Results.push_back(SplitVal); 10068 } 10069 10070 void AArch64TargetLowering::ReplaceNodeResults( 10071 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10072 switch (N->getOpcode()) { 10073 default: 10074 llvm_unreachable("Don't know how to custom expand this"); 10075 case ISD::BITCAST: 10076 ReplaceBITCASTResults(N, Results, DAG); 10077 return; 10078 case AArch64ISD::SADDV: 10079 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10080 return; 10081 case AArch64ISD::UADDV: 10082 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10083 return; 10084 case AArch64ISD::SMINV: 10085 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10086 return; 10087 case AArch64ISD::UMINV: 10088 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10089 return; 10090 case AArch64ISD::SMAXV: 10091 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10092 return; 10093 case AArch64ISD::UMAXV: 10094 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10095 return; 10096 case ISD::FP_TO_UINT: 10097 case ISD::FP_TO_SINT: 10098 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10099 // Let normal code take care of it by not adding anything to Results. 10100 return; 10101 } 10102 } 10103 10104 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10105 return true; 10106 } 10107 10108 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10109 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10110 // reciprocal if there are three or more FDIVs. 10111 return 3; 10112 } 10113 10114 TargetLoweringBase::LegalizeTypeAction 10115 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10116 MVT SVT = VT.getSimpleVT(); 10117 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10118 // v4i16, v2i32 instead of to promote. 10119 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10120 || SVT == MVT::v1f32) 10121 return TypeWidenVector; 10122 10123 return TargetLoweringBase::getPreferredVectorAction(VT); 10124 } 10125 10126 // Loads and stores less than 128-bits are already atomic; ones above that 10127 // are doomed anyway, so defer to the default libcall and blame the OS when 10128 // things go wrong. 10129 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10130 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10131 return Size == 128; 10132 } 10133 10134 // Loads and stores less than 128-bits are already atomic; ones above that 10135 // are doomed anyway, so defer to the default libcall and blame the OS when 10136 // things go wrong. 10137 TargetLowering::AtomicExpansionKind 10138 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10139 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10140 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10141 } 10142 10143 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10144 TargetLowering::AtomicExpansionKind 10145 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10146 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10147 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10148 } 10149 10150 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10151 AtomicCmpXchgInst *AI) const { 10152 return true; 10153 } 10154 10155 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10156 AtomicOrdering Ord) const { 10157 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10158 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10159 bool IsAcquire = isAtLeastAcquire(Ord); 10160 10161 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10162 // intrinsic must return {i64, i64} and we have to recombine them into a 10163 // single i128 here. 10164 if (ValTy->getPrimitiveSizeInBits() == 128) { 10165 Intrinsic::ID Int = 10166 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10167 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int); 10168 10169 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10170 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10171 10172 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10173 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10174 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10175 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10176 return Builder.CreateOr( 10177 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10178 } 10179 10180 Type *Tys[] = { Addr->getType() }; 10181 Intrinsic::ID Int = 10182 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10183 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys); 10184 10185 return Builder.CreateTruncOrBitCast( 10186 Builder.CreateCall(Ldxr, Addr), 10187 cast<PointerType>(Addr->getType())->getElementType()); 10188 } 10189 10190 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10191 IRBuilder<> &Builder) const { 10192 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10193 Builder.CreateCall( 10194 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10195 } 10196 10197 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10198 Value *Val, Value *Addr, 10199 AtomicOrdering Ord) const { 10200 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10201 bool IsRelease = isAtLeastRelease(Ord); 10202 10203 // Since the intrinsics must have legal type, the i128 intrinsics take two 10204 // parameters: "i64, i64". We must marshal Val into the appropriate form 10205 // before the call. 10206 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10207 Intrinsic::ID Int = 10208 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10209 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10210 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10211 10212 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10213 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10214 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10215 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10216 } 10217 10218 Intrinsic::ID Int = 10219 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10220 Type *Tys[] = { Addr->getType() }; 10221 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10222 10223 return Builder.CreateCall(Stxr, 10224 {Builder.CreateZExtOrBitCast( 10225 Val, Stxr->getFunctionType()->getParamType(0)), 10226 Addr}); 10227 } 10228 10229 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10230 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10231 return Ty->isArrayTy(); 10232 } 10233 10234 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10235 EVT) const { 10236 return false; 10237 } 10238 10239 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10240 if (!Subtarget->isTargetAndroid()) 10241 return TargetLowering::getSafeStackPointerLocation(IRB); 10242 10243 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10244 // definition of TLS_SLOT_SAFESTACK in 10245 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10246 const unsigned TlsOffset = 0x48; 10247 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10248 Function *ThreadPointerFunc = 10249 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer); 10250 return IRB.CreatePointerCast( 10251 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10252 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10253 } 10254 10255 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10256 // Update IsSplitCSR in AArch64unctionInfo. 10257 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10258 AFI->setIsSplitCSR(true); 10259 } 10260 10261 void AArch64TargetLowering::insertCopiesSplitCSR( 10262 MachineBasicBlock *Entry, 10263 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10264 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10265 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10266 if (!IStart) 10267 return; 10268 10269 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10270 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10271 MachineBasicBlock::iterator MBBI = Entry->begin(); 10272 for (const MCPhysReg *I = IStart; *I; ++I) { 10273 const TargetRegisterClass *RC = nullptr; 10274 if (AArch64::GPR64RegClass.contains(*I)) 10275 RC = &AArch64::GPR64RegClass; 10276 else if (AArch64::FPR64RegClass.contains(*I)) 10277 RC = &AArch64::FPR64RegClass; 10278 else 10279 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10280 10281 unsigned NewVR = MRI->createVirtualRegister(RC); 10282 // Create copy from CSR to a virtual register. 10283 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10284 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10285 // nounwind. If we want to generalize this later, we may need to emit 10286 // CFI pseudo-instructions. 10287 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10288 Attribute::NoUnwind) && 10289 "Function should be nounwind in insertCopiesSplitCSR!"); 10290 Entry->addLiveIn(*I); 10291 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10292 .addReg(*I); 10293 10294 // Insert the copy-back instructions right before the terminator. 10295 for (auto *Exit : Exits) 10296 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10297 TII->get(TargetOpcode::COPY), *I) 10298 .addReg(NewVR); 10299 } 10300 } 10301