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 static cl::opt<bool> 44 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 45 cl::desc("Allow AArch64 SLI/SRI formation"), 46 cl::init(false)); 47 48 // FIXME: The necessary dtprel relocations don't seem to be supported 49 // well in the GNU bfd and gold linkers at the moment. Therefore, by 50 // default, for now, fall back to GeneralDynamic code generation. 51 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 52 "aarch64-elf-ldtls-generation", cl::Hidden, 53 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 54 cl::init(false)); 55 56 /// Value type used for condition codes. 57 static const MVT MVT_CC = MVT::i32; 58 59 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 60 const AArch64Subtarget &STI) 61 : TargetLowering(TM), Subtarget(&STI) { 62 63 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 64 // we have to make something up. Arbitrarily, choose ZeroOrOne. 65 setBooleanContents(ZeroOrOneBooleanContent); 66 // When comparing vectors the result sets the different elements in the 67 // vector to all-one or all-zero. 68 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 69 70 // Set up the register classes. 71 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 72 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 73 74 if (Subtarget->hasFPARMv8()) { 75 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 76 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 77 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 78 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 79 } 80 81 if (Subtarget->hasNEON()) { 82 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 83 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 84 // Someone set us up the NEON. 85 addDRTypeForNEON(MVT::v2f32); 86 addDRTypeForNEON(MVT::v8i8); 87 addDRTypeForNEON(MVT::v4i16); 88 addDRTypeForNEON(MVT::v2i32); 89 addDRTypeForNEON(MVT::v1i64); 90 addDRTypeForNEON(MVT::v1f64); 91 addDRTypeForNEON(MVT::v4f16); 92 93 addQRTypeForNEON(MVT::v4f32); 94 addQRTypeForNEON(MVT::v2f64); 95 addQRTypeForNEON(MVT::v16i8); 96 addQRTypeForNEON(MVT::v8i16); 97 addQRTypeForNEON(MVT::v4i32); 98 addQRTypeForNEON(MVT::v2i64); 99 addQRTypeForNEON(MVT::v8f16); 100 } 101 102 // Compute derived properties from the register classes 103 computeRegisterProperties(Subtarget->getRegisterInfo()); 104 105 // Provide all sorts of operation actions 106 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 107 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 108 setOperationAction(ISD::SETCC, MVT::i32, Custom); 109 setOperationAction(ISD::SETCC, MVT::i64, Custom); 110 setOperationAction(ISD::SETCC, MVT::f32, Custom); 111 setOperationAction(ISD::SETCC, MVT::f64, Custom); 112 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 113 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 114 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 115 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 116 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 117 setOperationAction(ISD::SELECT, MVT::i32, Custom); 118 setOperationAction(ISD::SELECT, MVT::i64, Custom); 119 setOperationAction(ISD::SELECT, MVT::f32, Custom); 120 setOperationAction(ISD::SELECT, MVT::f64, Custom); 121 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 122 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 123 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 124 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 125 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 126 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 127 128 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 129 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 130 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 131 132 setOperationAction(ISD::FREM, MVT::f32, Expand); 133 setOperationAction(ISD::FREM, MVT::f64, Expand); 134 setOperationAction(ISD::FREM, MVT::f80, Expand); 135 136 // Custom lowering hooks are needed for XOR 137 // to fold it into CSINC/CSINV. 138 setOperationAction(ISD::XOR, MVT::i32, Custom); 139 setOperationAction(ISD::XOR, MVT::i64, Custom); 140 141 // Custom lowering hooks are needed for OR 142 // to fold it into CCMP. 143 setOperationAction(ISD::OR, MVT::i32, Custom); 144 setOperationAction(ISD::OR, MVT::i64, Custom); 145 146 // Custom lowering hooks are needed for AND 147 // to fold it into CCMP. 148 setOperationAction(ISD::AND, MVT::i32, Custom); 149 setOperationAction(ISD::AND, MVT::i64, Custom); 150 151 // Virtually no operation on f128 is legal, but LLVM can't expand them when 152 // there's a valid register class, so we need custom operations in most cases. 153 setOperationAction(ISD::FABS, MVT::f128, Expand); 154 setOperationAction(ISD::FADD, MVT::f128, Custom); 155 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 156 setOperationAction(ISD::FCOS, MVT::f128, Expand); 157 setOperationAction(ISD::FDIV, MVT::f128, Custom); 158 setOperationAction(ISD::FMA, MVT::f128, Expand); 159 setOperationAction(ISD::FMUL, MVT::f128, Custom); 160 setOperationAction(ISD::FNEG, MVT::f128, Expand); 161 setOperationAction(ISD::FPOW, MVT::f128, Expand); 162 setOperationAction(ISD::FREM, MVT::f128, Expand); 163 setOperationAction(ISD::FRINT, MVT::f128, Expand); 164 setOperationAction(ISD::FSIN, MVT::f128, Expand); 165 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 166 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 167 setOperationAction(ISD::FSUB, MVT::f128, Custom); 168 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 169 setOperationAction(ISD::SETCC, MVT::f128, Custom); 170 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 171 setOperationAction(ISD::SELECT, MVT::f128, Custom); 172 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 173 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 174 175 // Lowering for many of the conversions is actually specified by the non-f128 176 // type. The LowerXXX function will be trivial when f128 isn't involved. 177 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 178 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 179 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 180 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 181 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 182 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 183 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 184 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 185 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 186 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 187 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 188 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 189 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 190 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 191 192 // Variable arguments. 193 setOperationAction(ISD::VASTART, MVT::Other, Custom); 194 setOperationAction(ISD::VAARG, MVT::Other, Custom); 195 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 196 setOperationAction(ISD::VAEND, MVT::Other, Expand); 197 198 // Variable-sized objects. 199 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 200 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 201 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 202 203 // Constant pool entries 204 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 205 206 // BlockAddress 207 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 208 209 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 210 setOperationAction(ISD::ADDC, MVT::i32, Custom); 211 setOperationAction(ISD::ADDE, MVT::i32, Custom); 212 setOperationAction(ISD::SUBC, MVT::i32, Custom); 213 setOperationAction(ISD::SUBE, MVT::i32, Custom); 214 setOperationAction(ISD::ADDC, MVT::i64, Custom); 215 setOperationAction(ISD::ADDE, MVT::i64, Custom); 216 setOperationAction(ISD::SUBC, MVT::i64, Custom); 217 setOperationAction(ISD::SUBE, MVT::i64, Custom); 218 219 // AArch64 lacks both left-rotate and popcount instructions. 220 setOperationAction(ISD::ROTL, MVT::i32, Expand); 221 setOperationAction(ISD::ROTL, MVT::i64, Expand); 222 for (MVT VT : MVT::vector_valuetypes()) { 223 setOperationAction(ISD::ROTL, VT, Expand); 224 setOperationAction(ISD::ROTR, VT, Expand); 225 } 226 227 // AArch64 doesn't have {U|S}MUL_LOHI. 228 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 229 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 230 231 232 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 233 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 234 235 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 236 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 237 for (MVT VT : MVT::vector_valuetypes()) { 238 setOperationAction(ISD::SDIVREM, VT, Expand); 239 setOperationAction(ISD::UDIVREM, VT, Expand); 240 } 241 setOperationAction(ISD::SREM, MVT::i32, Expand); 242 setOperationAction(ISD::SREM, MVT::i64, Expand); 243 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 244 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 245 setOperationAction(ISD::UREM, MVT::i32, Expand); 246 setOperationAction(ISD::UREM, MVT::i64, Expand); 247 248 // Custom lower Add/Sub/Mul with overflow. 249 setOperationAction(ISD::SADDO, MVT::i32, Custom); 250 setOperationAction(ISD::SADDO, MVT::i64, Custom); 251 setOperationAction(ISD::UADDO, MVT::i32, Custom); 252 setOperationAction(ISD::UADDO, MVT::i64, Custom); 253 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 254 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 255 setOperationAction(ISD::USUBO, MVT::i32, Custom); 256 setOperationAction(ISD::USUBO, MVT::i64, Custom); 257 setOperationAction(ISD::SMULO, MVT::i32, Custom); 258 setOperationAction(ISD::SMULO, MVT::i64, Custom); 259 setOperationAction(ISD::UMULO, MVT::i32, Custom); 260 setOperationAction(ISD::UMULO, MVT::i64, Custom); 261 262 setOperationAction(ISD::FSIN, MVT::f32, Expand); 263 setOperationAction(ISD::FSIN, MVT::f64, Expand); 264 setOperationAction(ISD::FCOS, MVT::f32, Expand); 265 setOperationAction(ISD::FCOS, MVT::f64, Expand); 266 setOperationAction(ISD::FPOW, MVT::f32, Expand); 267 setOperationAction(ISD::FPOW, MVT::f64, Expand); 268 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 269 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 270 271 // f16 is a storage-only type, always promote it to f32. 272 setOperationAction(ISD::SETCC, MVT::f16, Promote); 273 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 274 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 275 setOperationAction(ISD::SELECT, MVT::f16, Promote); 276 setOperationAction(ISD::FADD, MVT::f16, Promote); 277 setOperationAction(ISD::FSUB, MVT::f16, Promote); 278 setOperationAction(ISD::FMUL, MVT::f16, Promote); 279 setOperationAction(ISD::FDIV, MVT::f16, Promote); 280 setOperationAction(ISD::FREM, MVT::f16, Promote); 281 setOperationAction(ISD::FMA, MVT::f16, Promote); 282 setOperationAction(ISD::FNEG, MVT::f16, Promote); 283 setOperationAction(ISD::FABS, MVT::f16, Promote); 284 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 285 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 286 setOperationAction(ISD::FCOS, MVT::f16, Promote); 287 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 288 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 289 setOperationAction(ISD::FPOW, MVT::f16, Promote); 290 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 291 setOperationAction(ISD::FRINT, MVT::f16, Promote); 292 setOperationAction(ISD::FSIN, MVT::f16, Promote); 293 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 294 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 295 setOperationAction(ISD::FEXP, MVT::f16, Promote); 296 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 297 setOperationAction(ISD::FLOG, MVT::f16, Promote); 298 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 299 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 300 setOperationAction(ISD::FROUND, MVT::f16, Promote); 301 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 302 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 303 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 304 setOperationAction(ISD::FMINNAN, MVT::f16, Promote); 305 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote); 306 307 // v4f16 is also a storage-only type, so promote it to v4f32 when that is 308 // known to be safe. 309 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 310 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 311 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 312 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 313 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 314 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 315 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 316 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 317 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 318 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 319 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 320 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 321 322 // Expand all other v4f16 operations. 323 // FIXME: We could generate better code by promoting some operations to 324 // a pair of v4f32s 325 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 326 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 327 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 328 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 329 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 330 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 331 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 332 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 333 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 334 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 335 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 336 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 337 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 338 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 339 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 340 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 341 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 342 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 343 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 344 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 345 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 346 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 347 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 348 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 349 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 350 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 351 352 353 // v8f16 is also a storage-only type, so expand it. 354 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 355 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 356 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 357 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 358 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 359 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 360 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 361 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 362 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 363 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 364 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 365 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 366 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 367 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 368 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 369 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 370 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 371 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 372 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 373 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 374 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 375 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 376 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 377 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 378 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 379 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 380 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 381 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 382 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 383 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 384 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 385 386 // AArch64 has implementations of a lot of rounding-like FP operations. 387 for (MVT Ty : {MVT::f32, MVT::f64}) { 388 setOperationAction(ISD::FFLOOR, Ty, Legal); 389 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 390 setOperationAction(ISD::FCEIL, Ty, Legal); 391 setOperationAction(ISD::FRINT, Ty, Legal); 392 setOperationAction(ISD::FTRUNC, Ty, Legal); 393 setOperationAction(ISD::FROUND, Ty, Legal); 394 setOperationAction(ISD::FMINNUM, Ty, Legal); 395 setOperationAction(ISD::FMAXNUM, Ty, Legal); 396 setOperationAction(ISD::FMINNAN, Ty, Legal); 397 setOperationAction(ISD::FMAXNAN, Ty, Legal); 398 } 399 400 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 401 402 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 403 404 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 405 // This requires the Performance Monitors extension. 406 if (Subtarget->hasPerfMon()) 407 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 408 409 if (Subtarget->isTargetMachO()) { 410 // For iOS, we don't want to the normal expansion of a libcall to 411 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 412 // traffic. 413 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 414 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 415 } else { 416 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 417 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 418 } 419 420 // Make floating-point constants legal for the large code model, so they don't 421 // become loads from the constant pool. 422 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 423 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 424 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 425 } 426 427 // AArch64 does not have floating-point extending loads, i1 sign-extending 428 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 429 for (MVT VT : MVT::fp_valuetypes()) { 430 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 434 } 435 for (MVT VT : MVT::integer_valuetypes()) 436 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 437 438 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 439 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 440 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 441 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 442 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 443 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 444 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 445 446 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 447 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 448 449 // Indexed loads and stores are supported. 450 for (unsigned im = (unsigned)ISD::PRE_INC; 451 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 452 setIndexedLoadAction(im, MVT::i8, Legal); 453 setIndexedLoadAction(im, MVT::i16, Legal); 454 setIndexedLoadAction(im, MVT::i32, Legal); 455 setIndexedLoadAction(im, MVT::i64, Legal); 456 setIndexedLoadAction(im, MVT::f64, Legal); 457 setIndexedLoadAction(im, MVT::f32, Legal); 458 setIndexedLoadAction(im, MVT::f16, Legal); 459 setIndexedStoreAction(im, MVT::i8, Legal); 460 setIndexedStoreAction(im, MVT::i16, Legal); 461 setIndexedStoreAction(im, MVT::i32, Legal); 462 setIndexedStoreAction(im, MVT::i64, Legal); 463 setIndexedStoreAction(im, MVT::f64, Legal); 464 setIndexedStoreAction(im, MVT::f32, Legal); 465 setIndexedStoreAction(im, MVT::f16, Legal); 466 } 467 468 // Trap. 469 setOperationAction(ISD::TRAP, MVT::Other, Legal); 470 471 // We combine OR nodes for bitfield operations. 472 setTargetDAGCombine(ISD::OR); 473 474 // Vector add and sub nodes may conceal a high-half opportunity. 475 // Also, try to fold ADD into CSINC/CSINV.. 476 setTargetDAGCombine(ISD::ADD); 477 setTargetDAGCombine(ISD::SUB); 478 setTargetDAGCombine(ISD::SRL); 479 setTargetDAGCombine(ISD::XOR); 480 setTargetDAGCombine(ISD::SINT_TO_FP); 481 setTargetDAGCombine(ISD::UINT_TO_FP); 482 483 setTargetDAGCombine(ISD::FP_TO_SINT); 484 setTargetDAGCombine(ISD::FP_TO_UINT); 485 setTargetDAGCombine(ISD::FDIV); 486 487 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 488 489 setTargetDAGCombine(ISD::ANY_EXTEND); 490 setTargetDAGCombine(ISD::ZERO_EXTEND); 491 setTargetDAGCombine(ISD::SIGN_EXTEND); 492 setTargetDAGCombine(ISD::BITCAST); 493 setTargetDAGCombine(ISD::CONCAT_VECTORS); 494 setTargetDAGCombine(ISD::STORE); 495 if (Subtarget->supportsAddressTopByteIgnored()) 496 setTargetDAGCombine(ISD::LOAD); 497 498 setTargetDAGCombine(ISD::MUL); 499 500 setTargetDAGCombine(ISD::SELECT); 501 setTargetDAGCombine(ISD::VSELECT); 502 503 setTargetDAGCombine(ISD::INTRINSIC_VOID); 504 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 505 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 506 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 507 508 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8; 509 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4; 510 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4; 511 512 setStackPointerRegisterToSaveRestore(AArch64::SP); 513 514 setSchedulingPreference(Sched::Hybrid); 515 516 // Enable TBZ/TBNZ 517 MaskAndBranchFoldingIsLegal = true; 518 EnableExtLdPromotion = true; 519 520 // Set required alignment. 521 setMinFunctionAlignment(2); 522 // Set preferred alignments. 523 setPrefFunctionAlignment(STI.getPrefFunctionAlignment()); 524 setPrefLoopAlignment(STI.getPrefLoopAlignment()); 525 526 setHasExtractBitsInsn(true); 527 528 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 529 530 if (Subtarget->hasNEON()) { 531 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 532 // silliness like this: 533 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 534 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 535 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 536 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 537 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 538 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 539 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 540 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 541 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 542 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 543 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 544 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 545 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 546 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 547 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 548 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 549 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 550 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 551 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 552 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 553 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 554 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 555 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 556 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 557 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 558 559 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 560 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 561 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 562 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 563 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 564 565 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 566 567 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 568 // elements smaller than i32, so promote the input to i32 first. 569 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote); 570 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote); 571 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote); 572 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote); 573 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16 574 // -> v8f16 conversions. 575 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote); 576 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote); 577 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 578 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote); 579 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 580 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 581 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 582 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 583 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 584 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 585 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 586 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 587 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 588 589 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 590 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 591 592 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand); 593 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand); 594 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand); 595 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand); 596 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand); 597 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand); 598 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand); 599 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand); 600 601 // AArch64 doesn't have MUL.2d: 602 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 603 // Custom handling for some quad-vector types to detect MULL. 604 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 605 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 606 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 607 608 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 609 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 610 // Likewise, narrowing and extending vector loads/stores aren't handled 611 // directly. 612 for (MVT VT : MVT::vector_valuetypes()) { 613 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 614 615 setOperationAction(ISD::MULHS, VT, Expand); 616 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 617 setOperationAction(ISD::MULHU, VT, Expand); 618 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 619 620 setOperationAction(ISD::BSWAP, VT, Expand); 621 622 for (MVT InnerVT : MVT::vector_valuetypes()) { 623 setTruncStoreAction(VT, InnerVT, Expand); 624 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 625 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 626 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 627 } 628 } 629 630 // AArch64 has implementations of a lot of rounding-like FP operations. 631 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 632 setOperationAction(ISD::FFLOOR, Ty, Legal); 633 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 634 setOperationAction(ISD::FCEIL, Ty, Legal); 635 setOperationAction(ISD::FRINT, Ty, Legal); 636 setOperationAction(ISD::FTRUNC, Ty, Legal); 637 setOperationAction(ISD::FROUND, Ty, Legal); 638 } 639 } 640 641 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 642 } 643 644 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 645 if (VT == MVT::v2f32 || VT == MVT::v4f16) { 646 setOperationAction(ISD::LOAD, VT, Promote); 647 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32); 648 649 setOperationAction(ISD::STORE, VT, Promote); 650 AddPromotedToType(ISD::STORE, VT, MVT::v2i32); 651 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) { 652 setOperationAction(ISD::LOAD, VT, Promote); 653 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64); 654 655 setOperationAction(ISD::STORE, VT, Promote); 656 AddPromotedToType(ISD::STORE, VT, MVT::v2i64); 657 } 658 659 // Mark vector float intrinsics as expand. 660 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 661 setOperationAction(ISD::FSIN, VT, Expand); 662 setOperationAction(ISD::FCOS, VT, Expand); 663 setOperationAction(ISD::FPOWI, VT, Expand); 664 setOperationAction(ISD::FPOW, VT, Expand); 665 setOperationAction(ISD::FLOG, VT, Expand); 666 setOperationAction(ISD::FLOG2, VT, Expand); 667 setOperationAction(ISD::FLOG10, VT, Expand); 668 setOperationAction(ISD::FEXP, VT, Expand); 669 setOperationAction(ISD::FEXP2, VT, Expand); 670 671 // But we do support custom-lowering for FCOPYSIGN. 672 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 673 } 674 675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 676 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 677 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 678 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 679 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 680 setOperationAction(ISD::SRA, VT, Custom); 681 setOperationAction(ISD::SRL, VT, Custom); 682 setOperationAction(ISD::SHL, VT, Custom); 683 setOperationAction(ISD::AND, VT, Custom); 684 setOperationAction(ISD::OR, VT, Custom); 685 setOperationAction(ISD::SETCC, VT, Custom); 686 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 687 688 setOperationAction(ISD::SELECT, VT, Expand); 689 setOperationAction(ISD::SELECT_CC, VT, Expand); 690 setOperationAction(ISD::VSELECT, VT, Expand); 691 for (MVT InnerVT : MVT::all_valuetypes()) 692 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 693 694 // CNT supports only B element sizes. 695 if (VT != MVT::v8i8 && VT != MVT::v16i8) 696 setOperationAction(ISD::CTPOP, VT, Expand); 697 698 setOperationAction(ISD::UDIV, VT, Expand); 699 setOperationAction(ISD::SDIV, VT, Expand); 700 setOperationAction(ISD::UREM, VT, Expand); 701 setOperationAction(ISD::SREM, VT, Expand); 702 setOperationAction(ISD::FREM, VT, Expand); 703 704 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 705 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 706 707 // [SU][MIN|MAX] are available for all NEON types apart from i64. 708 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 709 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 710 setOperationAction(Opcode, VT, Legal); 711 712 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!). 713 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16) 714 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN, 715 ISD::FMINNUM, ISD::FMAXNUM}) 716 setOperationAction(Opcode, VT, Legal); 717 718 if (Subtarget->isLittleEndian()) { 719 for (unsigned im = (unsigned)ISD::PRE_INC; 720 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 721 setIndexedLoadAction(im, VT, Legal); 722 setIndexedStoreAction(im, VT, Legal); 723 } 724 } 725 } 726 727 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 728 addRegisterClass(VT, &AArch64::FPR64RegClass); 729 addTypeForNEON(VT, MVT::v2i32); 730 } 731 732 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 733 addRegisterClass(VT, &AArch64::FPR128RegClass); 734 addTypeForNEON(VT, MVT::v4i32); 735 } 736 737 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 738 EVT VT) const { 739 if (!VT.isVector()) 740 return MVT::i32; 741 return VT.changeVectorElementTypeToInteger(); 742 } 743 744 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 745 /// Mask are known to be either zero or one and return them in the 746 /// KnownZero/KnownOne bitsets. 747 void AArch64TargetLowering::computeKnownBitsForTargetNode( 748 const SDValue Op, APInt &KnownZero, APInt &KnownOne, 749 const SelectionDAG &DAG, unsigned Depth) const { 750 switch (Op.getOpcode()) { 751 default: 752 break; 753 case AArch64ISD::CSEL: { 754 APInt KnownZero2, KnownOne2; 755 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1); 756 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1); 757 KnownZero &= KnownZero2; 758 KnownOne &= KnownOne2; 759 break; 760 } 761 case ISD::INTRINSIC_W_CHAIN: { 762 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 763 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 764 switch (IntID) { 765 default: return; 766 case Intrinsic::aarch64_ldaxr: 767 case Intrinsic::aarch64_ldxr: { 768 unsigned BitWidth = KnownOne.getBitWidth(); 769 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 770 unsigned MemBits = VT.getScalarType().getSizeInBits(); 771 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 772 return; 773 } 774 } 775 break; 776 } 777 case ISD::INTRINSIC_WO_CHAIN: 778 case ISD::INTRINSIC_VOID: { 779 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 780 switch (IntNo) { 781 default: 782 break; 783 case Intrinsic::aarch64_neon_umaxv: 784 case Intrinsic::aarch64_neon_uminv: { 785 // Figure out the datatype of the vector operand. The UMINV instruction 786 // will zero extend the result, so we can mark as known zero all the 787 // bits larger than the element datatype. 32-bit or larget doesn't need 788 // this as those are legal types and will be handled by isel directly. 789 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 790 unsigned BitWidth = KnownZero.getBitWidth(); 791 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 792 assert(BitWidth >= 8 && "Unexpected width!"); 793 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 794 KnownZero |= Mask; 795 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 796 assert(BitWidth >= 16 && "Unexpected width!"); 797 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 798 KnownZero |= Mask; 799 } 800 break; 801 } break; 802 } 803 } 804 } 805 } 806 807 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 808 EVT) const { 809 return MVT::i64; 810 } 811 812 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 813 unsigned AddrSpace, 814 unsigned Align, 815 bool *Fast) const { 816 if (Subtarget->requiresStrictAlign()) 817 return false; 818 819 if (Fast) { 820 // Some CPUs are fine with unaligned stores except for 128-bit ones. 821 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 822 // See comments in performSTORECombine() for more details about 823 // these conditions. 824 825 // Code that uses clang vector extensions can mark that it 826 // wants unaligned accesses to be treated as fast by 827 // underspecifying alignment to be 1 or 2. 828 Align <= 2 || 829 830 // Disregard v2i64. Memcpy lowering produces those and splitting 831 // them regresses performance on micro-benchmarks and olden/bh. 832 VT == MVT::v2i64; 833 } 834 return true; 835 } 836 837 FastISel * 838 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 839 const TargetLibraryInfo *libInfo) const { 840 return AArch64::createFastISel(funcInfo, libInfo); 841 } 842 843 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 844 switch ((AArch64ISD::NodeType)Opcode) { 845 case AArch64ISD::FIRST_NUMBER: break; 846 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 847 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 848 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 849 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 850 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 851 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 852 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 853 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 854 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 855 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 856 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 857 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 858 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 859 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 860 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 861 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 862 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 863 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 864 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 865 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 866 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 867 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 868 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 869 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 870 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 871 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 872 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 873 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 874 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 875 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 876 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 877 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 878 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 879 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 880 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 881 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 882 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 883 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 884 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 885 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 886 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 887 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 888 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 889 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 890 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 891 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 892 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 893 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 894 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 895 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 896 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 897 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 898 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 899 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 900 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 901 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 902 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 903 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 904 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 905 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 906 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 907 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 908 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 909 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 910 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 911 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 912 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 913 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 914 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 915 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 916 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 917 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 918 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 919 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 920 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 921 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 922 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 923 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 924 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 925 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 926 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 927 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 928 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 929 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 930 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 931 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 932 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 933 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 934 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 935 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 936 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 937 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 938 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 939 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 940 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 941 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 942 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 943 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 944 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 945 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 946 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 947 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 948 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 949 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 950 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 951 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 952 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 953 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 954 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 955 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 956 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 957 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 958 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 959 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 960 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 961 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 962 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 963 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 964 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 965 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 966 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 967 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 968 } 969 return nullptr; 970 } 971 972 MachineBasicBlock * 973 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI, 974 MachineBasicBlock *MBB) const { 975 // We materialise the F128CSEL pseudo-instruction as some control flow and a 976 // phi node: 977 978 // OrigBB: 979 // [... previous instrs leading to comparison ...] 980 // b.ne TrueBB 981 // b EndBB 982 // TrueBB: 983 // ; Fallthrough 984 // EndBB: 985 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 986 987 MachineFunction *MF = MBB->getParent(); 988 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 989 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 990 DebugLoc DL = MI->getDebugLoc(); 991 MachineFunction::iterator It = ++MBB->getIterator(); 992 993 unsigned DestReg = MI->getOperand(0).getReg(); 994 unsigned IfTrueReg = MI->getOperand(1).getReg(); 995 unsigned IfFalseReg = MI->getOperand(2).getReg(); 996 unsigned CondCode = MI->getOperand(3).getImm(); 997 bool NZCVKilled = MI->getOperand(4).isKill(); 998 999 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1000 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1001 MF->insert(It, TrueBB); 1002 MF->insert(It, EndBB); 1003 1004 // Transfer rest of current basic-block to EndBB 1005 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1006 MBB->end()); 1007 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1008 1009 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1010 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1011 MBB->addSuccessor(TrueBB); 1012 MBB->addSuccessor(EndBB); 1013 1014 // TrueBB falls through to the end. 1015 TrueBB->addSuccessor(EndBB); 1016 1017 if (!NZCVKilled) { 1018 TrueBB->addLiveIn(AArch64::NZCV); 1019 EndBB->addLiveIn(AArch64::NZCV); 1020 } 1021 1022 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1023 .addReg(IfTrueReg) 1024 .addMBB(TrueBB) 1025 .addReg(IfFalseReg) 1026 .addMBB(MBB); 1027 1028 MI->eraseFromParent(); 1029 return EndBB; 1030 } 1031 1032 MachineBasicBlock * 1033 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 1034 MachineBasicBlock *BB) const { 1035 switch (MI->getOpcode()) { 1036 default: 1037 #ifndef NDEBUG 1038 MI->dump(); 1039 #endif 1040 llvm_unreachable("Unexpected instruction for custom inserter!"); 1041 1042 case AArch64::F128CSEL: 1043 return EmitF128CSEL(MI, BB); 1044 1045 case TargetOpcode::STACKMAP: 1046 case TargetOpcode::PATCHPOINT: 1047 return emitPatchPoint(MI, BB); 1048 } 1049 } 1050 1051 //===----------------------------------------------------------------------===// 1052 // AArch64 Lowering private implementation. 1053 //===----------------------------------------------------------------------===// 1054 1055 //===----------------------------------------------------------------------===// 1056 // Lowering Code 1057 //===----------------------------------------------------------------------===// 1058 1059 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1060 /// CC 1061 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1062 switch (CC) { 1063 default: 1064 llvm_unreachable("Unknown condition code!"); 1065 case ISD::SETNE: 1066 return AArch64CC::NE; 1067 case ISD::SETEQ: 1068 return AArch64CC::EQ; 1069 case ISD::SETGT: 1070 return AArch64CC::GT; 1071 case ISD::SETGE: 1072 return AArch64CC::GE; 1073 case ISD::SETLT: 1074 return AArch64CC::LT; 1075 case ISD::SETLE: 1076 return AArch64CC::LE; 1077 case ISD::SETUGT: 1078 return AArch64CC::HI; 1079 case ISD::SETUGE: 1080 return AArch64CC::HS; 1081 case ISD::SETULT: 1082 return AArch64CC::LO; 1083 case ISD::SETULE: 1084 return AArch64CC::LS; 1085 } 1086 } 1087 1088 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1089 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1090 AArch64CC::CondCode &CondCode, 1091 AArch64CC::CondCode &CondCode2) { 1092 CondCode2 = AArch64CC::AL; 1093 switch (CC) { 1094 default: 1095 llvm_unreachable("Unknown FP condition!"); 1096 case ISD::SETEQ: 1097 case ISD::SETOEQ: 1098 CondCode = AArch64CC::EQ; 1099 break; 1100 case ISD::SETGT: 1101 case ISD::SETOGT: 1102 CondCode = AArch64CC::GT; 1103 break; 1104 case ISD::SETGE: 1105 case ISD::SETOGE: 1106 CondCode = AArch64CC::GE; 1107 break; 1108 case ISD::SETOLT: 1109 CondCode = AArch64CC::MI; 1110 break; 1111 case ISD::SETOLE: 1112 CondCode = AArch64CC::LS; 1113 break; 1114 case ISD::SETONE: 1115 CondCode = AArch64CC::MI; 1116 CondCode2 = AArch64CC::GT; 1117 break; 1118 case ISD::SETO: 1119 CondCode = AArch64CC::VC; 1120 break; 1121 case ISD::SETUO: 1122 CondCode = AArch64CC::VS; 1123 break; 1124 case ISD::SETUEQ: 1125 CondCode = AArch64CC::EQ; 1126 CondCode2 = AArch64CC::VS; 1127 break; 1128 case ISD::SETUGT: 1129 CondCode = AArch64CC::HI; 1130 break; 1131 case ISD::SETUGE: 1132 CondCode = AArch64CC::PL; 1133 break; 1134 case ISD::SETLT: 1135 case ISD::SETULT: 1136 CondCode = AArch64CC::LT; 1137 break; 1138 case ISD::SETLE: 1139 case ISD::SETULE: 1140 CondCode = AArch64CC::LE; 1141 break; 1142 case ISD::SETNE: 1143 case ISD::SETUNE: 1144 CondCode = AArch64CC::NE; 1145 break; 1146 } 1147 } 1148 1149 /// Convert a DAG fp condition code to an AArch64 CC. 1150 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1151 /// should be AND'ed instead of OR'ed. 1152 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1153 AArch64CC::CondCode &CondCode, 1154 AArch64CC::CondCode &CondCode2) { 1155 CondCode2 = AArch64CC::AL; 1156 switch (CC) { 1157 default: 1158 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1159 assert(CondCode2 == AArch64CC::AL); 1160 break; 1161 case ISD::SETONE: 1162 // (a one b) 1163 // == ((a olt b) || (a ogt b)) 1164 // == ((a ord b) && (a une b)) 1165 CondCode = AArch64CC::VC; 1166 CondCode2 = AArch64CC::NE; 1167 break; 1168 case ISD::SETUEQ: 1169 // (a ueq b) 1170 // == ((a uno b) || (a oeq b)) 1171 // == ((a ule b) && (a uge b)) 1172 CondCode = AArch64CC::PL; 1173 CondCode2 = AArch64CC::LE; 1174 break; 1175 } 1176 } 1177 1178 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1179 /// CC usable with the vector instructions. Fewer operations are available 1180 /// without a real NZCV register, so we have to use less efficient combinations 1181 /// to get the same effect. 1182 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1183 AArch64CC::CondCode &CondCode, 1184 AArch64CC::CondCode &CondCode2, 1185 bool &Invert) { 1186 Invert = false; 1187 switch (CC) { 1188 default: 1189 // Mostly the scalar mappings work fine. 1190 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1191 break; 1192 case ISD::SETUO: 1193 Invert = true; // Fallthrough 1194 case ISD::SETO: 1195 CondCode = AArch64CC::MI; 1196 CondCode2 = AArch64CC::GE; 1197 break; 1198 case ISD::SETUEQ: 1199 case ISD::SETULT: 1200 case ISD::SETULE: 1201 case ISD::SETUGT: 1202 case ISD::SETUGE: 1203 // All of the compare-mask comparisons are ordered, but we can switch 1204 // between the two by a double inversion. E.g. ULE == !OGT. 1205 Invert = true; 1206 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1207 break; 1208 } 1209 } 1210 1211 static bool isLegalArithImmed(uint64_t C) { 1212 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1213 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1214 } 1215 1216 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1217 const SDLoc &dl, SelectionDAG &DAG) { 1218 EVT VT = LHS.getValueType(); 1219 1220 if (VT.isFloatingPoint()) { 1221 assert(VT != MVT::f128); 1222 if (VT == MVT::f16) { 1223 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1224 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1225 VT = MVT::f32; 1226 } 1227 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1228 } 1229 1230 // The CMP instruction is just an alias for SUBS, and representing it as 1231 // SUBS means that it's possible to get CSE with subtract operations. 1232 // A later phase can perform the optimization of setting the destination 1233 // register to WZR/XZR if it ends up being unused. 1234 unsigned Opcode = AArch64ISD::SUBS; 1235 1236 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 1237 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1238 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on 1239 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags 1240 // can be set differently by this operation. It comes down to whether 1241 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1242 // everything is fine. If not then the optimization is wrong. Thus general 1243 // comparisons are only valid if op2 != 0. 1244 1245 // So, finally, the only LLVM-native comparisons that don't mention C and V 1246 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1247 // the absence of information about op2. 1248 Opcode = AArch64ISD::ADDS; 1249 RHS = RHS.getOperand(1); 1250 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1251 !isUnsignedIntSetCC(CC)) { 1252 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1253 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1254 // of the signed comparisons. 1255 Opcode = AArch64ISD::ANDS; 1256 RHS = LHS.getOperand(1); 1257 LHS = LHS.getOperand(0); 1258 } 1259 1260 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1261 .getValue(1); 1262 } 1263 1264 /// \defgroup AArch64CCMP CMP;CCMP matching 1265 /// 1266 /// These functions deal with the formation of CMP;CCMP;... sequences. 1267 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1268 /// a comparison. They set the NZCV flags to a predefined value if their 1269 /// predicate is false. This allows to express arbitrary conjunctions, for 1270 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))" 1271 /// expressed as: 1272 /// cmp A 1273 /// ccmp B, inv(CB), CA 1274 /// check for CB flags 1275 /// 1276 /// In general we can create code for arbitrary "... (and (and A B) C)" 1277 /// sequences. We can also implement some "or" expressions, because "(or A B)" 1278 /// is equivalent to "not (and (not A) (not B))" and we can implement some 1279 /// negation operations: 1280 /// We can negate the results of a single comparison by inverting the flags 1281 /// used when the predicate fails and inverting the flags tested in the next 1282 /// instruction; We can also negate the results of the whole previous 1283 /// conditional compare sequence by inverting the flags tested in the next 1284 /// instruction. However there is no way to negate the result of a partial 1285 /// sequence. 1286 /// 1287 /// Therefore on encountering an "or" expression we can negate the subtree on 1288 /// one side and have to be able to push the negate to the leafs of the subtree 1289 /// on the other side (see also the comments in code). As complete example: 1290 /// "or (or (setCA (cmp A)) (setCB (cmp B))) 1291 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1292 /// is transformed to 1293 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D)))) 1294 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1295 /// and implemented as: 1296 /// cmp C 1297 /// ccmp D, inv(CD), CC 1298 /// ccmp A, CA, inv(CD) 1299 /// ccmp B, CB, inv(CA) 1300 /// check for CB flags 1301 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented 1302 /// by conditional compare sequences. 1303 /// @{ 1304 1305 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1306 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1307 ISD::CondCode CC, SDValue CCOp, 1308 AArch64CC::CondCode Predicate, 1309 AArch64CC::CondCode OutCC, 1310 const SDLoc &DL, SelectionDAG &DAG) { 1311 unsigned Opcode = 0; 1312 if (LHS.getValueType().isFloatingPoint()) { 1313 assert(LHS.getValueType() != MVT::f128); 1314 if (LHS.getValueType() == MVT::f16) { 1315 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1316 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1317 } 1318 Opcode = AArch64ISD::FCCMP; 1319 } else if (RHS.getOpcode() == ISD::SUB) { 1320 SDValue SubOp0 = RHS.getOperand(0); 1321 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1322 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1323 Opcode = AArch64ISD::CCMN; 1324 RHS = RHS.getOperand(1); 1325 } 1326 } 1327 if (Opcode == 0) 1328 Opcode = AArch64ISD::CCMP; 1329 1330 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1331 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1332 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1333 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1334 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1335 } 1336 1337 /// Returns true if @p Val is a tree of AND/OR/SETCC operations. 1338 /// CanPushNegate is set to true if we can push a negate operation through 1339 /// the tree in a was that we are left with AND operations and negate operations 1340 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to 1341 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be 1342 /// brought into such a form. 1343 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate, 1344 unsigned Depth = 0) { 1345 if (!Val.hasOneUse()) 1346 return false; 1347 unsigned Opcode = Val->getOpcode(); 1348 if (Opcode == ISD::SETCC) { 1349 if (Val->getOperand(0).getValueType() == MVT::f128) 1350 return false; 1351 CanNegate = true; 1352 return true; 1353 } 1354 // Protect against exponential runtime and stack overflow. 1355 if (Depth > 6) 1356 return false; 1357 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1358 SDValue O0 = Val->getOperand(0); 1359 SDValue O1 = Val->getOperand(1); 1360 bool CanNegateL; 1361 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1)) 1362 return false; 1363 bool CanNegateR; 1364 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1)) 1365 return false; 1366 1367 if (Opcode == ISD::OR) { 1368 // For an OR expression we need to be able to negate at least one side or 1369 // we cannot do the transformation at all. 1370 if (!CanNegateL && !CanNegateR) 1371 return false; 1372 // We can however change a (not (or x y)) to (and (not x) (not y)) if we 1373 // can negate the x and y subtrees. 1374 CanNegate = CanNegateL && CanNegateR; 1375 } else { 1376 // If the operands are OR expressions then we finally need to negate their 1377 // outputs, we can only do that for the operand with emitted last by 1378 // negating OutCC, not for both operands. 1379 bool NeedsNegOutL = O0->getOpcode() == ISD::OR; 1380 bool NeedsNegOutR = O1->getOpcode() == ISD::OR; 1381 if (NeedsNegOutL && NeedsNegOutR) 1382 return false; 1383 // We cannot negate an AND operation (it would become an OR), 1384 CanNegate = false; 1385 } 1386 return true; 1387 } 1388 return false; 1389 } 1390 1391 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1392 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1393 /// Tries to transform the given i1 producing node @p Val to a series compare 1394 /// and conditional compare operations. @returns an NZCV flags producing node 1395 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1396 /// transformation was not possible. 1397 /// On recursive invocations @p PushNegate may be set to true to have negation 1398 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate 1399 /// for the comparisons in the current subtree; @p Depth limits the search 1400 /// depth to avoid stack overflow. 1401 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val, 1402 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1403 AArch64CC::CondCode Predicate) { 1404 // We're at a tree leaf, produce a conditional comparison operation. 1405 unsigned Opcode = Val->getOpcode(); 1406 if (Opcode == ISD::SETCC) { 1407 SDValue LHS = Val->getOperand(0); 1408 SDValue RHS = Val->getOperand(1); 1409 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1410 bool isInteger = LHS.getValueType().isInteger(); 1411 if (Negate) 1412 CC = getSetCCInverse(CC, isInteger); 1413 SDLoc DL(Val); 1414 // Determine OutCC and handle FP special case. 1415 if (isInteger) { 1416 OutCC = changeIntCCToAArch64CC(CC); 1417 } else { 1418 assert(LHS.getValueType().isFloatingPoint()); 1419 AArch64CC::CondCode ExtraCC; 1420 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1421 // Some floating point conditions can't be tested with a single condition 1422 // code. Construct an additional comparison in this case. 1423 if (ExtraCC != AArch64CC::AL) { 1424 SDValue ExtraCmp; 1425 if (!CCOp.getNode()) 1426 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1427 else 1428 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1429 ExtraCC, DL, DAG); 1430 CCOp = ExtraCmp; 1431 Predicate = ExtraCC; 1432 } 1433 } 1434 1435 // Produce a normal comparison if we are first in the chain 1436 if (!CCOp) 1437 return emitComparison(LHS, RHS, CC, DL, DAG); 1438 // Otherwise produce a ccmp. 1439 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1440 DAG); 1441 } 1442 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) && 1443 "Valid conjunction/disjunction tree"); 1444 1445 // Check if both sides can be transformed. 1446 SDValue LHS = Val->getOperand(0); 1447 SDValue RHS = Val->getOperand(1); 1448 1449 // In case of an OR we need to negate our operands and the result. 1450 // (A v B) <=> not(not(A) ^ not(B)) 1451 bool NegateOpsAndResult = Opcode == ISD::OR; 1452 // We can negate the results of all previous operations by inverting the 1453 // predicate flags giving us a free negation for one side. The other side 1454 // must be negatable by itself. 1455 if (NegateOpsAndResult) { 1456 // See which side we can negate. 1457 bool CanNegateL; 1458 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL); 1459 assert(isValidL && "Valid conjunction/disjunction tree"); 1460 (void)isValidL; 1461 1462 #ifndef NDEBUG 1463 bool CanNegateR; 1464 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR); 1465 assert(isValidR && "Valid conjunction/disjunction tree"); 1466 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree"); 1467 #endif 1468 1469 // Order the side which we cannot negate to RHS so we can emit it first. 1470 if (!CanNegateL) 1471 std::swap(LHS, RHS); 1472 } else { 1473 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR; 1474 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) && 1475 "Valid conjunction/disjunction tree"); 1476 // Order the side where we need to negate the output flags to RHS so it 1477 // gets emitted first. 1478 if (NeedsNegOutL) 1479 std::swap(LHS, RHS); 1480 } 1481 1482 // Emit RHS. If we want to negate the tree we only need to push a negate 1483 // through if we are already in a PushNegate case, otherwise we can negate 1484 // the "flags to test" afterwards. 1485 AArch64CC::CondCode RHSCC; 1486 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate, 1487 CCOp, Predicate); 1488 if (NegateOpsAndResult && !Negate) 1489 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1490 // Emit LHS. We may need to negate it. 1491 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC, 1492 NegateOpsAndResult, CmpR, 1493 RHSCC); 1494 // If we transformed an OR to and AND then we have to negate the result 1495 // (or absorb the Negate parameter). 1496 if (NegateOpsAndResult && !Negate) 1497 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1498 return CmpL; 1499 } 1500 1501 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1502 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1503 /// \see emitConjunctionDisjunctionTreeRec(). 1504 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val, 1505 AArch64CC::CondCode &OutCC) { 1506 bool CanNegate; 1507 if (!isConjunctionDisjunctionTree(Val, CanNegate)) 1508 return SDValue(); 1509 1510 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(), 1511 AArch64CC::AL); 1512 } 1513 1514 /// @} 1515 1516 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1517 SDValue &AArch64cc, SelectionDAG &DAG, 1518 const SDLoc &dl) { 1519 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1520 EVT VT = RHS.getValueType(); 1521 uint64_t C = RHSC->getZExtValue(); 1522 if (!isLegalArithImmed(C)) { 1523 // Constant does not fit, try adjusting it by one? 1524 switch (CC) { 1525 default: 1526 break; 1527 case ISD::SETLT: 1528 case ISD::SETGE: 1529 if ((VT == MVT::i32 && C != 0x80000000 && 1530 isLegalArithImmed((uint32_t)(C - 1))) || 1531 (VT == MVT::i64 && C != 0x80000000ULL && 1532 isLegalArithImmed(C - 1ULL))) { 1533 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1534 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1535 RHS = DAG.getConstant(C, dl, VT); 1536 } 1537 break; 1538 case ISD::SETULT: 1539 case ISD::SETUGE: 1540 if ((VT == MVT::i32 && C != 0 && 1541 isLegalArithImmed((uint32_t)(C - 1))) || 1542 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1543 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1544 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1545 RHS = DAG.getConstant(C, dl, VT); 1546 } 1547 break; 1548 case ISD::SETLE: 1549 case ISD::SETGT: 1550 if ((VT == MVT::i32 && C != INT32_MAX && 1551 isLegalArithImmed((uint32_t)(C + 1))) || 1552 (VT == MVT::i64 && C != INT64_MAX && 1553 isLegalArithImmed(C + 1ULL))) { 1554 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1555 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1556 RHS = DAG.getConstant(C, dl, VT); 1557 } 1558 break; 1559 case ISD::SETULE: 1560 case ISD::SETUGT: 1561 if ((VT == MVT::i32 && C != UINT32_MAX && 1562 isLegalArithImmed((uint32_t)(C + 1))) || 1563 (VT == MVT::i64 && C != UINT64_MAX && 1564 isLegalArithImmed(C + 1ULL))) { 1565 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1566 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1567 RHS = DAG.getConstant(C, dl, VT); 1568 } 1569 break; 1570 } 1571 } 1572 } 1573 SDValue Cmp; 1574 AArch64CC::CondCode AArch64CC; 1575 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1576 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1577 1578 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1579 // For the i8 operand, the largest immediate is 255, so this can be easily 1580 // encoded in the compare instruction. For the i16 operand, however, the 1581 // largest immediate cannot be encoded in the compare. 1582 // Therefore, use a sign extending load and cmn to avoid materializing the 1583 // -1 constant. For example, 1584 // movz w1, #65535 1585 // ldrh w0, [x0, #0] 1586 // cmp w0, w1 1587 // > 1588 // ldrsh w0, [x0, #0] 1589 // cmn w0, #1 1590 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1591 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1592 // ensure both the LHS and RHS are truly zero extended and to make sure the 1593 // transformation is profitable. 1594 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1595 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1596 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1597 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1598 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1599 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1600 SDValue SExt = 1601 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1602 DAG.getValueType(MVT::i16)); 1603 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1604 RHS.getValueType()), 1605 CC, dl, DAG); 1606 AArch64CC = changeIntCCToAArch64CC(CC); 1607 } 1608 } 1609 1610 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 1611 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) { 1612 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 1613 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 1614 } 1615 } 1616 } 1617 1618 if (!Cmp) { 1619 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 1620 AArch64CC = changeIntCCToAArch64CC(CC); 1621 } 1622 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 1623 return Cmp; 1624 } 1625 1626 // Attempt to form conditional compare sequences for and/or trees 1627 // with setcc leafs. 1628 static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) { 1629 SDValue LHS = Op.getOperand(0); 1630 SDValue RHS = Op.getOperand(1); 1631 if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC)) 1632 return Op; 1633 1634 bool CanNegate; 1635 if (!isConjunctionDisjunctionTree(Op, CanNegate)) 1636 return SDValue(); 1637 1638 EVT VT = Op.getValueType(); 1639 SDLoc DL(Op); 1640 SDValue TVal = DAG.getConstant(1, DL, VT); 1641 SDValue FVal = DAG.getConstant(0, DL, VT); 1642 SDValue CCVal; 1643 SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL); 1644 return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp); 1645 } 1646 1647 static std::pair<SDValue, SDValue> 1648 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 1649 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 1650 "Unsupported value type"); 1651 SDValue Value, Overflow; 1652 SDLoc DL(Op); 1653 SDValue LHS = Op.getOperand(0); 1654 SDValue RHS = Op.getOperand(1); 1655 unsigned Opc = 0; 1656 switch (Op.getOpcode()) { 1657 default: 1658 llvm_unreachable("Unknown overflow instruction!"); 1659 case ISD::SADDO: 1660 Opc = AArch64ISD::ADDS; 1661 CC = AArch64CC::VS; 1662 break; 1663 case ISD::UADDO: 1664 Opc = AArch64ISD::ADDS; 1665 CC = AArch64CC::HS; 1666 break; 1667 case ISD::SSUBO: 1668 Opc = AArch64ISD::SUBS; 1669 CC = AArch64CC::VS; 1670 break; 1671 case ISD::USUBO: 1672 Opc = AArch64ISD::SUBS; 1673 CC = AArch64CC::LO; 1674 break; 1675 // Multiply needs a little bit extra work. 1676 case ISD::SMULO: 1677 case ISD::UMULO: { 1678 CC = AArch64CC::NE; 1679 bool IsSigned = Op.getOpcode() == ISD::SMULO; 1680 if (Op.getValueType() == MVT::i32) { 1681 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1682 // For a 32 bit multiply with overflow check we want the instruction 1683 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 1684 // need to generate the following pattern: 1685 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 1686 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 1687 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 1688 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1689 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 1690 DAG.getConstant(0, DL, MVT::i64)); 1691 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 1692 // operation. We need to clear out the upper 32 bits, because we used a 1693 // widening multiply that wrote all 64 bits. In the end this should be a 1694 // noop. 1695 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 1696 if (IsSigned) { 1697 // The signed overflow check requires more than just a simple check for 1698 // any bit set in the upper 32 bits of the result. These bits could be 1699 // just the sign bits of a negative number. To perform the overflow 1700 // check we have to arithmetic shift right the 32nd bit of the result by 1701 // 31 bits. Then we compare the result to the upper 32 bits. 1702 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 1703 DAG.getConstant(32, DL, MVT::i64)); 1704 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 1705 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 1706 DAG.getConstant(31, DL, MVT::i64)); 1707 // It is important that LowerBits is last, otherwise the arithmetic 1708 // shift will not be folded into the compare (SUBS). 1709 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 1710 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1711 .getValue(1); 1712 } else { 1713 // The overflow check for unsigned multiply is easy. We only need to 1714 // check if any of the upper 32 bits are set. This can be done with a 1715 // CMP (shifted register). For that we need to generate the following 1716 // pattern: 1717 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 1718 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 1719 DAG.getConstant(32, DL, MVT::i64)); 1720 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1721 Overflow = 1722 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1723 DAG.getConstant(0, DL, MVT::i64), 1724 UpperBits).getValue(1); 1725 } 1726 break; 1727 } 1728 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 1729 // For the 64 bit multiply 1730 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1731 if (IsSigned) { 1732 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 1733 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 1734 DAG.getConstant(63, DL, MVT::i64)); 1735 // It is important that LowerBits is last, otherwise the arithmetic 1736 // shift will not be folded into the compare (SUBS). 1737 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1738 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1739 .getValue(1); 1740 } else { 1741 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 1742 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1743 Overflow = 1744 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1745 DAG.getConstant(0, DL, MVT::i64), 1746 UpperBits).getValue(1); 1747 } 1748 break; 1749 } 1750 } // switch (...) 1751 1752 if (Opc) { 1753 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 1754 1755 // Emit the AArch64 operation with overflow check. 1756 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 1757 Overflow = Value.getValue(1); 1758 } 1759 return std::make_pair(Value, Overflow); 1760 } 1761 1762 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 1763 RTLIB::Libcall Call) const { 1764 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1765 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 1766 } 1767 1768 SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const { 1769 if (Op.getValueType().isVector()) 1770 return LowerVectorAND(Op, DAG); 1771 return tryLowerToAArch64Cmp(Op, DAG); 1772 } 1773 1774 SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const { 1775 if (Op.getValueType().isVector()) 1776 return LowerVectorOR(Op, DAG); 1777 return tryLowerToAArch64Cmp(Op, DAG); 1778 } 1779 1780 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1781 SDValue Sel = Op.getOperand(0); 1782 SDValue Other = Op.getOperand(1); 1783 1784 // If neither operand is a SELECT_CC, give up. 1785 if (Sel.getOpcode() != ISD::SELECT_CC) 1786 std::swap(Sel, Other); 1787 if (Sel.getOpcode() != ISD::SELECT_CC) 1788 return Op; 1789 1790 // The folding we want to perform is: 1791 // (xor x, (select_cc a, b, cc, 0, -1) ) 1792 // --> 1793 // (csel x, (xor x, -1), cc ...) 1794 // 1795 // The latter will get matched to a CSINV instruction. 1796 1797 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 1798 SDValue LHS = Sel.getOperand(0); 1799 SDValue RHS = Sel.getOperand(1); 1800 SDValue TVal = Sel.getOperand(2); 1801 SDValue FVal = Sel.getOperand(3); 1802 SDLoc dl(Sel); 1803 1804 // FIXME: This could be generalized to non-integer comparisons. 1805 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 1806 return Op; 1807 1808 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 1809 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 1810 1811 // The values aren't constants, this isn't the pattern we're looking for. 1812 if (!CFVal || !CTVal) 1813 return Op; 1814 1815 // We can commute the SELECT_CC by inverting the condition. This 1816 // might be needed to make this fit into a CSINV pattern. 1817 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 1818 std::swap(TVal, FVal); 1819 std::swap(CTVal, CFVal); 1820 CC = ISD::getSetCCInverse(CC, true); 1821 } 1822 1823 // If the constants line up, perform the transform! 1824 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 1825 SDValue CCVal; 1826 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 1827 1828 FVal = Other; 1829 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 1830 DAG.getConstant(-1ULL, dl, Other.getValueType())); 1831 1832 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 1833 CCVal, Cmp); 1834 } 1835 1836 return Op; 1837 } 1838 1839 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 1840 EVT VT = Op.getValueType(); 1841 1842 // Let legalize expand this if it isn't a legal type yet. 1843 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 1844 return SDValue(); 1845 1846 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 1847 1848 unsigned Opc; 1849 bool ExtraOp = false; 1850 switch (Op.getOpcode()) { 1851 default: 1852 llvm_unreachable("Invalid code"); 1853 case ISD::ADDC: 1854 Opc = AArch64ISD::ADDS; 1855 break; 1856 case ISD::SUBC: 1857 Opc = AArch64ISD::SUBS; 1858 break; 1859 case ISD::ADDE: 1860 Opc = AArch64ISD::ADCS; 1861 ExtraOp = true; 1862 break; 1863 case ISD::SUBE: 1864 Opc = AArch64ISD::SBCS; 1865 ExtraOp = true; 1866 break; 1867 } 1868 1869 if (!ExtraOp) 1870 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 1871 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 1872 Op.getOperand(2)); 1873 } 1874 1875 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 1876 // Let legalize expand this if it isn't a legal type yet. 1877 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 1878 return SDValue(); 1879 1880 SDLoc dl(Op); 1881 AArch64CC::CondCode CC; 1882 // The actual operation that sets the overflow or carry flag. 1883 SDValue Value, Overflow; 1884 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 1885 1886 // We use 0 and 1 as false and true values. 1887 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 1888 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 1889 1890 // We use an inverted condition, because the conditional select is inverted 1891 // too. This will allow it to be selected to a single instruction: 1892 // CSINC Wd, WZR, WZR, invert(cond). 1893 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 1894 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 1895 CCVal, Overflow); 1896 1897 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 1898 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 1899 } 1900 1901 // Prefetch operands are: 1902 // 1: Address to prefetch 1903 // 2: bool isWrite 1904 // 3: int locality (0 = no locality ... 3 = extreme locality) 1905 // 4: bool isDataCache 1906 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 1907 SDLoc DL(Op); 1908 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 1909 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 1910 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 1911 1912 bool IsStream = !Locality; 1913 // When the locality number is set 1914 if (Locality) { 1915 // The front-end should have filtered out the out-of-range values 1916 assert(Locality <= 3 && "Prefetch locality out-of-range"); 1917 // The locality degree is the opposite of the cache speed. 1918 // Put the number the other way around. 1919 // The encoding starts at 0 for level 1 1920 Locality = 3 - Locality; 1921 } 1922 1923 // built the mask value encoding the expected behavior. 1924 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 1925 (!IsData << 3) | // IsDataCache bit 1926 (Locality << 1) | // Cache level bits 1927 (unsigned)IsStream; // Stream bit 1928 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 1929 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 1930 } 1931 1932 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 1933 SelectionDAG &DAG) const { 1934 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 1935 1936 RTLIB::Libcall LC; 1937 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 1938 1939 return LowerF128Call(Op, DAG, LC); 1940 } 1941 1942 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 1943 SelectionDAG &DAG) const { 1944 if (Op.getOperand(0).getValueType() != MVT::f128) { 1945 // It's legal except when f128 is involved 1946 return Op; 1947 } 1948 1949 RTLIB::Libcall LC; 1950 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 1951 1952 // FP_ROUND node has a second operand indicating whether it is known to be 1953 // precise. That doesn't take part in the LibCall so we can't directly use 1954 // LowerF128Call. 1955 SDValue SrcVal = Op.getOperand(0); 1956 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 1957 SDLoc(Op)).first; 1958 } 1959 1960 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 1961 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 1962 // Any additional optimization in this function should be recorded 1963 // in the cost tables. 1964 EVT InVT = Op.getOperand(0).getValueType(); 1965 EVT VT = Op.getValueType(); 1966 unsigned NumElts = InVT.getVectorNumElements(); 1967 1968 // f16 vectors are promoted to f32 before a conversion. 1969 if (InVT.getVectorElementType() == MVT::f16) { 1970 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 1971 SDLoc dl(Op); 1972 return DAG.getNode( 1973 Op.getOpcode(), dl, Op.getValueType(), 1974 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 1975 } 1976 1977 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 1978 SDLoc dl(Op); 1979 SDValue Cv = 1980 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 1981 Op.getOperand(0)); 1982 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 1983 } 1984 1985 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 1986 SDLoc dl(Op); 1987 MVT ExtVT = 1988 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 1989 VT.getVectorNumElements()); 1990 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 1991 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 1992 } 1993 1994 // Type changing conversions are illegal. 1995 return Op; 1996 } 1997 1998 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 1999 SelectionDAG &DAG) const { 2000 if (Op.getOperand(0).getValueType().isVector()) 2001 return LowerVectorFP_TO_INT(Op, DAG); 2002 2003 // f16 conversions are promoted to f32. 2004 if (Op.getOperand(0).getValueType() == MVT::f16) { 2005 SDLoc dl(Op); 2006 return DAG.getNode( 2007 Op.getOpcode(), dl, Op.getValueType(), 2008 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2009 } 2010 2011 if (Op.getOperand(0).getValueType() != MVT::f128) { 2012 // It's legal except when f128 is involved 2013 return Op; 2014 } 2015 2016 RTLIB::Libcall LC; 2017 if (Op.getOpcode() == ISD::FP_TO_SINT) 2018 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2019 else 2020 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2021 2022 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2023 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2024 } 2025 2026 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2027 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2028 // Any additional optimization in this function should be recorded 2029 // in the cost tables. 2030 EVT VT = Op.getValueType(); 2031 SDLoc dl(Op); 2032 SDValue In = Op.getOperand(0); 2033 EVT InVT = In.getValueType(); 2034 2035 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2036 MVT CastVT = 2037 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2038 InVT.getVectorNumElements()); 2039 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2040 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2041 } 2042 2043 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2044 unsigned CastOpc = 2045 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2046 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2047 In = DAG.getNode(CastOpc, dl, CastVT, In); 2048 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2049 } 2050 2051 return Op; 2052 } 2053 2054 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2055 SelectionDAG &DAG) const { 2056 if (Op.getValueType().isVector()) 2057 return LowerVectorINT_TO_FP(Op, DAG); 2058 2059 // f16 conversions are promoted to f32. 2060 if (Op.getValueType() == MVT::f16) { 2061 SDLoc dl(Op); 2062 return DAG.getNode( 2063 ISD::FP_ROUND, dl, MVT::f16, 2064 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2065 DAG.getIntPtrConstant(0, dl)); 2066 } 2067 2068 // i128 conversions are libcalls. 2069 if (Op.getOperand(0).getValueType() == MVT::i128) 2070 return SDValue(); 2071 2072 // Other conversions are legal, unless it's to the completely software-based 2073 // fp128. 2074 if (Op.getValueType() != MVT::f128) 2075 return Op; 2076 2077 RTLIB::Libcall LC; 2078 if (Op.getOpcode() == ISD::SINT_TO_FP) 2079 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2080 else 2081 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2082 2083 return LowerF128Call(Op, DAG, LC); 2084 } 2085 2086 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2087 SelectionDAG &DAG) const { 2088 // For iOS, we want to call an alternative entry point: __sincos_stret, 2089 // which returns the values in two S / D registers. 2090 SDLoc dl(Op); 2091 SDValue Arg = Op.getOperand(0); 2092 EVT ArgVT = Arg.getValueType(); 2093 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2094 2095 ArgListTy Args; 2096 ArgListEntry Entry; 2097 2098 Entry.Node = Arg; 2099 Entry.Ty = ArgTy; 2100 Entry.isSExt = false; 2101 Entry.isZExt = false; 2102 Args.push_back(Entry); 2103 2104 const char *LibcallName = 2105 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2106 SDValue Callee = 2107 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2108 2109 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 2110 TargetLowering::CallLoweringInfo CLI(DAG); 2111 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 2112 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2113 2114 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2115 return CallResult.first; 2116 } 2117 2118 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2119 if (Op.getValueType() != MVT::f16) 2120 return SDValue(); 2121 2122 assert(Op.getOperand(0).getValueType() == MVT::i16); 2123 SDLoc DL(Op); 2124 2125 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2126 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2127 return SDValue( 2128 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2129 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2130 0); 2131 } 2132 2133 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2134 if (OrigVT.getSizeInBits() >= 64) 2135 return OrigVT; 2136 2137 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2138 2139 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2140 switch (OrigSimpleTy) { 2141 default: llvm_unreachable("Unexpected Vector Type"); 2142 case MVT::v2i8: 2143 case MVT::v2i16: 2144 return MVT::v2i32; 2145 case MVT::v4i8: 2146 return MVT::v4i16; 2147 } 2148 } 2149 2150 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2151 const EVT &OrigTy, 2152 const EVT &ExtTy, 2153 unsigned ExtOpcode) { 2154 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2155 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2156 // 64-bits we need to insert a new extension so that it will be 64-bits. 2157 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2158 if (OrigTy.getSizeInBits() >= 64) 2159 return N; 2160 2161 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2162 EVT NewVT = getExtensionTo64Bits(OrigTy); 2163 2164 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2165 } 2166 2167 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2168 bool isSigned) { 2169 EVT VT = N->getValueType(0); 2170 2171 if (N->getOpcode() != ISD::BUILD_VECTOR) 2172 return false; 2173 2174 for (const SDValue &Elt : N->op_values()) { 2175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2176 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 2177 unsigned HalfSize = EltSize / 2; 2178 if (isSigned) { 2179 if (!isIntN(HalfSize, C->getSExtValue())) 2180 return false; 2181 } else { 2182 if (!isUIntN(HalfSize, C->getZExtValue())) 2183 return false; 2184 } 2185 continue; 2186 } 2187 return false; 2188 } 2189 2190 return true; 2191 } 2192 2193 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2194 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2195 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2196 N->getOperand(0)->getValueType(0), 2197 N->getValueType(0), 2198 N->getOpcode()); 2199 2200 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2201 EVT VT = N->getValueType(0); 2202 SDLoc dl(N); 2203 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 2204 unsigned NumElts = VT.getVectorNumElements(); 2205 MVT TruncVT = MVT::getIntegerVT(EltSize); 2206 SmallVector<SDValue, 8> Ops; 2207 for (unsigned i = 0; i != NumElts; ++i) { 2208 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2209 const APInt &CInt = C->getAPIntValue(); 2210 // Element types smaller than 32 bits are not legal, so use i32 elements. 2211 // The values are implicitly truncated so sext vs. zext doesn't matter. 2212 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2213 } 2214 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2215 } 2216 2217 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2218 if (N->getOpcode() == ISD::SIGN_EXTEND) 2219 return true; 2220 if (isExtendedBUILD_VECTOR(N, DAG, true)) 2221 return true; 2222 return false; 2223 } 2224 2225 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2226 if (N->getOpcode() == ISD::ZERO_EXTEND) 2227 return true; 2228 if (isExtendedBUILD_VECTOR(N, DAG, false)) 2229 return true; 2230 return false; 2231 } 2232 2233 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2234 unsigned Opcode = N->getOpcode(); 2235 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2236 SDNode *N0 = N->getOperand(0).getNode(); 2237 SDNode *N1 = N->getOperand(1).getNode(); 2238 return N0->hasOneUse() && N1->hasOneUse() && 2239 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2240 } 2241 return false; 2242 } 2243 2244 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2245 unsigned Opcode = N->getOpcode(); 2246 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2247 SDNode *N0 = N->getOperand(0).getNode(); 2248 SDNode *N1 = N->getOperand(1).getNode(); 2249 return N0->hasOneUse() && N1->hasOneUse() && 2250 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2251 } 2252 return false; 2253 } 2254 2255 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2256 // Multiplications are only custom-lowered for 128-bit vectors so that 2257 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2258 EVT VT = Op.getValueType(); 2259 assert(VT.is128BitVector() && VT.isInteger() && 2260 "unexpected type for custom-lowering ISD::MUL"); 2261 SDNode *N0 = Op.getOperand(0).getNode(); 2262 SDNode *N1 = Op.getOperand(1).getNode(); 2263 unsigned NewOpc = 0; 2264 bool isMLA = false; 2265 bool isN0SExt = isSignExtended(N0, DAG); 2266 bool isN1SExt = isSignExtended(N1, DAG); 2267 if (isN0SExt && isN1SExt) 2268 NewOpc = AArch64ISD::SMULL; 2269 else { 2270 bool isN0ZExt = isZeroExtended(N0, DAG); 2271 bool isN1ZExt = isZeroExtended(N1, DAG); 2272 if (isN0ZExt && isN1ZExt) 2273 NewOpc = AArch64ISD::UMULL; 2274 else if (isN1SExt || isN1ZExt) { 2275 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2276 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2277 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2278 NewOpc = AArch64ISD::SMULL; 2279 isMLA = true; 2280 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2281 NewOpc = AArch64ISD::UMULL; 2282 isMLA = true; 2283 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2284 std::swap(N0, N1); 2285 NewOpc = AArch64ISD::UMULL; 2286 isMLA = true; 2287 } 2288 } 2289 2290 if (!NewOpc) { 2291 if (VT == MVT::v2i64) 2292 // Fall through to expand this. It is not legal. 2293 return SDValue(); 2294 else 2295 // Other vector multiplications are legal. 2296 return Op; 2297 } 2298 } 2299 2300 // Legalize to a S/UMULL instruction 2301 SDLoc DL(Op); 2302 SDValue Op0; 2303 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2304 if (!isMLA) { 2305 Op0 = skipExtensionForVectorMULL(N0, DAG); 2306 assert(Op0.getValueType().is64BitVector() && 2307 Op1.getValueType().is64BitVector() && 2308 "unexpected types for extended operands to VMULL"); 2309 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2310 } 2311 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2312 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2313 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2314 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2315 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2316 EVT Op1VT = Op1.getValueType(); 2317 return DAG.getNode(N0->getOpcode(), DL, VT, 2318 DAG.getNode(NewOpc, DL, VT, 2319 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2320 DAG.getNode(NewOpc, DL, VT, 2321 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2322 } 2323 2324 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2325 SelectionDAG &DAG) const { 2326 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2327 SDLoc dl(Op); 2328 switch (IntNo) { 2329 default: return SDValue(); // Don't custom lower most intrinsics. 2330 case Intrinsic::thread_pointer: { 2331 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2332 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2333 } 2334 case Intrinsic::aarch64_neon_smax: 2335 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2336 Op.getOperand(1), Op.getOperand(2)); 2337 case Intrinsic::aarch64_neon_umax: 2338 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2339 Op.getOperand(1), Op.getOperand(2)); 2340 case Intrinsic::aarch64_neon_smin: 2341 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2342 Op.getOperand(1), Op.getOperand(2)); 2343 case Intrinsic::aarch64_neon_umin: 2344 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2345 Op.getOperand(1), Op.getOperand(2)); 2346 } 2347 } 2348 2349 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2350 SelectionDAG &DAG) const { 2351 switch (Op.getOpcode()) { 2352 default: 2353 llvm_unreachable("unimplemented operand"); 2354 return SDValue(); 2355 case ISD::BITCAST: 2356 return LowerBITCAST(Op, DAG); 2357 case ISD::GlobalAddress: 2358 return LowerGlobalAddress(Op, DAG); 2359 case ISD::GlobalTLSAddress: 2360 return LowerGlobalTLSAddress(Op, DAG); 2361 case ISD::SETCC: 2362 return LowerSETCC(Op, DAG); 2363 case ISD::BR_CC: 2364 return LowerBR_CC(Op, DAG); 2365 case ISD::SELECT: 2366 return LowerSELECT(Op, DAG); 2367 case ISD::SELECT_CC: 2368 return LowerSELECT_CC(Op, DAG); 2369 case ISD::JumpTable: 2370 return LowerJumpTable(Op, DAG); 2371 case ISD::ConstantPool: 2372 return LowerConstantPool(Op, DAG); 2373 case ISD::BlockAddress: 2374 return LowerBlockAddress(Op, DAG); 2375 case ISD::VASTART: 2376 return LowerVASTART(Op, DAG); 2377 case ISD::VACOPY: 2378 return LowerVACOPY(Op, DAG); 2379 case ISD::VAARG: 2380 return LowerVAARG(Op, DAG); 2381 case ISD::ADDC: 2382 case ISD::ADDE: 2383 case ISD::SUBC: 2384 case ISD::SUBE: 2385 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2386 case ISD::SADDO: 2387 case ISD::UADDO: 2388 case ISD::SSUBO: 2389 case ISD::USUBO: 2390 case ISD::SMULO: 2391 case ISD::UMULO: 2392 return LowerXALUO(Op, DAG); 2393 case ISD::FADD: 2394 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2395 case ISD::FSUB: 2396 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2397 case ISD::FMUL: 2398 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2399 case ISD::FDIV: 2400 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2401 case ISD::FP_ROUND: 2402 return LowerFP_ROUND(Op, DAG); 2403 case ISD::FP_EXTEND: 2404 return LowerFP_EXTEND(Op, DAG); 2405 case ISD::FRAMEADDR: 2406 return LowerFRAMEADDR(Op, DAG); 2407 case ISD::RETURNADDR: 2408 return LowerRETURNADDR(Op, DAG); 2409 case ISD::INSERT_VECTOR_ELT: 2410 return LowerINSERT_VECTOR_ELT(Op, DAG); 2411 case ISD::EXTRACT_VECTOR_ELT: 2412 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2413 case ISD::BUILD_VECTOR: 2414 return LowerBUILD_VECTOR(Op, DAG); 2415 case ISD::VECTOR_SHUFFLE: 2416 return LowerVECTOR_SHUFFLE(Op, DAG); 2417 case ISD::EXTRACT_SUBVECTOR: 2418 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2419 case ISD::SRA: 2420 case ISD::SRL: 2421 case ISD::SHL: 2422 return LowerVectorSRA_SRL_SHL(Op, DAG); 2423 case ISD::SHL_PARTS: 2424 return LowerShiftLeftParts(Op, DAG); 2425 case ISD::SRL_PARTS: 2426 case ISD::SRA_PARTS: 2427 return LowerShiftRightParts(Op, DAG); 2428 case ISD::CTPOP: 2429 return LowerCTPOP(Op, DAG); 2430 case ISD::FCOPYSIGN: 2431 return LowerFCOPYSIGN(Op, DAG); 2432 case ISD::AND: 2433 return LowerAND(Op, DAG); 2434 case ISD::OR: 2435 return LowerOR(Op, DAG); 2436 case ISD::XOR: 2437 return LowerXOR(Op, DAG); 2438 case ISD::PREFETCH: 2439 return LowerPREFETCH(Op, DAG); 2440 case ISD::SINT_TO_FP: 2441 case ISD::UINT_TO_FP: 2442 return LowerINT_TO_FP(Op, DAG); 2443 case ISD::FP_TO_SINT: 2444 case ISD::FP_TO_UINT: 2445 return LowerFP_TO_INT(Op, DAG); 2446 case ISD::FSINCOS: 2447 return LowerFSINCOS(Op, DAG); 2448 case ISD::MUL: 2449 return LowerMUL(Op, DAG); 2450 case ISD::INTRINSIC_WO_CHAIN: 2451 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2452 } 2453 } 2454 2455 //===----------------------------------------------------------------------===// 2456 // Calling Convention Implementation 2457 //===----------------------------------------------------------------------===// 2458 2459 #include "AArch64GenCallingConv.inc" 2460 2461 /// Selects the correct CCAssignFn for a given CallingConvention value. 2462 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2463 bool IsVarArg) const { 2464 switch (CC) { 2465 default: 2466 llvm_unreachable("Unsupported calling convention."); 2467 case CallingConv::WebKit_JS: 2468 return CC_AArch64_WebKit_JS; 2469 case CallingConv::GHC: 2470 return CC_AArch64_GHC; 2471 case CallingConv::C: 2472 case CallingConv::Fast: 2473 case CallingConv::PreserveMost: 2474 case CallingConv::CXX_FAST_TLS: 2475 if (!Subtarget->isTargetDarwin()) 2476 return CC_AArch64_AAPCS; 2477 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2478 } 2479 } 2480 2481 SDValue AArch64TargetLowering::LowerFormalArguments( 2482 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2483 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2484 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2485 MachineFunction &MF = DAG.getMachineFunction(); 2486 MachineFrameInfo *MFI = MF.getFrameInfo(); 2487 2488 // Assign locations to all of the incoming arguments. 2489 SmallVector<CCValAssign, 16> ArgLocs; 2490 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2491 *DAG.getContext()); 2492 2493 // At this point, Ins[].VT may already be promoted to i32. To correctly 2494 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2495 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2496 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2497 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2498 // LocVT. 2499 unsigned NumArgs = Ins.size(); 2500 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2501 unsigned CurArgIdx = 0; 2502 for (unsigned i = 0; i != NumArgs; ++i) { 2503 MVT ValVT = Ins[i].VT; 2504 if (Ins[i].isOrigArg()) { 2505 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2506 CurArgIdx = Ins[i].getOrigArgIndex(); 2507 2508 // Get type of the original argument. 2509 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2510 /*AllowUnknown*/ true); 2511 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2512 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2513 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2514 ValVT = MVT::i8; 2515 else if (ActualMVT == MVT::i16) 2516 ValVT = MVT::i16; 2517 } 2518 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2519 bool Res = 2520 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2521 assert(!Res && "Call operand has unhandled type"); 2522 (void)Res; 2523 } 2524 assert(ArgLocs.size() == Ins.size()); 2525 SmallVector<SDValue, 16> ArgValues; 2526 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2527 CCValAssign &VA = ArgLocs[i]; 2528 2529 if (Ins[i].Flags.isByVal()) { 2530 // Byval is used for HFAs in the PCS, but the system should work in a 2531 // non-compliant manner for larger structs. 2532 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2533 int Size = Ins[i].Flags.getByValSize(); 2534 unsigned NumRegs = (Size + 7) / 8; 2535 2536 // FIXME: This works on big-endian for composite byvals, which are the common 2537 // case. It should also work for fundamental types too. 2538 unsigned FrameIdx = 2539 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2540 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2541 InVals.push_back(FrameIdxN); 2542 2543 continue; 2544 } 2545 2546 if (VA.isRegLoc()) { 2547 // Arguments stored in registers. 2548 EVT RegVT = VA.getLocVT(); 2549 2550 SDValue ArgValue; 2551 const TargetRegisterClass *RC; 2552 2553 if (RegVT == MVT::i32) 2554 RC = &AArch64::GPR32RegClass; 2555 else if (RegVT == MVT::i64) 2556 RC = &AArch64::GPR64RegClass; 2557 else if (RegVT == MVT::f16) 2558 RC = &AArch64::FPR16RegClass; 2559 else if (RegVT == MVT::f32) 2560 RC = &AArch64::FPR32RegClass; 2561 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2562 RC = &AArch64::FPR64RegClass; 2563 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2564 RC = &AArch64::FPR128RegClass; 2565 else 2566 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2567 2568 // Transform the arguments in physical registers into virtual ones. 2569 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2570 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2571 2572 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2573 // to 64 bits. Insert an assert[sz]ext to capture this, then 2574 // truncate to the right size. 2575 switch (VA.getLocInfo()) { 2576 default: 2577 llvm_unreachable("Unknown loc info!"); 2578 case CCValAssign::Full: 2579 break; 2580 case CCValAssign::BCvt: 2581 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2582 break; 2583 case CCValAssign::AExt: 2584 case CCValAssign::SExt: 2585 case CCValAssign::ZExt: 2586 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2587 // nodes after our lowering. 2588 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2589 break; 2590 } 2591 2592 InVals.push_back(ArgValue); 2593 2594 } else { // VA.isRegLoc() 2595 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2596 unsigned ArgOffset = VA.getLocMemOffset(); 2597 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2598 2599 uint32_t BEAlign = 0; 2600 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2601 !Ins[i].Flags.isInConsecutiveRegs()) 2602 BEAlign = 8 - ArgSize; 2603 2604 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2605 2606 // Create load nodes to retrieve arguments from the stack. 2607 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2608 SDValue ArgValue; 2609 2610 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2611 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2612 MVT MemVT = VA.getValVT(); 2613 2614 switch (VA.getLocInfo()) { 2615 default: 2616 break; 2617 case CCValAssign::BCvt: 2618 MemVT = VA.getLocVT(); 2619 break; 2620 case CCValAssign::SExt: 2621 ExtType = ISD::SEXTLOAD; 2622 break; 2623 case CCValAssign::ZExt: 2624 ExtType = ISD::ZEXTLOAD; 2625 break; 2626 case CCValAssign::AExt: 2627 ExtType = ISD::EXTLOAD; 2628 break; 2629 } 2630 2631 ArgValue = DAG.getExtLoad( 2632 ExtType, DL, VA.getLocVT(), Chain, FIN, 2633 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2634 MemVT, false, false, false, 0); 2635 2636 InVals.push_back(ArgValue); 2637 } 2638 } 2639 2640 // varargs 2641 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2642 if (isVarArg) { 2643 if (!Subtarget->isTargetDarwin()) { 2644 // The AAPCS variadic function ABI is identical to the non-variadic 2645 // one. As a result there may be more arguments in registers and we should 2646 // save them for future reference. 2647 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2648 } 2649 2650 // This will point to the next argument passed via stack. 2651 unsigned StackOffset = CCInfo.getNextStackOffset(); 2652 // We currently pass all varargs at 8-byte alignment. 2653 StackOffset = ((StackOffset + 7) & ~7); 2654 FuncInfo->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true)); 2655 } 2656 2657 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2658 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2659 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2660 // This is a non-standard ABI so by fiat I say we're allowed to make full 2661 // use of the stack area to be popped, which must be aligned to 16 bytes in 2662 // any case: 2663 StackArgSize = alignTo(StackArgSize, 16); 2664 2665 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2666 // a multiple of 16. 2667 FuncInfo->setArgumentStackToRestore(StackArgSize); 2668 2669 // This realignment carries over to the available bytes below. Our own 2670 // callers will guarantee the space is free by giving an aligned value to 2671 // CALLSEQ_START. 2672 } 2673 // Even if we're not expected to free up the space, it's useful to know how 2674 // much is there while considering tail calls (because we can reuse it). 2675 FuncInfo->setBytesInStackArgArea(StackArgSize); 2676 2677 return Chain; 2678 } 2679 2680 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2681 SelectionDAG &DAG, 2682 const SDLoc &DL, 2683 SDValue &Chain) const { 2684 MachineFunction &MF = DAG.getMachineFunction(); 2685 MachineFrameInfo *MFI = MF.getFrameInfo(); 2686 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2687 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2688 2689 SmallVector<SDValue, 8> MemOps; 2690 2691 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2692 AArch64::X3, AArch64::X4, AArch64::X5, 2693 AArch64::X6, AArch64::X7 }; 2694 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2695 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2696 2697 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2698 int GPRIdx = 0; 2699 if (GPRSaveSize != 0) { 2700 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false); 2701 2702 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2703 2704 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2705 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2706 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2707 SDValue Store = DAG.getStore( 2708 Val.getValue(1), DL, Val, FIN, 2709 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false, 2710 false, 0); 2711 MemOps.push_back(Store); 2712 FIN = 2713 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2714 } 2715 } 2716 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2717 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2718 2719 if (Subtarget->hasFPARMv8()) { 2720 static const MCPhysReg FPRArgRegs[] = { 2721 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2722 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2723 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2724 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2725 2726 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2727 int FPRIdx = 0; 2728 if (FPRSaveSize != 0) { 2729 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false); 2730 2731 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2732 2733 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2734 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2735 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2736 2737 SDValue Store = DAG.getStore( 2738 Val.getValue(1), DL, Val, FIN, 2739 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16), 2740 false, false, 0); 2741 MemOps.push_back(Store); 2742 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 2743 DAG.getConstant(16, DL, PtrVT)); 2744 } 2745 } 2746 FuncInfo->setVarArgsFPRIndex(FPRIdx); 2747 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 2748 } 2749 2750 if (!MemOps.empty()) { 2751 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2752 } 2753 } 2754 2755 /// LowerCallResult - Lower the result values of a call into the 2756 /// appropriate copies out of appropriate physical registers. 2757 SDValue AArch64TargetLowering::LowerCallResult( 2758 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2759 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2760 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2761 SDValue ThisVal) const { 2762 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 2763 ? RetCC_AArch64_WebKit_JS 2764 : RetCC_AArch64_AAPCS; 2765 // Assign locations to each value returned by this call. 2766 SmallVector<CCValAssign, 16> RVLocs; 2767 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2768 *DAG.getContext()); 2769 CCInfo.AnalyzeCallResult(Ins, RetCC); 2770 2771 // Copy all of the result registers out of their specified physreg. 2772 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2773 CCValAssign VA = RVLocs[i]; 2774 2775 // Pass 'this' value directly from the argument to return value, to avoid 2776 // reg unit interference 2777 if (i == 0 && isThisReturn) { 2778 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 2779 "unexpected return calling convention register assignment"); 2780 InVals.push_back(ThisVal); 2781 continue; 2782 } 2783 2784 SDValue Val = 2785 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2786 Chain = Val.getValue(1); 2787 InFlag = Val.getValue(2); 2788 2789 switch (VA.getLocInfo()) { 2790 default: 2791 llvm_unreachable("Unknown loc info!"); 2792 case CCValAssign::Full: 2793 break; 2794 case CCValAssign::BCvt: 2795 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2796 break; 2797 } 2798 2799 InVals.push_back(Val); 2800 } 2801 2802 return Chain; 2803 } 2804 2805 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 2806 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2807 const SmallVectorImpl<ISD::OutputArg> &Outs, 2808 const SmallVectorImpl<SDValue> &OutVals, 2809 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2810 // For CallingConv::C this function knows whether the ABI needs 2811 // changing. That's not true for other conventions so they will have to opt in 2812 // manually. 2813 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 2814 return false; 2815 2816 MachineFunction &MF = DAG.getMachineFunction(); 2817 const Function *CallerF = MF.getFunction(); 2818 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2819 bool CCMatch = CallerCC == CalleeCC; 2820 2821 // Byval parameters hand the function a pointer directly into the stack area 2822 // we want to reuse during a tail call. Working around this *is* possible (see 2823 // X86) but less efficient and uglier in LowerCall. 2824 for (Function::const_arg_iterator i = CallerF->arg_begin(), 2825 e = CallerF->arg_end(); 2826 i != e; ++i) 2827 if (i->hasByValAttr()) 2828 return false; 2829 2830 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2831 return IsTailCallConvention(CalleeCC) && CCMatch; 2832 } 2833 2834 // Externally-defined functions with weak linkage should not be 2835 // tail-called on AArch64 when the OS does not support dynamic 2836 // pre-emption of symbols, as the AAELF spec requires normal calls 2837 // to undefined weak functions to be replaced with a NOP or jump to the 2838 // next instruction. The behaviour of branch instructions in this 2839 // situation (as used for tail calls) is implementation-defined, so we 2840 // cannot rely on the linker replacing the tail call with a return. 2841 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2842 const GlobalValue *GV = G->getGlobal(); 2843 const Triple &TT = getTargetMachine().getTargetTriple(); 2844 if (GV->hasExternalWeakLinkage() && 2845 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2846 return false; 2847 } 2848 2849 // Now we search for cases where we can use a tail call without changing the 2850 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 2851 // concept. 2852 2853 // I want anyone implementing a new calling convention to think long and hard 2854 // about this assert. 2855 assert((!isVarArg || CalleeCC == CallingConv::C) && 2856 "Unexpected variadic calling convention"); 2857 2858 LLVMContext &C = *DAG.getContext(); 2859 if (isVarArg && !Outs.empty()) { 2860 // At least two cases here: if caller is fastcc then we can't have any 2861 // memory arguments (we'd be expected to clean up the stack afterwards). If 2862 // caller is C then we could potentially use its argument area. 2863 2864 // FIXME: for now we take the most conservative of these in both cases: 2865 // disallow all variadic memory operands. 2866 SmallVector<CCValAssign, 16> ArgLocs; 2867 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2868 2869 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 2870 for (const CCValAssign &ArgLoc : ArgLocs) 2871 if (!ArgLoc.isRegLoc()) 2872 return false; 2873 } 2874 2875 // Check that the call results are passed in the same way. 2876 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2877 CCAssignFnForCall(CalleeCC, isVarArg), 2878 CCAssignFnForCall(CallerCC, isVarArg))) 2879 return false; 2880 // The callee has to preserve all registers the caller needs to preserve. 2881 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 2882 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2883 if (!CCMatch) { 2884 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2885 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2886 return false; 2887 } 2888 2889 // Nothing more to check if the callee is taking no arguments 2890 if (Outs.empty()) 2891 return true; 2892 2893 SmallVector<CCValAssign, 16> ArgLocs; 2894 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2895 2896 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2897 2898 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2899 2900 // If the stack arguments for this call do not fit into our own save area then 2901 // the call cannot be made tail. 2902 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2903 return false; 2904 2905 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2906 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2907 return false; 2908 2909 return true; 2910 } 2911 2912 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 2913 SelectionDAG &DAG, 2914 MachineFrameInfo *MFI, 2915 int ClobberedFI) const { 2916 SmallVector<SDValue, 8> ArgChains; 2917 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI); 2918 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1; 2919 2920 // Include the original chain at the beginning of the list. When this is 2921 // used by target LowerCall hooks, this helps legalize find the 2922 // CALLSEQ_BEGIN node. 2923 ArgChains.push_back(Chain); 2924 2925 // Add a chain value for each stack argument corresponding 2926 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 2927 UE = DAG.getEntryNode().getNode()->use_end(); 2928 U != UE; ++U) 2929 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 2930 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 2931 if (FI->getIndex() < 0) { 2932 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex()); 2933 int64_t InLastByte = InFirstByte; 2934 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1; 2935 2936 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 2937 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 2938 ArgChains.push_back(SDValue(L, 1)); 2939 } 2940 2941 // Build a tokenfactor for all the chains. 2942 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 2943 } 2944 2945 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 2946 bool TailCallOpt) const { 2947 return CallCC == CallingConv::Fast && TailCallOpt; 2948 } 2949 2950 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const { 2951 return CallCC == CallingConv::Fast || 2952 CallCC == CallingConv::PreserveMost; 2953 } 2954 2955 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 2956 /// and add input and output parameter nodes. 2957 SDValue 2958 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 2959 SmallVectorImpl<SDValue> &InVals) const { 2960 SelectionDAG &DAG = CLI.DAG; 2961 SDLoc &DL = CLI.DL; 2962 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2963 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2964 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2965 SDValue Chain = CLI.Chain; 2966 SDValue Callee = CLI.Callee; 2967 bool &IsTailCall = CLI.IsTailCall; 2968 CallingConv::ID CallConv = CLI.CallConv; 2969 bool IsVarArg = CLI.IsVarArg; 2970 2971 MachineFunction &MF = DAG.getMachineFunction(); 2972 bool IsThisReturn = false; 2973 2974 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2975 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2976 bool IsSibCall = false; 2977 2978 if (IsTailCall) { 2979 // Check if it's really possible to do a tail call. 2980 IsTailCall = isEligibleForTailCallOptimization( 2981 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2982 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall()) 2983 report_fatal_error("failed to perform tail call elimination on a call " 2984 "site marked musttail"); 2985 2986 // A sibling call is one where we're under the usual C ABI and not planning 2987 // to change that but can still do a tail call: 2988 if (!TailCallOpt && IsTailCall) 2989 IsSibCall = true; 2990 2991 if (IsTailCall) 2992 ++NumTailCalls; 2993 } 2994 2995 // Analyze operands of the call, assigning locations to each operand. 2996 SmallVector<CCValAssign, 16> ArgLocs; 2997 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 2998 *DAG.getContext()); 2999 3000 if (IsVarArg) { 3001 // Handle fixed and variable vector arguments differently. 3002 // Variable vector arguments always go into memory. 3003 unsigned NumArgs = Outs.size(); 3004 3005 for (unsigned i = 0; i != NumArgs; ++i) { 3006 MVT ArgVT = Outs[i].VT; 3007 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3008 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3009 /*IsVarArg=*/ !Outs[i].IsFixed); 3010 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3011 assert(!Res && "Call operand has unhandled type"); 3012 (void)Res; 3013 } 3014 } else { 3015 // At this point, Outs[].VT may already be promoted to i32. To correctly 3016 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3017 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3018 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3019 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3020 // LocVT. 3021 unsigned NumArgs = Outs.size(); 3022 for (unsigned i = 0; i != NumArgs; ++i) { 3023 MVT ValVT = Outs[i].VT; 3024 // Get type of the original argument. 3025 EVT ActualVT = getValueType(DAG.getDataLayout(), 3026 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3027 /*AllowUnknown*/ true); 3028 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3029 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3030 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3031 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3032 ValVT = MVT::i8; 3033 else if (ActualMVT == MVT::i16) 3034 ValVT = MVT::i16; 3035 3036 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3037 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3038 assert(!Res && "Call operand has unhandled type"); 3039 (void)Res; 3040 } 3041 } 3042 3043 // Get a count of how many bytes are to be pushed on the stack. 3044 unsigned NumBytes = CCInfo.getNextStackOffset(); 3045 3046 if (IsSibCall) { 3047 // Since we're not changing the ABI to make this a tail call, the memory 3048 // operands are already available in the caller's incoming argument space. 3049 NumBytes = 0; 3050 } 3051 3052 // FPDiff is the byte offset of the call's argument area from the callee's. 3053 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3054 // by this amount for a tail call. In a sibling call it must be 0 because the 3055 // caller will deallocate the entire stack and the callee still expects its 3056 // arguments to begin at SP+0. Completely unused for non-tail calls. 3057 int FPDiff = 0; 3058 3059 if (IsTailCall && !IsSibCall) { 3060 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3061 3062 // Since callee will pop argument stack as a tail call, we must keep the 3063 // popped size 16-byte aligned. 3064 NumBytes = alignTo(NumBytes, 16); 3065 3066 // FPDiff will be negative if this tail call requires more space than we 3067 // would automatically have in our incoming argument space. Positive if we 3068 // can actually shrink the stack. 3069 FPDiff = NumReusableBytes - NumBytes; 3070 3071 // The stack pointer must be 16-byte aligned at all times it's used for a 3072 // memory operation, which in practice means at *all* times and in 3073 // particular across call boundaries. Therefore our own arguments started at 3074 // a 16-byte aligned SP and the delta applied for the tail call should 3075 // satisfy the same constraint. 3076 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3077 } 3078 3079 // Adjust the stack pointer for the new arguments... 3080 // These operations are automatically eliminated by the prolog/epilog pass 3081 if (!IsSibCall) 3082 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, 3083 true), 3084 DL); 3085 3086 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3087 getPointerTy(DAG.getDataLayout())); 3088 3089 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3090 SmallVector<SDValue, 8> MemOpChains; 3091 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3092 3093 // Walk the register/memloc assignments, inserting copies/loads. 3094 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3095 ++i, ++realArgIdx) { 3096 CCValAssign &VA = ArgLocs[i]; 3097 SDValue Arg = OutVals[realArgIdx]; 3098 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3099 3100 // Promote the value if needed. 3101 switch (VA.getLocInfo()) { 3102 default: 3103 llvm_unreachable("Unknown loc info!"); 3104 case CCValAssign::Full: 3105 break; 3106 case CCValAssign::SExt: 3107 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3108 break; 3109 case CCValAssign::ZExt: 3110 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3111 break; 3112 case CCValAssign::AExt: 3113 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3114 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3115 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3116 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3117 } 3118 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3119 break; 3120 case CCValAssign::BCvt: 3121 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3122 break; 3123 case CCValAssign::FPExt: 3124 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3125 break; 3126 } 3127 3128 if (VA.isRegLoc()) { 3129 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) { 3130 assert(VA.getLocVT() == MVT::i64 && 3131 "unexpected calling convention register assignment"); 3132 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3133 "unexpected use of 'returned'"); 3134 IsThisReturn = true; 3135 } 3136 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3137 } else { 3138 assert(VA.isMemLoc()); 3139 3140 SDValue DstAddr; 3141 MachinePointerInfo DstInfo; 3142 3143 // FIXME: This works on big-endian for composite byvals, which are the 3144 // common case. It should also work for fundamental types too. 3145 uint32_t BEAlign = 0; 3146 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3147 : VA.getValVT().getSizeInBits(); 3148 OpSize = (OpSize + 7) / 8; 3149 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3150 !Flags.isInConsecutiveRegs()) { 3151 if (OpSize < 8) 3152 BEAlign = 8 - OpSize; 3153 } 3154 unsigned LocMemOffset = VA.getLocMemOffset(); 3155 int32_t Offset = LocMemOffset + BEAlign; 3156 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3157 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3158 3159 if (IsTailCall) { 3160 Offset = Offset + FPDiff; 3161 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 3162 3163 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3164 DstInfo = 3165 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3166 3167 // Make sure any stack arguments overlapping with where we're storing 3168 // are loaded before this eventual operation. Otherwise they'll be 3169 // clobbered. 3170 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3171 } else { 3172 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3173 3174 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3175 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3176 LocMemOffset); 3177 } 3178 3179 if (Outs[i].Flags.isByVal()) { 3180 SDValue SizeNode = 3181 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3182 SDValue Cpy = DAG.getMemcpy( 3183 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3184 /*isVol = */ false, /*AlwaysInline = */ false, 3185 /*isTailCall = */ false, 3186 DstInfo, MachinePointerInfo()); 3187 3188 MemOpChains.push_back(Cpy); 3189 } else { 3190 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3191 // promoted to a legal register type i32, we should truncate Arg back to 3192 // i1/i8/i16. 3193 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3194 VA.getValVT() == MVT::i16) 3195 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3196 3197 SDValue Store = 3198 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0); 3199 MemOpChains.push_back(Store); 3200 } 3201 } 3202 } 3203 3204 if (!MemOpChains.empty()) 3205 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3206 3207 // Build a sequence of copy-to-reg nodes chained together with token chain 3208 // and flag operands which copy the outgoing args into the appropriate regs. 3209 SDValue InFlag; 3210 for (auto &RegToPass : RegsToPass) { 3211 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3212 RegToPass.second, InFlag); 3213 InFlag = Chain.getValue(1); 3214 } 3215 3216 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3217 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3218 // node so that legalize doesn't hack it. 3219 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3220 Subtarget->isTargetMachO()) { 3221 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3222 const GlobalValue *GV = G->getGlobal(); 3223 bool InternalLinkage = GV->hasInternalLinkage(); 3224 if (InternalLinkage) 3225 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3226 else { 3227 Callee = 3228 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3229 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3230 } 3231 } else if (ExternalSymbolSDNode *S = 3232 dyn_cast<ExternalSymbolSDNode>(Callee)) { 3233 const char *Sym = S->getSymbol(); 3234 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3235 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3236 } 3237 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3238 const GlobalValue *GV = G->getGlobal(); 3239 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3240 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3241 const char *Sym = S->getSymbol(); 3242 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3243 } 3244 3245 // We don't usually want to end the call-sequence here because we would tidy 3246 // the frame up *after* the call, however in the ABI-changing tail-call case 3247 // we've carefully laid out the parameters so that when sp is reset they'll be 3248 // in the correct location. 3249 if (IsTailCall && !IsSibCall) { 3250 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3251 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3252 InFlag = Chain.getValue(1); 3253 } 3254 3255 std::vector<SDValue> Ops; 3256 Ops.push_back(Chain); 3257 Ops.push_back(Callee); 3258 3259 if (IsTailCall) { 3260 // Each tail call may have to adjust the stack by a different amount, so 3261 // this information must travel along with the operation for eventual 3262 // consumption by emitEpilogue. 3263 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3264 } 3265 3266 // Add argument registers to the end of the list so that they are known live 3267 // into the call. 3268 for (auto &RegToPass : RegsToPass) 3269 Ops.push_back(DAG.getRegister(RegToPass.first, 3270 RegToPass.second.getValueType())); 3271 3272 // Add a register mask operand representing the call-preserved registers. 3273 const uint32_t *Mask; 3274 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3275 if (IsThisReturn) { 3276 // For 'this' returns, use the X0-preserving mask if applicable 3277 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3278 if (!Mask) { 3279 IsThisReturn = false; 3280 Mask = TRI->getCallPreservedMask(MF, CallConv); 3281 } 3282 } else 3283 Mask = TRI->getCallPreservedMask(MF, CallConv); 3284 3285 assert(Mask && "Missing call preserved mask for calling convention"); 3286 Ops.push_back(DAG.getRegisterMask(Mask)); 3287 3288 if (InFlag.getNode()) 3289 Ops.push_back(InFlag); 3290 3291 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3292 3293 // If we're doing a tall call, use a TC_RETURN here rather than an 3294 // actual call instruction. 3295 if (IsTailCall) { 3296 MF.getFrameInfo()->setHasTailCall(); 3297 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3298 } 3299 3300 // Returns a chain and a flag for retval copy to use. 3301 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3302 InFlag = Chain.getValue(1); 3303 3304 uint64_t CalleePopBytes = 3305 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3306 3307 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3308 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3309 InFlag, DL); 3310 if (!Ins.empty()) 3311 InFlag = Chain.getValue(1); 3312 3313 // Handle result values, copying them out of physregs into vregs that we 3314 // return. 3315 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3316 InVals, IsThisReturn, 3317 IsThisReturn ? OutVals[0] : SDValue()); 3318 } 3319 3320 bool AArch64TargetLowering::CanLowerReturn( 3321 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3322 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3323 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3324 ? RetCC_AArch64_WebKit_JS 3325 : RetCC_AArch64_AAPCS; 3326 SmallVector<CCValAssign, 16> RVLocs; 3327 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3328 return CCInfo.CheckReturn(Outs, RetCC); 3329 } 3330 3331 SDValue 3332 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3333 bool isVarArg, 3334 const SmallVectorImpl<ISD::OutputArg> &Outs, 3335 const SmallVectorImpl<SDValue> &OutVals, 3336 const SDLoc &DL, SelectionDAG &DAG) const { 3337 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3338 ? RetCC_AArch64_WebKit_JS 3339 : RetCC_AArch64_AAPCS; 3340 SmallVector<CCValAssign, 16> RVLocs; 3341 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3342 *DAG.getContext()); 3343 CCInfo.AnalyzeReturn(Outs, RetCC); 3344 3345 // Copy the result values into the output registers. 3346 SDValue Flag; 3347 SmallVector<SDValue, 4> RetOps(1, Chain); 3348 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3349 ++i, ++realRVLocIdx) { 3350 CCValAssign &VA = RVLocs[i]; 3351 assert(VA.isRegLoc() && "Can only return in registers!"); 3352 SDValue Arg = OutVals[realRVLocIdx]; 3353 3354 switch (VA.getLocInfo()) { 3355 default: 3356 llvm_unreachable("Unknown loc info!"); 3357 case CCValAssign::Full: 3358 if (Outs[i].ArgVT == MVT::i1) { 3359 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3360 // value. This is strictly redundant on Darwin (which uses "zeroext 3361 // i1"), but will be optimised out before ISel. 3362 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3363 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3364 } 3365 break; 3366 case CCValAssign::BCvt: 3367 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3368 break; 3369 } 3370 3371 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3372 Flag = Chain.getValue(1); 3373 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3374 } 3375 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3376 const MCPhysReg *I = 3377 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3378 if (I) { 3379 for (; *I; ++I) { 3380 if (AArch64::GPR64RegClass.contains(*I)) 3381 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3382 else if (AArch64::FPR64RegClass.contains(*I)) 3383 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3384 else 3385 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3386 } 3387 } 3388 3389 RetOps[0] = Chain; // Update chain. 3390 3391 // Add the flag if we have it. 3392 if (Flag.getNode()) 3393 RetOps.push_back(Flag); 3394 3395 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3396 } 3397 3398 //===----------------------------------------------------------------------===// 3399 // Other Lowering Code 3400 //===----------------------------------------------------------------------===// 3401 3402 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3403 SelectionDAG &DAG) const { 3404 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3405 SDLoc DL(Op); 3406 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3407 const GlobalValue *GV = GN->getGlobal(); 3408 unsigned char OpFlags = 3409 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3410 3411 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3412 "unexpected offset in global node"); 3413 3414 // This also catched the large code model case for Darwin. 3415 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3416 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 3417 // FIXME: Once remat is capable of dealing with instructions with register 3418 // operands, expand this into two nodes instead of using a wrapper node. 3419 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 3420 } 3421 3422 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3423 const unsigned char MO_NC = AArch64II::MO_NC; 3424 return DAG.getNode( 3425 AArch64ISD::WrapperLarge, DL, PtrVT, 3426 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3), 3427 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 3428 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 3429 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 3430 } else { 3431 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and 3432 // the only correct model on Darwin. 3433 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 3434 OpFlags | AArch64II::MO_PAGE); 3435 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC; 3436 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags); 3437 3438 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 3439 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 3440 } 3441 } 3442 3443 /// \brief Convert a TLS address reference into the correct sequence of loads 3444 /// and calls to compute the variable's address (for Darwin, currently) and 3445 /// return an SDValue containing the final node. 3446 3447 /// Darwin only has one TLS scheme which must be capable of dealing with the 3448 /// fully general situation, in the worst case. This means: 3449 /// + "extern __thread" declaration. 3450 /// + Defined in a possibly unknown dynamic library. 3451 /// 3452 /// The general system is that each __thread variable has a [3 x i64] descriptor 3453 /// which contains information used by the runtime to calculate the address. The 3454 /// only part of this the compiler needs to know about is the first xword, which 3455 /// contains a function pointer that must be called with the address of the 3456 /// entire descriptor in "x0". 3457 /// 3458 /// Since this descriptor may be in a different unit, in general even the 3459 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3460 /// is: 3461 /// adrp x0, _var@TLVPPAGE 3462 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3463 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3464 /// ; the function pointer 3465 /// blr x1 ; Uses descriptor address in x0 3466 /// ; Address of _var is now in x0. 3467 /// 3468 /// If the address of _var's descriptor *is* known to the linker, then it can 3469 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3470 /// a slight efficiency gain. 3471 SDValue 3472 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3473 SelectionDAG &DAG) const { 3474 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3475 3476 SDLoc DL(Op); 3477 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3478 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3479 3480 SDValue TLVPAddr = 3481 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3482 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3483 3484 // The first entry in the descriptor is a function pointer that we must call 3485 // to obtain the address of the variable. 3486 SDValue Chain = DAG.getEntryNode(); 3487 SDValue FuncTLVGet = 3488 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, 3489 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, 3490 true, true, 8); 3491 Chain = FuncTLVGet.getValue(1); 3492 3493 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3494 MFI->setAdjustsStack(true); 3495 3496 // TLS calls preserve all registers except those that absolutely must be 3497 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3498 // silly). 3499 const uint32_t *Mask = 3500 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3501 3502 // Finally, we can make the call. This is just a degenerate version of a 3503 // normal AArch64 call node: x0 takes the address of the descriptor, and 3504 // returns the address of the variable in this thread. 3505 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3506 Chain = 3507 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3508 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3509 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3510 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3511 } 3512 3513 /// When accessing thread-local variables under either the general-dynamic or 3514 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3515 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3516 /// is a function pointer to carry out the resolution. 3517 /// 3518 /// The sequence is: 3519 /// adrp x0, :tlsdesc:var 3520 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3521 /// add x0, x0, #:tlsdesc_lo12:var 3522 /// .tlsdesccall var 3523 /// blr x1 3524 /// (TPIDR_EL0 offset now in x0) 3525 /// 3526 /// The above sequence must be produced unscheduled, to enable the linker to 3527 /// optimize/relax this sequence. 3528 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3529 /// above sequence, and expanded really late in the compilation flow, to ensure 3530 /// the sequence is produced as per above. 3531 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 3532 const SDLoc &DL, 3533 SelectionDAG &DAG) const { 3534 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3535 3536 SDValue Chain = DAG.getEntryNode(); 3537 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3538 3539 SmallVector<SDValue, 2> Ops; 3540 Ops.push_back(Chain); 3541 Ops.push_back(SymAddr); 3542 3543 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops); 3544 SDValue Glue = Chain.getValue(1); 3545 3546 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3547 } 3548 3549 SDValue 3550 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3551 SelectionDAG &DAG) const { 3552 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3553 assert(getTargetMachine().getCodeModel() == CodeModel::Small && 3554 "ELF TLS only supported in small memory model"); 3555 // Different choices can be made for the maximum size of the TLS area for a 3556 // module. For the small address model, the default TLS size is 16MiB and the 3557 // maximum TLS size is 4GiB. 3558 // FIXME: add -mtls-size command line option and make it control the 16MiB 3559 // vs. 4GiB code sequence generation. 3560 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3561 3562 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3563 3564 if (DAG.getTarget().Options.EmulatedTLS) 3565 return LowerToTLSEmulatedModel(GA, DAG); 3566 3567 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3568 if (Model == TLSModel::LocalDynamic) 3569 Model = TLSModel::GeneralDynamic; 3570 } 3571 3572 SDValue TPOff; 3573 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3574 SDLoc DL(Op); 3575 const GlobalValue *GV = GA->getGlobal(); 3576 3577 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3578 3579 if (Model == TLSModel::LocalExec) { 3580 SDValue HiVar = DAG.getTargetGlobalAddress( 3581 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3582 SDValue LoVar = DAG.getTargetGlobalAddress( 3583 GV, DL, PtrVT, 0, 3584 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3585 3586 SDValue TPWithOff_lo = 3587 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3588 HiVar, 3589 DAG.getTargetConstant(0, DL, MVT::i32)), 3590 0); 3591 SDValue TPWithOff = 3592 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3593 LoVar, 3594 DAG.getTargetConstant(0, DL, MVT::i32)), 3595 0); 3596 return TPWithOff; 3597 } else if (Model == TLSModel::InitialExec) { 3598 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3599 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3600 } else if (Model == TLSModel::LocalDynamic) { 3601 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3602 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3603 // the beginning of the module's TLS region, followed by a DTPREL offset 3604 // calculation. 3605 3606 // These accesses will need deduplicating if there's more than one. 3607 AArch64FunctionInfo *MFI = 3608 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3609 MFI->incNumLocalDynamicTLSAccesses(); 3610 3611 // The call needs a relocation too for linker relaxation. It doesn't make 3612 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3613 // the address. 3614 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3615 AArch64II::MO_TLS); 3616 3617 // Now we can calculate the offset from TPIDR_EL0 to this module's 3618 // thread-local area. 3619 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3620 3621 // Now use :dtprel_whatever: operations to calculate this variable's offset 3622 // in its thread-storage area. 3623 SDValue HiVar = DAG.getTargetGlobalAddress( 3624 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3625 SDValue LoVar = DAG.getTargetGlobalAddress( 3626 GV, DL, MVT::i64, 0, 3627 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3628 3629 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3630 DAG.getTargetConstant(0, DL, MVT::i32)), 3631 0); 3632 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3633 DAG.getTargetConstant(0, DL, MVT::i32)), 3634 0); 3635 } else if (Model == TLSModel::GeneralDynamic) { 3636 // The call needs a relocation too for linker relaxation. It doesn't make 3637 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3638 // the address. 3639 SDValue SymAddr = 3640 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3641 3642 // Finally we can make a call to calculate the offset from tpidr_el0. 3643 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3644 } else 3645 llvm_unreachable("Unsupported ELF TLS access model"); 3646 3647 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3648 } 3649 3650 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3651 SelectionDAG &DAG) const { 3652 if (Subtarget->isTargetDarwin()) 3653 return LowerDarwinGlobalTLSAddress(Op, DAG); 3654 else if (Subtarget->isTargetELF()) 3655 return LowerELFGlobalTLSAddress(Op, DAG); 3656 3657 llvm_unreachable("Unexpected platform trying to use TLS"); 3658 } 3659 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3660 SDValue Chain = Op.getOperand(0); 3661 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3662 SDValue LHS = Op.getOperand(2); 3663 SDValue RHS = Op.getOperand(3); 3664 SDValue Dest = Op.getOperand(4); 3665 SDLoc dl(Op); 3666 3667 // Handle f128 first, since lowering it will result in comparing the return 3668 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3669 // is expecting to deal with. 3670 if (LHS.getValueType() == MVT::f128) { 3671 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3672 3673 // If softenSetCCOperands returned a scalar, we need to compare the result 3674 // against zero to select between true and false values. 3675 if (!RHS.getNode()) { 3676 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3677 CC = ISD::SETNE; 3678 } 3679 } 3680 3681 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 3682 // instruction. 3683 unsigned Opc = LHS.getOpcode(); 3684 if (LHS.getResNo() == 1 && isOneConstant(RHS) && 3685 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3686 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 3687 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 3688 "Unexpected condition code."); 3689 // Only lower legal XALUO ops. 3690 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 3691 return SDValue(); 3692 3693 // The actual operation with overflow check. 3694 AArch64CC::CondCode OFCC; 3695 SDValue Value, Overflow; 3696 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 3697 3698 if (CC == ISD::SETNE) 3699 OFCC = getInvertedCondCode(OFCC); 3700 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 3701 3702 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3703 Overflow); 3704 } 3705 3706 if (LHS.getValueType().isInteger()) { 3707 assert((LHS.getValueType() == RHS.getValueType()) && 3708 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3709 3710 // If the RHS of the comparison is zero, we can potentially fold this 3711 // to a specialized branch. 3712 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 3713 if (RHSC && RHSC->getZExtValue() == 0) { 3714 if (CC == ISD::SETEQ) { 3715 // See if we can use a TBZ to fold in an AND as well. 3716 // TBZ has a smaller branch displacement than CBZ. If the offset is 3717 // out of bounds, a late MI-layer pass rewrites branches. 3718 // 403.gcc is an example that hits this case. 3719 if (LHS.getOpcode() == ISD::AND && 3720 isa<ConstantSDNode>(LHS.getOperand(1)) && 3721 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3722 SDValue Test = LHS.getOperand(0); 3723 uint64_t Mask = LHS.getConstantOperandVal(1); 3724 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 3725 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3726 Dest); 3727 } 3728 3729 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 3730 } else if (CC == ISD::SETNE) { 3731 // See if we can use a TBZ to fold in an AND as well. 3732 // TBZ has a smaller branch displacement than CBZ. If the offset is 3733 // out of bounds, a late MI-layer pass rewrites branches. 3734 // 403.gcc is an example that hits this case. 3735 if (LHS.getOpcode() == ISD::AND && 3736 isa<ConstantSDNode>(LHS.getOperand(1)) && 3737 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3738 SDValue Test = LHS.getOperand(0); 3739 uint64_t Mask = LHS.getConstantOperandVal(1); 3740 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 3741 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3742 Dest); 3743 } 3744 3745 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 3746 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 3747 // Don't combine AND since emitComparison converts the AND to an ANDS 3748 // (a.k.a. TST) and the test in the test bit and branch instruction 3749 // becomes redundant. This would also increase register pressure. 3750 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1; 3751 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 3752 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3753 } 3754 } 3755 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 3756 LHS.getOpcode() != ISD::AND) { 3757 // Don't combine AND since emitComparison converts the AND to an ANDS 3758 // (a.k.a. TST) and the test in the test bit and branch instruction 3759 // becomes redundant. This would also increase register pressure. 3760 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1; 3761 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 3762 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3763 } 3764 3765 SDValue CCVal; 3766 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 3767 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3768 Cmp); 3769 } 3770 3771 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3772 3773 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 3774 // clean. Some of them require two branches to implement. 3775 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3776 AArch64CC::CondCode CC1, CC2; 3777 changeFPCCToAArch64CC(CC, CC1, CC2); 3778 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3779 SDValue BR1 = 3780 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 3781 if (CC2 != AArch64CC::AL) { 3782 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3783 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 3784 Cmp); 3785 } 3786 3787 return BR1; 3788 } 3789 3790 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 3791 SelectionDAG &DAG) const { 3792 EVT VT = Op.getValueType(); 3793 SDLoc DL(Op); 3794 3795 SDValue In1 = Op.getOperand(0); 3796 SDValue In2 = Op.getOperand(1); 3797 EVT SrcVT = In2.getValueType(); 3798 3799 if (SrcVT.bitsLT(VT)) 3800 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 3801 else if (SrcVT.bitsGT(VT)) 3802 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 3803 3804 EVT VecVT; 3805 EVT EltVT; 3806 uint64_t EltMask; 3807 SDValue VecVal1, VecVal2; 3808 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 3809 EltVT = MVT::i32; 3810 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 3811 EltMask = 0x80000000ULL; 3812 3813 if (!VT.isVector()) { 3814 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3815 DAG.getUNDEF(VecVT), In1); 3816 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3817 DAG.getUNDEF(VecVT), In2); 3818 } else { 3819 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3820 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3821 } 3822 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 3823 EltVT = MVT::i64; 3824 VecVT = MVT::v2i64; 3825 3826 // We want to materialize a mask with the high bit set, but the AdvSIMD 3827 // immediate moves cannot materialize that in a single instruction for 3828 // 64-bit elements. Instead, materialize zero and then negate it. 3829 EltMask = 0; 3830 3831 if (!VT.isVector()) { 3832 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3833 DAG.getUNDEF(VecVT), In1); 3834 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3835 DAG.getUNDEF(VecVT), In2); 3836 } else { 3837 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3838 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3839 } 3840 } else { 3841 llvm_unreachable("Invalid type for copysign!"); 3842 } 3843 3844 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 3845 3846 // If we couldn't materialize the mask above, then the mask vector will be 3847 // the zero vector, and we need to negate it here. 3848 if (VT == MVT::f64 || VT == MVT::v2f64) { 3849 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 3850 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 3851 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 3852 } 3853 3854 SDValue Sel = 3855 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 3856 3857 if (VT == MVT::f32) 3858 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 3859 else if (VT == MVT::f64) 3860 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 3861 else 3862 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 3863 } 3864 3865 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 3866 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 3867 Attribute::NoImplicitFloat)) 3868 return SDValue(); 3869 3870 if (!Subtarget->hasNEON()) 3871 return SDValue(); 3872 3873 // While there is no integer popcount instruction, it can 3874 // be more efficiently lowered to the following sequence that uses 3875 // AdvSIMD registers/instructions as long as the copies to/from 3876 // the AdvSIMD registers are cheap. 3877 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 3878 // CNT V0.8B, V0.8B // 8xbyte pop-counts 3879 // ADDV B0, V0.8B // sum 8xbyte pop-counts 3880 // UMOV X0, V0.B[0] // copy byte result back to integer reg 3881 SDValue Val = Op.getOperand(0); 3882 SDLoc DL(Op); 3883 EVT VT = Op.getValueType(); 3884 3885 if (VT == MVT::i32) 3886 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 3887 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 3888 3889 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 3890 SDValue UaddLV = DAG.getNode( 3891 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 3892 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 3893 3894 if (VT == MVT::i64) 3895 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 3896 return UaddLV; 3897 } 3898 3899 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3900 3901 if (Op.getValueType().isVector()) 3902 return LowerVSETCC(Op, DAG); 3903 3904 SDValue LHS = Op.getOperand(0); 3905 SDValue RHS = Op.getOperand(1); 3906 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3907 SDLoc dl(Op); 3908 3909 // We chose ZeroOrOneBooleanContents, so use zero and one. 3910 EVT VT = Op.getValueType(); 3911 SDValue TVal = DAG.getConstant(1, dl, VT); 3912 SDValue FVal = DAG.getConstant(0, dl, VT); 3913 3914 // Handle f128 first, since one possible outcome is a normal integer 3915 // comparison which gets picked up by the next if statement. 3916 if (LHS.getValueType() == MVT::f128) { 3917 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3918 3919 // If softenSetCCOperands returned a scalar, use it. 3920 if (!RHS.getNode()) { 3921 assert(LHS.getValueType() == Op.getValueType() && 3922 "Unexpected setcc expansion!"); 3923 return LHS; 3924 } 3925 } 3926 3927 if (LHS.getValueType().isInteger()) { 3928 SDValue CCVal; 3929 SDValue Cmp = 3930 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 3931 3932 // Note that we inverted the condition above, so we reverse the order of 3933 // the true and false operands here. This will allow the setcc to be 3934 // matched to a single CSINC instruction. 3935 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 3936 } 3937 3938 // Now we know we're dealing with FP values. 3939 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3940 3941 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 3942 // and do the comparison. 3943 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3944 3945 AArch64CC::CondCode CC1, CC2; 3946 changeFPCCToAArch64CC(CC, CC1, CC2); 3947 if (CC2 == AArch64CC::AL) { 3948 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 3949 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3950 3951 // Note that we inverted the condition above, so we reverse the order of 3952 // the true and false operands here. This will allow the setcc to be 3953 // matched to a single CSINC instruction. 3954 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 3955 } else { 3956 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 3957 // totally clean. Some of them require two CSELs to implement. As is in 3958 // this case, we emit the first CSEL and then emit a second using the output 3959 // of the first as the RHS. We're effectively OR'ing the two CC's together. 3960 3961 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 3962 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3963 SDValue CS1 = 3964 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 3965 3966 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3967 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 3968 } 3969 } 3970 3971 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 3972 SDValue RHS, SDValue TVal, 3973 SDValue FVal, const SDLoc &dl, 3974 SelectionDAG &DAG) const { 3975 // Handle f128 first, because it will result in a comparison of some RTLIB 3976 // call result against zero. 3977 if (LHS.getValueType() == MVT::f128) { 3978 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3979 3980 // If softenSetCCOperands returned a scalar, we need to compare the result 3981 // against zero to select between true and false values. 3982 if (!RHS.getNode()) { 3983 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3984 CC = ISD::SETNE; 3985 } 3986 } 3987 3988 // Also handle f16, for which we need to do a f32 comparison. 3989 if (LHS.getValueType() == MVT::f16) { 3990 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 3991 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 3992 } 3993 3994 // Next, handle integers. 3995 if (LHS.getValueType().isInteger()) { 3996 assert((LHS.getValueType() == RHS.getValueType()) && 3997 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3998 3999 unsigned Opcode = AArch64ISD::CSEL; 4000 4001 // If both the TVal and the FVal are constants, see if we can swap them in 4002 // order to for a CSINV or CSINC out of them. 4003 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4004 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4005 4006 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4007 std::swap(TVal, FVal); 4008 std::swap(CTVal, CFVal); 4009 CC = ISD::getSetCCInverse(CC, true); 4010 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4011 std::swap(TVal, FVal); 4012 std::swap(CTVal, CFVal); 4013 CC = ISD::getSetCCInverse(CC, true); 4014 } else if (TVal.getOpcode() == ISD::XOR) { 4015 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4016 // with a CSINV rather than a CSEL. 4017 if (isAllOnesConstant(TVal.getOperand(1))) { 4018 std::swap(TVal, FVal); 4019 std::swap(CTVal, CFVal); 4020 CC = ISD::getSetCCInverse(CC, true); 4021 } 4022 } else if (TVal.getOpcode() == ISD::SUB) { 4023 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4024 // that we can match with a CSNEG rather than a CSEL. 4025 if (isNullConstant(TVal.getOperand(0))) { 4026 std::swap(TVal, FVal); 4027 std::swap(CTVal, CFVal); 4028 CC = ISD::getSetCCInverse(CC, true); 4029 } 4030 } else if (CTVal && CFVal) { 4031 const int64_t TrueVal = CTVal->getSExtValue(); 4032 const int64_t FalseVal = CFVal->getSExtValue(); 4033 bool Swap = false; 4034 4035 // If both TVal and FVal are constants, see if FVal is the 4036 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4037 // instead of a CSEL in that case. 4038 if (TrueVal == ~FalseVal) { 4039 Opcode = AArch64ISD::CSINV; 4040 } else if (TrueVal == -FalseVal) { 4041 Opcode = AArch64ISD::CSNEG; 4042 } else if (TVal.getValueType() == MVT::i32) { 4043 // If our operands are only 32-bit wide, make sure we use 32-bit 4044 // arithmetic for the check whether we can use CSINC. This ensures that 4045 // the addition in the check will wrap around properly in case there is 4046 // an overflow (which would not be the case if we do the check with 4047 // 64-bit arithmetic). 4048 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4049 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4050 4051 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4052 Opcode = AArch64ISD::CSINC; 4053 4054 if (TrueVal32 > FalseVal32) { 4055 Swap = true; 4056 } 4057 } 4058 // 64-bit check whether we can use CSINC. 4059 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4060 Opcode = AArch64ISD::CSINC; 4061 4062 if (TrueVal > FalseVal) { 4063 Swap = true; 4064 } 4065 } 4066 4067 // Swap TVal and FVal if necessary. 4068 if (Swap) { 4069 std::swap(TVal, FVal); 4070 std::swap(CTVal, CFVal); 4071 CC = ISD::getSetCCInverse(CC, true); 4072 } 4073 4074 if (Opcode != AArch64ISD::CSEL) { 4075 // Drop FVal since we can get its value by simply inverting/negating 4076 // TVal. 4077 FVal = TVal; 4078 } 4079 } 4080 4081 SDValue CCVal; 4082 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4083 4084 EVT VT = TVal.getValueType(); 4085 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4086 } 4087 4088 // Now we know we're dealing with FP values. 4089 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4090 assert(LHS.getValueType() == RHS.getValueType()); 4091 EVT VT = TVal.getValueType(); 4092 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4093 4094 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4095 // clean. Some of them require two CSELs to implement. 4096 AArch64CC::CondCode CC1, CC2; 4097 changeFPCCToAArch64CC(CC, CC1, CC2); 4098 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4099 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4100 4101 // If we need a second CSEL, emit it, using the output of the first as the 4102 // RHS. We're effectively OR'ing the two CC's together. 4103 if (CC2 != AArch64CC::AL) { 4104 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4105 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4106 } 4107 4108 // Otherwise, return the output of the first CSEL. 4109 return CS1; 4110 } 4111 4112 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4113 SelectionDAG &DAG) const { 4114 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4115 SDValue LHS = Op.getOperand(0); 4116 SDValue RHS = Op.getOperand(1); 4117 SDValue TVal = Op.getOperand(2); 4118 SDValue FVal = Op.getOperand(3); 4119 SDLoc DL(Op); 4120 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4121 } 4122 4123 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4124 SelectionDAG &DAG) const { 4125 SDValue CCVal = Op->getOperand(0); 4126 SDValue TVal = Op->getOperand(1); 4127 SDValue FVal = Op->getOperand(2); 4128 SDLoc DL(Op); 4129 4130 unsigned Opc = CCVal.getOpcode(); 4131 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4132 // instruction. 4133 if (CCVal.getResNo() == 1 && 4134 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4135 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4136 // Only lower legal XALUO ops. 4137 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4138 return SDValue(); 4139 4140 AArch64CC::CondCode OFCC; 4141 SDValue Value, Overflow; 4142 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4143 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4144 4145 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4146 CCVal, Overflow); 4147 } 4148 4149 // Lower it the same way as we would lower a SELECT_CC node. 4150 ISD::CondCode CC; 4151 SDValue LHS, RHS; 4152 if (CCVal.getOpcode() == ISD::SETCC) { 4153 LHS = CCVal.getOperand(0); 4154 RHS = CCVal.getOperand(1); 4155 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4156 } else { 4157 LHS = CCVal; 4158 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4159 CC = ISD::SETNE; 4160 } 4161 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4162 } 4163 4164 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4165 SelectionDAG &DAG) const { 4166 // Jump table entries as PC relative offsets. No additional tweaking 4167 // is necessary here. Just get the address of the jump table. 4168 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4169 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4170 SDLoc DL(Op); 4171 4172 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4173 !Subtarget->isTargetMachO()) { 4174 const unsigned char MO_NC = AArch64II::MO_NC; 4175 return DAG.getNode( 4176 AArch64ISD::WrapperLarge, DL, PtrVT, 4177 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3), 4178 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC), 4179 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC), 4180 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4181 AArch64II::MO_G0 | MO_NC)); 4182 } 4183 4184 SDValue Hi = 4185 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE); 4186 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4187 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4188 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4189 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4190 } 4191 4192 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4193 SelectionDAG &DAG) const { 4194 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4195 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4196 SDLoc DL(Op); 4197 4198 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4199 // Use the GOT for the large code model on iOS. 4200 if (Subtarget->isTargetMachO()) { 4201 SDValue GotAddr = DAG.getTargetConstantPool( 4202 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4203 AArch64II::MO_GOT); 4204 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 4205 } 4206 4207 const unsigned char MO_NC = AArch64II::MO_NC; 4208 return DAG.getNode( 4209 AArch64ISD::WrapperLarge, DL, PtrVT, 4210 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4211 CP->getOffset(), AArch64II::MO_G3), 4212 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4213 CP->getOffset(), AArch64II::MO_G2 | MO_NC), 4214 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4215 CP->getOffset(), AArch64II::MO_G1 | MO_NC), 4216 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4217 CP->getOffset(), AArch64II::MO_G0 | MO_NC)); 4218 } else { 4219 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on 4220 // ELF, the only valid one on Darwin. 4221 SDValue Hi = 4222 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4223 CP->getOffset(), AArch64II::MO_PAGE); 4224 SDValue Lo = DAG.getTargetConstantPool( 4225 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4226 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4227 4228 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4229 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4230 } 4231 } 4232 4233 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4234 SelectionDAG &DAG) const { 4235 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 4236 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4237 SDLoc DL(Op); 4238 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4239 !Subtarget->isTargetMachO()) { 4240 const unsigned char MO_NC = AArch64II::MO_NC; 4241 return DAG.getNode( 4242 AArch64ISD::WrapperLarge, DL, PtrVT, 4243 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3), 4244 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 4245 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 4246 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 4247 } else { 4248 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE); 4249 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF | 4250 AArch64II::MO_NC); 4251 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4252 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4253 } 4254 } 4255 4256 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4257 SelectionDAG &DAG) const { 4258 AArch64FunctionInfo *FuncInfo = 4259 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4260 4261 SDLoc DL(Op); 4262 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4263 getPointerTy(DAG.getDataLayout())); 4264 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4265 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4266 MachinePointerInfo(SV), false, false, 0); 4267 } 4268 4269 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4270 SelectionDAG &DAG) const { 4271 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4272 // Standard, section B.3. 4273 MachineFunction &MF = DAG.getMachineFunction(); 4274 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4275 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4276 SDLoc DL(Op); 4277 4278 SDValue Chain = Op.getOperand(0); 4279 SDValue VAList = Op.getOperand(1); 4280 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4281 SmallVector<SDValue, 4> MemOps; 4282 4283 // void *__stack at offset 0 4284 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4285 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4286 MachinePointerInfo(SV), false, false, 8)); 4287 4288 // void *__gr_top at offset 8 4289 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4290 if (GPRSize > 0) { 4291 SDValue GRTop, GRTopAddr; 4292 4293 GRTopAddr = 4294 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4295 4296 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4297 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4298 DAG.getConstant(GPRSize, DL, PtrVT)); 4299 4300 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4301 MachinePointerInfo(SV, 8), false, false, 8)); 4302 } 4303 4304 // void *__vr_top at offset 16 4305 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4306 if (FPRSize > 0) { 4307 SDValue VRTop, VRTopAddr; 4308 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4309 DAG.getConstant(16, DL, PtrVT)); 4310 4311 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4312 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4313 DAG.getConstant(FPRSize, DL, PtrVT)); 4314 4315 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4316 MachinePointerInfo(SV, 16), false, false, 8)); 4317 } 4318 4319 // int __gr_offs at offset 24 4320 SDValue GROffsAddr = 4321 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4322 MemOps.push_back(DAG.getStore(Chain, DL, 4323 DAG.getConstant(-GPRSize, DL, MVT::i32), 4324 GROffsAddr, MachinePointerInfo(SV, 24), false, 4325 false, 4)); 4326 4327 // int __vr_offs at offset 28 4328 SDValue VROffsAddr = 4329 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4330 MemOps.push_back(DAG.getStore(Chain, DL, 4331 DAG.getConstant(-FPRSize, DL, MVT::i32), 4332 VROffsAddr, MachinePointerInfo(SV, 28), false, 4333 false, 4)); 4334 4335 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4336 } 4337 4338 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4339 SelectionDAG &DAG) const { 4340 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG) 4341 : LowerAAPCS_VASTART(Op, DAG); 4342 } 4343 4344 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4345 SelectionDAG &DAG) const { 4346 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4347 // pointer. 4348 SDLoc DL(Op); 4349 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32; 4350 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4351 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4352 4353 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4354 Op.getOperand(2), 4355 DAG.getConstant(VaListSize, DL, MVT::i32), 4356 8, false, false, false, MachinePointerInfo(DestSV), 4357 MachinePointerInfo(SrcSV)); 4358 } 4359 4360 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4361 assert(Subtarget->isTargetDarwin() && 4362 "automatic va_arg instruction only works on Darwin"); 4363 4364 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4365 EVT VT = Op.getValueType(); 4366 SDLoc DL(Op); 4367 SDValue Chain = Op.getOperand(0); 4368 SDValue Addr = Op.getOperand(1); 4369 unsigned Align = Op.getConstantOperandVal(3); 4370 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4371 4372 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V), 4373 false, false, false, 0); 4374 Chain = VAList.getValue(1); 4375 4376 if (Align > 8) { 4377 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4378 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4379 DAG.getConstant(Align - 1, DL, PtrVT)); 4380 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4381 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4382 } 4383 4384 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4385 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4386 4387 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4388 // up to 64 bits. At the very least, we have to increase the striding of the 4389 // vaargs list to match this, and for FP values we need to introduce 4390 // FP_ROUND nodes as well. 4391 if (VT.isInteger() && !VT.isVector()) 4392 ArgSize = 8; 4393 bool NeedFPTrunc = false; 4394 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4395 ArgSize = 8; 4396 NeedFPTrunc = true; 4397 } 4398 4399 // Increment the pointer, VAList, to the next vaarg 4400 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4401 DAG.getConstant(ArgSize, DL, PtrVT)); 4402 // Store the incremented VAList to the legalized pointer 4403 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V), 4404 false, false, 0); 4405 4406 // Load the actual argument out of the pointer VAList 4407 if (NeedFPTrunc) { 4408 // Load the value as an f64. 4409 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList, 4410 MachinePointerInfo(), false, false, false, 0); 4411 // Round the value down to an f32. 4412 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4413 DAG.getIntPtrConstant(1, DL)); 4414 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4415 // Merge the rounded value with the chain output of the load. 4416 return DAG.getMergeValues(Ops, DL); 4417 } 4418 4419 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false, 4420 false, false, 0); 4421 } 4422 4423 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4424 SelectionDAG &DAG) const { 4425 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4426 MFI->setFrameAddressIsTaken(true); 4427 4428 EVT VT = Op.getValueType(); 4429 SDLoc DL(Op); 4430 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4431 SDValue FrameAddr = 4432 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4433 while (Depth--) 4434 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4435 MachinePointerInfo(), false, false, false, 0); 4436 return FrameAddr; 4437 } 4438 4439 // FIXME? Maybe this could be a TableGen attribute on some registers and 4440 // this table could be generated automatically from RegInfo. 4441 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4442 SelectionDAG &DAG) const { 4443 unsigned Reg = StringSwitch<unsigned>(RegName) 4444 .Case("sp", AArch64::SP) 4445 .Default(0); 4446 if (Reg) 4447 return Reg; 4448 report_fatal_error(Twine("Invalid register name \"" 4449 + StringRef(RegName) + "\".")); 4450 } 4451 4452 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4453 SelectionDAG &DAG) const { 4454 MachineFunction &MF = DAG.getMachineFunction(); 4455 MachineFrameInfo *MFI = MF.getFrameInfo(); 4456 MFI->setReturnAddressIsTaken(true); 4457 4458 EVT VT = Op.getValueType(); 4459 SDLoc DL(Op); 4460 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4461 if (Depth) { 4462 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4463 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4464 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4465 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4466 MachinePointerInfo(), false, false, false, 0); 4467 } 4468 4469 // Return LR, which contains the return address. Mark it an implicit live-in. 4470 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4471 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4472 } 4473 4474 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4475 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4476 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4477 SelectionDAG &DAG) const { 4478 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4479 EVT VT = Op.getValueType(); 4480 unsigned VTBits = VT.getSizeInBits(); 4481 SDLoc dl(Op); 4482 SDValue ShOpLo = Op.getOperand(0); 4483 SDValue ShOpHi = Op.getOperand(1); 4484 SDValue ShAmt = Op.getOperand(2); 4485 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4486 4487 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4488 4489 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4490 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4491 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4492 4493 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4494 // is "undef". We wanted 0, so CSEL it directly. 4495 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4496 ISD::SETEQ, dl, DAG); 4497 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4498 HiBitsForLo = 4499 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4500 HiBitsForLo, CCVal, Cmp); 4501 4502 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4503 DAG.getConstant(VTBits, dl, MVT::i64)); 4504 4505 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4506 SDValue LoForNormalShift = 4507 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4508 4509 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4510 dl, DAG); 4511 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4512 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4513 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4514 LoForNormalShift, CCVal, Cmp); 4515 4516 // AArch64 shifts larger than the register width are wrapped rather than 4517 // clamped, so we can't just emit "hi >> x". 4518 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4519 SDValue HiForBigShift = 4520 Opc == ISD::SRA 4521 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4522 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4523 : DAG.getConstant(0, dl, VT); 4524 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4525 HiForNormalShift, CCVal, Cmp); 4526 4527 SDValue Ops[2] = { Lo, Hi }; 4528 return DAG.getMergeValues(Ops, dl); 4529 } 4530 4531 4532 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4533 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4534 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4535 SelectionDAG &DAG) const { 4536 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4537 EVT VT = Op.getValueType(); 4538 unsigned VTBits = VT.getSizeInBits(); 4539 SDLoc dl(Op); 4540 SDValue ShOpLo = Op.getOperand(0); 4541 SDValue ShOpHi = Op.getOperand(1); 4542 SDValue ShAmt = Op.getOperand(2); 4543 4544 assert(Op.getOpcode() == ISD::SHL_PARTS); 4545 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4546 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4547 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4548 4549 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4550 // is "undef". We wanted 0, so CSEL it directly. 4551 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4552 ISD::SETEQ, dl, DAG); 4553 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4554 LoBitsForHi = 4555 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4556 LoBitsForHi, CCVal, Cmp); 4557 4558 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4559 DAG.getConstant(VTBits, dl, MVT::i64)); 4560 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4561 SDValue HiForNormalShift = 4562 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4563 4564 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4565 4566 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4567 dl, DAG); 4568 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4569 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4570 HiForNormalShift, CCVal, Cmp); 4571 4572 // AArch64 shifts of larger than register sizes are wrapped rather than 4573 // clamped, so we can't just emit "lo << a" if a is too big. 4574 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4575 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4576 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4577 LoForNormalShift, CCVal, Cmp); 4578 4579 SDValue Ops[2] = { Lo, Hi }; 4580 return DAG.getMergeValues(Ops, dl); 4581 } 4582 4583 bool AArch64TargetLowering::isOffsetFoldingLegal( 4584 const GlobalAddressSDNode *GA) const { 4585 // The AArch64 target doesn't support folding offsets into global addresses. 4586 return false; 4587 } 4588 4589 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4590 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4591 // FIXME: We should be able to handle f128 as well with a clever lowering. 4592 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32)) 4593 return true; 4594 4595 if (VT == MVT::f64) 4596 return AArch64_AM::getFP64Imm(Imm) != -1; 4597 else if (VT == MVT::f32) 4598 return AArch64_AM::getFP32Imm(Imm) != -1; 4599 return false; 4600 } 4601 4602 //===----------------------------------------------------------------------===// 4603 // AArch64 Optimization Hooks 4604 //===----------------------------------------------------------------------===// 4605 4606 /// getEstimate - Return the appropriate estimate DAG for either the reciprocal 4607 /// or the reciprocal square root. 4608 static SDValue getEstimate(const AArch64Subtarget &ST, 4609 const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode, 4610 const SDValue &Operand, unsigned &ExtraSteps) { 4611 if (!ST.hasNEON()) 4612 return SDValue(); 4613 4614 EVT VT = Operand.getValueType(); 4615 4616 std::string RecipOp; 4617 RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt"; 4618 RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp; 4619 RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f"; 4620 4621 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals; 4622 if (!Recips.isEnabled(RecipOp)) 4623 return SDValue(); 4624 4625 ExtraSteps = Recips.getRefinementSteps(RecipOp); 4626 return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 4627 } 4628 4629 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 4630 DAGCombinerInfo &DCI, unsigned &ExtraSteps) const { 4631 return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps); 4632 } 4633 4634 SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand, 4635 DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const { 4636 UseOneConst = true; 4637 return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps); 4638 } 4639 4640 //===----------------------------------------------------------------------===// 4641 // AArch64 Inline Assembly Support 4642 //===----------------------------------------------------------------------===// 4643 4644 // Table of Constraints 4645 // TODO: This is the current set of constraints supported by ARM for the 4646 // compiler, not all of them may make sense, e.g. S may be difficult to support. 4647 // 4648 // r - A general register 4649 // w - An FP/SIMD register of some size in the range v0-v31 4650 // x - An FP/SIMD register of some size in the range v0-v15 4651 // I - Constant that can be used with an ADD instruction 4652 // J - Constant that can be used with a SUB instruction 4653 // K - Constant that can be used with a 32-bit logical instruction 4654 // L - Constant that can be used with a 64-bit logical instruction 4655 // M - Constant that can be used as a 32-bit MOV immediate 4656 // N - Constant that can be used as a 64-bit MOV immediate 4657 // Q - A memory reference with base register and no offset 4658 // S - A symbolic address 4659 // Y - Floating point constant zero 4660 // Z - Integer constant zero 4661 // 4662 // Note that general register operands will be output using their 64-bit x 4663 // register name, whatever the size of the variable, unless the asm operand 4664 // is prefixed by the %w modifier. Floating-point and SIMD register operands 4665 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 4666 // %q modifier. 4667 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4668 // At this point, we have to lower this constraint to something else, so we 4669 // lower it to an "r" or "w". However, by doing this we will force the result 4670 // to be in register, while the X constraint is much more permissive. 4671 // 4672 // Although we are correct (we are free to emit anything, without 4673 // constraints), we might break use cases that would expect us to be more 4674 // efficient and emit something else. 4675 if (!Subtarget->hasFPARMv8()) 4676 return "r"; 4677 4678 if (ConstraintVT.isFloatingPoint()) 4679 return "w"; 4680 4681 if (ConstraintVT.isVector() && 4682 (ConstraintVT.getSizeInBits() == 64 || 4683 ConstraintVT.getSizeInBits() == 128)) 4684 return "w"; 4685 4686 return "r"; 4687 } 4688 4689 /// getConstraintType - Given a constraint letter, return the type of 4690 /// constraint it is for this target. 4691 AArch64TargetLowering::ConstraintType 4692 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 4693 if (Constraint.size() == 1) { 4694 switch (Constraint[0]) { 4695 default: 4696 break; 4697 case 'z': 4698 return C_Other; 4699 case 'x': 4700 case 'w': 4701 return C_RegisterClass; 4702 // An address with a single base register. Due to the way we 4703 // currently handle addresses it is the same as 'r'. 4704 case 'Q': 4705 return C_Memory; 4706 } 4707 } 4708 return TargetLowering::getConstraintType(Constraint); 4709 } 4710 4711 /// Examine constraint type and operand type and determine a weight value. 4712 /// This object must already have been set up with the operand type 4713 /// and the current alternative constraint selected. 4714 TargetLowering::ConstraintWeight 4715 AArch64TargetLowering::getSingleConstraintMatchWeight( 4716 AsmOperandInfo &info, const char *constraint) const { 4717 ConstraintWeight weight = CW_Invalid; 4718 Value *CallOperandVal = info.CallOperandVal; 4719 // If we don't have a value, we can't do a match, 4720 // but allow it at the lowest weight. 4721 if (!CallOperandVal) 4722 return CW_Default; 4723 Type *type = CallOperandVal->getType(); 4724 // Look at the constraint type. 4725 switch (*constraint) { 4726 default: 4727 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 4728 break; 4729 case 'x': 4730 case 'w': 4731 if (type->isFloatingPointTy() || type->isVectorTy()) 4732 weight = CW_Register; 4733 break; 4734 case 'z': 4735 weight = CW_Constant; 4736 break; 4737 } 4738 return weight; 4739 } 4740 4741 std::pair<unsigned, const TargetRegisterClass *> 4742 AArch64TargetLowering::getRegForInlineAsmConstraint( 4743 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 4744 if (Constraint.size() == 1) { 4745 switch (Constraint[0]) { 4746 case 'r': 4747 if (VT.getSizeInBits() == 64) 4748 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 4749 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 4750 case 'w': 4751 if (VT == MVT::f32) 4752 return std::make_pair(0U, &AArch64::FPR32RegClass); 4753 if (VT.getSizeInBits() == 64) 4754 return std::make_pair(0U, &AArch64::FPR64RegClass); 4755 if (VT.getSizeInBits() == 128) 4756 return std::make_pair(0U, &AArch64::FPR128RegClass); 4757 break; 4758 // The instructions that this constraint is designed for can 4759 // only take 128-bit registers so just use that regclass. 4760 case 'x': 4761 if (VT.getSizeInBits() == 128) 4762 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 4763 break; 4764 } 4765 } 4766 if (StringRef("{cc}").equals_lower(Constraint)) 4767 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 4768 4769 // Use the default implementation in TargetLowering to convert the register 4770 // constraint into a member of a register class. 4771 std::pair<unsigned, const TargetRegisterClass *> Res; 4772 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4773 4774 // Not found as a standard register? 4775 if (!Res.second) { 4776 unsigned Size = Constraint.size(); 4777 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 4778 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 4779 int RegNo; 4780 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 4781 if (!Failed && RegNo >= 0 && RegNo <= 31) { 4782 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 4783 // By default we'll emit v0-v31 for this unless there's a modifier where 4784 // we'll emit the correct register as well. 4785 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 4786 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 4787 Res.second = &AArch64::FPR64RegClass; 4788 } else { 4789 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 4790 Res.second = &AArch64::FPR128RegClass; 4791 } 4792 } 4793 } 4794 } 4795 4796 return Res; 4797 } 4798 4799 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 4800 /// vector. If it is invalid, don't add anything to Ops. 4801 void AArch64TargetLowering::LowerAsmOperandForConstraint( 4802 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 4803 SelectionDAG &DAG) const { 4804 SDValue Result; 4805 4806 // Currently only support length 1 constraints. 4807 if (Constraint.length() != 1) 4808 return; 4809 4810 char ConstraintLetter = Constraint[0]; 4811 switch (ConstraintLetter) { 4812 default: 4813 break; 4814 4815 // This set of constraints deal with valid constants for various instructions. 4816 // Validate and return a target constant for them if we can. 4817 case 'z': { 4818 // 'z' maps to xzr or wzr so it needs an input of 0. 4819 if (!isNullConstant(Op)) 4820 return; 4821 4822 if (Op.getValueType() == MVT::i64) 4823 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 4824 else 4825 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 4826 break; 4827 } 4828 4829 case 'I': 4830 case 'J': 4831 case 'K': 4832 case 'L': 4833 case 'M': 4834 case 'N': 4835 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4836 if (!C) 4837 return; 4838 4839 // Grab the value and do some validation. 4840 uint64_t CVal = C->getZExtValue(); 4841 switch (ConstraintLetter) { 4842 // The I constraint applies only to simple ADD or SUB immediate operands: 4843 // i.e. 0 to 4095 with optional shift by 12 4844 // The J constraint applies only to ADD or SUB immediates that would be 4845 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 4846 // instruction [or vice versa], in other words -1 to -4095 with optional 4847 // left shift by 12. 4848 case 'I': 4849 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 4850 break; 4851 return; 4852 case 'J': { 4853 uint64_t NVal = -C->getSExtValue(); 4854 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 4855 CVal = C->getSExtValue(); 4856 break; 4857 } 4858 return; 4859 } 4860 // The K and L constraints apply *only* to logical immediates, including 4861 // what used to be the MOVI alias for ORR (though the MOVI alias has now 4862 // been removed and MOV should be used). So these constraints have to 4863 // distinguish between bit patterns that are valid 32-bit or 64-bit 4864 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 4865 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 4866 // versa. 4867 case 'K': 4868 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4869 break; 4870 return; 4871 case 'L': 4872 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4873 break; 4874 return; 4875 // The M and N constraints are a superset of K and L respectively, for use 4876 // with the MOV (immediate) alias. As well as the logical immediates they 4877 // also match 32 or 64-bit immediates that can be loaded either using a 4878 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 4879 // (M) or 64-bit 0x1234000000000000 (N) etc. 4880 // As a note some of this code is liberally stolen from the asm parser. 4881 case 'M': { 4882 if (!isUInt<32>(CVal)) 4883 return; 4884 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4885 break; 4886 if ((CVal & 0xFFFF) == CVal) 4887 break; 4888 if ((CVal & 0xFFFF0000ULL) == CVal) 4889 break; 4890 uint64_t NCVal = ~(uint32_t)CVal; 4891 if ((NCVal & 0xFFFFULL) == NCVal) 4892 break; 4893 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4894 break; 4895 return; 4896 } 4897 case 'N': { 4898 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4899 break; 4900 if ((CVal & 0xFFFFULL) == CVal) 4901 break; 4902 if ((CVal & 0xFFFF0000ULL) == CVal) 4903 break; 4904 if ((CVal & 0xFFFF00000000ULL) == CVal) 4905 break; 4906 if ((CVal & 0xFFFF000000000000ULL) == CVal) 4907 break; 4908 uint64_t NCVal = ~CVal; 4909 if ((NCVal & 0xFFFFULL) == NCVal) 4910 break; 4911 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4912 break; 4913 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 4914 break; 4915 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 4916 break; 4917 return; 4918 } 4919 default: 4920 return; 4921 } 4922 4923 // All assembler immediates are 64-bit integers. 4924 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 4925 break; 4926 } 4927 4928 if (Result.getNode()) { 4929 Ops.push_back(Result); 4930 return; 4931 } 4932 4933 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 4934 } 4935 4936 //===----------------------------------------------------------------------===// 4937 // AArch64 Advanced SIMD Support 4938 //===----------------------------------------------------------------------===// 4939 4940 /// WidenVector - Given a value in the V64 register class, produce the 4941 /// equivalent value in the V128 register class. 4942 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 4943 EVT VT = V64Reg.getValueType(); 4944 unsigned NarrowSize = VT.getVectorNumElements(); 4945 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 4946 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 4947 SDLoc DL(V64Reg); 4948 4949 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 4950 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 4951 } 4952 4953 /// getExtFactor - Determine the adjustment factor for the position when 4954 /// generating an "extract from vector registers" instruction. 4955 static unsigned getExtFactor(SDValue &V) { 4956 EVT EltType = V.getValueType().getVectorElementType(); 4957 return EltType.getSizeInBits() / 8; 4958 } 4959 4960 /// NarrowVector - Given a value in the V128 register class, produce the 4961 /// equivalent value in the V64 register class. 4962 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 4963 EVT VT = V128Reg.getValueType(); 4964 unsigned WideSize = VT.getVectorNumElements(); 4965 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 4966 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 4967 SDLoc DL(V128Reg); 4968 4969 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 4970 } 4971 4972 // Gather data to see if the operation can be modelled as a 4973 // shuffle in combination with VEXTs. 4974 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 4975 SelectionDAG &DAG) const { 4976 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 4977 SDLoc dl(Op); 4978 EVT VT = Op.getValueType(); 4979 unsigned NumElts = VT.getVectorNumElements(); 4980 4981 struct ShuffleSourceInfo { 4982 SDValue Vec; 4983 unsigned MinElt; 4984 unsigned MaxElt; 4985 4986 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 4987 // be compatible with the shuffle we intend to construct. As a result 4988 // ShuffleVec will be some sliding window into the original Vec. 4989 SDValue ShuffleVec; 4990 4991 // Code should guarantee that element i in Vec starts at element "WindowBase 4992 // + i * WindowScale in ShuffleVec". 4993 int WindowBase; 4994 int WindowScale; 4995 4996 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 4997 ShuffleSourceInfo(SDValue Vec) 4998 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 4999 WindowScale(1) {} 5000 }; 5001 5002 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5003 // node. 5004 SmallVector<ShuffleSourceInfo, 2> Sources; 5005 for (unsigned i = 0; i < NumElts; ++i) { 5006 SDValue V = Op.getOperand(i); 5007 if (V.isUndef()) 5008 continue; 5009 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5010 !isa<ConstantSDNode>(V.getOperand(1))) { 5011 // A shuffle can only come from building a vector from various 5012 // elements of other vectors, provided their indices are constant. 5013 return SDValue(); 5014 } 5015 5016 // Add this element source to the list if it's not already there. 5017 SDValue SourceVec = V.getOperand(0); 5018 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec); 5019 if (Source == Sources.end()) 5020 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5021 5022 // Update the minimum and maximum lane number seen. 5023 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5024 Source->MinElt = std::min(Source->MinElt, EltNo); 5025 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5026 } 5027 5028 // Currently only do something sane when at most two source vectors 5029 // are involved. 5030 if (Sources.size() > 2) 5031 return SDValue(); 5032 5033 // Find out the smallest element size among result and two sources, and use 5034 // it as element size to build the shuffle_vector. 5035 EVT SmallestEltTy = VT.getVectorElementType(); 5036 for (auto &Source : Sources) { 5037 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5038 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5039 SmallestEltTy = SrcEltTy; 5040 } 5041 } 5042 unsigned ResMultiplier = 5043 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits(); 5044 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5045 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5046 5047 // If the source vector is too wide or too narrow, we may nevertheless be able 5048 // to construct a compatible shuffle either by concatenating it with UNDEF or 5049 // extracting a suitable range of elements. 5050 for (auto &Src : Sources) { 5051 EVT SrcVT = Src.ShuffleVec.getValueType(); 5052 5053 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5054 continue; 5055 5056 // This stage of the search produces a source with the same element type as 5057 // the original, but with a total width matching the BUILD_VECTOR output. 5058 EVT EltVT = SrcVT.getVectorElementType(); 5059 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5060 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5061 5062 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5063 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5064 // We can pad out the smaller vector for free, so if it's part of a 5065 // shuffle... 5066 Src.ShuffleVec = 5067 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5068 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5069 continue; 5070 } 5071 5072 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5073 5074 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5075 // Span too large for a VEXT to cope 5076 return SDValue(); 5077 } 5078 5079 if (Src.MinElt >= NumSrcElts) { 5080 // The extraction can just take the second half 5081 Src.ShuffleVec = 5082 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5083 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5084 Src.WindowBase = -NumSrcElts; 5085 } else if (Src.MaxElt < NumSrcElts) { 5086 // The extraction can just take the first half 5087 Src.ShuffleVec = 5088 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5089 DAG.getConstant(0, dl, MVT::i64)); 5090 } else { 5091 // An actual VEXT is needed 5092 SDValue VEXTSrc1 = 5093 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5094 DAG.getConstant(0, dl, MVT::i64)); 5095 SDValue VEXTSrc2 = 5096 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5097 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5098 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5099 5100 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5101 VEXTSrc2, 5102 DAG.getConstant(Imm, dl, MVT::i32)); 5103 Src.WindowBase = -Src.MinElt; 5104 } 5105 } 5106 5107 // Another possible incompatibility occurs from the vector element types. We 5108 // can fix this by bitcasting the source vectors to the same type we intend 5109 // for the shuffle. 5110 for (auto &Src : Sources) { 5111 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5112 if (SrcEltTy == SmallestEltTy) 5113 continue; 5114 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5115 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5116 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5117 Src.WindowBase *= Src.WindowScale; 5118 } 5119 5120 // Final sanity check before we try to actually produce a shuffle. 5121 DEBUG( 5122 for (auto Src : Sources) 5123 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5124 ); 5125 5126 // The stars all align, our next step is to produce the mask for the shuffle. 5127 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5128 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits(); 5129 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5130 SDValue Entry = Op.getOperand(i); 5131 if (Entry.isUndef()) 5132 continue; 5133 5134 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0)); 5135 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5136 5137 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5138 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5139 // segment. 5140 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5141 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 5142 VT.getVectorElementType().getSizeInBits()); 5143 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5144 5145 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5146 // starting at the appropriate offset. 5147 int *LaneMask = &Mask[i * ResMultiplier]; 5148 5149 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5150 ExtractBase += NumElts * (Src - Sources.begin()); 5151 for (int j = 0; j < LanesDefined; ++j) 5152 LaneMask[j] = ExtractBase + j; 5153 } 5154 5155 // Final check before we try to produce nonsense... 5156 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5157 return SDValue(); 5158 5159 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5160 for (unsigned i = 0; i < Sources.size(); ++i) 5161 ShuffleOps[i] = Sources[i].ShuffleVec; 5162 5163 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5164 ShuffleOps[1], &Mask[0]); 5165 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5166 } 5167 5168 // check if an EXT instruction can handle the shuffle mask when the 5169 // vector sources of the shuffle are the same. 5170 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5171 unsigned NumElts = VT.getVectorNumElements(); 5172 5173 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5174 if (M[0] < 0) 5175 return false; 5176 5177 Imm = M[0]; 5178 5179 // If this is a VEXT shuffle, the immediate value is the index of the first 5180 // element. The other shuffle indices must be the successive elements after 5181 // the first one. 5182 unsigned ExpectedElt = Imm; 5183 for (unsigned i = 1; i < NumElts; ++i) { 5184 // Increment the expected index. If it wraps around, just follow it 5185 // back to index zero and keep going. 5186 ++ExpectedElt; 5187 if (ExpectedElt == NumElts) 5188 ExpectedElt = 0; 5189 5190 if (M[i] < 0) 5191 continue; // ignore UNDEF indices 5192 if (ExpectedElt != static_cast<unsigned>(M[i])) 5193 return false; 5194 } 5195 5196 return true; 5197 } 5198 5199 // check if an EXT instruction can handle the shuffle mask when the 5200 // vector sources of the shuffle are different. 5201 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5202 unsigned &Imm) { 5203 // Look for the first non-undef element. 5204 const int *FirstRealElt = std::find_if(M.begin(), M.end(), 5205 [](int Elt) {return Elt >= 0;}); 5206 5207 // Benefit form APInt to handle overflow when calculating expected element. 5208 unsigned NumElts = VT.getVectorNumElements(); 5209 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5210 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5211 // The following shuffle indices must be the successive elements after the 5212 // first real element. 5213 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5214 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5215 if (FirstWrongElt != M.end()) 5216 return false; 5217 5218 // The index of an EXT is the first element if it is not UNDEF. 5219 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5220 // value of the first element. E.g. 5221 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5222 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5223 // ExpectedElt is the last mask index plus 1. 5224 Imm = ExpectedElt.getZExtValue(); 5225 5226 // There are two difference cases requiring to reverse input vectors. 5227 // For example, for vector <4 x i32> we have the following cases, 5228 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5229 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5230 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5231 // to reverse two input vectors. 5232 if (Imm < NumElts) 5233 ReverseEXT = true; 5234 else 5235 Imm -= NumElts; 5236 5237 return true; 5238 } 5239 5240 /// isREVMask - Check if a vector shuffle corresponds to a REV 5241 /// instruction with the specified blocksize. (The order of the elements 5242 /// within each block of the vector is reversed.) 5243 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5244 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5245 "Only possible block sizes for REV are: 16, 32, 64"); 5246 5247 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 5248 if (EltSz == 64) 5249 return false; 5250 5251 unsigned NumElts = VT.getVectorNumElements(); 5252 unsigned BlockElts = M[0] + 1; 5253 // If the first shuffle index is UNDEF, be optimistic. 5254 if (M[0] < 0) 5255 BlockElts = BlockSize / EltSz; 5256 5257 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5258 return false; 5259 5260 for (unsigned i = 0; i < NumElts; ++i) { 5261 if (M[i] < 0) 5262 continue; // ignore UNDEF indices 5263 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5264 return false; 5265 } 5266 5267 return true; 5268 } 5269 5270 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5271 unsigned NumElts = VT.getVectorNumElements(); 5272 WhichResult = (M[0] == 0 ? 0 : 1); 5273 unsigned Idx = WhichResult * NumElts / 2; 5274 for (unsigned i = 0; i != NumElts; i += 2) { 5275 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5276 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5277 return false; 5278 Idx += 1; 5279 } 5280 5281 return true; 5282 } 5283 5284 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5285 unsigned NumElts = VT.getVectorNumElements(); 5286 WhichResult = (M[0] == 0 ? 0 : 1); 5287 for (unsigned i = 0; i != NumElts; ++i) { 5288 if (M[i] < 0) 5289 continue; // ignore UNDEF indices 5290 if ((unsigned)M[i] != 2 * i + WhichResult) 5291 return false; 5292 } 5293 5294 return true; 5295 } 5296 5297 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5298 unsigned NumElts = VT.getVectorNumElements(); 5299 WhichResult = (M[0] == 0 ? 0 : 1); 5300 for (unsigned i = 0; i < NumElts; i += 2) { 5301 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5302 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5303 return false; 5304 } 5305 return true; 5306 } 5307 5308 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5309 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5310 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5311 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5312 unsigned NumElts = VT.getVectorNumElements(); 5313 WhichResult = (M[0] == 0 ? 0 : 1); 5314 unsigned Idx = WhichResult * NumElts / 2; 5315 for (unsigned i = 0; i != NumElts; i += 2) { 5316 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5317 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5318 return false; 5319 Idx += 1; 5320 } 5321 5322 return true; 5323 } 5324 5325 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5326 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5327 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5328 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5329 unsigned Half = VT.getVectorNumElements() / 2; 5330 WhichResult = (M[0] == 0 ? 0 : 1); 5331 for (unsigned j = 0; j != 2; ++j) { 5332 unsigned Idx = WhichResult; 5333 for (unsigned i = 0; i != Half; ++i) { 5334 int MIdx = M[i + j * Half]; 5335 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5336 return false; 5337 Idx += 2; 5338 } 5339 } 5340 5341 return true; 5342 } 5343 5344 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5345 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5346 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5347 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5348 unsigned NumElts = VT.getVectorNumElements(); 5349 WhichResult = (M[0] == 0 ? 0 : 1); 5350 for (unsigned i = 0; i < NumElts; i += 2) { 5351 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5352 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5353 return false; 5354 } 5355 return true; 5356 } 5357 5358 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5359 bool &DstIsLeft, int &Anomaly) { 5360 if (M.size() != static_cast<size_t>(NumInputElements)) 5361 return false; 5362 5363 int NumLHSMatch = 0, NumRHSMatch = 0; 5364 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5365 5366 for (int i = 0; i < NumInputElements; ++i) { 5367 if (M[i] == -1) { 5368 ++NumLHSMatch; 5369 ++NumRHSMatch; 5370 continue; 5371 } 5372 5373 if (M[i] == i) 5374 ++NumLHSMatch; 5375 else 5376 LastLHSMismatch = i; 5377 5378 if (M[i] == i + NumInputElements) 5379 ++NumRHSMatch; 5380 else 5381 LastRHSMismatch = i; 5382 } 5383 5384 if (NumLHSMatch == NumInputElements - 1) { 5385 DstIsLeft = true; 5386 Anomaly = LastLHSMismatch; 5387 return true; 5388 } else if (NumRHSMatch == NumInputElements - 1) { 5389 DstIsLeft = false; 5390 Anomaly = LastRHSMismatch; 5391 return true; 5392 } 5393 5394 return false; 5395 } 5396 5397 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5398 if (VT.getSizeInBits() != 128) 5399 return false; 5400 5401 unsigned NumElts = VT.getVectorNumElements(); 5402 5403 for (int I = 0, E = NumElts / 2; I != E; I++) { 5404 if (Mask[I] != I) 5405 return false; 5406 } 5407 5408 int Offset = NumElts / 2; 5409 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5410 if (Mask[I] != I + SplitLHS * Offset) 5411 return false; 5412 } 5413 5414 return true; 5415 } 5416 5417 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5418 SDLoc DL(Op); 5419 EVT VT = Op.getValueType(); 5420 SDValue V0 = Op.getOperand(0); 5421 SDValue V1 = Op.getOperand(1); 5422 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5423 5424 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5425 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5426 return SDValue(); 5427 5428 bool SplitV0 = V0.getValueType().getSizeInBits() == 128; 5429 5430 if (!isConcatMask(Mask, VT, SplitV0)) 5431 return SDValue(); 5432 5433 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5434 VT.getVectorNumElements() / 2); 5435 if (SplitV0) { 5436 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5437 DAG.getConstant(0, DL, MVT::i64)); 5438 } 5439 if (V1.getValueType().getSizeInBits() == 128) { 5440 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5441 DAG.getConstant(0, DL, MVT::i64)); 5442 } 5443 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5444 } 5445 5446 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5447 /// the specified operations to build the shuffle. 5448 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5449 SDValue RHS, SelectionDAG &DAG, 5450 const SDLoc &dl) { 5451 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5452 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5453 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5454 5455 enum { 5456 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5457 OP_VREV, 5458 OP_VDUP0, 5459 OP_VDUP1, 5460 OP_VDUP2, 5461 OP_VDUP3, 5462 OP_VEXT1, 5463 OP_VEXT2, 5464 OP_VEXT3, 5465 OP_VUZPL, // VUZP, left result 5466 OP_VUZPR, // VUZP, right result 5467 OP_VZIPL, // VZIP, left result 5468 OP_VZIPR, // VZIP, right result 5469 OP_VTRNL, // VTRN, left result 5470 OP_VTRNR // VTRN, right result 5471 }; 5472 5473 if (OpNum == OP_COPY) { 5474 if (LHSID == (1 * 9 + 2) * 9 + 3) 5475 return LHS; 5476 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5477 return RHS; 5478 } 5479 5480 SDValue OpLHS, OpRHS; 5481 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5482 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5483 EVT VT = OpLHS.getValueType(); 5484 5485 switch (OpNum) { 5486 default: 5487 llvm_unreachable("Unknown shuffle opcode!"); 5488 case OP_VREV: 5489 // VREV divides the vector in half and swaps within the half. 5490 if (VT.getVectorElementType() == MVT::i32 || 5491 VT.getVectorElementType() == MVT::f32) 5492 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5493 // vrev <4 x i16> -> REV32 5494 if (VT.getVectorElementType() == MVT::i16 || 5495 VT.getVectorElementType() == MVT::f16) 5496 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5497 // vrev <4 x i8> -> REV16 5498 assert(VT.getVectorElementType() == MVT::i8); 5499 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5500 case OP_VDUP0: 5501 case OP_VDUP1: 5502 case OP_VDUP2: 5503 case OP_VDUP3: { 5504 EVT EltTy = VT.getVectorElementType(); 5505 unsigned Opcode; 5506 if (EltTy == MVT::i8) 5507 Opcode = AArch64ISD::DUPLANE8; 5508 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5509 Opcode = AArch64ISD::DUPLANE16; 5510 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5511 Opcode = AArch64ISD::DUPLANE32; 5512 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5513 Opcode = AArch64ISD::DUPLANE64; 5514 else 5515 llvm_unreachable("Invalid vector element type?"); 5516 5517 if (VT.getSizeInBits() == 64) 5518 OpLHS = WidenVector(OpLHS, DAG); 5519 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5520 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5521 } 5522 case OP_VEXT1: 5523 case OP_VEXT2: 5524 case OP_VEXT3: { 5525 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5526 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5527 DAG.getConstant(Imm, dl, MVT::i32)); 5528 } 5529 case OP_VUZPL: 5530 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5531 OpRHS); 5532 case OP_VUZPR: 5533 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5534 OpRHS); 5535 case OP_VZIPL: 5536 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5537 OpRHS); 5538 case OP_VZIPR: 5539 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5540 OpRHS); 5541 case OP_VTRNL: 5542 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5543 OpRHS); 5544 case OP_VTRNR: 5545 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5546 OpRHS); 5547 } 5548 } 5549 5550 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5551 SelectionDAG &DAG) { 5552 // Check to see if we can use the TBL instruction. 5553 SDValue V1 = Op.getOperand(0); 5554 SDValue V2 = Op.getOperand(1); 5555 SDLoc DL(Op); 5556 5557 EVT EltVT = Op.getValueType().getVectorElementType(); 5558 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5559 5560 SmallVector<SDValue, 8> TBLMask; 5561 for (int Val : ShuffleMask) { 5562 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 5563 unsigned Offset = Byte + Val * BytesPerElt; 5564 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 5565 } 5566 } 5567 5568 MVT IndexVT = MVT::v8i8; 5569 unsigned IndexLen = 8; 5570 if (Op.getValueType().getSizeInBits() == 128) { 5571 IndexVT = MVT::v16i8; 5572 IndexLen = 16; 5573 } 5574 5575 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 5576 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 5577 5578 SDValue Shuffle; 5579 if (V2.getNode()->isUndef()) { 5580 if (IndexLen == 8) 5581 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 5582 Shuffle = DAG.getNode( 5583 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5584 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5585 DAG.getBuildVector(IndexVT, DL, 5586 makeArrayRef(TBLMask.data(), IndexLen))); 5587 } else { 5588 if (IndexLen == 8) { 5589 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 5590 Shuffle = DAG.getNode( 5591 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5592 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5593 DAG.getBuildVector(IndexVT, DL, 5594 makeArrayRef(TBLMask.data(), IndexLen))); 5595 } else { 5596 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 5597 // cannot currently represent the register constraints on the input 5598 // table registers. 5599 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 5600 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 5601 // IndexLen)); 5602 Shuffle = DAG.getNode( 5603 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5604 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 5605 V2Cst, DAG.getBuildVector(IndexVT, DL, 5606 makeArrayRef(TBLMask.data(), IndexLen))); 5607 } 5608 } 5609 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 5610 } 5611 5612 static unsigned getDUPLANEOp(EVT EltType) { 5613 if (EltType == MVT::i8) 5614 return AArch64ISD::DUPLANE8; 5615 if (EltType == MVT::i16 || EltType == MVT::f16) 5616 return AArch64ISD::DUPLANE16; 5617 if (EltType == MVT::i32 || EltType == MVT::f32) 5618 return AArch64ISD::DUPLANE32; 5619 if (EltType == MVT::i64 || EltType == MVT::f64) 5620 return AArch64ISD::DUPLANE64; 5621 5622 llvm_unreachable("Invalid vector element type?"); 5623 } 5624 5625 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 5626 SelectionDAG &DAG) const { 5627 SDLoc dl(Op); 5628 EVT VT = Op.getValueType(); 5629 5630 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5631 5632 // Convert shuffles that are directly supported on NEON to target-specific 5633 // DAG nodes, instead of keeping them as shuffles and matching them again 5634 // during code selection. This is more efficient and avoids the possibility 5635 // of inconsistencies between legalization and selection. 5636 ArrayRef<int> ShuffleMask = SVN->getMask(); 5637 5638 SDValue V1 = Op.getOperand(0); 5639 SDValue V2 = Op.getOperand(1); 5640 5641 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], 5642 V1.getValueType().getSimpleVT())) { 5643 int Lane = SVN->getSplatIndex(); 5644 // If this is undef splat, generate it via "just" vdup, if possible. 5645 if (Lane == -1) 5646 Lane = 0; 5647 5648 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 5649 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 5650 V1.getOperand(0)); 5651 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 5652 // constant. If so, we can just reference the lane's definition directly. 5653 if (V1.getOpcode() == ISD::BUILD_VECTOR && 5654 !isa<ConstantSDNode>(V1.getOperand(Lane))) 5655 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 5656 5657 // Otherwise, duplicate from the lane of the input vector. 5658 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 5659 5660 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 5661 // to make a vector of the same size as this SHUFFLE. We can ignore the 5662 // extract entirely, and canonicalise the concat using WidenVector. 5663 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 5664 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 5665 V1 = V1.getOperand(0); 5666 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 5667 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 5668 Lane -= Idx * VT.getVectorNumElements() / 2; 5669 V1 = WidenVector(V1.getOperand(Idx), DAG); 5670 } else if (VT.getSizeInBits() == 64) 5671 V1 = WidenVector(V1, DAG); 5672 5673 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 5674 } 5675 5676 if (isREVMask(ShuffleMask, VT, 64)) 5677 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 5678 if (isREVMask(ShuffleMask, VT, 32)) 5679 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 5680 if (isREVMask(ShuffleMask, VT, 16)) 5681 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 5682 5683 bool ReverseEXT = false; 5684 unsigned Imm; 5685 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 5686 if (ReverseEXT) 5687 std::swap(V1, V2); 5688 Imm *= getExtFactor(V1); 5689 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 5690 DAG.getConstant(Imm, dl, MVT::i32)); 5691 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 5692 Imm *= getExtFactor(V1); 5693 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 5694 DAG.getConstant(Imm, dl, MVT::i32)); 5695 } 5696 5697 unsigned WhichResult; 5698 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 5699 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5700 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5701 } 5702 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 5703 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5704 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5705 } 5706 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 5707 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5708 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5709 } 5710 5711 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5712 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5713 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5714 } 5715 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5716 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5717 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5718 } 5719 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5720 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5721 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5722 } 5723 5724 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 5725 return Concat; 5726 5727 bool DstIsLeft; 5728 int Anomaly; 5729 int NumInputElements = V1.getValueType().getVectorNumElements(); 5730 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 5731 SDValue DstVec = DstIsLeft ? V1 : V2; 5732 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 5733 5734 SDValue SrcVec = V1; 5735 int SrcLane = ShuffleMask[Anomaly]; 5736 if (SrcLane >= NumInputElements) { 5737 SrcVec = V2; 5738 SrcLane -= VT.getVectorNumElements(); 5739 } 5740 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 5741 5742 EVT ScalarVT = VT.getVectorElementType(); 5743 5744 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 5745 ScalarVT = MVT::i32; 5746 5747 return DAG.getNode( 5748 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 5749 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 5750 DstLaneV); 5751 } 5752 5753 // If the shuffle is not directly supported and it has 4 elements, use 5754 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5755 unsigned NumElts = VT.getVectorNumElements(); 5756 if (NumElts == 4) { 5757 unsigned PFIndexes[4]; 5758 for (unsigned i = 0; i != 4; ++i) { 5759 if (ShuffleMask[i] < 0) 5760 PFIndexes[i] = 8; 5761 else 5762 PFIndexes[i] = ShuffleMask[i]; 5763 } 5764 5765 // Compute the index in the perfect shuffle table. 5766 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 5767 PFIndexes[2] * 9 + PFIndexes[3]; 5768 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5769 unsigned Cost = (PFEntry >> 30); 5770 5771 if (Cost <= 4) 5772 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5773 } 5774 5775 return GenerateTBL(Op, ShuffleMask, DAG); 5776 } 5777 5778 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 5779 APInt &UndefBits) { 5780 EVT VT = BVN->getValueType(0); 5781 APInt SplatBits, SplatUndef; 5782 unsigned SplatBitSize; 5783 bool HasAnyUndefs; 5784 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5785 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 5786 5787 for (unsigned i = 0; i < NumSplats; ++i) { 5788 CnstBits <<= SplatBitSize; 5789 UndefBits <<= SplatBitSize; 5790 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 5791 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 5792 } 5793 5794 return true; 5795 } 5796 5797 return false; 5798 } 5799 5800 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 5801 SelectionDAG &DAG) const { 5802 BuildVectorSDNode *BVN = 5803 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 5804 SDValue LHS = Op.getOperand(0); 5805 SDLoc dl(Op); 5806 EVT VT = Op.getValueType(); 5807 5808 if (!BVN) 5809 return Op; 5810 5811 APInt CnstBits(VT.getSizeInBits(), 0); 5812 APInt UndefBits(VT.getSizeInBits(), 0); 5813 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 5814 // We only have BIC vector immediate instruction, which is and-not. 5815 CnstBits = ~CnstBits; 5816 5817 // We make use of a little bit of goto ickiness in order to avoid having to 5818 // duplicate the immediate matching logic for the undef toggled case. 5819 bool SecondTry = false; 5820 AttemptModImm: 5821 5822 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 5823 CnstBits = CnstBits.zextOrTrunc(64); 5824 uint64_t CnstVal = CnstBits.getZExtValue(); 5825 5826 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 5827 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 5828 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5829 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5830 DAG.getConstant(CnstVal, dl, MVT::i32), 5831 DAG.getConstant(0, dl, MVT::i32)); 5832 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5833 } 5834 5835 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 5836 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 5837 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5838 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5839 DAG.getConstant(CnstVal, dl, MVT::i32), 5840 DAG.getConstant(8, dl, MVT::i32)); 5841 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5842 } 5843 5844 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 5845 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 5846 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5847 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5848 DAG.getConstant(CnstVal, dl, MVT::i32), 5849 DAG.getConstant(16, dl, MVT::i32)); 5850 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5851 } 5852 5853 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 5854 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 5855 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5856 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5857 DAG.getConstant(CnstVal, dl, MVT::i32), 5858 DAG.getConstant(24, dl, MVT::i32)); 5859 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5860 } 5861 5862 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 5863 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 5864 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5865 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5866 DAG.getConstant(CnstVal, dl, MVT::i32), 5867 DAG.getConstant(0, dl, MVT::i32)); 5868 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5869 } 5870 5871 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 5872 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 5873 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5874 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5875 DAG.getConstant(CnstVal, dl, MVT::i32), 5876 DAG.getConstant(8, dl, MVT::i32)); 5877 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5878 } 5879 } 5880 5881 if (SecondTry) 5882 goto FailedModImm; 5883 SecondTry = true; 5884 CnstBits = ~UndefBits; 5885 goto AttemptModImm; 5886 } 5887 5888 // We can always fall back to a non-immediate AND. 5889 FailedModImm: 5890 return Op; 5891 } 5892 5893 // Specialized code to quickly find if PotentialBVec is a BuildVector that 5894 // consists of only the same constant int value, returned in reference arg 5895 // ConstVal 5896 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 5897 uint64_t &ConstVal) { 5898 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 5899 if (!Bvec) 5900 return false; 5901 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 5902 if (!FirstElt) 5903 return false; 5904 EVT VT = Bvec->getValueType(0); 5905 unsigned NumElts = VT.getVectorNumElements(); 5906 for (unsigned i = 1; i < NumElts; ++i) 5907 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 5908 return false; 5909 ConstVal = FirstElt->getZExtValue(); 5910 return true; 5911 } 5912 5913 static unsigned getIntrinsicID(const SDNode *N) { 5914 unsigned Opcode = N->getOpcode(); 5915 switch (Opcode) { 5916 default: 5917 return Intrinsic::not_intrinsic; 5918 case ISD::INTRINSIC_WO_CHAIN: { 5919 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5920 if (IID < Intrinsic::num_intrinsics) 5921 return IID; 5922 return Intrinsic::not_intrinsic; 5923 } 5924 } 5925 } 5926 5927 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 5928 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 5929 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 5930 // Also, logical shift right -> sri, with the same structure. 5931 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 5932 EVT VT = N->getValueType(0); 5933 5934 if (!VT.isVector()) 5935 return SDValue(); 5936 5937 SDLoc DL(N); 5938 5939 // Is the first op an AND? 5940 const SDValue And = N->getOperand(0); 5941 if (And.getOpcode() != ISD::AND) 5942 return SDValue(); 5943 5944 // Is the second op an shl or lshr? 5945 SDValue Shift = N->getOperand(1); 5946 // This will have been turned into: AArch64ISD::VSHL vector, #shift 5947 // or AArch64ISD::VLSHR vector, #shift 5948 unsigned ShiftOpc = Shift.getOpcode(); 5949 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 5950 return SDValue(); 5951 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 5952 5953 // Is the shift amount constant? 5954 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 5955 if (!C2node) 5956 return SDValue(); 5957 5958 // Is the and mask vector all constant? 5959 uint64_t C1; 5960 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 5961 return SDValue(); 5962 5963 // Is C1 == ~C2, taking into account how much one can shift elements of a 5964 // particular size? 5965 uint64_t C2 = C2node->getZExtValue(); 5966 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits(); 5967 if (C2 > ElemSizeInBits) 5968 return SDValue(); 5969 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 5970 if ((C1 & ElemMask) != (~C2 & ElemMask)) 5971 return SDValue(); 5972 5973 SDValue X = And.getOperand(0); 5974 SDValue Y = Shift.getOperand(0); 5975 5976 unsigned Intrin = 5977 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 5978 SDValue ResultSLI = 5979 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 5980 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 5981 Shift.getOperand(1)); 5982 5983 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 5984 DEBUG(N->dump(&DAG)); 5985 DEBUG(dbgs() << "into: \n"); 5986 DEBUG(ResultSLI->dump(&DAG)); 5987 5988 ++NumShiftInserts; 5989 return ResultSLI; 5990 } 5991 5992 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 5993 SelectionDAG &DAG) const { 5994 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 5995 if (EnableAArch64SlrGeneration) { 5996 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 5997 return Res; 5998 } 5999 6000 BuildVectorSDNode *BVN = 6001 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 6002 SDValue LHS = Op.getOperand(1); 6003 SDLoc dl(Op); 6004 EVT VT = Op.getValueType(); 6005 6006 // OR commutes, so try swapping the operands. 6007 if (!BVN) { 6008 LHS = Op.getOperand(0); 6009 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6010 } 6011 if (!BVN) 6012 return Op; 6013 6014 APInt CnstBits(VT.getSizeInBits(), 0); 6015 APInt UndefBits(VT.getSizeInBits(), 0); 6016 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6017 // We make use of a little bit of goto ickiness in order to avoid having to 6018 // duplicate the immediate matching logic for the undef toggled case. 6019 bool SecondTry = false; 6020 AttemptModImm: 6021 6022 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6023 CnstBits = CnstBits.zextOrTrunc(64); 6024 uint64_t CnstVal = CnstBits.getZExtValue(); 6025 6026 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6027 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6028 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6029 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6030 DAG.getConstant(CnstVal, dl, MVT::i32), 6031 DAG.getConstant(0, dl, MVT::i32)); 6032 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6033 } 6034 6035 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6036 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6037 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6038 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6039 DAG.getConstant(CnstVal, dl, MVT::i32), 6040 DAG.getConstant(8, dl, MVT::i32)); 6041 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6042 } 6043 6044 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6045 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6046 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6047 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6048 DAG.getConstant(CnstVal, dl, MVT::i32), 6049 DAG.getConstant(16, dl, MVT::i32)); 6050 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6051 } 6052 6053 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6054 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6055 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6056 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6057 DAG.getConstant(CnstVal, dl, MVT::i32), 6058 DAG.getConstant(24, dl, MVT::i32)); 6059 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6060 } 6061 6062 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6063 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6064 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6065 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6066 DAG.getConstant(CnstVal, dl, MVT::i32), 6067 DAG.getConstant(0, dl, MVT::i32)); 6068 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6069 } 6070 6071 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6072 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6073 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6074 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6075 DAG.getConstant(CnstVal, dl, MVT::i32), 6076 DAG.getConstant(8, dl, MVT::i32)); 6077 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6078 } 6079 } 6080 6081 if (SecondTry) 6082 goto FailedModImm; 6083 SecondTry = true; 6084 CnstBits = UndefBits; 6085 goto AttemptModImm; 6086 } 6087 6088 // We can always fall back to a non-immediate OR. 6089 FailedModImm: 6090 return Op; 6091 } 6092 6093 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6094 // be truncated to fit element width. 6095 static SDValue NormalizeBuildVector(SDValue Op, 6096 SelectionDAG &DAG) { 6097 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6098 SDLoc dl(Op); 6099 EVT VT = Op.getValueType(); 6100 EVT EltTy= VT.getVectorElementType(); 6101 6102 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6103 return Op; 6104 6105 SmallVector<SDValue, 16> Ops; 6106 for (SDValue Lane : Op->ops()) { 6107 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6108 APInt LowBits(EltTy.getSizeInBits(), 6109 CstLane->getZExtValue()); 6110 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6111 } 6112 Ops.push_back(Lane); 6113 } 6114 return DAG.getBuildVector(VT, dl, Ops); 6115 } 6116 6117 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6118 SelectionDAG &DAG) const { 6119 SDLoc dl(Op); 6120 EVT VT = Op.getValueType(); 6121 Op = NormalizeBuildVector(Op, DAG); 6122 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6123 6124 APInt CnstBits(VT.getSizeInBits(), 0); 6125 APInt UndefBits(VT.getSizeInBits(), 0); 6126 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6127 // We make use of a little bit of goto ickiness in order to avoid having to 6128 // duplicate the immediate matching logic for the undef toggled case. 6129 bool SecondTry = false; 6130 AttemptModImm: 6131 6132 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6133 CnstBits = CnstBits.zextOrTrunc(64); 6134 uint64_t CnstVal = CnstBits.getZExtValue(); 6135 6136 // Certain magic vector constants (used to express things like NOT 6137 // and NEG) are passed through unmodified. This allows codegen patterns 6138 // for these operations to match. Special-purpose patterns will lower 6139 // these immediates to MOVIs if it proves necessary. 6140 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6141 return Op; 6142 6143 // The many faces of MOVI... 6144 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6145 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6146 if (VT.getSizeInBits() == 128) { 6147 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6148 DAG.getConstant(CnstVal, dl, MVT::i32)); 6149 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6150 } 6151 6152 // Support the V64 version via subregister insertion. 6153 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6154 DAG.getConstant(CnstVal, dl, MVT::i32)); 6155 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6156 } 6157 6158 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6159 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6160 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6161 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6162 DAG.getConstant(CnstVal, dl, MVT::i32), 6163 DAG.getConstant(0, dl, MVT::i32)); 6164 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6165 } 6166 6167 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6168 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6169 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6170 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6171 DAG.getConstant(CnstVal, dl, MVT::i32), 6172 DAG.getConstant(8, dl, MVT::i32)); 6173 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6174 } 6175 6176 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6177 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6178 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6179 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6180 DAG.getConstant(CnstVal, dl, MVT::i32), 6181 DAG.getConstant(16, dl, MVT::i32)); 6182 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6183 } 6184 6185 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6186 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6187 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6188 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6189 DAG.getConstant(CnstVal, dl, MVT::i32), 6190 DAG.getConstant(24, dl, MVT::i32)); 6191 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6192 } 6193 6194 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6195 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6196 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6197 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6198 DAG.getConstant(CnstVal, dl, MVT::i32), 6199 DAG.getConstant(0, dl, MVT::i32)); 6200 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6201 } 6202 6203 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6204 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6205 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6206 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6207 DAG.getConstant(CnstVal, dl, MVT::i32), 6208 DAG.getConstant(8, dl, MVT::i32)); 6209 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6210 } 6211 6212 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6213 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6214 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6215 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6216 DAG.getConstant(CnstVal, dl, MVT::i32), 6217 DAG.getConstant(264, dl, MVT::i32)); 6218 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6219 } 6220 6221 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6222 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6223 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6224 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6225 DAG.getConstant(CnstVal, dl, MVT::i32), 6226 DAG.getConstant(272, dl, MVT::i32)); 6227 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6228 } 6229 6230 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6231 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6232 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6233 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6234 DAG.getConstant(CnstVal, dl, MVT::i32)); 6235 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6236 } 6237 6238 // The few faces of FMOV... 6239 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6240 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6241 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6242 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6243 DAG.getConstant(CnstVal, dl, MVT::i32)); 6244 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6245 } 6246 6247 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6248 VT.getSizeInBits() == 128) { 6249 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6250 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6251 DAG.getConstant(CnstVal, dl, MVT::i32)); 6252 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6253 } 6254 6255 // The many faces of MVNI... 6256 CnstVal = ~CnstVal; 6257 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6258 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6259 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6260 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6261 DAG.getConstant(CnstVal, dl, MVT::i32), 6262 DAG.getConstant(0, dl, MVT::i32)); 6263 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6264 } 6265 6266 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6267 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6268 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6269 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6270 DAG.getConstant(CnstVal, dl, MVT::i32), 6271 DAG.getConstant(8, dl, MVT::i32)); 6272 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6273 } 6274 6275 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6276 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6277 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6278 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6279 DAG.getConstant(CnstVal, dl, MVT::i32), 6280 DAG.getConstant(16, dl, MVT::i32)); 6281 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6282 } 6283 6284 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6285 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6286 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6287 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6288 DAG.getConstant(CnstVal, dl, MVT::i32), 6289 DAG.getConstant(24, dl, MVT::i32)); 6290 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6291 } 6292 6293 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6294 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6295 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6296 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6297 DAG.getConstant(CnstVal, dl, MVT::i32), 6298 DAG.getConstant(0, dl, MVT::i32)); 6299 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6300 } 6301 6302 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6303 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6304 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6305 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6306 DAG.getConstant(CnstVal, dl, MVT::i32), 6307 DAG.getConstant(8, dl, MVT::i32)); 6308 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6309 } 6310 6311 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6312 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6313 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6314 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6315 DAG.getConstant(CnstVal, dl, MVT::i32), 6316 DAG.getConstant(264, dl, MVT::i32)); 6317 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6318 } 6319 6320 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6321 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6322 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6323 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6324 DAG.getConstant(CnstVal, dl, MVT::i32), 6325 DAG.getConstant(272, dl, MVT::i32)); 6326 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6327 } 6328 } 6329 6330 if (SecondTry) 6331 goto FailedModImm; 6332 SecondTry = true; 6333 CnstBits = UndefBits; 6334 goto AttemptModImm; 6335 } 6336 FailedModImm: 6337 6338 // Scan through the operands to find some interesting properties we can 6339 // exploit: 6340 // 1) If only one value is used, we can use a DUP, or 6341 // 2) if only the low element is not undef, we can just insert that, or 6342 // 3) if only one constant value is used (w/ some non-constant lanes), 6343 // we can splat the constant value into the whole vector then fill 6344 // in the non-constant lanes. 6345 // 4) FIXME: If different constant values are used, but we can intelligently 6346 // select the values we'll be overwriting for the non-constant 6347 // lanes such that we can directly materialize the vector 6348 // some other way (MOVI, e.g.), we can be sneaky. 6349 unsigned NumElts = VT.getVectorNumElements(); 6350 bool isOnlyLowElement = true; 6351 bool usesOnlyOneValue = true; 6352 bool usesOnlyOneConstantValue = true; 6353 bool isConstant = true; 6354 unsigned NumConstantLanes = 0; 6355 SDValue Value; 6356 SDValue ConstantValue; 6357 for (unsigned i = 0; i < NumElts; ++i) { 6358 SDValue V = Op.getOperand(i); 6359 if (V.isUndef()) 6360 continue; 6361 if (i > 0) 6362 isOnlyLowElement = false; 6363 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6364 isConstant = false; 6365 6366 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6367 ++NumConstantLanes; 6368 if (!ConstantValue.getNode()) 6369 ConstantValue = V; 6370 else if (ConstantValue != V) 6371 usesOnlyOneConstantValue = false; 6372 } 6373 6374 if (!Value.getNode()) 6375 Value = V; 6376 else if (V != Value) 6377 usesOnlyOneValue = false; 6378 } 6379 6380 if (!Value.getNode()) 6381 return DAG.getUNDEF(VT); 6382 6383 if (isOnlyLowElement) 6384 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6385 6386 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6387 // i32 and try again. 6388 if (usesOnlyOneValue) { 6389 if (!isConstant) { 6390 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6391 Value.getValueType() != VT) 6392 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6393 6394 // This is actually a DUPLANExx operation, which keeps everything vectory. 6395 6396 // DUPLANE works on 128-bit vectors, widen it if necessary. 6397 SDValue Lane = Value.getOperand(1); 6398 Value = Value.getOperand(0); 6399 if (Value.getValueType().getSizeInBits() == 64) 6400 Value = WidenVector(Value, DAG); 6401 6402 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6403 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6404 } 6405 6406 if (VT.getVectorElementType().isFloatingPoint()) { 6407 SmallVector<SDValue, 8> Ops; 6408 EVT EltTy = VT.getVectorElementType(); 6409 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6410 "Unsupported floating-point vector type"); 6411 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6412 for (unsigned i = 0; i < NumElts; ++i) 6413 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6414 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6415 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6416 Val = LowerBUILD_VECTOR(Val, DAG); 6417 if (Val.getNode()) 6418 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6419 } 6420 } 6421 6422 // If there was only one constant value used and for more than one lane, 6423 // start by splatting that value, then replace the non-constant lanes. This 6424 // is better than the default, which will perform a separate initialization 6425 // for each lane. 6426 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6427 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6428 // Now insert the non-constant lanes. 6429 for (unsigned i = 0; i < NumElts; ++i) { 6430 SDValue V = Op.getOperand(i); 6431 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6432 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6433 // Note that type legalization likely mucked about with the VT of the 6434 // source operand, so we may have to convert it here before inserting. 6435 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6436 } 6437 } 6438 return Val; 6439 } 6440 6441 // If all elements are constants and the case above didn't get hit, fall back 6442 // to the default expansion, which will generate a load from the constant 6443 // pool. 6444 if (isConstant) 6445 return SDValue(); 6446 6447 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6448 if (NumElts >= 4) { 6449 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6450 return shuffle; 6451 } 6452 6453 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6454 // know the default expansion would otherwise fall back on something even 6455 // worse. For a vector with one or two non-undef values, that's 6456 // scalar_to_vector for the elements followed by a shuffle (provided the 6457 // shuffle is valid for the target) and materialization element by element 6458 // on the stack followed by a load for everything else. 6459 if (!isConstant && !usesOnlyOneValue) { 6460 SDValue Vec = DAG.getUNDEF(VT); 6461 SDValue Op0 = Op.getOperand(0); 6462 unsigned ElemSize = VT.getVectorElementType().getSizeInBits(); 6463 unsigned i = 0; 6464 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to 6465 // a) Avoid a RMW dependency on the full vector register, and 6466 // b) Allow the register coalescer to fold away the copy if the 6467 // value is already in an S or D register. 6468 // Do not do this for UNDEF/LOAD nodes because we have better patterns 6469 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR. 6470 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD && 6471 (ElemSize == 32 || ElemSize == 64)) { 6472 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub; 6473 MachineSDNode *N = 6474 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0, 6475 DAG.getTargetConstant(SubIdx, dl, MVT::i32)); 6476 Vec = SDValue(N, 0); 6477 ++i; 6478 } 6479 for (; i < NumElts; ++i) { 6480 SDValue V = Op.getOperand(i); 6481 if (V.isUndef()) 6482 continue; 6483 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6484 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6485 } 6486 return Vec; 6487 } 6488 6489 // Just use the default expansion. We failed to find a better alternative. 6490 return SDValue(); 6491 } 6492 6493 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6494 SelectionDAG &DAG) const { 6495 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6496 6497 // Check for non-constant or out of range lane. 6498 EVT VT = Op.getOperand(0).getValueType(); 6499 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6500 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6501 return SDValue(); 6502 6503 6504 // Insertion/extraction are legal for V128 types. 6505 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6506 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6507 VT == MVT::v8f16) 6508 return Op; 6509 6510 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6511 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6512 return SDValue(); 6513 6514 // For V64 types, we perform insertion by expanding the value 6515 // to a V128 type and perform the insertion on that. 6516 SDLoc DL(Op); 6517 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6518 EVT WideTy = WideVec.getValueType(); 6519 6520 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6521 Op.getOperand(1), Op.getOperand(2)); 6522 // Re-narrow the resultant vector. 6523 return NarrowVector(Node, DAG); 6524 } 6525 6526 SDValue 6527 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6528 SelectionDAG &DAG) const { 6529 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6530 6531 // Check for non-constant or out of range lane. 6532 EVT VT = Op.getOperand(0).getValueType(); 6533 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6534 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6535 return SDValue(); 6536 6537 6538 // Insertion/extraction are legal for V128 types. 6539 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6540 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6541 VT == MVT::v8f16) 6542 return Op; 6543 6544 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6545 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6546 return SDValue(); 6547 6548 // For V64 types, we perform extraction by expanding the value 6549 // to a V128 type and perform the extraction on that. 6550 SDLoc DL(Op); 6551 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6552 EVT WideTy = WideVec.getValueType(); 6553 6554 EVT ExtrTy = WideTy.getVectorElementType(); 6555 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 6556 ExtrTy = MVT::i32; 6557 6558 // For extractions, we just return the result directly. 6559 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 6560 Op.getOperand(1)); 6561 } 6562 6563 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 6564 SelectionDAG &DAG) const { 6565 EVT VT = Op.getOperand(0).getValueType(); 6566 SDLoc dl(Op); 6567 // Just in case... 6568 if (!VT.isVector()) 6569 return SDValue(); 6570 6571 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6572 if (!Cst) 6573 return SDValue(); 6574 unsigned Val = Cst->getZExtValue(); 6575 6576 unsigned Size = Op.getValueType().getSizeInBits(); 6577 6578 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 6579 if (Val == 0) 6580 return Op; 6581 6582 // If this is extracting the upper 64-bits of a 128-bit vector, we match 6583 // that directly. 6584 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64) 6585 return Op; 6586 6587 return SDValue(); 6588 } 6589 6590 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6591 EVT VT) const { 6592 if (VT.getVectorNumElements() == 4 && 6593 (VT.is128BitVector() || VT.is64BitVector())) { 6594 unsigned PFIndexes[4]; 6595 for (unsigned i = 0; i != 4; ++i) { 6596 if (M[i] < 0) 6597 PFIndexes[i] = 8; 6598 else 6599 PFIndexes[i] = M[i]; 6600 } 6601 6602 // Compute the index in the perfect shuffle table. 6603 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6604 PFIndexes[2] * 9 + PFIndexes[3]; 6605 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6606 unsigned Cost = (PFEntry >> 30); 6607 6608 if (Cost <= 4) 6609 return true; 6610 } 6611 6612 bool DummyBool; 6613 int DummyInt; 6614 unsigned DummyUnsigned; 6615 6616 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 6617 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 6618 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 6619 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 6620 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 6621 isZIPMask(M, VT, DummyUnsigned) || 6622 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 6623 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 6624 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 6625 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 6626 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 6627 } 6628 6629 /// getVShiftImm - Check if this is a valid build_vector for the immediate 6630 /// operand of a vector shift operation, where all the elements of the 6631 /// build_vector must have the same constant integer value. 6632 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6633 // Ignore bit_converts. 6634 while (Op.getOpcode() == ISD::BITCAST) 6635 Op = Op.getOperand(0); 6636 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6637 APInt SplatBits, SplatUndef; 6638 unsigned SplatBitSize; 6639 bool HasAnyUndefs; 6640 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 6641 HasAnyUndefs, ElementBits) || 6642 SplatBitSize > ElementBits) 6643 return false; 6644 Cnt = SplatBits.getSExtValue(); 6645 return true; 6646 } 6647 6648 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6649 /// operand of a vector shift left operation. That value must be in the range: 6650 /// 0 <= Value < ElementBits for a left shift; or 6651 /// 0 <= Value <= ElementBits for a long left shift. 6652 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6653 assert(VT.isVector() && "vector shift count is not a vector type"); 6654 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 6655 if (!getVShiftImm(Op, ElementBits, Cnt)) 6656 return false; 6657 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6658 } 6659 6660 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6661 /// operand of a vector shift right operation. The value must be in the range: 6662 /// 1 <= Value <= ElementBits for a right shift; or 6663 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 6664 assert(VT.isVector() && "vector shift count is not a vector type"); 6665 int64_t ElementBits = VT.getVectorElementType().getSizeInBits(); 6666 if (!getVShiftImm(Op, ElementBits, Cnt)) 6667 return false; 6668 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6669 } 6670 6671 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 6672 SelectionDAG &DAG) const { 6673 EVT VT = Op.getValueType(); 6674 SDLoc DL(Op); 6675 int64_t Cnt; 6676 6677 if (!Op.getOperand(1).getValueType().isVector()) 6678 return Op; 6679 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 6680 6681 switch (Op.getOpcode()) { 6682 default: 6683 llvm_unreachable("unexpected shift opcode"); 6684 6685 case ISD::SHL: 6686 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 6687 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 6688 DAG.getConstant(Cnt, DL, MVT::i32)); 6689 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6690 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 6691 MVT::i32), 6692 Op.getOperand(0), Op.getOperand(1)); 6693 case ISD::SRA: 6694 case ISD::SRL: 6695 // Right shift immediate 6696 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 6697 unsigned Opc = 6698 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 6699 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 6700 DAG.getConstant(Cnt, DL, MVT::i32)); 6701 } 6702 6703 // Right shift register. Note, there is not a shift right register 6704 // instruction, but the shift left register instruction takes a signed 6705 // value, where negative numbers specify a right shift. 6706 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 6707 : Intrinsic::aarch64_neon_ushl; 6708 // negate the shift amount 6709 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 6710 SDValue NegShiftLeft = 6711 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6712 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 6713 NegShift); 6714 return NegShiftLeft; 6715 } 6716 6717 return SDValue(); 6718 } 6719 6720 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 6721 AArch64CC::CondCode CC, bool NoNans, EVT VT, 6722 const SDLoc &dl, SelectionDAG &DAG) { 6723 EVT SrcVT = LHS.getValueType(); 6724 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 6725 "function only supposed to emit natural comparisons"); 6726 6727 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 6728 APInt CnstBits(VT.getSizeInBits(), 0); 6729 APInt UndefBits(VT.getSizeInBits(), 0); 6730 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 6731 bool IsZero = IsCnst && (CnstBits == 0); 6732 6733 if (SrcVT.getVectorElementType().isFloatingPoint()) { 6734 switch (CC) { 6735 default: 6736 return SDValue(); 6737 case AArch64CC::NE: { 6738 SDValue Fcmeq; 6739 if (IsZero) 6740 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6741 else 6742 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6743 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 6744 } 6745 case AArch64CC::EQ: 6746 if (IsZero) 6747 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6748 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6749 case AArch64CC::GE: 6750 if (IsZero) 6751 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 6752 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 6753 case AArch64CC::GT: 6754 if (IsZero) 6755 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 6756 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 6757 case AArch64CC::LS: 6758 if (IsZero) 6759 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 6760 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 6761 case AArch64CC::LT: 6762 if (!NoNans) 6763 return SDValue(); 6764 // If we ignore NaNs then we can use to the MI implementation. 6765 // Fallthrough. 6766 case AArch64CC::MI: 6767 if (IsZero) 6768 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 6769 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 6770 } 6771 } 6772 6773 switch (CC) { 6774 default: 6775 return SDValue(); 6776 case AArch64CC::NE: { 6777 SDValue Cmeq; 6778 if (IsZero) 6779 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6780 else 6781 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6782 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 6783 } 6784 case AArch64CC::EQ: 6785 if (IsZero) 6786 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6787 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6788 case AArch64CC::GE: 6789 if (IsZero) 6790 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 6791 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 6792 case AArch64CC::GT: 6793 if (IsZero) 6794 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 6795 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 6796 case AArch64CC::LE: 6797 if (IsZero) 6798 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 6799 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 6800 case AArch64CC::LS: 6801 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 6802 case AArch64CC::LO: 6803 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 6804 case AArch64CC::LT: 6805 if (IsZero) 6806 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 6807 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 6808 case AArch64CC::HI: 6809 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 6810 case AArch64CC::HS: 6811 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 6812 } 6813 } 6814 6815 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 6816 SelectionDAG &DAG) const { 6817 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6818 SDValue LHS = Op.getOperand(0); 6819 SDValue RHS = Op.getOperand(1); 6820 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 6821 SDLoc dl(Op); 6822 6823 if (LHS.getValueType().getVectorElementType().isInteger()) { 6824 assert(LHS.getValueType() == RHS.getValueType()); 6825 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6826 SDValue Cmp = 6827 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 6828 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6829 } 6830 6831 if (LHS.getValueType().getVectorElementType() == MVT::f16) 6832 return SDValue(); 6833 6834 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 6835 LHS.getValueType().getVectorElementType() == MVT::f64); 6836 6837 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6838 // clean. Some of them require two branches to implement. 6839 AArch64CC::CondCode CC1, CC2; 6840 bool ShouldInvert; 6841 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 6842 6843 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 6844 SDValue Cmp = 6845 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 6846 if (!Cmp.getNode()) 6847 return SDValue(); 6848 6849 if (CC2 != AArch64CC::AL) { 6850 SDValue Cmp2 = 6851 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 6852 if (!Cmp2.getNode()) 6853 return SDValue(); 6854 6855 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 6856 } 6857 6858 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6859 6860 if (ShouldInvert) 6861 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 6862 6863 return Cmp; 6864 } 6865 6866 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 6867 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 6868 /// specified in the intrinsic calls. 6869 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 6870 const CallInst &I, 6871 unsigned Intrinsic) const { 6872 auto &DL = I.getModule()->getDataLayout(); 6873 switch (Intrinsic) { 6874 case Intrinsic::aarch64_neon_ld2: 6875 case Intrinsic::aarch64_neon_ld3: 6876 case Intrinsic::aarch64_neon_ld4: 6877 case Intrinsic::aarch64_neon_ld1x2: 6878 case Intrinsic::aarch64_neon_ld1x3: 6879 case Intrinsic::aarch64_neon_ld1x4: 6880 case Intrinsic::aarch64_neon_ld2lane: 6881 case Intrinsic::aarch64_neon_ld3lane: 6882 case Intrinsic::aarch64_neon_ld4lane: 6883 case Intrinsic::aarch64_neon_ld2r: 6884 case Intrinsic::aarch64_neon_ld3r: 6885 case Intrinsic::aarch64_neon_ld4r: { 6886 Info.opc = ISD::INTRINSIC_W_CHAIN; 6887 // Conservatively set memVT to the entire set of vectors loaded. 6888 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 6889 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6890 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6891 Info.offset = 0; 6892 Info.align = 0; 6893 Info.vol = false; // volatile loads with NEON intrinsics not supported 6894 Info.readMem = true; 6895 Info.writeMem = false; 6896 return true; 6897 } 6898 case Intrinsic::aarch64_neon_st2: 6899 case Intrinsic::aarch64_neon_st3: 6900 case Intrinsic::aarch64_neon_st4: 6901 case Intrinsic::aarch64_neon_st1x2: 6902 case Intrinsic::aarch64_neon_st1x3: 6903 case Intrinsic::aarch64_neon_st1x4: 6904 case Intrinsic::aarch64_neon_st2lane: 6905 case Intrinsic::aarch64_neon_st3lane: 6906 case Intrinsic::aarch64_neon_st4lane: { 6907 Info.opc = ISD::INTRINSIC_VOID; 6908 // Conservatively set memVT to the entire set of vectors stored. 6909 unsigned NumElts = 0; 6910 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 6911 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 6912 if (!ArgTy->isVectorTy()) 6913 break; 6914 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 6915 } 6916 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6917 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6918 Info.offset = 0; 6919 Info.align = 0; 6920 Info.vol = false; // volatile stores with NEON intrinsics not supported 6921 Info.readMem = false; 6922 Info.writeMem = true; 6923 return true; 6924 } 6925 case Intrinsic::aarch64_ldaxr: 6926 case Intrinsic::aarch64_ldxr: { 6927 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 6928 Info.opc = ISD::INTRINSIC_W_CHAIN; 6929 Info.memVT = MVT::getVT(PtrTy->getElementType()); 6930 Info.ptrVal = I.getArgOperand(0); 6931 Info.offset = 0; 6932 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 6933 Info.vol = true; 6934 Info.readMem = true; 6935 Info.writeMem = false; 6936 return true; 6937 } 6938 case Intrinsic::aarch64_stlxr: 6939 case Intrinsic::aarch64_stxr: { 6940 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 6941 Info.opc = ISD::INTRINSIC_W_CHAIN; 6942 Info.memVT = MVT::getVT(PtrTy->getElementType()); 6943 Info.ptrVal = I.getArgOperand(1); 6944 Info.offset = 0; 6945 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 6946 Info.vol = true; 6947 Info.readMem = false; 6948 Info.writeMem = true; 6949 return true; 6950 } 6951 case Intrinsic::aarch64_ldaxp: 6952 case Intrinsic::aarch64_ldxp: { 6953 Info.opc = ISD::INTRINSIC_W_CHAIN; 6954 Info.memVT = MVT::i128; 6955 Info.ptrVal = I.getArgOperand(0); 6956 Info.offset = 0; 6957 Info.align = 16; 6958 Info.vol = true; 6959 Info.readMem = true; 6960 Info.writeMem = false; 6961 return true; 6962 } 6963 case Intrinsic::aarch64_stlxp: 6964 case Intrinsic::aarch64_stxp: { 6965 Info.opc = ISD::INTRINSIC_W_CHAIN; 6966 Info.memVT = MVT::i128; 6967 Info.ptrVal = I.getArgOperand(2); 6968 Info.offset = 0; 6969 Info.align = 16; 6970 Info.vol = true; 6971 Info.readMem = false; 6972 Info.writeMem = true; 6973 return true; 6974 } 6975 default: 6976 break; 6977 } 6978 6979 return false; 6980 } 6981 6982 // Truncations from 64-bit GPR to 32-bit GPR is free. 6983 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 6984 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 6985 return false; 6986 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 6987 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 6988 return NumBits1 > NumBits2; 6989 } 6990 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 6991 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 6992 return false; 6993 unsigned NumBits1 = VT1.getSizeInBits(); 6994 unsigned NumBits2 = VT2.getSizeInBits(); 6995 return NumBits1 > NumBits2; 6996 } 6997 6998 /// Check if it is profitable to hoist instruction in then/else to if. 6999 /// Not profitable if I and it's user can form a FMA instruction 7000 /// because we prefer FMSUB/FMADD. 7001 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 7002 if (I->getOpcode() != Instruction::FMul) 7003 return true; 7004 7005 if (I->getNumUses() != 1) 7006 return true; 7007 7008 Instruction *User = I->user_back(); 7009 7010 if (User && 7011 !(User->getOpcode() == Instruction::FSub || 7012 User->getOpcode() == Instruction::FAdd)) 7013 return true; 7014 7015 const TargetOptions &Options = getTargetMachine().Options; 7016 const DataLayout &DL = I->getModule()->getDataLayout(); 7017 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 7018 7019 return !(isFMAFasterThanFMulAndFAdd(VT) && 7020 isOperationLegalOrCustom(ISD::FMA, VT) && 7021 (Options.AllowFPOpFusion == FPOpFusion::Fast || 7022 Options.UnsafeFPMath)); 7023 } 7024 7025 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 7026 // 64-bit GPR. 7027 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 7028 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7029 return false; 7030 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7031 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7032 return NumBits1 == 32 && NumBits2 == 64; 7033 } 7034 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 7035 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7036 return false; 7037 unsigned NumBits1 = VT1.getSizeInBits(); 7038 unsigned NumBits2 = VT2.getSizeInBits(); 7039 return NumBits1 == 32 && NumBits2 == 64; 7040 } 7041 7042 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7043 EVT VT1 = Val.getValueType(); 7044 if (isZExtFree(VT1, VT2)) { 7045 return true; 7046 } 7047 7048 if (Val.getOpcode() != ISD::LOAD) 7049 return false; 7050 7051 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7052 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7053 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7054 VT1.getSizeInBits() <= 32); 7055 } 7056 7057 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7058 if (isa<FPExtInst>(Ext)) 7059 return false; 7060 7061 // Vector types are next free. 7062 if (Ext->getType()->isVectorTy()) 7063 return false; 7064 7065 for (const Use &U : Ext->uses()) { 7066 // The extension is free if we can fold it with a left shift in an 7067 // addressing mode or an arithmetic operation: add, sub, and cmp. 7068 7069 // Is there a shift? 7070 const Instruction *Instr = cast<Instruction>(U.getUser()); 7071 7072 // Is this a constant shift? 7073 switch (Instr->getOpcode()) { 7074 case Instruction::Shl: 7075 if (!isa<ConstantInt>(Instr->getOperand(1))) 7076 return false; 7077 break; 7078 case Instruction::GetElementPtr: { 7079 gep_type_iterator GTI = gep_type_begin(Instr); 7080 auto &DL = Ext->getModule()->getDataLayout(); 7081 std::advance(GTI, U.getOperandNo()); 7082 Type *IdxTy = *GTI; 7083 // This extension will end up with a shift because of the scaling factor. 7084 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7085 // Get the shift amount based on the scaling factor: 7086 // log2(sizeof(IdxTy)) - log2(8). 7087 uint64_t ShiftAmt = 7088 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7089 // Is the constant foldable in the shift of the addressing mode? 7090 // I.e., shift amount is between 1 and 4 inclusive. 7091 if (ShiftAmt == 0 || ShiftAmt > 4) 7092 return false; 7093 break; 7094 } 7095 case Instruction::Trunc: 7096 // Check if this is a noop. 7097 // trunc(sext ty1 to ty2) to ty1. 7098 if (Instr->getType() == Ext->getOperand(0)->getType()) 7099 continue; 7100 // FALL THROUGH. 7101 default: 7102 return false; 7103 } 7104 7105 // At this point we can use the bfm family, so this extension is free 7106 // for that use. 7107 } 7108 return true; 7109 } 7110 7111 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType, 7112 unsigned &RequiredAligment) const { 7113 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy()) 7114 return false; 7115 // Cyclone supports unaligned accesses. 7116 RequiredAligment = 0; 7117 unsigned NumBits = LoadedType->getPrimitiveSizeInBits(); 7118 return NumBits == 32 || NumBits == 64; 7119 } 7120 7121 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7122 unsigned &RequiredAligment) const { 7123 if (!LoadedType.isSimple() || 7124 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7125 return false; 7126 // Cyclone supports unaligned accesses. 7127 RequiredAligment = 0; 7128 unsigned NumBits = LoadedType.getSizeInBits(); 7129 return NumBits == 32 || NumBits == 64; 7130 } 7131 7132 /// \brief Lower an interleaved load into a ldN intrinsic. 7133 /// 7134 /// E.g. Lower an interleaved load (Factor = 2): 7135 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7136 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7137 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7138 /// 7139 /// Into: 7140 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7141 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7142 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7143 bool AArch64TargetLowering::lowerInterleavedLoad( 7144 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7145 ArrayRef<unsigned> Indices, unsigned Factor) const { 7146 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7147 "Invalid interleave factor"); 7148 assert(!Shuffles.empty() && "Empty shufflevector input"); 7149 assert(Shuffles.size() == Indices.size() && 7150 "Unmatched number of shufflevectors and indices"); 7151 7152 const DataLayout &DL = LI->getModule()->getDataLayout(); 7153 7154 VectorType *VecTy = Shuffles[0]->getType(); 7155 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7156 7157 // Skip if we do not have NEON and skip illegal vector types. 7158 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128)) 7159 return false; 7160 7161 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7162 // load integer vectors first and then convert to pointer vectors. 7163 Type *EltTy = VecTy->getVectorElementType(); 7164 if (EltTy->isPointerTy()) 7165 VecTy = 7166 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7167 7168 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7169 Type *Tys[2] = {VecTy, PtrTy}; 7170 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7171 Intrinsic::aarch64_neon_ld3, 7172 Intrinsic::aarch64_neon_ld4}; 7173 Function *LdNFunc = 7174 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7175 7176 IRBuilder<> Builder(LI); 7177 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy); 7178 7179 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN"); 7180 7181 // Replace uses of each shufflevector with the corresponding vector loaded 7182 // by ldN. 7183 for (unsigned i = 0; i < Shuffles.size(); i++) { 7184 ShuffleVectorInst *SVI = Shuffles[i]; 7185 unsigned Index = Indices[i]; 7186 7187 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7188 7189 // Convert the integer vector to pointer vector if the element is pointer. 7190 if (EltTy->isPointerTy()) 7191 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType()); 7192 7193 SVI->replaceAllUsesWith(SubVec); 7194 } 7195 7196 return true; 7197 } 7198 7199 /// \brief Get a mask consisting of sequential integers starting from \p Start. 7200 /// 7201 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 7202 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 7203 unsigned NumElts) { 7204 SmallVector<Constant *, 16> Mask; 7205 for (unsigned i = 0; i < NumElts; i++) 7206 Mask.push_back(Builder.getInt32(Start + i)); 7207 7208 return ConstantVector::get(Mask); 7209 } 7210 7211 /// \brief Lower an interleaved store into a stN intrinsic. 7212 /// 7213 /// E.g. Lower an interleaved store (Factor = 3): 7214 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7215 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7216 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7217 /// 7218 /// Into: 7219 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7220 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7221 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7222 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7223 /// 7224 /// Note that the new shufflevectors will be removed and we'll only generate one 7225 /// st3 instruction in CodeGen. 7226 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7227 ShuffleVectorInst *SVI, 7228 unsigned Factor) const { 7229 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7230 "Invalid interleave factor"); 7231 7232 VectorType *VecTy = SVI->getType(); 7233 assert(VecTy->getVectorNumElements() % Factor == 0 && 7234 "Invalid interleaved store"); 7235 7236 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 7237 Type *EltTy = VecTy->getVectorElementType(); 7238 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 7239 7240 const DataLayout &DL = SI->getModule()->getDataLayout(); 7241 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 7242 7243 // Skip if we do not have NEON and skip illegal vector types. 7244 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128)) 7245 return false; 7246 7247 Value *Op0 = SVI->getOperand(0); 7248 Value *Op1 = SVI->getOperand(1); 7249 IRBuilder<> Builder(SI); 7250 7251 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7252 // vectors to integer vectors. 7253 if (EltTy->isPointerTy()) { 7254 Type *IntTy = DL.getIntPtrType(EltTy); 7255 unsigned NumOpElts = 7256 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7257 7258 // Convert to the corresponding integer vector. 7259 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7260 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7261 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7262 7263 SubVecTy = VectorType::get(IntTy, NumSubElts); 7264 } 7265 7266 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7267 Type *Tys[2] = {SubVecTy, PtrTy}; 7268 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7269 Intrinsic::aarch64_neon_st3, 7270 Intrinsic::aarch64_neon_st4}; 7271 Function *StNFunc = 7272 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7273 7274 SmallVector<Value *, 5> Ops; 7275 7276 // Split the shufflevector operands into sub vectors for the new stN call. 7277 for (unsigned i = 0; i < Factor; i++) 7278 Ops.push_back(Builder.CreateShuffleVector( 7279 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 7280 7281 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy)); 7282 Builder.CreateCall(StNFunc, Ops); 7283 return true; 7284 } 7285 7286 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7287 unsigned AlignCheck) { 7288 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7289 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7290 } 7291 7292 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7293 unsigned SrcAlign, bool IsMemset, 7294 bool ZeroMemset, 7295 bool MemcpyStrSrc, 7296 MachineFunction &MF) const { 7297 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7298 // instruction to materialize the v2i64 zero and one store (with restrictive 7299 // addressing mode). Just do two i64 store of zero-registers. 7300 bool Fast; 7301 const Function *F = MF.getFunction(); 7302 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7303 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7304 (memOpAlign(SrcAlign, DstAlign, 16) || 7305 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7306 return MVT::f128; 7307 7308 if (Size >= 8 && 7309 (memOpAlign(SrcAlign, DstAlign, 8) || 7310 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7311 return MVT::i64; 7312 7313 if (Size >= 4 && 7314 (memOpAlign(SrcAlign, DstAlign, 4) || 7315 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7316 return MVT::i32; 7317 7318 return MVT::Other; 7319 } 7320 7321 // 12-bit optionally shifted immediates are legal for adds. 7322 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7323 // Avoid UB for INT64_MIN. 7324 if (Immed == std::numeric_limits<int64_t>::min()) 7325 return false; 7326 // Same encoding for add/sub, just flip the sign. 7327 Immed = std::abs(Immed); 7328 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7329 } 7330 7331 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7332 // immediates is the same as for an add or a sub. 7333 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7334 return isLegalAddImmediate(Immed); 7335 } 7336 7337 /// isLegalAddressingMode - Return true if the addressing mode represented 7338 /// by AM is legal for this target, for a load/store of the specified type. 7339 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7340 const AddrMode &AM, Type *Ty, 7341 unsigned AS) const { 7342 // AArch64 has five basic addressing modes: 7343 // reg 7344 // reg + 9-bit signed offset 7345 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7346 // reg1 + reg2 7347 // reg + SIZE_IN_BYTES * reg 7348 7349 // No global is ever allowed as a base. 7350 if (AM.BaseGV) 7351 return false; 7352 7353 // No reg+reg+imm addressing. 7354 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7355 return false; 7356 7357 // check reg + imm case: 7358 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7359 uint64_t NumBytes = 0; 7360 if (Ty->isSized()) { 7361 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7362 NumBytes = NumBits / 8; 7363 if (!isPowerOf2_64(NumBits)) 7364 NumBytes = 0; 7365 } 7366 7367 if (!AM.Scale) { 7368 int64_t Offset = AM.BaseOffs; 7369 7370 // 9-bit signed offset 7371 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1) 7372 return true; 7373 7374 // 12-bit unsigned offset 7375 unsigned shift = Log2_64(NumBytes); 7376 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 7377 // Must be a multiple of NumBytes (NumBytes is a power of 2) 7378 (Offset >> shift) << shift == Offset) 7379 return true; 7380 return false; 7381 } 7382 7383 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 7384 7385 return !AM.Scale || AM.Scale == 1 || 7386 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 7387 } 7388 7389 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 7390 const AddrMode &AM, Type *Ty, 7391 unsigned AS) const { 7392 // Scaling factors are not free at all. 7393 // Operands | Rt Latency 7394 // ------------------------------------------- 7395 // Rt, [Xn, Xm] | 4 7396 // ------------------------------------------- 7397 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 7398 // Rt, [Xn, Wm, <extend> #imm] | 7399 if (isLegalAddressingMode(DL, AM, Ty, AS)) 7400 // Scale represents reg2 * scale, thus account for 1 if 7401 // it is not equal to 0 or 1. 7402 return AM.Scale != 0 && AM.Scale != 1; 7403 return -1; 7404 } 7405 7406 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7407 VT = VT.getScalarType(); 7408 7409 if (!VT.isSimple()) 7410 return false; 7411 7412 switch (VT.getSimpleVT().SimpleTy) { 7413 case MVT::f32: 7414 case MVT::f64: 7415 return true; 7416 default: 7417 break; 7418 } 7419 7420 return false; 7421 } 7422 7423 const MCPhysReg * 7424 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 7425 // LR is a callee-save register, but we must treat it as clobbered by any call 7426 // site. Hence we include LR in the scratch registers, which are in turn added 7427 // as implicit-defs for stackmaps and patchpoints. 7428 static const MCPhysReg ScratchRegs[] = { 7429 AArch64::X16, AArch64::X17, AArch64::LR, 0 7430 }; 7431 return ScratchRegs; 7432 } 7433 7434 bool 7435 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 7436 EVT VT = N->getValueType(0); 7437 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 7438 // it with shift to let it be lowered to UBFX. 7439 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 7440 isa<ConstantSDNode>(N->getOperand(1))) { 7441 uint64_t TruncMask = N->getConstantOperandVal(1); 7442 if (isMask_64(TruncMask) && 7443 N->getOperand(0).getOpcode() == ISD::SRL && 7444 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 7445 return false; 7446 } 7447 return true; 7448 } 7449 7450 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 7451 Type *Ty) const { 7452 assert(Ty->isIntegerTy()); 7453 7454 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 7455 if (BitSize == 0) 7456 return false; 7457 7458 int64_t Val = Imm.getSExtValue(); 7459 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 7460 return true; 7461 7462 if ((int64_t)Val < 0) 7463 Val = ~Val; 7464 if (BitSize == 32) 7465 Val &= (1LL << 32) - 1; 7466 7467 unsigned LZ = countLeadingZeros((uint64_t)Val); 7468 unsigned Shift = (63 - LZ) / 16; 7469 // MOVZ is free so return true for one or fewer MOVK. 7470 return Shift < 3; 7471 } 7472 7473 /// Turn vector tests of the signbit in the form of: 7474 /// xor (sra X, elt_size(X)-1), -1 7475 /// into: 7476 /// cmge X, X, #0 7477 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 7478 const AArch64Subtarget *Subtarget) { 7479 EVT VT = N->getValueType(0); 7480 if (!Subtarget->hasNEON() || !VT.isVector()) 7481 return SDValue(); 7482 7483 // There must be a shift right algebraic before the xor, and the xor must be a 7484 // 'not' operation. 7485 SDValue Shift = N->getOperand(0); 7486 SDValue Ones = N->getOperand(1); 7487 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 7488 !ISD::isBuildVectorAllOnes(Ones.getNode())) 7489 return SDValue(); 7490 7491 // The shift should be smearing the sign bit across each vector element. 7492 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7493 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 7494 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 7495 return SDValue(); 7496 7497 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 7498 } 7499 7500 // Generate SUBS and CSEL for integer abs. 7501 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 7502 EVT VT = N->getValueType(0); 7503 7504 SDValue N0 = N->getOperand(0); 7505 SDValue N1 = N->getOperand(1); 7506 SDLoc DL(N); 7507 7508 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 7509 // and change it to SUB and CSEL. 7510 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 7511 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 7512 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 7513 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 7514 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 7515 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7516 N0.getOperand(0)); 7517 // Generate SUBS & CSEL. 7518 SDValue Cmp = 7519 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 7520 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 7521 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 7522 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 7523 SDValue(Cmp.getNode(), 1)); 7524 } 7525 return SDValue(); 7526 } 7527 7528 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 7529 TargetLowering::DAGCombinerInfo &DCI, 7530 const AArch64Subtarget *Subtarget) { 7531 if (DCI.isBeforeLegalizeOps()) 7532 return SDValue(); 7533 7534 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 7535 return Cmp; 7536 7537 return performIntegerAbsCombine(N, DAG); 7538 } 7539 7540 SDValue 7541 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7542 SelectionDAG &DAG, 7543 std::vector<SDNode *> *Created) const { 7544 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 7545 if (isIntDivCheap(N->getValueType(0), Attr)) 7546 return SDValue(N,0); // Lower SDIV as SDIV 7547 7548 // fold (sdiv X, pow2) 7549 EVT VT = N->getValueType(0); 7550 if ((VT != MVT::i32 && VT != MVT::i64) || 7551 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 7552 return SDValue(); 7553 7554 SDLoc DL(N); 7555 SDValue N0 = N->getOperand(0); 7556 unsigned Lg2 = Divisor.countTrailingZeros(); 7557 SDValue Zero = DAG.getConstant(0, DL, VT); 7558 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 7559 7560 // Add (N0 < 0) ? Pow2 - 1 : 0; 7561 SDValue CCVal; 7562 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 7563 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 7564 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 7565 7566 if (Created) { 7567 Created->push_back(Cmp.getNode()); 7568 Created->push_back(Add.getNode()); 7569 Created->push_back(CSel.getNode()); 7570 } 7571 7572 // Divide by pow2. 7573 SDValue SRA = 7574 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 7575 7576 // If we're dividing by a positive value, we're done. Otherwise, we must 7577 // negate the result. 7578 if (Divisor.isNonNegative()) 7579 return SRA; 7580 7581 if (Created) 7582 Created->push_back(SRA.getNode()); 7583 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 7584 } 7585 7586 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 7587 TargetLowering::DAGCombinerInfo &DCI, 7588 const AArch64Subtarget *Subtarget) { 7589 if (DCI.isBeforeLegalizeOps()) 7590 return SDValue(); 7591 7592 // Multiplication of a power of two plus/minus one can be done more 7593 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 7594 // future CPUs have a cheaper MADD instruction, this may need to be 7595 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 7596 // 64-bit is 5 cycles, so this is always a win. 7597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 7598 const APInt &Value = C->getAPIntValue(); 7599 EVT VT = N->getValueType(0); 7600 SDLoc DL(N); 7601 if (Value.isNonNegative()) { 7602 // (mul x, 2^N + 1) => (add (shl x, N), x) 7603 APInt VM1 = Value - 1; 7604 if (VM1.isPowerOf2()) { 7605 SDValue ShiftedVal = 7606 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7607 DAG.getConstant(VM1.logBase2(), DL, MVT::i64)); 7608 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, 7609 N->getOperand(0)); 7610 } 7611 // (mul x, 2^N - 1) => (sub (shl x, N), x) 7612 APInt VP1 = Value + 1; 7613 if (VP1.isPowerOf2()) { 7614 SDValue ShiftedVal = 7615 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7616 DAG.getConstant(VP1.logBase2(), DL, MVT::i64)); 7617 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal, 7618 N->getOperand(0)); 7619 } 7620 } else { 7621 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 7622 APInt VNP1 = -Value + 1; 7623 if (VNP1.isPowerOf2()) { 7624 SDValue ShiftedVal = 7625 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7626 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64)); 7627 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), 7628 ShiftedVal); 7629 } 7630 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 7631 APInt VNM1 = -Value - 1; 7632 if (VNM1.isPowerOf2()) { 7633 SDValue ShiftedVal = 7634 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 7635 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64)); 7636 SDValue Add = 7637 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0)); 7638 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add); 7639 } 7640 } 7641 } 7642 return SDValue(); 7643 } 7644 7645 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 7646 SelectionDAG &DAG) { 7647 // Take advantage of vector comparisons producing 0 or -1 in each lane to 7648 // optimize away operation when it's from a constant. 7649 // 7650 // The general transformation is: 7651 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 7652 // AND(VECTOR_CMP(x,y), constant2) 7653 // constant2 = UNARYOP(constant) 7654 7655 // Early exit if this isn't a vector operation, the operand of the 7656 // unary operation isn't a bitwise AND, or if the sizes of the operations 7657 // aren't the same. 7658 EVT VT = N->getValueType(0); 7659 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 7660 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 7661 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 7662 return SDValue(); 7663 7664 // Now check that the other operand of the AND is a constant. We could 7665 // make the transformation for non-constant splats as well, but it's unclear 7666 // that would be a benefit as it would not eliminate any operations, just 7667 // perform one more step in scalar code before moving to the vector unit. 7668 if (BuildVectorSDNode *BV = 7669 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 7670 // Bail out if the vector isn't a constant. 7671 if (!BV->isConstant()) 7672 return SDValue(); 7673 7674 // Everything checks out. Build up the new and improved node. 7675 SDLoc DL(N); 7676 EVT IntVT = BV->getValueType(0); 7677 // Create a new constant of the appropriate type for the transformed 7678 // DAG. 7679 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 7680 // The AND node needs bitcasts to/from an integer vector type around it. 7681 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 7682 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 7683 N->getOperand(0)->getOperand(0), MaskConst); 7684 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 7685 return Res; 7686 } 7687 7688 return SDValue(); 7689 } 7690 7691 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 7692 const AArch64Subtarget *Subtarget) { 7693 // First try to optimize away the conversion when it's conditionally from 7694 // a constant. Vectors only. 7695 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 7696 return Res; 7697 7698 EVT VT = N->getValueType(0); 7699 if (VT != MVT::f32 && VT != MVT::f64) 7700 return SDValue(); 7701 7702 // Only optimize when the source and destination types have the same width. 7703 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits()) 7704 return SDValue(); 7705 7706 // If the result of an integer load is only used by an integer-to-float 7707 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 7708 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 7709 SDValue N0 = N->getOperand(0); 7710 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7711 // Do not change the width of a volatile load. 7712 !cast<LoadSDNode>(N0)->isVolatile()) { 7713 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7714 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7715 LN0->getPointerInfo(), LN0->isVolatile(), 7716 LN0->isNonTemporal(), LN0->isInvariant(), 7717 LN0->getAlignment()); 7718 7719 // Make sure successors of the original load stay after it by updating them 7720 // to use the new Chain. 7721 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 7722 7723 unsigned Opcode = 7724 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 7725 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 7726 } 7727 7728 return SDValue(); 7729 } 7730 7731 /// Fold a floating-point multiply by power of two into floating-point to 7732 /// fixed-point conversion. 7733 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 7734 const AArch64Subtarget *Subtarget) { 7735 if (!Subtarget->hasNEON()) 7736 return SDValue(); 7737 7738 SDValue Op = N->getOperand(0); 7739 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 7740 Op.getOpcode() != ISD::FMUL) 7741 return SDValue(); 7742 7743 SDValue ConstVec = Op->getOperand(1); 7744 if (!isa<BuildVectorSDNode>(ConstVec)) 7745 return SDValue(); 7746 7747 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 7748 uint32_t FloatBits = FloatTy.getSizeInBits(); 7749 if (FloatBits != 32 && FloatBits != 64) 7750 return SDValue(); 7751 7752 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 7753 uint32_t IntBits = IntTy.getSizeInBits(); 7754 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7755 return SDValue(); 7756 7757 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 7758 if (IntBits > FloatBits) 7759 return SDValue(); 7760 7761 BitVector UndefElements; 7762 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7763 int32_t Bits = IntBits == 64 ? 64 : 32; 7764 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 7765 if (C == -1 || C == 0 || C > Bits) 7766 return SDValue(); 7767 7768 MVT ResTy; 7769 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7770 switch (NumLanes) { 7771 default: 7772 return SDValue(); 7773 case 2: 7774 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7775 break; 7776 case 4: 7777 ResTy = MVT::v4i32; 7778 break; 7779 } 7780 7781 SDLoc DL(N); 7782 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7783 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 7784 : Intrinsic::aarch64_neon_vcvtfp2fxu; 7785 SDValue FixConv = 7786 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 7787 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 7788 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 7789 // We can handle smaller integers by generating an extra trunc. 7790 if (IntBits < FloatBits) 7791 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 7792 7793 return FixConv; 7794 } 7795 7796 /// Fold a floating-point divide by power of two into fixed-point to 7797 /// floating-point conversion. 7798 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 7799 const AArch64Subtarget *Subtarget) { 7800 if (!Subtarget->hasNEON()) 7801 return SDValue(); 7802 7803 SDValue Op = N->getOperand(0); 7804 unsigned Opc = Op->getOpcode(); 7805 if (!Op.getValueType().isVector() || 7806 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 7807 return SDValue(); 7808 7809 SDValue ConstVec = N->getOperand(1); 7810 if (!isa<BuildVectorSDNode>(ConstVec)) 7811 return SDValue(); 7812 7813 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 7814 int32_t IntBits = IntTy.getSizeInBits(); 7815 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7816 return SDValue(); 7817 7818 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 7819 int32_t FloatBits = FloatTy.getSizeInBits(); 7820 if (FloatBits != 32 && FloatBits != 64) 7821 return SDValue(); 7822 7823 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 7824 if (IntBits > FloatBits) 7825 return SDValue(); 7826 7827 BitVector UndefElements; 7828 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7829 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 7830 if (C == -1 || C == 0 || C > FloatBits) 7831 return SDValue(); 7832 7833 MVT ResTy; 7834 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7835 switch (NumLanes) { 7836 default: 7837 return SDValue(); 7838 case 2: 7839 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7840 break; 7841 case 4: 7842 ResTy = MVT::v4i32; 7843 break; 7844 } 7845 7846 SDLoc DL(N); 7847 SDValue ConvInput = Op.getOperand(0); 7848 bool IsSigned = Opc == ISD::SINT_TO_FP; 7849 if (IntBits < FloatBits) 7850 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 7851 ResTy, ConvInput); 7852 7853 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 7854 : Intrinsic::aarch64_neon_vcvtfxu2fp; 7855 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 7856 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 7857 DAG.getConstant(C, DL, MVT::i32)); 7858 } 7859 7860 /// An EXTR instruction is made up of two shifts, ORed together. This helper 7861 /// searches for and classifies those shifts. 7862 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 7863 bool &FromHi) { 7864 if (N.getOpcode() == ISD::SHL) 7865 FromHi = false; 7866 else if (N.getOpcode() == ISD::SRL) 7867 FromHi = true; 7868 else 7869 return false; 7870 7871 if (!isa<ConstantSDNode>(N.getOperand(1))) 7872 return false; 7873 7874 ShiftAmount = N->getConstantOperandVal(1); 7875 Src = N->getOperand(0); 7876 return true; 7877 } 7878 7879 /// EXTR instruction extracts a contiguous chunk of bits from two existing 7880 /// registers viewed as a high/low pair. This function looks for the pattern: 7881 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an 7882 /// EXTR. Can't quite be done in TableGen because the two immediates aren't 7883 /// independent. 7884 static SDValue tryCombineToEXTR(SDNode *N, 7885 TargetLowering::DAGCombinerInfo &DCI) { 7886 SelectionDAG &DAG = DCI.DAG; 7887 SDLoc DL(N); 7888 EVT VT = N->getValueType(0); 7889 7890 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 7891 7892 if (VT != MVT::i32 && VT != MVT::i64) 7893 return SDValue(); 7894 7895 SDValue LHS; 7896 uint32_t ShiftLHS = 0; 7897 bool LHSFromHi = 0; 7898 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 7899 return SDValue(); 7900 7901 SDValue RHS; 7902 uint32_t ShiftRHS = 0; 7903 bool RHSFromHi = 0; 7904 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 7905 return SDValue(); 7906 7907 // If they're both trying to come from the high part of the register, they're 7908 // not really an EXTR. 7909 if (LHSFromHi == RHSFromHi) 7910 return SDValue(); 7911 7912 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 7913 return SDValue(); 7914 7915 if (LHSFromHi) { 7916 std::swap(LHS, RHS); 7917 std::swap(ShiftLHS, ShiftRHS); 7918 } 7919 7920 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 7921 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 7922 } 7923 7924 static SDValue tryCombineToBSL(SDNode *N, 7925 TargetLowering::DAGCombinerInfo &DCI) { 7926 EVT VT = N->getValueType(0); 7927 SelectionDAG &DAG = DCI.DAG; 7928 SDLoc DL(N); 7929 7930 if (!VT.isVector()) 7931 return SDValue(); 7932 7933 SDValue N0 = N->getOperand(0); 7934 if (N0.getOpcode() != ISD::AND) 7935 return SDValue(); 7936 7937 SDValue N1 = N->getOperand(1); 7938 if (N1.getOpcode() != ISD::AND) 7939 return SDValue(); 7940 7941 // We only have to look for constant vectors here since the general, variable 7942 // case can be handled in TableGen. 7943 unsigned Bits = VT.getVectorElementType().getSizeInBits(); 7944 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 7945 for (int i = 1; i >= 0; --i) 7946 for (int j = 1; j >= 0; --j) { 7947 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 7948 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 7949 if (!BVN0 || !BVN1) 7950 continue; 7951 7952 bool FoundMatch = true; 7953 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 7954 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 7955 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 7956 if (!CN0 || !CN1 || 7957 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 7958 FoundMatch = false; 7959 break; 7960 } 7961 } 7962 7963 if (FoundMatch) 7964 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 7965 N0->getOperand(1 - i), N1->getOperand(1 - j)); 7966 } 7967 7968 return SDValue(); 7969 } 7970 7971 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 7972 const AArch64Subtarget *Subtarget) { 7973 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 7974 SelectionDAG &DAG = DCI.DAG; 7975 EVT VT = N->getValueType(0); 7976 7977 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 7978 return SDValue(); 7979 7980 if (SDValue Res = tryCombineToEXTR(N, DCI)) 7981 return Res; 7982 7983 if (SDValue Res = tryCombineToBSL(N, DCI)) 7984 return Res; 7985 7986 return SDValue(); 7987 } 7988 7989 static SDValue performSRLCombine(SDNode *N, 7990 TargetLowering::DAGCombinerInfo &DCI) { 7991 SelectionDAG &DAG = DCI.DAG; 7992 EVT VT = N->getValueType(0); 7993 if (VT != MVT::i32 && VT != MVT::i64) 7994 return SDValue(); 7995 7996 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 7997 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 7998 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 7999 SDValue N0 = N->getOperand(0); 8000 if (N0.getOpcode() == ISD::BSWAP) { 8001 SDLoc DL(N); 8002 SDValue N1 = N->getOperand(1); 8003 SDValue N00 = N0.getOperand(0); 8004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 8005 uint64_t ShiftAmt = C->getZExtValue(); 8006 if (VT == MVT::i32 && ShiftAmt == 16 && 8007 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 8008 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8009 if (VT == MVT::i64 && ShiftAmt == 32 && 8010 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 8011 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8012 } 8013 } 8014 return SDValue(); 8015 } 8016 8017 static SDValue performBitcastCombine(SDNode *N, 8018 TargetLowering::DAGCombinerInfo &DCI, 8019 SelectionDAG &DAG) { 8020 // Wait 'til after everything is legalized to try this. That way we have 8021 // legal vector types and such. 8022 if (DCI.isBeforeLegalizeOps()) 8023 return SDValue(); 8024 8025 // Remove extraneous bitcasts around an extract_subvector. 8026 // For example, 8027 // (v4i16 (bitconvert 8028 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 8029 // becomes 8030 // (extract_subvector ((v8i16 ...), (i64 4))) 8031 8032 // Only interested in 64-bit vectors as the ultimate result. 8033 EVT VT = N->getValueType(0); 8034 if (!VT.isVector()) 8035 return SDValue(); 8036 if (VT.getSimpleVT().getSizeInBits() != 64) 8037 return SDValue(); 8038 // Is the operand an extract_subvector starting at the beginning or halfway 8039 // point of the vector? A low half may also come through as an 8040 // EXTRACT_SUBREG, so look for that, too. 8041 SDValue Op0 = N->getOperand(0); 8042 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 8043 !(Op0->isMachineOpcode() && 8044 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 8045 return SDValue(); 8046 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 8047 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8048 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 8049 return SDValue(); 8050 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 8051 if (idx != AArch64::dsub) 8052 return SDValue(); 8053 // The dsub reference is equivalent to a lane zero subvector reference. 8054 idx = 0; 8055 } 8056 // Look through the bitcast of the input to the extract. 8057 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 8058 return SDValue(); 8059 SDValue Source = Op0->getOperand(0)->getOperand(0); 8060 // If the source type has twice the number of elements as our destination 8061 // type, we know this is an extract of the high or low half of the vector. 8062 EVT SVT = Source->getValueType(0); 8063 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 8064 return SDValue(); 8065 8066 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 8067 8068 // Create the simplified form to just extract the low or high half of the 8069 // vector directly rather than bothering with the bitcasts. 8070 SDLoc dl(N); 8071 unsigned NumElements = VT.getVectorNumElements(); 8072 if (idx) { 8073 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8074 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8075 } else { 8076 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8077 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8078 Source, SubReg), 8079 0); 8080 } 8081 } 8082 8083 static SDValue performConcatVectorsCombine(SDNode *N, 8084 TargetLowering::DAGCombinerInfo &DCI, 8085 SelectionDAG &DAG) { 8086 SDLoc dl(N); 8087 EVT VT = N->getValueType(0); 8088 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8089 8090 // Optimize concat_vectors of truncated vectors, where the intermediate 8091 // type is illegal, to avoid said illegality, e.g., 8092 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8093 // (v2i16 (truncate (v2i64))))) 8094 // -> 8095 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8096 // (v4i32 (bitcast (v2i64))), 8097 // <0, 2, 4, 6>))) 8098 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8099 // on both input and result type, so we might generate worse code. 8100 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8101 if (N->getNumOperands() == 2 && 8102 N0->getOpcode() == ISD::TRUNCATE && 8103 N1->getOpcode() == ISD::TRUNCATE) { 8104 SDValue N00 = N0->getOperand(0); 8105 SDValue N10 = N1->getOperand(0); 8106 EVT N00VT = N00.getValueType(); 8107 8108 if (N00VT == N10.getValueType() && 8109 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8110 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8111 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8112 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8113 for (size_t i = 0; i < Mask.size(); ++i) 8114 Mask[i] = i * 2; 8115 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8116 DAG.getVectorShuffle( 8117 MidVT, dl, 8118 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8119 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8120 } 8121 } 8122 8123 // Wait 'til after everything is legalized to try this. That way we have 8124 // legal vector types and such. 8125 if (DCI.isBeforeLegalizeOps()) 8126 return SDValue(); 8127 8128 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8129 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8130 // canonicalise to that. 8131 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8132 assert(VT.getVectorElementType().getSizeInBits() == 64); 8133 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8134 DAG.getConstant(0, dl, MVT::i64)); 8135 } 8136 8137 // Canonicalise concat_vectors so that the right-hand vector has as few 8138 // bit-casts as possible before its real operation. The primary matching 8139 // destination for these operations will be the narrowing "2" instructions, 8140 // which depend on the operation being performed on this right-hand vector. 8141 // For example, 8142 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8143 // becomes 8144 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8145 8146 if (N1->getOpcode() != ISD::BITCAST) 8147 return SDValue(); 8148 SDValue RHS = N1->getOperand(0); 8149 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8150 // If the RHS is not a vector, this is not the pattern we're looking for. 8151 if (!RHSTy.isVector()) 8152 return SDValue(); 8153 8154 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8155 8156 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8157 RHSTy.getVectorNumElements() * 2); 8158 return DAG.getNode(ISD::BITCAST, dl, VT, 8159 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8160 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8161 RHS)); 8162 } 8163 8164 static SDValue tryCombineFixedPointConvert(SDNode *N, 8165 TargetLowering::DAGCombinerInfo &DCI, 8166 SelectionDAG &DAG) { 8167 // Wait 'til after everything is legalized to try this. That way we have 8168 // legal vector types and such. 8169 if (DCI.isBeforeLegalizeOps()) 8170 return SDValue(); 8171 // Transform a scalar conversion of a value from a lane extract into a 8172 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8173 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8174 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8175 // 8176 // The second form interacts better with instruction selection and the 8177 // register allocator to avoid cross-class register copies that aren't 8178 // coalescable due to a lane reference. 8179 8180 // Check the operand and see if it originates from a lane extract. 8181 SDValue Op1 = N->getOperand(1); 8182 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8183 // Yep, no additional predication needed. Perform the transform. 8184 SDValue IID = N->getOperand(0); 8185 SDValue Shift = N->getOperand(2); 8186 SDValue Vec = Op1.getOperand(0); 8187 SDValue Lane = Op1.getOperand(1); 8188 EVT ResTy = N->getValueType(0); 8189 EVT VecResTy; 8190 SDLoc DL(N); 8191 8192 // The vector width should be 128 bits by the time we get here, even 8193 // if it started as 64 bits (the extract_vector handling will have 8194 // done so). 8195 assert(Vec.getValueType().getSizeInBits() == 128 && 8196 "unexpected vector size on extract_vector_elt!"); 8197 if (Vec.getValueType() == MVT::v4i32) 8198 VecResTy = MVT::v4f32; 8199 else if (Vec.getValueType() == MVT::v2i64) 8200 VecResTy = MVT::v2f64; 8201 else 8202 llvm_unreachable("unexpected vector type!"); 8203 8204 SDValue Convert = 8205 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8206 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8207 } 8208 return SDValue(); 8209 } 8210 8211 // AArch64 high-vector "long" operations are formed by performing the non-high 8212 // version on an extract_subvector of each operand which gets the high half: 8213 // 8214 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8215 // 8216 // However, there are cases which don't have an extract_high explicitly, but 8217 // have another operation that can be made compatible with one for free. For 8218 // example: 8219 // 8220 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8221 // 8222 // This routine does the actual conversion of such DUPs, once outer routines 8223 // have determined that everything else is in order. 8224 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8225 // similarly here. 8226 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8227 switch (N.getOpcode()) { 8228 case AArch64ISD::DUP: 8229 case AArch64ISD::DUPLANE8: 8230 case AArch64ISD::DUPLANE16: 8231 case AArch64ISD::DUPLANE32: 8232 case AArch64ISD::DUPLANE64: 8233 case AArch64ISD::MOVI: 8234 case AArch64ISD::MOVIshift: 8235 case AArch64ISD::MOVIedit: 8236 case AArch64ISD::MOVImsl: 8237 case AArch64ISD::MVNIshift: 8238 case AArch64ISD::MVNImsl: 8239 break; 8240 default: 8241 // FMOV could be supported, but isn't very useful, as it would only occur 8242 // if you passed a bitcast' floating point immediate to an eligible long 8243 // integer op (addl, smull, ...). 8244 return SDValue(); 8245 } 8246 8247 MVT NarrowTy = N.getSimpleValueType(); 8248 if (!NarrowTy.is64BitVector()) 8249 return SDValue(); 8250 8251 MVT ElementTy = NarrowTy.getVectorElementType(); 8252 unsigned NumElems = NarrowTy.getVectorNumElements(); 8253 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8254 8255 SDLoc dl(N); 8256 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8257 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8258 DAG.getConstant(NumElems, dl, MVT::i64)); 8259 } 8260 8261 static bool isEssentiallyExtractSubvector(SDValue N) { 8262 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8263 return true; 8264 8265 return N.getOpcode() == ISD::BITCAST && 8266 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8267 } 8268 8269 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8270 struct GenericSetCCInfo { 8271 const SDValue *Opnd0; 8272 const SDValue *Opnd1; 8273 ISD::CondCode CC; 8274 }; 8275 8276 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8277 struct AArch64SetCCInfo { 8278 const SDValue *Cmp; 8279 AArch64CC::CondCode CC; 8280 }; 8281 8282 /// \brief Helper structure to keep track of SetCC information. 8283 union SetCCInfo { 8284 GenericSetCCInfo Generic; 8285 AArch64SetCCInfo AArch64; 8286 }; 8287 8288 /// \brief Helper structure to be able to read SetCC information. If set to 8289 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8290 /// GenericSetCCInfo. 8291 struct SetCCInfoAndKind { 8292 SetCCInfo Info; 8293 bool IsAArch64; 8294 }; 8295 8296 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8297 /// an 8298 /// AArch64 lowered one. 8299 /// \p SetCCInfo is filled accordingly. 8300 /// \post SetCCInfo is meanginfull only when this function returns true. 8301 /// \return True when Op is a kind of SET_CC operation. 8302 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8303 // If this is a setcc, this is straight forward. 8304 if (Op.getOpcode() == ISD::SETCC) { 8305 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8306 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8307 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8308 SetCCInfo.IsAArch64 = false; 8309 return true; 8310 } 8311 // Otherwise, check if this is a matching csel instruction. 8312 // In other words: 8313 // - csel 1, 0, cc 8314 // - csel 0, 1, !cc 8315 if (Op.getOpcode() != AArch64ISD::CSEL) 8316 return false; 8317 // Set the information about the operands. 8318 // TODO: we want the operands of the Cmp not the csel 8319 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8320 SetCCInfo.IsAArch64 = true; 8321 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8322 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8323 8324 // Check that the operands matches the constraints: 8325 // (1) Both operands must be constants. 8326 // (2) One must be 1 and the other must be 0. 8327 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 8328 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8329 8330 // Check (1). 8331 if (!TValue || !FValue) 8332 return false; 8333 8334 // Check (2). 8335 if (!TValue->isOne()) { 8336 // Update the comparison when we are interested in !cc. 8337 std::swap(TValue, FValue); 8338 SetCCInfo.Info.AArch64.CC = 8339 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 8340 } 8341 return TValue->isOne() && FValue->isNullValue(); 8342 } 8343 8344 // Returns true if Op is setcc or zext of setcc. 8345 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 8346 if (isSetCC(Op, Info)) 8347 return true; 8348 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 8349 isSetCC(Op->getOperand(0), Info)); 8350 } 8351 8352 // The folding we want to perform is: 8353 // (add x, [zext] (setcc cc ...) ) 8354 // --> 8355 // (csel x, (add x, 1), !cc ...) 8356 // 8357 // The latter will get matched to a CSINC instruction. 8358 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 8359 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 8360 SDValue LHS = Op->getOperand(0); 8361 SDValue RHS = Op->getOperand(1); 8362 SetCCInfoAndKind InfoAndKind; 8363 8364 // If neither operand is a SET_CC, give up. 8365 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 8366 std::swap(LHS, RHS); 8367 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 8368 return SDValue(); 8369 } 8370 8371 // FIXME: This could be generatized to work for FP comparisons. 8372 EVT CmpVT = InfoAndKind.IsAArch64 8373 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 8374 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 8375 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 8376 return SDValue(); 8377 8378 SDValue CCVal; 8379 SDValue Cmp; 8380 SDLoc dl(Op); 8381 if (InfoAndKind.IsAArch64) { 8382 CCVal = DAG.getConstant( 8383 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 8384 MVT::i32); 8385 Cmp = *InfoAndKind.Info.AArch64.Cmp; 8386 } else 8387 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 8388 *InfoAndKind.Info.Generic.Opnd1, 8389 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 8390 CCVal, DAG, dl); 8391 8392 EVT VT = Op->getValueType(0); 8393 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 8394 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 8395 } 8396 8397 // The basic add/sub long vector instructions have variants with "2" on the end 8398 // which act on the high-half of their inputs. They are normally matched by 8399 // patterns like: 8400 // 8401 // (add (zeroext (extract_high LHS)), 8402 // (zeroext (extract_high RHS))) 8403 // -> uaddl2 vD, vN, vM 8404 // 8405 // However, if one of the extracts is something like a duplicate, this 8406 // instruction can still be used profitably. This function puts the DAG into a 8407 // more appropriate form for those patterns to trigger. 8408 static SDValue performAddSubLongCombine(SDNode *N, 8409 TargetLowering::DAGCombinerInfo &DCI, 8410 SelectionDAG &DAG) { 8411 if (DCI.isBeforeLegalizeOps()) 8412 return SDValue(); 8413 8414 MVT VT = N->getSimpleValueType(0); 8415 if (!VT.is128BitVector()) { 8416 if (N->getOpcode() == ISD::ADD) 8417 return performSetccAddFolding(N, DAG); 8418 return SDValue(); 8419 } 8420 8421 // Make sure both branches are extended in the same way. 8422 SDValue LHS = N->getOperand(0); 8423 SDValue RHS = N->getOperand(1); 8424 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 8425 LHS.getOpcode() != ISD::SIGN_EXTEND) || 8426 LHS.getOpcode() != RHS.getOpcode()) 8427 return SDValue(); 8428 8429 unsigned ExtType = LHS.getOpcode(); 8430 8431 // It's not worth doing if at least one of the inputs isn't already an 8432 // extract, but we don't know which it'll be so we have to try both. 8433 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 8434 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 8435 if (!RHS.getNode()) 8436 return SDValue(); 8437 8438 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 8439 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 8440 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 8441 if (!LHS.getNode()) 8442 return SDValue(); 8443 8444 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 8445 } 8446 8447 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 8448 } 8449 8450 // Massage DAGs which we can use the high-half "long" operations on into 8451 // something isel will recognize better. E.g. 8452 // 8453 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 8454 // (aarch64_neon_umull (extract_high (v2i64 vec))) 8455 // (extract_high (v2i64 (dup128 scalar))))) 8456 // 8457 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 8458 TargetLowering::DAGCombinerInfo &DCI, 8459 SelectionDAG &DAG) { 8460 if (DCI.isBeforeLegalizeOps()) 8461 return SDValue(); 8462 8463 SDValue LHS = N->getOperand(1); 8464 SDValue RHS = N->getOperand(2); 8465 assert(LHS.getValueType().is64BitVector() && 8466 RHS.getValueType().is64BitVector() && 8467 "unexpected shape for long operation"); 8468 8469 // Either node could be a DUP, but it's not worth doing both of them (you'd 8470 // just as well use the non-high version) so look for a corresponding extract 8471 // operation on the other "wing". 8472 if (isEssentiallyExtractSubvector(LHS)) { 8473 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 8474 if (!RHS.getNode()) 8475 return SDValue(); 8476 } else if (isEssentiallyExtractSubvector(RHS)) { 8477 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 8478 if (!LHS.getNode()) 8479 return SDValue(); 8480 } 8481 8482 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 8483 N->getOperand(0), LHS, RHS); 8484 } 8485 8486 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 8487 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 8488 unsigned ElemBits = ElemTy.getSizeInBits(); 8489 8490 int64_t ShiftAmount; 8491 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 8492 APInt SplatValue, SplatUndef; 8493 unsigned SplatBitSize; 8494 bool HasAnyUndefs; 8495 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 8496 HasAnyUndefs, ElemBits) || 8497 SplatBitSize != ElemBits) 8498 return SDValue(); 8499 8500 ShiftAmount = SplatValue.getSExtValue(); 8501 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 8502 ShiftAmount = CVN->getSExtValue(); 8503 } else 8504 return SDValue(); 8505 8506 unsigned Opcode; 8507 bool IsRightShift; 8508 switch (IID) { 8509 default: 8510 llvm_unreachable("Unknown shift intrinsic"); 8511 case Intrinsic::aarch64_neon_sqshl: 8512 Opcode = AArch64ISD::SQSHL_I; 8513 IsRightShift = false; 8514 break; 8515 case Intrinsic::aarch64_neon_uqshl: 8516 Opcode = AArch64ISD::UQSHL_I; 8517 IsRightShift = false; 8518 break; 8519 case Intrinsic::aarch64_neon_srshl: 8520 Opcode = AArch64ISD::SRSHR_I; 8521 IsRightShift = true; 8522 break; 8523 case Intrinsic::aarch64_neon_urshl: 8524 Opcode = AArch64ISD::URSHR_I; 8525 IsRightShift = true; 8526 break; 8527 case Intrinsic::aarch64_neon_sqshlu: 8528 Opcode = AArch64ISD::SQSHLU_I; 8529 IsRightShift = false; 8530 break; 8531 } 8532 8533 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 8534 SDLoc dl(N); 8535 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8536 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 8537 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 8538 SDLoc dl(N); 8539 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8540 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 8541 } 8542 8543 return SDValue(); 8544 } 8545 8546 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 8547 // the intrinsics must be legal and take an i32, this means there's almost 8548 // certainly going to be a zext in the DAG which we can eliminate. 8549 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 8550 SDValue AndN = N->getOperand(2); 8551 if (AndN.getOpcode() != ISD::AND) 8552 return SDValue(); 8553 8554 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 8555 if (!CMask || CMask->getZExtValue() != Mask) 8556 return SDValue(); 8557 8558 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 8559 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 8560 } 8561 8562 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 8563 SelectionDAG &DAG) { 8564 SDLoc dl(N); 8565 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 8566 DAG.getNode(Opc, dl, 8567 N->getOperand(1).getSimpleValueType(), 8568 N->getOperand(1)), 8569 DAG.getConstant(0, dl, MVT::i64)); 8570 } 8571 8572 static SDValue performIntrinsicCombine(SDNode *N, 8573 TargetLowering::DAGCombinerInfo &DCI, 8574 const AArch64Subtarget *Subtarget) { 8575 SelectionDAG &DAG = DCI.DAG; 8576 unsigned IID = getIntrinsicID(N); 8577 switch (IID) { 8578 default: 8579 break; 8580 case Intrinsic::aarch64_neon_vcvtfxs2fp: 8581 case Intrinsic::aarch64_neon_vcvtfxu2fp: 8582 return tryCombineFixedPointConvert(N, DCI, DAG); 8583 case Intrinsic::aarch64_neon_saddv: 8584 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 8585 case Intrinsic::aarch64_neon_uaddv: 8586 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 8587 case Intrinsic::aarch64_neon_sminv: 8588 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 8589 case Intrinsic::aarch64_neon_uminv: 8590 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 8591 case Intrinsic::aarch64_neon_smaxv: 8592 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 8593 case Intrinsic::aarch64_neon_umaxv: 8594 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 8595 case Intrinsic::aarch64_neon_fmax: 8596 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 8597 N->getOperand(1), N->getOperand(2)); 8598 case Intrinsic::aarch64_neon_fmin: 8599 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 8600 N->getOperand(1), N->getOperand(2)); 8601 case Intrinsic::aarch64_neon_fmaxnm: 8602 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 8603 N->getOperand(1), N->getOperand(2)); 8604 case Intrinsic::aarch64_neon_fminnm: 8605 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 8606 N->getOperand(1), N->getOperand(2)); 8607 case Intrinsic::aarch64_neon_smull: 8608 case Intrinsic::aarch64_neon_umull: 8609 case Intrinsic::aarch64_neon_pmull: 8610 case Intrinsic::aarch64_neon_sqdmull: 8611 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 8612 case Intrinsic::aarch64_neon_sqshl: 8613 case Intrinsic::aarch64_neon_uqshl: 8614 case Intrinsic::aarch64_neon_sqshlu: 8615 case Intrinsic::aarch64_neon_srshl: 8616 case Intrinsic::aarch64_neon_urshl: 8617 return tryCombineShiftImm(IID, N, DAG); 8618 case Intrinsic::aarch64_crc32b: 8619 case Intrinsic::aarch64_crc32cb: 8620 return tryCombineCRC32(0xff, N, DAG); 8621 case Intrinsic::aarch64_crc32h: 8622 case Intrinsic::aarch64_crc32ch: 8623 return tryCombineCRC32(0xffff, N, DAG); 8624 } 8625 return SDValue(); 8626 } 8627 8628 static SDValue performExtendCombine(SDNode *N, 8629 TargetLowering::DAGCombinerInfo &DCI, 8630 SelectionDAG &DAG) { 8631 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 8632 // we can convert that DUP into another extract_high (of a bigger DUP), which 8633 // helps the backend to decide that an sabdl2 would be useful, saving a real 8634 // extract_high operation. 8635 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 8636 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 8637 SDNode *ABDNode = N->getOperand(0).getNode(); 8638 unsigned IID = getIntrinsicID(ABDNode); 8639 if (IID == Intrinsic::aarch64_neon_sabd || 8640 IID == Intrinsic::aarch64_neon_uabd) { 8641 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 8642 if (!NewABD.getNode()) 8643 return SDValue(); 8644 8645 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 8646 NewABD); 8647 } 8648 } 8649 8650 // This is effectively a custom type legalization for AArch64. 8651 // 8652 // Type legalization will split an extend of a small, legal, type to a larger 8653 // illegal type by first splitting the destination type, often creating 8654 // illegal source types, which then get legalized in isel-confusing ways, 8655 // leading to really terrible codegen. E.g., 8656 // %result = v8i32 sext v8i8 %value 8657 // becomes 8658 // %losrc = extract_subreg %value, ... 8659 // %hisrc = extract_subreg %value, ... 8660 // %lo = v4i32 sext v4i8 %losrc 8661 // %hi = v4i32 sext v4i8 %hisrc 8662 // Things go rapidly downhill from there. 8663 // 8664 // For AArch64, the [sz]ext vector instructions can only go up one element 8665 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 8666 // take two instructions. 8667 // 8668 // This implies that the most efficient way to do the extend from v8i8 8669 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 8670 // the normal splitting to happen for the v8i16->v8i32. 8671 8672 // This is pre-legalization to catch some cases where the default 8673 // type legalization will create ill-tempered code. 8674 if (!DCI.isBeforeLegalizeOps()) 8675 return SDValue(); 8676 8677 // We're only interested in cleaning things up for non-legal vector types 8678 // here. If both the source and destination are legal, things will just 8679 // work naturally without any fiddling. 8680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8681 EVT ResVT = N->getValueType(0); 8682 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 8683 return SDValue(); 8684 // If the vector type isn't a simple VT, it's beyond the scope of what 8685 // we're worried about here. Let legalization do its thing and hope for 8686 // the best. 8687 SDValue Src = N->getOperand(0); 8688 EVT SrcVT = Src->getValueType(0); 8689 if (!ResVT.isSimple() || !SrcVT.isSimple()) 8690 return SDValue(); 8691 8692 // If the source VT is a 64-bit vector, we can play games and get the 8693 // better results we want. 8694 if (SrcVT.getSizeInBits() != 64) 8695 return SDValue(); 8696 8697 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits(); 8698 unsigned ElementCount = SrcVT.getVectorNumElements(); 8699 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 8700 SDLoc DL(N); 8701 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 8702 8703 // Now split the rest of the operation into two halves, each with a 64 8704 // bit source. 8705 EVT LoVT, HiVT; 8706 SDValue Lo, Hi; 8707 unsigned NumElements = ResVT.getVectorNumElements(); 8708 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 8709 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 8710 ResVT.getVectorElementType(), NumElements / 2); 8711 8712 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 8713 LoVT.getVectorNumElements()); 8714 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8715 DAG.getConstant(0, DL, MVT::i64)); 8716 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8717 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 8718 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 8719 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 8720 8721 // Now combine the parts back together so we still have a single result 8722 // like the combiner expects. 8723 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 8724 } 8725 8726 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 8727 /// value. The load store optimizer pass will merge them to store pair stores. 8728 /// This has better performance than a splat of the scalar followed by a split 8729 /// vector store. Even if the stores are not merged it is four stores vs a dup, 8730 /// followed by an ext.b and two stores. 8731 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) { 8732 SDValue StVal = St->getValue(); 8733 EVT VT = StVal.getValueType(); 8734 8735 // Don't replace floating point stores, they possibly won't be transformed to 8736 // stp because of the store pair suppress pass. 8737 if (VT.isFloatingPoint()) 8738 return SDValue(); 8739 8740 // Check for insert vector elements. 8741 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 8742 return SDValue(); 8743 8744 // We can express a splat as store pair(s) for 2 or 4 elements. 8745 unsigned NumVecElts = VT.getVectorNumElements(); 8746 if (NumVecElts != 4 && NumVecElts != 2) 8747 return SDValue(); 8748 SDValue SplatVal = StVal.getOperand(1); 8749 unsigned RemainInsertElts = NumVecElts - 1; 8750 8751 // Check that this is a splat. 8752 while (--RemainInsertElts) { 8753 SDValue NextInsertElt = StVal.getOperand(0); 8754 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT) 8755 return SDValue(); 8756 if (NextInsertElt.getOperand(1) != SplatVal) 8757 return SDValue(); 8758 StVal = NextInsertElt; 8759 } 8760 unsigned OrigAlignment = St->getAlignment(); 8761 unsigned EltOffset = NumVecElts == 4 ? 4 : 8; 8762 unsigned Alignment = std::min(OrigAlignment, EltOffset); 8763 8764 // Create scalar stores. This is at least as good as the code sequence for a 8765 // split unaligned store which is a dup.s, ext.b, and two stores. 8766 // Most of the time the three stores should be replaced by store pair 8767 // instructions (stp). 8768 SDLoc DL(St); 8769 SDValue BasePtr = St->getBasePtr(); 8770 SDValue NewST1 = 8771 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(), 8772 St->isVolatile(), St->isNonTemporal(), St->getAlignment()); 8773 8774 unsigned Offset = EltOffset; 8775 while (--NumVecElts) { 8776 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8777 DAG.getConstant(Offset, DL, MVT::i64)); 8778 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 8779 St->getPointerInfo(), St->isVolatile(), 8780 St->isNonTemporal(), Alignment); 8781 Offset += EltOffset; 8782 } 8783 return NewST1; 8784 } 8785 8786 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8787 SelectionDAG &DAG, 8788 const AArch64Subtarget *Subtarget) { 8789 if (!DCI.isBeforeLegalize()) 8790 return SDValue(); 8791 8792 StoreSDNode *S = cast<StoreSDNode>(N); 8793 if (S->isVolatile()) 8794 return SDValue(); 8795 8796 // FIXME: The logic for deciding if an unaligned store should be split should 8797 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 8798 // a call to that function here. 8799 8800 if (!Subtarget->isMisaligned128StoreSlow()) 8801 return SDValue(); 8802 8803 // Don't split at -Oz. 8804 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 8805 return SDValue(); 8806 8807 SDValue StVal = S->getValue(); 8808 EVT VT = StVal.getValueType(); 8809 8810 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 8811 // those up regresses performance on micro-benchmarks and olden/bh. 8812 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 8813 return SDValue(); 8814 8815 // Split unaligned 16B stores. They are terrible for performance. 8816 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 8817 // extensions can use this to mark that it does not want splitting to happen 8818 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 8819 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 8820 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 8821 S->getAlignment() <= 2) 8822 return SDValue(); 8823 8824 // If we get a splat of a scalar convert this vector store to a store of 8825 // scalars. They will be merged into store pairs thereby removing two 8826 // instructions. 8827 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S)) 8828 return ReplacedSplat; 8829 8830 SDLoc DL(S); 8831 unsigned NumElts = VT.getVectorNumElements() / 2; 8832 // Split VT into two. 8833 EVT HalfVT = 8834 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 8835 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 8836 DAG.getConstant(0, DL, MVT::i64)); 8837 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 8838 DAG.getConstant(NumElts, DL, MVT::i64)); 8839 SDValue BasePtr = S->getBasePtr(); 8840 SDValue NewST1 = 8841 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 8842 S->isVolatile(), S->isNonTemporal(), S->getAlignment()); 8843 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8844 DAG.getConstant(8, DL, MVT::i64)); 8845 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 8846 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(), 8847 S->getAlignment()); 8848 } 8849 8850 /// Target-specific DAG combine function for post-increment LD1 (lane) and 8851 /// post-increment LD1R. 8852 static SDValue performPostLD1Combine(SDNode *N, 8853 TargetLowering::DAGCombinerInfo &DCI, 8854 bool IsLaneOp) { 8855 if (DCI.isBeforeLegalizeOps()) 8856 return SDValue(); 8857 8858 SelectionDAG &DAG = DCI.DAG; 8859 EVT VT = N->getValueType(0); 8860 8861 unsigned LoadIdx = IsLaneOp ? 1 : 0; 8862 SDNode *LD = N->getOperand(LoadIdx).getNode(); 8863 // If it is not LOAD, can not do such combine. 8864 if (LD->getOpcode() != ISD::LOAD) 8865 return SDValue(); 8866 8867 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 8868 EVT MemVT = LoadSDN->getMemoryVT(); 8869 // Check if memory operand is the same type as the vector element. 8870 if (MemVT != VT.getVectorElementType()) 8871 return SDValue(); 8872 8873 // Check if there are other uses. If so, do not combine as it will introduce 8874 // an extra load. 8875 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 8876 ++UI) { 8877 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 8878 continue; 8879 if (*UI != N) 8880 return SDValue(); 8881 } 8882 8883 SDValue Addr = LD->getOperand(1); 8884 SDValue Vector = N->getOperand(0); 8885 // Search for a use of the address operand that is an increment. 8886 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 8887 Addr.getNode()->use_end(); UI != UE; ++UI) { 8888 SDNode *User = *UI; 8889 if (User->getOpcode() != ISD::ADD 8890 || UI.getUse().getResNo() != Addr.getResNo()) 8891 continue; 8892 8893 // Check that the add is independent of the load. Otherwise, folding it 8894 // would create a cycle. 8895 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 8896 continue; 8897 // Also check that add is not used in the vector operand. This would also 8898 // create a cycle. 8899 if (User->isPredecessorOf(Vector.getNode())) 8900 continue; 8901 8902 // If the increment is a constant, it must match the memory ref size. 8903 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 8904 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 8905 uint32_t IncVal = CInc->getZExtValue(); 8906 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 8907 if (IncVal != NumBytes) 8908 continue; 8909 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 8910 } 8911 8912 // Finally, check that the vector doesn't depend on the load. 8913 // Again, this would create a cycle. 8914 // The load depending on the vector is fine, as that's the case for the 8915 // LD1*post we'll eventually generate anyway. 8916 if (LoadSDN->isPredecessorOf(Vector.getNode())) 8917 continue; 8918 8919 SmallVector<SDValue, 8> Ops; 8920 Ops.push_back(LD->getOperand(0)); // Chain 8921 if (IsLaneOp) { 8922 Ops.push_back(Vector); // The vector to be inserted 8923 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 8924 } 8925 Ops.push_back(Addr); 8926 Ops.push_back(Inc); 8927 8928 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 8929 SDVTList SDTys = DAG.getVTList(Tys); 8930 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 8931 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 8932 MemVT, 8933 LoadSDN->getMemOperand()); 8934 8935 // Update the uses. 8936 SmallVector<SDValue, 2> NewResults; 8937 NewResults.push_back(SDValue(LD, 0)); // The result of load 8938 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain 8939 DCI.CombineTo(LD, NewResults); 8940 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 8941 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 8942 8943 break; 8944 } 8945 return SDValue(); 8946 } 8947 8948 /// Simplify \Addr given that the top byte of it is ignored by HW during 8949 /// address translation. 8950 static bool performTBISimplification(SDValue Addr, 8951 TargetLowering::DAGCombinerInfo &DCI, 8952 SelectionDAG &DAG) { 8953 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 8954 APInt KnownZero, KnownOne; 8955 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 8956 DCI.isBeforeLegalizeOps()); 8957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8958 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) { 8959 DCI.CommitTargetLoweringOpt(TLO); 8960 return true; 8961 } 8962 return false; 8963 } 8964 8965 static SDValue performSTORECombine(SDNode *N, 8966 TargetLowering::DAGCombinerInfo &DCI, 8967 SelectionDAG &DAG, 8968 const AArch64Subtarget *Subtarget) { 8969 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget)) 8970 return Split; 8971 8972 if (Subtarget->supportsAddressTopByteIgnored() && 8973 performTBISimplification(N->getOperand(2), DCI, DAG)) 8974 return SDValue(N, 0); 8975 8976 return SDValue(); 8977 } 8978 8979 /// This function handles the log2-shuffle pattern produced by the 8980 /// LoopVectorizer for the across vector reduction. It consists of 8981 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements 8982 /// are reduced, where s is an induction variable from 0 to 8983 /// log2(NumVectorElements). 8984 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV, 8985 unsigned Op, 8986 SelectionDAG &DAG) { 8987 EVT VTy = OpV->getOperand(0).getValueType(); 8988 if (!VTy.isVector()) 8989 return SDValue(); 8990 8991 int NumVecElts = VTy.getVectorNumElements(); 8992 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 8993 if (NumVecElts != 4) 8994 return SDValue(); 8995 } else { 8996 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16) 8997 return SDValue(); 8998 } 8999 9000 int NumExpectedSteps = APInt(8, NumVecElts).logBase2(); 9001 SDValue PreOp = OpV; 9002 // Iterate over each step of the across vector reduction. 9003 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) { 9004 SDValue CurOp = PreOp.getOperand(0); 9005 SDValue Shuffle = PreOp.getOperand(1); 9006 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) { 9007 // Try to swap the 1st and 2nd operand as add and min/max instructions 9008 // are commutative. 9009 CurOp = PreOp.getOperand(1); 9010 Shuffle = PreOp.getOperand(0); 9011 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) 9012 return SDValue(); 9013 } 9014 9015 // Check if the input vector is fed by the operator we want to handle, 9016 // except the last step; the very first input vector is not necessarily 9017 // the same operator we are handling. 9018 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1))) 9019 return SDValue(); 9020 9021 // Check if it forms one step of the across vector reduction. 9022 // E.g., 9023 // %cur = add %1, %0 9024 // %shuffle = vector_shuffle %cur, <2, 3, u, u> 9025 // %pre = add %cur, %shuffle 9026 if (Shuffle.getOperand(0) != CurOp) 9027 return SDValue(); 9028 9029 int NumMaskElts = 1 << CurStep; 9030 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask(); 9031 // Check mask values in each step. 9032 // We expect the shuffle mask in each step follows a specific pattern 9033 // denoted here by the <M, U> form, where M is a sequence of integers 9034 // starting from NumMaskElts, increasing by 1, and the number integers 9035 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number 9036 // of undef in U should be NumVecElts - NumMaskElts. 9037 // E.g., for <8 x i16>, mask values in each step should be : 9038 // step 0 : <1,u,u,u,u,u,u,u> 9039 // step 1 : <2,3,u,u,u,u,u,u> 9040 // step 2 : <4,5,6,7,u,u,u,u> 9041 for (int i = 0; i < NumVecElts; ++i) 9042 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) || 9043 (i >= NumMaskElts && !(Mask[i] < 0))) 9044 return SDValue(); 9045 9046 PreOp = CurOp; 9047 } 9048 unsigned Opcode; 9049 bool IsIntrinsic = false; 9050 9051 switch (Op) { 9052 default: 9053 llvm_unreachable("Unexpected operator for across vector reduction"); 9054 case ISD::ADD: 9055 Opcode = AArch64ISD::UADDV; 9056 break; 9057 case ISD::SMAX: 9058 Opcode = AArch64ISD::SMAXV; 9059 break; 9060 case ISD::UMAX: 9061 Opcode = AArch64ISD::UMAXV; 9062 break; 9063 case ISD::SMIN: 9064 Opcode = AArch64ISD::SMINV; 9065 break; 9066 case ISD::UMIN: 9067 Opcode = AArch64ISD::UMINV; 9068 break; 9069 case ISD::FMAXNUM: 9070 Opcode = Intrinsic::aarch64_neon_fmaxnmv; 9071 IsIntrinsic = true; 9072 break; 9073 case ISD::FMINNUM: 9074 Opcode = Intrinsic::aarch64_neon_fminnmv; 9075 IsIntrinsic = true; 9076 break; 9077 } 9078 SDLoc DL(N); 9079 9080 return IsIntrinsic 9081 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0), 9082 DAG.getConstant(Opcode, DL, MVT::i32), PreOp) 9083 : DAG.getNode( 9084 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), 9085 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp), 9086 DAG.getConstant(0, DL, MVT::i64)); 9087 } 9088 9089 /// Target-specific DAG combine for the across vector min/max reductions. 9090 /// This function specifically handles the final clean-up step of the vector 9091 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle 9092 /// pattern, which narrows down and finds the final min/max value from all 9093 /// elements of the vector. 9094 /// For example, for a <16 x i8> vector : 9095 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> 9096 /// %smax0 = smax %arr, svn0 9097 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u> 9098 /// %smax1 = smax %smax0, %svn1 9099 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9100 /// %smax2 = smax %smax1, svn2 9101 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9102 /// %sc = setcc %smax2, %svn3, gt 9103 /// %n0 = extract_vector_elt %sc, #0 9104 /// %n1 = extract_vector_elt %smax2, #0 9105 /// %n2 = extract_vector_elt $smax2, #1 9106 /// %result = select %n0, %n1, n2 9107 /// becomes : 9108 /// %1 = smaxv %0 9109 /// %result = extract_vector_elt %1, 0 9110 static SDValue 9111 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG, 9112 const AArch64Subtarget *Subtarget) { 9113 if (!Subtarget->hasNEON()) 9114 return SDValue(); 9115 9116 SDValue N0 = N->getOperand(0); 9117 SDValue IfTrue = N->getOperand(1); 9118 SDValue IfFalse = N->getOperand(2); 9119 9120 // Check if the SELECT merges up the final result of the min/max 9121 // from a vector. 9122 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9123 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9124 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9125 return SDValue(); 9126 9127 // Expect N0 is fed by SETCC. 9128 SDValue SetCC = N0.getOperand(0); 9129 EVT SetCCVT = SetCC.getValueType(); 9130 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() || 9131 SetCCVT.getVectorElementType() != MVT::i1) 9132 return SDValue(); 9133 9134 SDValue VectorOp = SetCC.getOperand(0); 9135 unsigned Op = VectorOp->getOpcode(); 9136 // Check if the input vector is fed by the operator we want to handle. 9137 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN && 9138 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM) 9139 return SDValue(); 9140 9141 EVT VTy = VectorOp.getValueType(); 9142 if (!VTy.isVector()) 9143 return SDValue(); 9144 9145 if (VTy.getSizeInBits() < 64) 9146 return SDValue(); 9147 9148 EVT EltTy = VTy.getVectorElementType(); 9149 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 9150 if (EltTy != MVT::f32) 9151 return SDValue(); 9152 } else { 9153 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9154 return SDValue(); 9155 } 9156 9157 // Check if extracting from the same vector. 9158 // For example, 9159 // %sc = setcc %vector, %svn1, gt 9160 // %n0 = extract_vector_elt %sc, #0 9161 // %n1 = extract_vector_elt %vector, #0 9162 // %n2 = extract_vector_elt $vector, #1 9163 if (!(VectorOp == IfTrue->getOperand(0) && 9164 VectorOp == IfFalse->getOperand(0))) 9165 return SDValue(); 9166 9167 // Check if the condition code is matched with the operator type. 9168 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 9169 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) || 9170 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) || 9171 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) || 9172 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) || 9173 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE && 9174 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT && 9175 CC != ISD::SETGE) || 9176 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE && 9177 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT && 9178 CC != ISD::SETLE)) 9179 return SDValue(); 9180 9181 // Expect to check only lane 0 from the vector SETCC. 9182 if (!isNullConstant(N0.getOperand(1))) 9183 return SDValue(); 9184 9185 // Expect to extract the true value from lane 0. 9186 if (!isNullConstant(IfTrue.getOperand(1))) 9187 return SDValue(); 9188 9189 // Expect to extract the false value from lane 1. 9190 if (!isOneConstant(IfFalse.getOperand(1))) 9191 return SDValue(); 9192 9193 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG); 9194 } 9195 9196 /// Target-specific DAG combine for the across vector add reduction. 9197 /// This function specifically handles the final clean-up step of the vector 9198 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle 9199 /// pattern, which adds all elements of a vector together. 9200 /// For example, for a <4 x i32> vector : 9201 /// %1 = vector_shuffle %0, <2,3,u,u> 9202 /// %2 = add %0, %1 9203 /// %3 = vector_shuffle %2, <1,u,u,u> 9204 /// %4 = add %2, %3 9205 /// %result = extract_vector_elt %4, 0 9206 /// becomes : 9207 /// %0 = uaddv %0 9208 /// %result = extract_vector_elt %0, 0 9209 static SDValue 9210 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG, 9211 const AArch64Subtarget *Subtarget) { 9212 if (!Subtarget->hasNEON()) 9213 return SDValue(); 9214 SDValue N0 = N->getOperand(0); 9215 SDValue N1 = N->getOperand(1); 9216 9217 // Check if the input vector is fed by the ADD. 9218 if (N0->getOpcode() != ISD::ADD) 9219 return SDValue(); 9220 9221 // The vector extract idx must constant zero because we only expect the final 9222 // result of the reduction is placed in lane 0. 9223 if (!isNullConstant(N1)) 9224 return SDValue(); 9225 9226 EVT VTy = N0.getValueType(); 9227 if (!VTy.isVector()) 9228 return SDValue(); 9229 9230 EVT EltTy = VTy.getVectorElementType(); 9231 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9232 return SDValue(); 9233 9234 if (VTy.getSizeInBits() < 64) 9235 return SDValue(); 9236 9237 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG); 9238 } 9239 9240 /// Target-specific DAG combine function for NEON load/store intrinsics 9241 /// to merge base address updates. 9242 static SDValue performNEONPostLDSTCombine(SDNode *N, 9243 TargetLowering::DAGCombinerInfo &DCI, 9244 SelectionDAG &DAG) { 9245 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9246 return SDValue(); 9247 9248 unsigned AddrOpIdx = N->getNumOperands() - 1; 9249 SDValue Addr = N->getOperand(AddrOpIdx); 9250 9251 // Search for a use of the address operand that is an increment. 9252 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9253 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9254 SDNode *User = *UI; 9255 if (User->getOpcode() != ISD::ADD || 9256 UI.getUse().getResNo() != Addr.getResNo()) 9257 continue; 9258 9259 // Check that the add is independent of the load/store. Otherwise, folding 9260 // it would create a cycle. 9261 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9262 continue; 9263 9264 // Find the new opcode for the updating load/store. 9265 bool IsStore = false; 9266 bool IsLaneOp = false; 9267 bool IsDupOp = false; 9268 unsigned NewOpc = 0; 9269 unsigned NumVecs = 0; 9270 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9271 switch (IntNo) { 9272 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9273 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9274 NumVecs = 2; break; 9275 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9276 NumVecs = 3; break; 9277 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9278 NumVecs = 4; break; 9279 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9280 NumVecs = 2; IsStore = true; break; 9281 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9282 NumVecs = 3; IsStore = true; break; 9283 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9284 NumVecs = 4; IsStore = true; break; 9285 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9286 NumVecs = 2; break; 9287 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9288 NumVecs = 3; break; 9289 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9290 NumVecs = 4; break; 9291 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9292 NumVecs = 2; IsStore = true; break; 9293 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9294 NumVecs = 3; IsStore = true; break; 9295 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9296 NumVecs = 4; IsStore = true; break; 9297 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9298 NumVecs = 2; IsDupOp = true; break; 9299 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9300 NumVecs = 3; IsDupOp = true; break; 9301 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9302 NumVecs = 4; IsDupOp = true; break; 9303 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9304 NumVecs = 2; IsLaneOp = true; break; 9305 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9306 NumVecs = 3; IsLaneOp = true; break; 9307 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9308 NumVecs = 4; IsLaneOp = true; break; 9309 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9310 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9311 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9312 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9313 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9314 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9315 } 9316 9317 EVT VecTy; 9318 if (IsStore) 9319 VecTy = N->getOperand(2).getValueType(); 9320 else 9321 VecTy = N->getValueType(0); 9322 9323 // If the increment is a constant, it must match the memory ref size. 9324 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9325 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9326 uint32_t IncVal = CInc->getZExtValue(); 9327 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9328 if (IsLaneOp || IsDupOp) 9329 NumBytes /= VecTy.getVectorNumElements(); 9330 if (IncVal != NumBytes) 9331 continue; 9332 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9333 } 9334 SmallVector<SDValue, 8> Ops; 9335 Ops.push_back(N->getOperand(0)); // Incoming chain 9336 // Load lane and store have vector list as input. 9337 if (IsLaneOp || IsStore) 9338 for (unsigned i = 2; i < AddrOpIdx; ++i) 9339 Ops.push_back(N->getOperand(i)); 9340 Ops.push_back(Addr); // Base register 9341 Ops.push_back(Inc); 9342 9343 // Return Types. 9344 EVT Tys[6]; 9345 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9346 unsigned n; 9347 for (n = 0; n < NumResultVecs; ++n) 9348 Tys[n] = VecTy; 9349 Tys[n++] = MVT::i64; // Type of write back register 9350 Tys[n] = MVT::Other; // Type of the chain 9351 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9352 9353 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9354 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9355 MemInt->getMemoryVT(), 9356 MemInt->getMemOperand()); 9357 9358 // Update the uses. 9359 std::vector<SDValue> NewResults; 9360 for (unsigned i = 0; i < NumResultVecs; ++i) { 9361 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9362 } 9363 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9364 DCI.CombineTo(N, NewResults); 9365 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9366 9367 break; 9368 } 9369 return SDValue(); 9370 } 9371 9372 // Checks to see if the value is the prescribed width and returns information 9373 // about its extension mode. 9374 static 9375 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9376 ExtType = ISD::NON_EXTLOAD; 9377 switch(V.getNode()->getOpcode()) { 9378 default: 9379 return false; 9380 case ISD::LOAD: { 9381 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9382 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9383 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9384 ExtType = LoadNode->getExtensionType(); 9385 return true; 9386 } 9387 return false; 9388 } 9389 case ISD::AssertSext: { 9390 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9391 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9392 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9393 ExtType = ISD::SEXTLOAD; 9394 return true; 9395 } 9396 return false; 9397 } 9398 case ISD::AssertZext: { 9399 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9400 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9401 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9402 ExtType = ISD::ZEXTLOAD; 9403 return true; 9404 } 9405 return false; 9406 } 9407 case ISD::Constant: 9408 case ISD::TargetConstant: { 9409 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9410 1LL << (width - 1); 9411 } 9412 } 9413 9414 return true; 9415 } 9416 9417 // This function does a whole lot of voodoo to determine if the tests are 9418 // equivalent without and with a mask. Essentially what happens is that given a 9419 // DAG resembling: 9420 // 9421 // +-------------+ +-------------+ +-------------+ +-------------+ 9422 // | Input | | AddConstant | | CompConstant| | CC | 9423 // +-------------+ +-------------+ +-------------+ +-------------+ 9424 // | | | | 9425 // V V | +----------+ 9426 // +-------------+ +----+ | | 9427 // | ADD | |0xff| | | 9428 // +-------------+ +----+ | | 9429 // | | | | 9430 // V V | | 9431 // +-------------+ | | 9432 // | AND | | | 9433 // +-------------+ | | 9434 // | | | 9435 // +-----+ | | 9436 // | | | 9437 // V V V 9438 // +-------------+ 9439 // | CMP | 9440 // +-------------+ 9441 // 9442 // The AND node may be safely removed for some combinations of inputs. In 9443 // particular we need to take into account the extension type of the Input, 9444 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9445 // width of the input (this can work for any width inputs, the above graph is 9446 // specific to 8 bits. 9447 // 9448 // The specific equations were worked out by generating output tables for each 9449 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9450 // problem was simplified by working with 4 bit inputs, which means we only 9451 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9452 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9453 // patterns present in both extensions (0,7). For every distinct set of 9454 // AddConstant and CompConstants bit patterns we can consider the masked and 9455 // unmasked versions to be equivalent if the result of this function is true for 9456 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9457 // 9458 // sub w8, w0, w1 9459 // and w10, w8, #0x0f 9460 // cmp w8, w2 9461 // cset w9, AArch64CC 9462 // cmp w10, w2 9463 // cset w11, AArch64CC 9464 // cmp w9, w11 9465 // cset w0, eq 9466 // ret 9467 // 9468 // Since the above function shows when the outputs are equivalent it defines 9469 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9470 // would be expensive to run during compiles. The equations below were written 9471 // in a test harness that confirmed they gave equivalent outputs to the above 9472 // for all inputs function, so they can be used determine if the removal is 9473 // legal instead. 9474 // 9475 // isEquivalentMaskless() is the code for testing if the AND can be removed 9476 // factored out of the DAG recognition as the DAG can take several forms. 9477 9478 static bool isEquivalentMaskless(unsigned CC, unsigned width, 9479 ISD::LoadExtType ExtType, int AddConstant, 9480 int CompConstant) { 9481 // By being careful about our equations and only writing the in term 9482 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 9483 // make them generally applicable to all bit widths. 9484 int MaxUInt = (1 << width); 9485 9486 // For the purposes of these comparisons sign extending the type is 9487 // equivalent to zero extending the add and displacing it by half the integer 9488 // width. Provided we are careful and make sure our equations are valid over 9489 // the whole range we can just adjust the input and avoid writing equations 9490 // for sign extended inputs. 9491 if (ExtType == ISD::SEXTLOAD) 9492 AddConstant -= (1 << (width-1)); 9493 9494 switch(CC) { 9495 case AArch64CC::LE: 9496 case AArch64CC::GT: { 9497 if ((AddConstant == 0) || 9498 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 9499 (AddConstant >= 0 && CompConstant < 0) || 9500 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 9501 return true; 9502 } break; 9503 case AArch64CC::LT: 9504 case AArch64CC::GE: { 9505 if ((AddConstant == 0) || 9506 (AddConstant >= 0 && CompConstant <= 0) || 9507 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 9508 return true; 9509 } break; 9510 case AArch64CC::HI: 9511 case AArch64CC::LS: { 9512 if ((AddConstant >= 0 && CompConstant < 0) || 9513 (AddConstant <= 0 && CompConstant >= -1 && 9514 CompConstant < AddConstant + MaxUInt)) 9515 return true; 9516 } break; 9517 case AArch64CC::PL: 9518 case AArch64CC::MI: { 9519 if ((AddConstant == 0) || 9520 (AddConstant > 0 && CompConstant <= 0) || 9521 (AddConstant < 0 && CompConstant <= AddConstant)) 9522 return true; 9523 } break; 9524 case AArch64CC::LO: 9525 case AArch64CC::HS: { 9526 if ((AddConstant >= 0 && CompConstant <= 0) || 9527 (AddConstant <= 0 && CompConstant >= 0 && 9528 CompConstant <= AddConstant + MaxUInt)) 9529 return true; 9530 } break; 9531 case AArch64CC::EQ: 9532 case AArch64CC::NE: { 9533 if ((AddConstant > 0 && CompConstant < 0) || 9534 (AddConstant < 0 && CompConstant >= 0 && 9535 CompConstant < AddConstant + MaxUInt) || 9536 (AddConstant >= 0 && CompConstant >= 0 && 9537 CompConstant >= AddConstant) || 9538 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 9539 9540 return true; 9541 } break; 9542 case AArch64CC::VS: 9543 case AArch64CC::VC: 9544 case AArch64CC::AL: 9545 case AArch64CC::NV: 9546 return true; 9547 case AArch64CC::Invalid: 9548 break; 9549 } 9550 9551 return false; 9552 } 9553 9554 static 9555 SDValue performCONDCombine(SDNode *N, 9556 TargetLowering::DAGCombinerInfo &DCI, 9557 SelectionDAG &DAG, unsigned CCIndex, 9558 unsigned CmpIndex) { 9559 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 9560 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 9561 unsigned CondOpcode = SubsNode->getOpcode(); 9562 9563 if (CondOpcode != AArch64ISD::SUBS) 9564 return SDValue(); 9565 9566 // There is a SUBS feeding this condition. Is it fed by a mask we can 9567 // use? 9568 9569 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 9570 unsigned MaskBits = 0; 9571 9572 if (AndNode->getOpcode() != ISD::AND) 9573 return SDValue(); 9574 9575 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 9576 uint32_t CNV = CN->getZExtValue(); 9577 if (CNV == 255) 9578 MaskBits = 8; 9579 else if (CNV == 65535) 9580 MaskBits = 16; 9581 } 9582 9583 if (!MaskBits) 9584 return SDValue(); 9585 9586 SDValue AddValue = AndNode->getOperand(0); 9587 9588 if (AddValue.getOpcode() != ISD::ADD) 9589 return SDValue(); 9590 9591 // The basic dag structure is correct, grab the inputs and validate them. 9592 9593 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 9594 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 9595 SDValue SubsInputValue = SubsNode->getOperand(1); 9596 9597 // The mask is present and the provenance of all the values is a smaller type, 9598 // lets see if the mask is superfluous. 9599 9600 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 9601 !isa<ConstantSDNode>(SubsInputValue.getNode())) 9602 return SDValue(); 9603 9604 ISD::LoadExtType ExtType; 9605 9606 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 9607 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 9608 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 9609 return SDValue(); 9610 9611 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 9612 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 9613 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 9614 return SDValue(); 9615 9616 // The AND is not necessary, remove it. 9617 9618 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 9619 SubsNode->getValueType(1)); 9620 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 9621 9622 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 9623 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 9624 9625 return SDValue(N, 0); 9626 } 9627 9628 // Optimize compare with zero and branch. 9629 static SDValue performBRCONDCombine(SDNode *N, 9630 TargetLowering::DAGCombinerInfo &DCI, 9631 SelectionDAG &DAG) { 9632 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 9633 N = NV.getNode(); 9634 SDValue Chain = N->getOperand(0); 9635 SDValue Dest = N->getOperand(1); 9636 SDValue CCVal = N->getOperand(2); 9637 SDValue Cmp = N->getOperand(3); 9638 9639 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 9640 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 9641 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 9642 return SDValue(); 9643 9644 unsigned CmpOpc = Cmp.getOpcode(); 9645 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 9646 return SDValue(); 9647 9648 // Only attempt folding if there is only one use of the flag and no use of the 9649 // value. 9650 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 9651 return SDValue(); 9652 9653 SDValue LHS = Cmp.getOperand(0); 9654 SDValue RHS = Cmp.getOperand(1); 9655 9656 assert(LHS.getValueType() == RHS.getValueType() && 9657 "Expected the value type to be the same for both operands!"); 9658 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 9659 return SDValue(); 9660 9661 if (isNullConstant(LHS)) 9662 std::swap(LHS, RHS); 9663 9664 if (!isNullConstant(RHS)) 9665 return SDValue(); 9666 9667 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 9668 LHS.getOpcode() == ISD::SRL) 9669 return SDValue(); 9670 9671 // Fold the compare into the branch instruction. 9672 SDValue BR; 9673 if (CC == AArch64CC::EQ) 9674 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9675 else 9676 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9677 9678 // Do not add new nodes to DAG combiner worklist. 9679 DCI.CombineTo(N, BR, false); 9680 9681 return SDValue(); 9682 } 9683 9684 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 9685 // as well as whether the test should be inverted. This code is required to 9686 // catch these cases (as opposed to standard dag combines) because 9687 // AArch64ISD::TBZ is matched during legalization. 9688 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 9689 SelectionDAG &DAG) { 9690 9691 if (!Op->hasOneUse()) 9692 return Op; 9693 9694 // We don't handle undef/constant-fold cases below, as they should have 9695 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 9696 // etc.) 9697 9698 // (tbz (trunc x), b) -> (tbz x, b) 9699 // This case is just here to enable more of the below cases to be caught. 9700 if (Op->getOpcode() == ISD::TRUNCATE && 9701 Bit < Op->getValueType(0).getSizeInBits()) { 9702 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9703 } 9704 9705 if (Op->getNumOperands() != 2) 9706 return Op; 9707 9708 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 9709 if (!C) 9710 return Op; 9711 9712 switch (Op->getOpcode()) { 9713 default: 9714 return Op; 9715 9716 // (tbz (and x, m), b) -> (tbz x, b) 9717 case ISD::AND: 9718 if ((C->getZExtValue() >> Bit) & 1) 9719 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9720 return Op; 9721 9722 // (tbz (shl x, c), b) -> (tbz x, b-c) 9723 case ISD::SHL: 9724 if (C->getZExtValue() <= Bit && 9725 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9726 Bit = Bit - C->getZExtValue(); 9727 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9728 } 9729 return Op; 9730 9731 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 9732 case ISD::SRA: 9733 Bit = Bit + C->getZExtValue(); 9734 if (Bit >= Op->getValueType(0).getSizeInBits()) 9735 Bit = Op->getValueType(0).getSizeInBits() - 1; 9736 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9737 9738 // (tbz (srl x, c), b) -> (tbz x, b+c) 9739 case ISD::SRL: 9740 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9741 Bit = Bit + C->getZExtValue(); 9742 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9743 } 9744 return Op; 9745 9746 // (tbz (xor x, -1), b) -> (tbnz x, b) 9747 case ISD::XOR: 9748 if ((C->getZExtValue() >> Bit) & 1) 9749 Invert = !Invert; 9750 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9751 } 9752 } 9753 9754 // Optimize test single bit zero/non-zero and branch. 9755 static SDValue performTBZCombine(SDNode *N, 9756 TargetLowering::DAGCombinerInfo &DCI, 9757 SelectionDAG &DAG) { 9758 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9759 bool Invert = false; 9760 SDValue TestSrc = N->getOperand(1); 9761 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 9762 9763 if (TestSrc == NewTestSrc) 9764 return SDValue(); 9765 9766 unsigned NewOpc = N->getOpcode(); 9767 if (Invert) { 9768 if (NewOpc == AArch64ISD::TBZ) 9769 NewOpc = AArch64ISD::TBNZ; 9770 else { 9771 assert(NewOpc == AArch64ISD::TBNZ); 9772 NewOpc = AArch64ISD::TBZ; 9773 } 9774 } 9775 9776 SDLoc DL(N); 9777 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 9778 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 9779 } 9780 9781 // vselect (v1i1 setcc) -> 9782 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 9783 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 9784 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 9785 // such VSELECT. 9786 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 9787 SDValue N0 = N->getOperand(0); 9788 EVT CCVT = N0.getValueType(); 9789 9790 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 9791 CCVT.getVectorElementType() != MVT::i1) 9792 return SDValue(); 9793 9794 EVT ResVT = N->getValueType(0); 9795 EVT CmpVT = N0.getOperand(0).getValueType(); 9796 // Only combine when the result type is of the same size as the compared 9797 // operands. 9798 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 9799 return SDValue(); 9800 9801 SDValue IfTrue = N->getOperand(1); 9802 SDValue IfFalse = N->getOperand(2); 9803 SDValue SetCC = 9804 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 9805 N0.getOperand(0), N0.getOperand(1), 9806 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9807 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 9808 IfTrue, IfFalse); 9809 } 9810 9811 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 9812 /// the compare-mask instructions rather than going via NZCV, even if LHS and 9813 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 9814 /// with a vector one followed by a DUP shuffle on the result. 9815 static SDValue performSelectCombine(SDNode *N, 9816 TargetLowering::DAGCombinerInfo &DCI) { 9817 SelectionDAG &DAG = DCI.DAG; 9818 SDValue N0 = N->getOperand(0); 9819 EVT ResVT = N->getValueType(0); 9820 9821 if (N0.getOpcode() != ISD::SETCC) 9822 return SDValue(); 9823 9824 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 9825 // scalar SetCCResultType. We also don't expect vectors, because we assume 9826 // that selects fed by vector SETCCs are canonicalized to VSELECT. 9827 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 9828 "Scalar-SETCC feeding SELECT has unexpected result type!"); 9829 9830 // If NumMaskElts == 0, the comparison is larger than select result. The 9831 // largest real NEON comparison is 64-bits per lane, which means the result is 9832 // at most 32-bits and an illegal vector. Just bail out for now. 9833 EVT SrcVT = N0.getOperand(0).getValueType(); 9834 9835 // Don't try to do this optimization when the setcc itself has i1 operands. 9836 // There are no legal vectors of i1, so this would be pointless. 9837 if (SrcVT == MVT::i1) 9838 return SDValue(); 9839 9840 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 9841 if (!ResVT.isVector() || NumMaskElts == 0) 9842 return SDValue(); 9843 9844 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 9845 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 9846 9847 // Also bail out if the vector CCVT isn't the same size as ResVT. 9848 // This can happen if the SETCC operand size doesn't divide the ResVT size 9849 // (e.g., f64 vs v3f32). 9850 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 9851 return SDValue(); 9852 9853 // Make sure we didn't create illegal types, if we're not supposed to. 9854 assert(DCI.isBeforeLegalize() || 9855 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 9856 9857 // First perform a vector comparison, where lane 0 is the one we're interested 9858 // in. 9859 SDLoc DL(N0); 9860 SDValue LHS = 9861 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 9862 SDValue RHS = 9863 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 9864 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 9865 9866 // Now duplicate the comparison mask we want across all other lanes. 9867 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 9868 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data()); 9869 Mask = DAG.getNode(ISD::BITCAST, DL, 9870 ResVT.changeVectorElementTypeToInteger(), Mask); 9871 9872 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 9873 } 9874 9875 /// Get rid of unnecessary NVCASTs (that don't change the type). 9876 static SDValue performNVCASTCombine(SDNode *N) { 9877 if (N->getValueType(0) == N->getOperand(0).getValueType()) 9878 return N->getOperand(0); 9879 9880 return SDValue(); 9881 } 9882 9883 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 9884 DAGCombinerInfo &DCI) const { 9885 SelectionDAG &DAG = DCI.DAG; 9886 switch (N->getOpcode()) { 9887 default: 9888 break; 9889 case ISD::ADD: 9890 case ISD::SUB: 9891 return performAddSubLongCombine(N, DCI, DAG); 9892 case ISD::XOR: 9893 return performXorCombine(N, DAG, DCI, Subtarget); 9894 case ISD::MUL: 9895 return performMulCombine(N, DAG, DCI, Subtarget); 9896 case ISD::SINT_TO_FP: 9897 case ISD::UINT_TO_FP: 9898 return performIntToFpCombine(N, DAG, Subtarget); 9899 case ISD::FP_TO_SINT: 9900 case ISD::FP_TO_UINT: 9901 return performFpToIntCombine(N, DAG, Subtarget); 9902 case ISD::FDIV: 9903 return performFDivCombine(N, DAG, Subtarget); 9904 case ISD::OR: 9905 return performORCombine(N, DCI, Subtarget); 9906 case ISD::SRL: 9907 return performSRLCombine(N, DCI); 9908 case ISD::INTRINSIC_WO_CHAIN: 9909 return performIntrinsicCombine(N, DCI, Subtarget); 9910 case ISD::ANY_EXTEND: 9911 case ISD::ZERO_EXTEND: 9912 case ISD::SIGN_EXTEND: 9913 return performExtendCombine(N, DCI, DAG); 9914 case ISD::BITCAST: 9915 return performBitcastCombine(N, DCI, DAG); 9916 case ISD::CONCAT_VECTORS: 9917 return performConcatVectorsCombine(N, DCI, DAG); 9918 case ISD::SELECT: { 9919 SDValue RV = performSelectCombine(N, DCI); 9920 if (!RV.getNode()) 9921 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget); 9922 return RV; 9923 } 9924 case ISD::VSELECT: 9925 return performVSelectCombine(N, DCI.DAG); 9926 case ISD::LOAD: 9927 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 9928 return SDValue(N, 0); 9929 break; 9930 case ISD::STORE: 9931 return performSTORECombine(N, DCI, DAG, Subtarget); 9932 case AArch64ISD::BRCOND: 9933 return performBRCONDCombine(N, DCI, DAG); 9934 case AArch64ISD::TBNZ: 9935 case AArch64ISD::TBZ: 9936 return performTBZCombine(N, DCI, DAG); 9937 case AArch64ISD::CSEL: 9938 return performCONDCombine(N, DCI, DAG, 2, 3); 9939 case AArch64ISD::DUP: 9940 return performPostLD1Combine(N, DCI, false); 9941 case AArch64ISD::NVCAST: 9942 return performNVCASTCombine(N); 9943 case ISD::INSERT_VECTOR_ELT: 9944 return performPostLD1Combine(N, DCI, true); 9945 case ISD::EXTRACT_VECTOR_ELT: 9946 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget); 9947 case ISD::INTRINSIC_VOID: 9948 case ISD::INTRINSIC_W_CHAIN: 9949 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 9950 case Intrinsic::aarch64_neon_ld2: 9951 case Intrinsic::aarch64_neon_ld3: 9952 case Intrinsic::aarch64_neon_ld4: 9953 case Intrinsic::aarch64_neon_ld1x2: 9954 case Intrinsic::aarch64_neon_ld1x3: 9955 case Intrinsic::aarch64_neon_ld1x4: 9956 case Intrinsic::aarch64_neon_ld2lane: 9957 case Intrinsic::aarch64_neon_ld3lane: 9958 case Intrinsic::aarch64_neon_ld4lane: 9959 case Intrinsic::aarch64_neon_ld2r: 9960 case Intrinsic::aarch64_neon_ld3r: 9961 case Intrinsic::aarch64_neon_ld4r: 9962 case Intrinsic::aarch64_neon_st2: 9963 case Intrinsic::aarch64_neon_st3: 9964 case Intrinsic::aarch64_neon_st4: 9965 case Intrinsic::aarch64_neon_st1x2: 9966 case Intrinsic::aarch64_neon_st1x3: 9967 case Intrinsic::aarch64_neon_st1x4: 9968 case Intrinsic::aarch64_neon_st2lane: 9969 case Intrinsic::aarch64_neon_st3lane: 9970 case Intrinsic::aarch64_neon_st4lane: 9971 return performNEONPostLDSTCombine(N, DCI, DAG); 9972 default: 9973 break; 9974 } 9975 } 9976 return SDValue(); 9977 } 9978 9979 // Check if the return value is used as only a return value, as otherwise 9980 // we can't perform a tail-call. In particular, we need to check for 9981 // target ISD nodes that are returns and any other "odd" constructs 9982 // that the generic analysis code won't necessarily catch. 9983 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 9984 SDValue &Chain) const { 9985 if (N->getNumValues() != 1) 9986 return false; 9987 if (!N->hasNUsesOfValue(1, 0)) 9988 return false; 9989 9990 SDValue TCChain = Chain; 9991 SDNode *Copy = *N->use_begin(); 9992 if (Copy->getOpcode() == ISD::CopyToReg) { 9993 // If the copy has a glue operand, we conservatively assume it isn't safe to 9994 // perform a tail call. 9995 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 9996 MVT::Glue) 9997 return false; 9998 TCChain = Copy->getOperand(0); 9999 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 10000 return false; 10001 10002 bool HasRet = false; 10003 for (SDNode *Node : Copy->uses()) { 10004 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 10005 return false; 10006 HasRet = true; 10007 } 10008 10009 if (!HasRet) 10010 return false; 10011 10012 Chain = TCChain; 10013 return true; 10014 } 10015 10016 // Return whether the an instruction can potentially be optimized to a tail 10017 // call. This will cause the optimizers to attempt to move, or duplicate, 10018 // return instructions to help enable tail call optimizations for this 10019 // instruction. 10020 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 10021 return CI->isTailCall(); 10022 } 10023 10024 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 10025 SDValue &Offset, 10026 ISD::MemIndexedMode &AM, 10027 bool &IsInc, 10028 SelectionDAG &DAG) const { 10029 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 10030 return false; 10031 10032 Base = Op->getOperand(0); 10033 // All of the indexed addressing mode instructions take a signed 10034 // 9 bit immediate offset. 10035 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 10036 int64_t RHSC = (int64_t)RHS->getZExtValue(); 10037 if (RHSC >= 256 || RHSC <= -256) 10038 return false; 10039 IsInc = (Op->getOpcode() == ISD::ADD); 10040 Offset = Op->getOperand(1); 10041 return true; 10042 } 10043 return false; 10044 } 10045 10046 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10047 SDValue &Offset, 10048 ISD::MemIndexedMode &AM, 10049 SelectionDAG &DAG) const { 10050 EVT VT; 10051 SDValue Ptr; 10052 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10053 VT = LD->getMemoryVT(); 10054 Ptr = LD->getBasePtr(); 10055 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10056 VT = ST->getMemoryVT(); 10057 Ptr = ST->getBasePtr(); 10058 } else 10059 return false; 10060 10061 bool IsInc; 10062 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 10063 return false; 10064 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 10065 return true; 10066 } 10067 10068 bool AArch64TargetLowering::getPostIndexedAddressParts( 10069 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10070 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10071 EVT VT; 10072 SDValue Ptr; 10073 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10074 VT = LD->getMemoryVT(); 10075 Ptr = LD->getBasePtr(); 10076 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10077 VT = ST->getMemoryVT(); 10078 Ptr = ST->getBasePtr(); 10079 } else 10080 return false; 10081 10082 bool IsInc; 10083 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10084 return false; 10085 // Post-indexing updates the base, so it's not a valid transform 10086 // if that's not the same as the load's pointer. 10087 if (Ptr != Base) 10088 return false; 10089 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10090 return true; 10091 } 10092 10093 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10094 SelectionDAG &DAG) { 10095 SDLoc DL(N); 10096 SDValue Op = N->getOperand(0); 10097 10098 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10099 return; 10100 10101 Op = SDValue( 10102 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10103 DAG.getUNDEF(MVT::i32), Op, 10104 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10105 0); 10106 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10107 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10108 } 10109 10110 static void ReplaceReductionResults(SDNode *N, 10111 SmallVectorImpl<SDValue> &Results, 10112 SelectionDAG &DAG, unsigned InterOp, 10113 unsigned AcrossOp) { 10114 EVT LoVT, HiVT; 10115 SDValue Lo, Hi; 10116 SDLoc dl(N); 10117 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10118 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10119 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10120 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10121 Results.push_back(SplitVal); 10122 } 10123 10124 static void ReplaceCMP_SWAP_128Results(SDNode *N, 10125 SmallVectorImpl<SDValue> & Results, 10126 SelectionDAG &DAG) { 10127 assert(N->getValueType(0) == MVT::i128 && 10128 "AtomicCmpSwap on types less than 128 should be legal"); 10129 SDValue Ops[] = {N->getOperand(1), 10130 N->getOperand(2)->getOperand(0), 10131 N->getOperand(2)->getOperand(1), 10132 N->getOperand(3)->getOperand(0), 10133 N->getOperand(3)->getOperand(1), 10134 N->getOperand(0)}; 10135 SDNode *CmpSwap = DAG.getMachineNode( 10136 AArch64::CMP_SWAP_128, SDLoc(N), 10137 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 10138 10139 MachineFunction &MF = DAG.getMachineFunction(); 10140 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 10141 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 10142 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 10143 10144 Results.push_back(SDValue(CmpSwap, 0)); 10145 Results.push_back(SDValue(CmpSwap, 1)); 10146 Results.push_back(SDValue(CmpSwap, 3)); 10147 } 10148 10149 void AArch64TargetLowering::ReplaceNodeResults( 10150 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10151 switch (N->getOpcode()) { 10152 default: 10153 llvm_unreachable("Don't know how to custom expand this"); 10154 case ISD::BITCAST: 10155 ReplaceBITCASTResults(N, Results, DAG); 10156 return; 10157 case AArch64ISD::SADDV: 10158 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10159 return; 10160 case AArch64ISD::UADDV: 10161 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10162 return; 10163 case AArch64ISD::SMINV: 10164 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10165 return; 10166 case AArch64ISD::UMINV: 10167 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10168 return; 10169 case AArch64ISD::SMAXV: 10170 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10171 return; 10172 case AArch64ISD::UMAXV: 10173 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10174 return; 10175 case ISD::FP_TO_UINT: 10176 case ISD::FP_TO_SINT: 10177 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10178 // Let normal code take care of it by not adding anything to Results. 10179 return; 10180 case ISD::ATOMIC_CMP_SWAP: 10181 ReplaceCMP_SWAP_128Results(N, Results, DAG); 10182 return; 10183 } 10184 } 10185 10186 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10187 if (!Subtarget->isTargetAndroid()) 10188 return true; 10189 return TargetLowering::useLoadStackGuardNode(); 10190 } 10191 10192 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10193 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10194 // reciprocal if there are three or more FDIVs. 10195 return 3; 10196 } 10197 10198 TargetLoweringBase::LegalizeTypeAction 10199 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10200 MVT SVT = VT.getSimpleVT(); 10201 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10202 // v4i16, v2i32 instead of to promote. 10203 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10204 || SVT == MVT::v1f32) 10205 return TypeWidenVector; 10206 10207 return TargetLoweringBase::getPreferredVectorAction(VT); 10208 } 10209 10210 // Loads and stores less than 128-bits are already atomic; ones above that 10211 // are doomed anyway, so defer to the default libcall and blame the OS when 10212 // things go wrong. 10213 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10214 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10215 return Size == 128; 10216 } 10217 10218 // Loads and stores less than 128-bits are already atomic; ones above that 10219 // are doomed anyway, so defer to the default libcall and blame the OS when 10220 // things go wrong. 10221 TargetLowering::AtomicExpansionKind 10222 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10223 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10224 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10225 } 10226 10227 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10228 TargetLowering::AtomicExpansionKind 10229 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10230 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10231 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10232 } 10233 10234 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10235 AtomicCmpXchgInst *AI) const { 10236 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 10237 // implement cmpxchg without spilling. If the address being exchanged is also 10238 // on the stack and close enough to the spill slot, this can lead to a 10239 // situation where the monitor always gets cleared and the atomic operation 10240 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 10241 return getTargetMachine().getOptLevel() != 0; 10242 } 10243 10244 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10245 AtomicOrdering Ord) const { 10246 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10247 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10248 bool IsAcquire = isAcquireOrStronger(Ord); 10249 10250 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10251 // intrinsic must return {i64, i64} and we have to recombine them into a 10252 // single i128 here. 10253 if (ValTy->getPrimitiveSizeInBits() == 128) { 10254 Intrinsic::ID Int = 10255 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10256 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int); 10257 10258 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10259 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10260 10261 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10262 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10263 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10264 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10265 return Builder.CreateOr( 10266 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10267 } 10268 10269 Type *Tys[] = { Addr->getType() }; 10270 Intrinsic::ID Int = 10271 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10272 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys); 10273 10274 return Builder.CreateTruncOrBitCast( 10275 Builder.CreateCall(Ldxr, Addr), 10276 cast<PointerType>(Addr->getType())->getElementType()); 10277 } 10278 10279 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10280 IRBuilder<> &Builder) const { 10281 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10282 Builder.CreateCall( 10283 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10284 } 10285 10286 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10287 Value *Val, Value *Addr, 10288 AtomicOrdering Ord) const { 10289 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10290 bool IsRelease = isReleaseOrStronger(Ord); 10291 10292 // Since the intrinsics must have legal type, the i128 intrinsics take two 10293 // parameters: "i64, i64". We must marshal Val into the appropriate form 10294 // before the call. 10295 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10296 Intrinsic::ID Int = 10297 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10298 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10299 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10300 10301 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10302 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10303 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10304 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10305 } 10306 10307 Intrinsic::ID Int = 10308 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10309 Type *Tys[] = { Addr->getType() }; 10310 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10311 10312 return Builder.CreateCall(Stxr, 10313 {Builder.CreateZExtOrBitCast( 10314 Val, Stxr->getFunctionType()->getParamType(0)), 10315 Addr}); 10316 } 10317 10318 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10319 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10320 return Ty->isArrayTy(); 10321 } 10322 10323 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10324 EVT) const { 10325 return false; 10326 } 10327 10328 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 10329 if (!Subtarget->isTargetAndroid()) 10330 return TargetLowering::getIRStackGuard(IRB); 10331 10332 // Android provides a fixed TLS slot for the stack cookie. See the definition 10333 // of TLS_SLOT_STACK_GUARD in 10334 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10335 const unsigned TlsOffset = 0x28; 10336 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10337 Function *ThreadPointerFunc = 10338 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10339 return IRB.CreatePointerCast( 10340 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10341 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10342 } 10343 10344 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10345 if (!Subtarget->isTargetAndroid()) 10346 return TargetLowering::getSafeStackPointerLocation(IRB); 10347 10348 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10349 // definition of TLS_SLOT_SAFESTACK in 10350 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10351 const unsigned TlsOffset = 0x48; 10352 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10353 Function *ThreadPointerFunc = 10354 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10355 return IRB.CreatePointerCast( 10356 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10357 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10358 } 10359 10360 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10361 // Update IsSplitCSR in AArch64unctionInfo. 10362 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10363 AFI->setIsSplitCSR(true); 10364 } 10365 10366 void AArch64TargetLowering::insertCopiesSplitCSR( 10367 MachineBasicBlock *Entry, 10368 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10369 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10370 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10371 if (!IStart) 10372 return; 10373 10374 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10375 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10376 MachineBasicBlock::iterator MBBI = Entry->begin(); 10377 for (const MCPhysReg *I = IStart; *I; ++I) { 10378 const TargetRegisterClass *RC = nullptr; 10379 if (AArch64::GPR64RegClass.contains(*I)) 10380 RC = &AArch64::GPR64RegClass; 10381 else if (AArch64::FPR64RegClass.contains(*I)) 10382 RC = &AArch64::FPR64RegClass; 10383 else 10384 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10385 10386 unsigned NewVR = MRI->createVirtualRegister(RC); 10387 // Create copy from CSR to a virtual register. 10388 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10389 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10390 // nounwind. If we want to generalize this later, we may need to emit 10391 // CFI pseudo-instructions. 10392 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10393 Attribute::NoUnwind) && 10394 "Function should be nounwind in insertCopiesSplitCSR!"); 10395 Entry->addLiveIn(*I); 10396 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10397 .addReg(*I); 10398 10399 // Insert the copy-back instructions right before the terminator. 10400 for (auto *Exit : Exits) 10401 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10402 TII->get(TargetOpcode::COPY), *I) 10403 .addReg(NewVR); 10404 } 10405 } 10406 10407 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const { 10408 // Integer division on AArch64 is expensive. However, when aggressively 10409 // optimizing for code size, we prefer to use a div instruction, as it is 10410 // usually smaller than the alternative sequence. 10411 // The exception to this is vector division. Since AArch64 doesn't have vector 10412 // integer division, leaving the division as-is is a loss even in terms of 10413 // size, because it will have to be scalarized, while the alternative code 10414 // sequence can be performed in vector form. 10415 bool OptSize = 10416 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 10417 return OptSize && !VT.isVector(); 10418 } 10419