1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the AArch64TargetLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AArch64ISelLowering.h" 15 #include "AArch64CallingConvention.h" 16 #include "AArch64MachineFunctionInfo.h" 17 #include "AArch64PerfectShuffle.h" 18 #include "AArch64RegisterInfo.h" 19 #include "AArch64Subtarget.h" 20 #include "MCTargetDesc/AArch64AddressingModes.h" 21 #include "Utils/AArch64BaseInfo.h" 22 #include "llvm/ADT/APFloat.h" 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/Analysis/VectorUtils.h" 33 #include "llvm/CodeGen/CallingConvLower.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineMemOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/MachineValueType.h" 42 #include "llvm/CodeGen/RuntimeLibcalls.h" 43 #include "llvm/CodeGen/SelectionDAG.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Attributes.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugLoc.h" 50 #include "llvm/IR/DerivedTypes.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/GetElementPtrTypeIterator.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/IRBuilder.h" 55 #include "llvm/IR/Instruction.h" 56 #include "llvm/IR/Instructions.h" 57 #include "llvm/IR/Intrinsics.h" 58 #include "llvm/IR/Module.h" 59 #include "llvm/IR/OperandTraits.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/Use.h" 62 #include "llvm/IR/Value.h" 63 #include "llvm/MC/MCRegisterInfo.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CodeGen.h" 66 #include "llvm/Support/CommandLine.h" 67 #include "llvm/Support/Compiler.h" 68 #include "llvm/Support/Debug.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/KnownBits.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/Target/TargetCallingConv.h" 74 #include "llvm/Target/TargetInstrInfo.h" 75 #include "llvm/Target/TargetMachine.h" 76 #include "llvm/Target/TargetOptions.h" 77 #include <algorithm> 78 #include <bitset> 79 #include <cassert> 80 #include <cctype> 81 #include <cstdint> 82 #include <cstdlib> 83 #include <iterator> 84 #include <limits> 85 #include <tuple> 86 #include <utility> 87 #include <vector> 88 89 using namespace llvm; 90 91 #define DEBUG_TYPE "aarch64-lower" 92 93 STATISTIC(NumTailCalls, "Number of tail calls"); 94 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 96 97 static cl::opt<bool> 98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 99 cl::desc("Allow AArch64 SLI/SRI formation"), 100 cl::init(false)); 101 102 // FIXME: The necessary dtprel relocations don't seem to be supported 103 // well in the GNU bfd and gold linkers at the moment. Therefore, by 104 // default, for now, fall back to GeneralDynamic code generation. 105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 106 "aarch64-elf-ldtls-generation", cl::Hidden, 107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 112 cl::desc("Enable AArch64 logical imm instruction " 113 "optimization"), 114 cl::init(true)); 115 116 /// Value type used for condition codes. 117 static const MVT MVT_CC = MVT::i32; 118 119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 120 const AArch64Subtarget &STI) 121 : TargetLowering(TM), Subtarget(&STI) { 122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 123 // we have to make something up. Arbitrarily, choose ZeroOrOne. 124 setBooleanContents(ZeroOrOneBooleanContent); 125 // When comparing vectors the result sets the different elements in the 126 // vector to all-one or all-zero. 127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 128 129 // Set up the register classes. 130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 132 133 if (Subtarget->hasFPARMv8()) { 134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 138 } 139 140 if (Subtarget->hasNEON()) { 141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 143 // Someone set us up the NEON. 144 addDRTypeForNEON(MVT::v2f32); 145 addDRTypeForNEON(MVT::v8i8); 146 addDRTypeForNEON(MVT::v4i16); 147 addDRTypeForNEON(MVT::v2i32); 148 addDRTypeForNEON(MVT::v1i64); 149 addDRTypeForNEON(MVT::v1f64); 150 addDRTypeForNEON(MVT::v4f16); 151 152 addQRTypeForNEON(MVT::v4f32); 153 addQRTypeForNEON(MVT::v2f64); 154 addQRTypeForNEON(MVT::v16i8); 155 addQRTypeForNEON(MVT::v8i16); 156 addQRTypeForNEON(MVT::v4i32); 157 addQRTypeForNEON(MVT::v2i64); 158 addQRTypeForNEON(MVT::v8f16); 159 } 160 161 // Compute derived properties from the register classes 162 computeRegisterProperties(Subtarget->getRegisterInfo()); 163 164 // Provide all sorts of operation actions 165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 167 setOperationAction(ISD::SETCC, MVT::i32, Custom); 168 setOperationAction(ISD::SETCC, MVT::i64, Custom); 169 setOperationAction(ISD::SETCC, MVT::f16, Custom); 170 setOperationAction(ISD::SETCC, MVT::f32, Custom); 171 setOperationAction(ISD::SETCC, MVT::f64, Custom); 172 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 173 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 174 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 175 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 176 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 177 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 178 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 179 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 180 setOperationAction(ISD::SELECT, MVT::i32, Custom); 181 setOperationAction(ISD::SELECT, MVT::i64, Custom); 182 setOperationAction(ISD::SELECT, MVT::f16, Custom); 183 setOperationAction(ISD::SELECT, MVT::f32, Custom); 184 setOperationAction(ISD::SELECT, MVT::f64, Custom); 185 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 186 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 187 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 188 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 189 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 190 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 191 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 192 193 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 194 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 195 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 196 197 setOperationAction(ISD::FREM, MVT::f32, Expand); 198 setOperationAction(ISD::FREM, MVT::f64, Expand); 199 setOperationAction(ISD::FREM, MVT::f80, Expand); 200 201 // Custom lowering hooks are needed for XOR 202 // to fold it into CSINC/CSINV. 203 setOperationAction(ISD::XOR, MVT::i32, Custom); 204 setOperationAction(ISD::XOR, MVT::i64, Custom); 205 206 // Virtually no operation on f128 is legal, but LLVM can't expand them when 207 // there's a valid register class, so we need custom operations in most cases. 208 setOperationAction(ISD::FABS, MVT::f128, Expand); 209 setOperationAction(ISD::FADD, MVT::f128, Custom); 210 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 211 setOperationAction(ISD::FCOS, MVT::f128, Expand); 212 setOperationAction(ISD::FDIV, MVT::f128, Custom); 213 setOperationAction(ISD::FMA, MVT::f128, Expand); 214 setOperationAction(ISD::FMUL, MVT::f128, Custom); 215 setOperationAction(ISD::FNEG, MVT::f128, Expand); 216 setOperationAction(ISD::FPOW, MVT::f128, Expand); 217 setOperationAction(ISD::FREM, MVT::f128, Expand); 218 setOperationAction(ISD::FRINT, MVT::f128, Expand); 219 setOperationAction(ISD::FSIN, MVT::f128, Expand); 220 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 221 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 222 setOperationAction(ISD::FSUB, MVT::f128, Custom); 223 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 224 setOperationAction(ISD::SETCC, MVT::f128, Custom); 225 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 226 setOperationAction(ISD::SELECT, MVT::f128, Custom); 227 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 228 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 229 230 // Lowering for many of the conversions is actually specified by the non-f128 231 // type. The LowerXXX function will be trivial when f128 isn't involved. 232 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 233 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 234 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 235 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 236 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 237 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 238 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 239 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 240 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 242 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 243 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 244 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 245 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 246 247 // Variable arguments. 248 setOperationAction(ISD::VASTART, MVT::Other, Custom); 249 setOperationAction(ISD::VAARG, MVT::Other, Custom); 250 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 251 setOperationAction(ISD::VAEND, MVT::Other, Expand); 252 253 // Variable-sized objects. 254 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 255 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 256 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 257 258 // Constant pool entries 259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 260 261 // BlockAddress 262 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 263 264 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 265 setOperationAction(ISD::ADDC, MVT::i32, Custom); 266 setOperationAction(ISD::ADDE, MVT::i32, Custom); 267 setOperationAction(ISD::SUBC, MVT::i32, Custom); 268 setOperationAction(ISD::SUBE, MVT::i32, Custom); 269 setOperationAction(ISD::ADDC, MVT::i64, Custom); 270 setOperationAction(ISD::ADDE, MVT::i64, Custom); 271 setOperationAction(ISD::SUBC, MVT::i64, Custom); 272 setOperationAction(ISD::SUBE, MVT::i64, Custom); 273 274 // AArch64 lacks both left-rotate and popcount instructions. 275 setOperationAction(ISD::ROTL, MVT::i32, Expand); 276 setOperationAction(ISD::ROTL, MVT::i64, Expand); 277 for (MVT VT : MVT::vector_valuetypes()) { 278 setOperationAction(ISD::ROTL, VT, Expand); 279 setOperationAction(ISD::ROTR, VT, Expand); 280 } 281 282 // AArch64 doesn't have {U|S}MUL_LOHI. 283 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 284 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 285 286 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 287 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 288 289 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 290 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 291 for (MVT VT : MVT::vector_valuetypes()) { 292 setOperationAction(ISD::SDIVREM, VT, Expand); 293 setOperationAction(ISD::UDIVREM, VT, Expand); 294 } 295 setOperationAction(ISD::SREM, MVT::i32, Expand); 296 setOperationAction(ISD::SREM, MVT::i64, Expand); 297 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 298 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 299 setOperationAction(ISD::UREM, MVT::i32, Expand); 300 setOperationAction(ISD::UREM, MVT::i64, Expand); 301 302 // Custom lower Add/Sub/Mul with overflow. 303 setOperationAction(ISD::SADDO, MVT::i32, Custom); 304 setOperationAction(ISD::SADDO, MVT::i64, Custom); 305 setOperationAction(ISD::UADDO, MVT::i32, Custom); 306 setOperationAction(ISD::UADDO, MVT::i64, Custom); 307 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 308 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 309 setOperationAction(ISD::USUBO, MVT::i32, Custom); 310 setOperationAction(ISD::USUBO, MVT::i64, Custom); 311 setOperationAction(ISD::SMULO, MVT::i32, Custom); 312 setOperationAction(ISD::SMULO, MVT::i64, Custom); 313 setOperationAction(ISD::UMULO, MVT::i32, Custom); 314 setOperationAction(ISD::UMULO, MVT::i64, Custom); 315 316 setOperationAction(ISD::FSIN, MVT::f32, Expand); 317 setOperationAction(ISD::FSIN, MVT::f64, Expand); 318 setOperationAction(ISD::FCOS, MVT::f32, Expand); 319 setOperationAction(ISD::FCOS, MVT::f64, Expand); 320 setOperationAction(ISD::FPOW, MVT::f32, Expand); 321 setOperationAction(ISD::FPOW, MVT::f64, Expand); 322 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 323 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 324 if (Subtarget->hasFullFP16()) 325 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 326 else 327 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 328 329 setOperationAction(ISD::FREM, MVT::f16, Promote); 330 setOperationAction(ISD::FREM, MVT::v4f16, Promote); 331 setOperationAction(ISD::FREM, MVT::v8f16, Promote); 332 setOperationAction(ISD::FPOW, MVT::f16, Promote); 333 setOperationAction(ISD::FPOW, MVT::v4f16, Promote); 334 setOperationAction(ISD::FPOW, MVT::v8f16, Promote); 335 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 336 setOperationAction(ISD::FCOS, MVT::f16, Promote); 337 setOperationAction(ISD::FCOS, MVT::v4f16, Promote); 338 setOperationAction(ISD::FCOS, MVT::v8f16, Promote); 339 setOperationAction(ISD::FSIN, MVT::f16, Promote); 340 setOperationAction(ISD::FSIN, MVT::v4f16, Promote); 341 setOperationAction(ISD::FSIN, MVT::v8f16, Promote); 342 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 343 setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote); 344 setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote); 345 setOperationAction(ISD::FEXP, MVT::f16, Promote); 346 setOperationAction(ISD::FEXP, MVT::v4f16, Promote); 347 setOperationAction(ISD::FEXP, MVT::v8f16, Promote); 348 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 349 setOperationAction(ISD::FEXP2, MVT::v4f16, Promote); 350 setOperationAction(ISD::FEXP2, MVT::v8f16, Promote); 351 setOperationAction(ISD::FLOG, MVT::f16, Promote); 352 setOperationAction(ISD::FLOG, MVT::v4f16, Promote); 353 setOperationAction(ISD::FLOG, MVT::v8f16, Promote); 354 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 355 setOperationAction(ISD::FLOG2, MVT::v4f16, Promote); 356 setOperationAction(ISD::FLOG2, MVT::v8f16, Promote); 357 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 358 setOperationAction(ISD::FLOG10, MVT::v4f16, Promote); 359 setOperationAction(ISD::FLOG10, MVT::v8f16, Promote); 360 361 if (!Subtarget->hasFullFP16()) { 362 setOperationAction(ISD::SELECT, MVT::f16, Promote); 363 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 364 setOperationAction(ISD::SETCC, MVT::f16, Promote); 365 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 366 setOperationAction(ISD::FADD, MVT::f16, Promote); 367 setOperationAction(ISD::FSUB, MVT::f16, Promote); 368 setOperationAction(ISD::FMUL, MVT::f16, Promote); 369 setOperationAction(ISD::FDIV, MVT::f16, Promote); 370 setOperationAction(ISD::FMA, MVT::f16, Promote); 371 setOperationAction(ISD::FNEG, MVT::f16, Promote); 372 setOperationAction(ISD::FABS, MVT::f16, Promote); 373 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 374 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 375 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 376 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 377 setOperationAction(ISD::FRINT, MVT::f16, Promote); 378 setOperationAction(ISD::FROUND, MVT::f16, Promote); 379 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 380 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 381 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 382 setOperationAction(ISD::FMINNAN, MVT::f16, Promote); 383 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote); 384 385 // promote v4f16 to v4f32 when that is known to be safe. 386 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 387 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 388 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 389 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 390 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 391 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 392 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 393 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 394 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 395 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 396 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 397 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 398 399 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 400 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 401 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 402 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 403 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 404 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 405 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 406 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 407 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 408 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 409 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 410 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 411 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 412 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 413 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 414 415 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 416 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 417 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 418 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 419 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 420 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 421 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 422 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 423 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 424 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 425 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 426 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 427 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 428 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 429 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 430 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 431 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 432 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 433 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 434 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 435 } 436 437 // AArch64 has implementations of a lot of rounding-like FP operations. 438 for (MVT Ty : {MVT::f32, MVT::f64}) { 439 setOperationAction(ISD::FFLOOR, Ty, Legal); 440 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 441 setOperationAction(ISD::FCEIL, Ty, Legal); 442 setOperationAction(ISD::FRINT, Ty, Legal); 443 setOperationAction(ISD::FTRUNC, Ty, Legal); 444 setOperationAction(ISD::FROUND, Ty, Legal); 445 setOperationAction(ISD::FMINNUM, Ty, Legal); 446 setOperationAction(ISD::FMAXNUM, Ty, Legal); 447 setOperationAction(ISD::FMINNAN, Ty, Legal); 448 setOperationAction(ISD::FMAXNAN, Ty, Legal); 449 } 450 451 if (Subtarget->hasFullFP16()) { 452 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 453 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 454 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 455 setOperationAction(ISD::FRINT, MVT::f16, Legal); 456 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 457 setOperationAction(ISD::FROUND, MVT::f16, Legal); 458 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 459 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 460 setOperationAction(ISD::FMINNAN, MVT::f16, Legal); 461 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal); 462 } 463 464 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 465 466 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 467 468 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 469 // This requires the Performance Monitors extension. 470 if (Subtarget->hasPerfMon()) 471 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 472 473 if (Subtarget->isTargetMachO()) { 474 // For iOS, we don't want to the normal expansion of a libcall to 475 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 476 // traffic. 477 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 478 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 479 } else { 480 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 481 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 482 } 483 484 // Make floating-point constants legal for the large code model, so they don't 485 // become loads from the constant pool. 486 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 487 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 488 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 489 } 490 491 // AArch64 does not have floating-point extending loads, i1 sign-extending 492 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 493 for (MVT VT : MVT::fp_valuetypes()) { 494 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 495 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 496 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 497 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 498 } 499 for (MVT VT : MVT::integer_valuetypes()) 500 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 501 502 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 503 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 504 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 505 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 506 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 507 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 508 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 509 510 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 511 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 512 513 // Indexed loads and stores are supported. 514 for (unsigned im = (unsigned)ISD::PRE_INC; 515 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 516 setIndexedLoadAction(im, MVT::i8, Legal); 517 setIndexedLoadAction(im, MVT::i16, Legal); 518 setIndexedLoadAction(im, MVT::i32, Legal); 519 setIndexedLoadAction(im, MVT::i64, Legal); 520 setIndexedLoadAction(im, MVT::f64, Legal); 521 setIndexedLoadAction(im, MVT::f32, Legal); 522 setIndexedLoadAction(im, MVT::f16, Legal); 523 setIndexedStoreAction(im, MVT::i8, Legal); 524 setIndexedStoreAction(im, MVT::i16, Legal); 525 setIndexedStoreAction(im, MVT::i32, Legal); 526 setIndexedStoreAction(im, MVT::i64, Legal); 527 setIndexedStoreAction(im, MVT::f64, Legal); 528 setIndexedStoreAction(im, MVT::f32, Legal); 529 setIndexedStoreAction(im, MVT::f16, Legal); 530 } 531 532 // Trap. 533 setOperationAction(ISD::TRAP, MVT::Other, Legal); 534 535 // We combine OR nodes for bitfield operations. 536 setTargetDAGCombine(ISD::OR); 537 538 // Vector add and sub nodes may conceal a high-half opportunity. 539 // Also, try to fold ADD into CSINC/CSINV.. 540 setTargetDAGCombine(ISD::ADD); 541 setTargetDAGCombine(ISD::SUB); 542 setTargetDAGCombine(ISD::SRL); 543 setTargetDAGCombine(ISD::XOR); 544 setTargetDAGCombine(ISD::SINT_TO_FP); 545 setTargetDAGCombine(ISD::UINT_TO_FP); 546 547 setTargetDAGCombine(ISD::FP_TO_SINT); 548 setTargetDAGCombine(ISD::FP_TO_UINT); 549 setTargetDAGCombine(ISD::FDIV); 550 551 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 552 553 setTargetDAGCombine(ISD::ANY_EXTEND); 554 setTargetDAGCombine(ISD::ZERO_EXTEND); 555 setTargetDAGCombine(ISD::SIGN_EXTEND); 556 setTargetDAGCombine(ISD::BITCAST); 557 setTargetDAGCombine(ISD::CONCAT_VECTORS); 558 setTargetDAGCombine(ISD::STORE); 559 if (Subtarget->supportsAddressTopByteIgnored()) 560 setTargetDAGCombine(ISD::LOAD); 561 562 setTargetDAGCombine(ISD::MUL); 563 564 setTargetDAGCombine(ISD::SELECT); 565 setTargetDAGCombine(ISD::VSELECT); 566 567 setTargetDAGCombine(ISD::INTRINSIC_VOID); 568 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 569 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 570 571 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8; 572 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4; 573 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4; 574 575 setStackPointerRegisterToSaveRestore(AArch64::SP); 576 577 setSchedulingPreference(Sched::Hybrid); 578 579 EnableExtLdPromotion = true; 580 581 // Set required alignment. 582 setMinFunctionAlignment(2); 583 // Set preferred alignments. 584 setPrefFunctionAlignment(STI.getPrefFunctionAlignment()); 585 setPrefLoopAlignment(STI.getPrefLoopAlignment()); 586 587 // Only change the limit for entries in a jump table if specified by 588 // the subtarget, but not at the command line. 589 unsigned MaxJT = STI.getMaximumJumpTableSize(); 590 if (MaxJT && getMaximumJumpTableSize() == 0) 591 setMaximumJumpTableSize(MaxJT); 592 593 setHasExtractBitsInsn(true); 594 595 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 596 597 if (Subtarget->hasNEON()) { 598 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 599 // silliness like this: 600 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 601 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 602 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 603 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 604 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 605 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 606 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 607 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 608 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 609 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 610 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 611 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 612 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 613 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 614 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 615 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 616 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 617 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 618 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 619 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 620 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 621 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 622 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 623 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 624 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 625 626 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 627 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 628 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 629 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 630 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 631 632 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 633 634 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 635 // elements smaller than i32, so promote the input to i32 first. 636 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote); 637 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote); 638 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote); 639 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote); 640 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16 641 // -> v8f16 conversions. 642 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote); 643 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote); 644 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 645 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote); 646 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 647 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 648 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 649 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 650 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 651 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 652 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 653 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 654 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 655 656 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 657 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 658 659 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand); 660 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand); 661 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand); 662 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand); 663 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand); 664 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand); 665 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand); 666 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand); 667 668 // AArch64 doesn't have MUL.2d: 669 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 670 // Custom handling for some quad-vector types to detect MULL. 671 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 672 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 673 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 674 675 // Vector reductions 676 for (MVT VT : MVT::integer_valuetypes()) { 677 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 678 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 679 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 681 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 682 } 683 for (MVT VT : MVT::fp_valuetypes()) { 684 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 685 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 686 } 687 688 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 689 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 690 // Likewise, narrowing and extending vector loads/stores aren't handled 691 // directly. 692 for (MVT VT : MVT::vector_valuetypes()) { 693 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 694 695 setOperationAction(ISD::MULHS, VT, Expand); 696 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 697 setOperationAction(ISD::MULHU, VT, Expand); 698 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 699 700 setOperationAction(ISD::BSWAP, VT, Expand); 701 702 for (MVT InnerVT : MVT::vector_valuetypes()) { 703 setTruncStoreAction(VT, InnerVT, Expand); 704 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 705 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 706 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 707 } 708 } 709 710 // AArch64 has implementations of a lot of rounding-like FP operations. 711 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 712 setOperationAction(ISD::FFLOOR, Ty, Legal); 713 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 714 setOperationAction(ISD::FCEIL, Ty, Legal); 715 setOperationAction(ISD::FRINT, Ty, Legal); 716 setOperationAction(ISD::FTRUNC, Ty, Legal); 717 setOperationAction(ISD::FROUND, Ty, Legal); 718 } 719 } 720 721 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 722 } 723 724 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 725 if (VT == MVT::v2f32 || VT == MVT::v4f16) { 726 setOperationAction(ISD::LOAD, VT, Promote); 727 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32); 728 729 setOperationAction(ISD::STORE, VT, Promote); 730 AddPromotedToType(ISD::STORE, VT, MVT::v2i32); 731 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) { 732 setOperationAction(ISD::LOAD, VT, Promote); 733 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64); 734 735 setOperationAction(ISD::STORE, VT, Promote); 736 AddPromotedToType(ISD::STORE, VT, MVT::v2i64); 737 } 738 739 // Mark vector float intrinsics as expand. 740 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 741 setOperationAction(ISD::FSIN, VT, Expand); 742 setOperationAction(ISD::FCOS, VT, Expand); 743 setOperationAction(ISD::FPOW, VT, Expand); 744 setOperationAction(ISD::FLOG, VT, Expand); 745 setOperationAction(ISD::FLOG2, VT, Expand); 746 setOperationAction(ISD::FLOG10, VT, Expand); 747 setOperationAction(ISD::FEXP, VT, Expand); 748 setOperationAction(ISD::FEXP2, VT, Expand); 749 750 // But we do support custom-lowering for FCOPYSIGN. 751 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 752 } 753 754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 755 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 756 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 757 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 758 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 759 setOperationAction(ISD::SRA, VT, Custom); 760 setOperationAction(ISD::SRL, VT, Custom); 761 setOperationAction(ISD::SHL, VT, Custom); 762 setOperationAction(ISD::AND, VT, Custom); 763 setOperationAction(ISD::OR, VT, Custom); 764 setOperationAction(ISD::SETCC, VT, Custom); 765 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 766 767 setOperationAction(ISD::SELECT, VT, Expand); 768 setOperationAction(ISD::SELECT_CC, VT, Expand); 769 setOperationAction(ISD::VSELECT, VT, Expand); 770 for (MVT InnerVT : MVT::all_valuetypes()) 771 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 772 773 // CNT supports only B element sizes. 774 if (VT != MVT::v8i8 && VT != MVT::v16i8) 775 setOperationAction(ISD::CTPOP, VT, Expand); 776 777 setOperationAction(ISD::UDIV, VT, Expand); 778 setOperationAction(ISD::SDIV, VT, Expand); 779 setOperationAction(ISD::UREM, VT, Expand); 780 setOperationAction(ISD::SREM, VT, Expand); 781 setOperationAction(ISD::FREM, VT, Expand); 782 783 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 784 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 785 786 if (!VT.isFloatingPoint()) 787 setOperationAction(ISD::ABS, VT, Legal); 788 789 // [SU][MIN|MAX] are available for all NEON types apart from i64. 790 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 791 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 792 setOperationAction(Opcode, VT, Legal); 793 794 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 795 if (VT.isFloatingPoint() && 796 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 797 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN, 798 ISD::FMINNUM, ISD::FMAXNUM}) 799 setOperationAction(Opcode, VT, Legal); 800 801 if (Subtarget->isLittleEndian()) { 802 for (unsigned im = (unsigned)ISD::PRE_INC; 803 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 804 setIndexedLoadAction(im, VT, Legal); 805 setIndexedStoreAction(im, VT, Legal); 806 } 807 } 808 } 809 810 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 811 addRegisterClass(VT, &AArch64::FPR64RegClass); 812 addTypeForNEON(VT, MVT::v2i32); 813 } 814 815 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 816 addRegisterClass(VT, &AArch64::FPR128RegClass); 817 addTypeForNEON(VT, MVT::v4i32); 818 } 819 820 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 821 EVT VT) const { 822 if (!VT.isVector()) 823 return MVT::i32; 824 return VT.changeVectorElementTypeToInteger(); 825 } 826 827 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 828 const APInt &Demanded, 829 TargetLowering::TargetLoweringOpt &TLO, 830 unsigned NewOpc) { 831 uint64_t OldImm = Imm, NewImm, Enc; 832 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 833 834 // Return if the immediate is already all zeros, all ones, a bimm32 or a 835 // bimm64. 836 if (Imm == 0 || Imm == Mask || 837 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 838 return false; 839 840 unsigned EltSize = Size; 841 uint64_t DemandedBits = Demanded.getZExtValue(); 842 843 // Clear bits that are not demanded. 844 Imm &= DemandedBits; 845 846 while (true) { 847 // The goal here is to set the non-demanded bits in a way that minimizes 848 // the number of switching between 0 and 1. In order to achieve this goal, 849 // we set the non-demanded bits to the value of the preceding demanded bits. 850 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 851 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 852 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 853 // The final result is 0b11000011. 854 uint64_t NonDemandedBits = ~DemandedBits; 855 uint64_t InvertedImm = ~Imm & DemandedBits; 856 uint64_t RotatedImm = 857 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 858 NonDemandedBits; 859 uint64_t Sum = RotatedImm + NonDemandedBits; 860 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 861 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 862 NewImm = (Imm | Ones) & Mask; 863 864 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 865 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 866 // we halve the element size and continue the search. 867 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 868 break; 869 870 // We cannot shrink the element size any further if it is 2-bits. 871 if (EltSize == 2) 872 return false; 873 874 EltSize /= 2; 875 Mask >>= EltSize; 876 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 877 878 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 879 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 880 return false; 881 882 // Merge the upper and lower halves of Imm and DemandedBits. 883 Imm |= Hi; 884 DemandedBits |= DemandedBitsHi; 885 } 886 887 ++NumOptimizedImms; 888 889 // Replicate the element across the register width. 890 while (EltSize < Size) { 891 NewImm |= NewImm << EltSize; 892 EltSize *= 2; 893 } 894 895 (void)OldImm; 896 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 897 "demanded bits should never be altered"); 898 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 899 900 // Create the new constant immediate node. 901 EVT VT = Op.getValueType(); 902 SDLoc DL(Op); 903 SDValue New; 904 905 // If the new constant immediate is all-zeros or all-ones, let the target 906 // independent DAG combine optimize this node. 907 if (NewImm == 0 || NewImm == OrigMask) { 908 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 909 TLO.DAG.getConstant(NewImm, DL, VT)); 910 // Otherwise, create a machine node so that target independent DAG combine 911 // doesn't undo this optimization. 912 } else { 913 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 914 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 915 New = SDValue( 916 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 917 } 918 919 return TLO.CombineTo(Op, New); 920 } 921 922 bool AArch64TargetLowering::targetShrinkDemandedConstant( 923 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 924 // Delay this optimization to as late as possible. 925 if (!TLO.LegalOps) 926 return false; 927 928 if (!EnableOptimizeLogicalImm) 929 return false; 930 931 EVT VT = Op.getValueType(); 932 if (VT.isVector()) 933 return false; 934 935 unsigned Size = VT.getSizeInBits(); 936 assert((Size == 32 || Size == 64) && 937 "i32 or i64 is expected after legalization."); 938 939 // Exit early if we demand all bits. 940 if (Demanded.countPopulation() == Size) 941 return false; 942 943 unsigned NewOpc; 944 switch (Op.getOpcode()) { 945 default: 946 return false; 947 case ISD::AND: 948 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 949 break; 950 case ISD::OR: 951 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 952 break; 953 case ISD::XOR: 954 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 955 break; 956 } 957 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 958 if (!C) 959 return false; 960 uint64_t Imm = C->getZExtValue(); 961 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 962 } 963 964 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 965 /// Mask are known to be either zero or one and return them Known. 966 void AArch64TargetLowering::computeKnownBitsForTargetNode( 967 const SDValue Op, KnownBits &Known, 968 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 969 switch (Op.getOpcode()) { 970 default: 971 break; 972 case AArch64ISD::CSEL: { 973 KnownBits Known2; 974 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1); 975 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1); 976 Known.Zero &= Known2.Zero; 977 Known.One &= Known2.One; 978 break; 979 } 980 case ISD::INTRINSIC_W_CHAIN: { 981 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 982 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 983 switch (IntID) { 984 default: return; 985 case Intrinsic::aarch64_ldaxr: 986 case Intrinsic::aarch64_ldxr: { 987 unsigned BitWidth = Known.getBitWidth(); 988 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 989 unsigned MemBits = VT.getScalarSizeInBits(); 990 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 991 return; 992 } 993 } 994 break; 995 } 996 case ISD::INTRINSIC_WO_CHAIN: 997 case ISD::INTRINSIC_VOID: { 998 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 999 switch (IntNo) { 1000 default: 1001 break; 1002 case Intrinsic::aarch64_neon_umaxv: 1003 case Intrinsic::aarch64_neon_uminv: { 1004 // Figure out the datatype of the vector operand. The UMINV instruction 1005 // will zero extend the result, so we can mark as known zero all the 1006 // bits larger than the element datatype. 32-bit or larget doesn't need 1007 // this as those are legal types and will be handled by isel directly. 1008 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1009 unsigned BitWidth = Known.getBitWidth(); 1010 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1011 assert(BitWidth >= 8 && "Unexpected width!"); 1012 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1013 Known.Zero |= Mask; 1014 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1015 assert(BitWidth >= 16 && "Unexpected width!"); 1016 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1017 Known.Zero |= Mask; 1018 } 1019 break; 1020 } break; 1021 } 1022 } 1023 } 1024 } 1025 1026 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1027 EVT) const { 1028 return MVT::i64; 1029 } 1030 1031 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 1032 unsigned AddrSpace, 1033 unsigned Align, 1034 bool *Fast) const { 1035 if (Subtarget->requiresStrictAlign()) 1036 return false; 1037 1038 if (Fast) { 1039 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1040 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1041 // See comments in performSTORECombine() for more details about 1042 // these conditions. 1043 1044 // Code that uses clang vector extensions can mark that it 1045 // wants unaligned accesses to be treated as fast by 1046 // underspecifying alignment to be 1 or 2. 1047 Align <= 2 || 1048 1049 // Disregard v2i64. Memcpy lowering produces those and splitting 1050 // them regresses performance on micro-benchmarks and olden/bh. 1051 VT == MVT::v2i64; 1052 } 1053 return true; 1054 } 1055 1056 FastISel * 1057 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1058 const TargetLibraryInfo *libInfo) const { 1059 return AArch64::createFastISel(funcInfo, libInfo); 1060 } 1061 1062 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1063 switch ((AArch64ISD::NodeType)Opcode) { 1064 case AArch64ISD::FIRST_NUMBER: break; 1065 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1066 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1067 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1068 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1069 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1070 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1071 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1072 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1073 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1074 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1075 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1076 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1077 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1078 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1079 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1080 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1081 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1082 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1083 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1084 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1085 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1086 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1087 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1088 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1089 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1090 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1091 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1092 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1093 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1094 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1095 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1096 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1097 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1098 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1099 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1100 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1101 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1102 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1103 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 1104 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1105 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1106 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1107 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1108 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1109 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1110 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1111 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1112 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1113 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1114 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1115 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1116 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1117 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1118 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1119 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1120 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1121 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1122 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1123 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1124 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1125 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1126 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1127 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1128 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1129 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1130 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1131 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1132 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1133 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1134 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1135 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1136 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1137 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1138 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1139 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1140 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1141 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1142 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1143 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1144 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1145 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1146 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1147 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1148 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1149 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1150 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1151 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1152 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1153 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1154 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1155 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1156 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1157 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1158 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1159 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1160 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1161 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1162 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1163 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1164 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1165 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1166 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1167 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1168 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1169 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1170 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1171 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1172 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1173 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1174 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1175 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1176 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1177 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1178 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1179 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1180 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1181 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1182 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1183 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1184 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1185 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1186 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1187 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1188 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1189 } 1190 return nullptr; 1191 } 1192 1193 MachineBasicBlock * 1194 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1195 MachineBasicBlock *MBB) const { 1196 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1197 // phi node: 1198 1199 // OrigBB: 1200 // [... previous instrs leading to comparison ...] 1201 // b.ne TrueBB 1202 // b EndBB 1203 // TrueBB: 1204 // ; Fallthrough 1205 // EndBB: 1206 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1207 1208 MachineFunction *MF = MBB->getParent(); 1209 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1210 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1211 DebugLoc DL = MI.getDebugLoc(); 1212 MachineFunction::iterator It = ++MBB->getIterator(); 1213 1214 unsigned DestReg = MI.getOperand(0).getReg(); 1215 unsigned IfTrueReg = MI.getOperand(1).getReg(); 1216 unsigned IfFalseReg = MI.getOperand(2).getReg(); 1217 unsigned CondCode = MI.getOperand(3).getImm(); 1218 bool NZCVKilled = MI.getOperand(4).isKill(); 1219 1220 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1221 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1222 MF->insert(It, TrueBB); 1223 MF->insert(It, EndBB); 1224 1225 // Transfer rest of current basic-block to EndBB 1226 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1227 MBB->end()); 1228 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1229 1230 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1231 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1232 MBB->addSuccessor(TrueBB); 1233 MBB->addSuccessor(EndBB); 1234 1235 // TrueBB falls through to the end. 1236 TrueBB->addSuccessor(EndBB); 1237 1238 if (!NZCVKilled) { 1239 TrueBB->addLiveIn(AArch64::NZCV); 1240 EndBB->addLiveIn(AArch64::NZCV); 1241 } 1242 1243 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1244 .addReg(IfTrueReg) 1245 .addMBB(TrueBB) 1246 .addReg(IfFalseReg) 1247 .addMBB(MBB); 1248 1249 MI.eraseFromParent(); 1250 return EndBB; 1251 } 1252 1253 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1254 MachineInstr &MI, MachineBasicBlock *BB) const { 1255 switch (MI.getOpcode()) { 1256 default: 1257 #ifndef NDEBUG 1258 MI.dump(); 1259 #endif 1260 llvm_unreachable("Unexpected instruction for custom inserter!"); 1261 1262 case AArch64::F128CSEL: 1263 return EmitF128CSEL(MI, BB); 1264 1265 case TargetOpcode::STACKMAP: 1266 case TargetOpcode::PATCHPOINT: 1267 return emitPatchPoint(MI, BB); 1268 } 1269 } 1270 1271 //===----------------------------------------------------------------------===// 1272 // AArch64 Lowering private implementation. 1273 //===----------------------------------------------------------------------===// 1274 1275 //===----------------------------------------------------------------------===// 1276 // Lowering Code 1277 //===----------------------------------------------------------------------===// 1278 1279 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1280 /// CC 1281 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1282 switch (CC) { 1283 default: 1284 llvm_unreachable("Unknown condition code!"); 1285 case ISD::SETNE: 1286 return AArch64CC::NE; 1287 case ISD::SETEQ: 1288 return AArch64CC::EQ; 1289 case ISD::SETGT: 1290 return AArch64CC::GT; 1291 case ISD::SETGE: 1292 return AArch64CC::GE; 1293 case ISD::SETLT: 1294 return AArch64CC::LT; 1295 case ISD::SETLE: 1296 return AArch64CC::LE; 1297 case ISD::SETUGT: 1298 return AArch64CC::HI; 1299 case ISD::SETUGE: 1300 return AArch64CC::HS; 1301 case ISD::SETULT: 1302 return AArch64CC::LO; 1303 case ISD::SETULE: 1304 return AArch64CC::LS; 1305 } 1306 } 1307 1308 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1309 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1310 AArch64CC::CondCode &CondCode, 1311 AArch64CC::CondCode &CondCode2) { 1312 CondCode2 = AArch64CC::AL; 1313 switch (CC) { 1314 default: 1315 llvm_unreachable("Unknown FP condition!"); 1316 case ISD::SETEQ: 1317 case ISD::SETOEQ: 1318 CondCode = AArch64CC::EQ; 1319 break; 1320 case ISD::SETGT: 1321 case ISD::SETOGT: 1322 CondCode = AArch64CC::GT; 1323 break; 1324 case ISD::SETGE: 1325 case ISD::SETOGE: 1326 CondCode = AArch64CC::GE; 1327 break; 1328 case ISD::SETOLT: 1329 CondCode = AArch64CC::MI; 1330 break; 1331 case ISD::SETOLE: 1332 CondCode = AArch64CC::LS; 1333 break; 1334 case ISD::SETONE: 1335 CondCode = AArch64CC::MI; 1336 CondCode2 = AArch64CC::GT; 1337 break; 1338 case ISD::SETO: 1339 CondCode = AArch64CC::VC; 1340 break; 1341 case ISD::SETUO: 1342 CondCode = AArch64CC::VS; 1343 break; 1344 case ISD::SETUEQ: 1345 CondCode = AArch64CC::EQ; 1346 CondCode2 = AArch64CC::VS; 1347 break; 1348 case ISD::SETUGT: 1349 CondCode = AArch64CC::HI; 1350 break; 1351 case ISD::SETUGE: 1352 CondCode = AArch64CC::PL; 1353 break; 1354 case ISD::SETLT: 1355 case ISD::SETULT: 1356 CondCode = AArch64CC::LT; 1357 break; 1358 case ISD::SETLE: 1359 case ISD::SETULE: 1360 CondCode = AArch64CC::LE; 1361 break; 1362 case ISD::SETNE: 1363 case ISD::SETUNE: 1364 CondCode = AArch64CC::NE; 1365 break; 1366 } 1367 } 1368 1369 /// Convert a DAG fp condition code to an AArch64 CC. 1370 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1371 /// should be AND'ed instead of OR'ed. 1372 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1373 AArch64CC::CondCode &CondCode, 1374 AArch64CC::CondCode &CondCode2) { 1375 CondCode2 = AArch64CC::AL; 1376 switch (CC) { 1377 default: 1378 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1379 assert(CondCode2 == AArch64CC::AL); 1380 break; 1381 case ISD::SETONE: 1382 // (a one b) 1383 // == ((a olt b) || (a ogt b)) 1384 // == ((a ord b) && (a une b)) 1385 CondCode = AArch64CC::VC; 1386 CondCode2 = AArch64CC::NE; 1387 break; 1388 case ISD::SETUEQ: 1389 // (a ueq b) 1390 // == ((a uno b) || (a oeq b)) 1391 // == ((a ule b) && (a uge b)) 1392 CondCode = AArch64CC::PL; 1393 CondCode2 = AArch64CC::LE; 1394 break; 1395 } 1396 } 1397 1398 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1399 /// CC usable with the vector instructions. Fewer operations are available 1400 /// without a real NZCV register, so we have to use less efficient combinations 1401 /// to get the same effect. 1402 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1403 AArch64CC::CondCode &CondCode, 1404 AArch64CC::CondCode &CondCode2, 1405 bool &Invert) { 1406 Invert = false; 1407 switch (CC) { 1408 default: 1409 // Mostly the scalar mappings work fine. 1410 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1411 break; 1412 case ISD::SETUO: 1413 Invert = true; 1414 LLVM_FALLTHROUGH; 1415 case ISD::SETO: 1416 CondCode = AArch64CC::MI; 1417 CondCode2 = AArch64CC::GE; 1418 break; 1419 case ISD::SETUEQ: 1420 case ISD::SETULT: 1421 case ISD::SETULE: 1422 case ISD::SETUGT: 1423 case ISD::SETUGE: 1424 // All of the compare-mask comparisons are ordered, but we can switch 1425 // between the two by a double inversion. E.g. ULE == !OGT. 1426 Invert = true; 1427 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1428 break; 1429 } 1430 } 1431 1432 static bool isLegalArithImmed(uint64_t C) { 1433 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1434 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1435 DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n")); 1436 return IsLegal; 1437 } 1438 1439 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1440 const SDLoc &dl, SelectionDAG &DAG) { 1441 EVT VT = LHS.getValueType(); 1442 const bool FullFP16 = 1443 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1444 1445 if (VT.isFloatingPoint()) { 1446 assert(VT != MVT::f128); 1447 if (VT == MVT::f16 && !FullFP16) { 1448 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1449 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1450 VT = MVT::f32; 1451 } 1452 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1453 } 1454 1455 // The CMP instruction is just an alias for SUBS, and representing it as 1456 // SUBS means that it's possible to get CSE with subtract operations. 1457 // A later phase can perform the optimization of setting the destination 1458 // register to WZR/XZR if it ends up being unused. 1459 unsigned Opcode = AArch64ISD::SUBS; 1460 1461 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 1462 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1463 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on 1464 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags 1465 // can be set differently by this operation. It comes down to whether 1466 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1467 // everything is fine. If not then the optimization is wrong. Thus general 1468 // comparisons are only valid if op2 != 0. 1469 1470 // So, finally, the only LLVM-native comparisons that don't mention C and V 1471 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1472 // the absence of information about op2. 1473 Opcode = AArch64ISD::ADDS; 1474 RHS = RHS.getOperand(1); 1475 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1476 !isUnsignedIntSetCC(CC)) { 1477 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1478 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1479 // of the signed comparisons. 1480 Opcode = AArch64ISD::ANDS; 1481 RHS = LHS.getOperand(1); 1482 LHS = LHS.getOperand(0); 1483 } 1484 1485 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1486 .getValue(1); 1487 } 1488 1489 /// \defgroup AArch64CCMP CMP;CCMP matching 1490 /// 1491 /// These functions deal with the formation of CMP;CCMP;... sequences. 1492 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1493 /// a comparison. They set the NZCV flags to a predefined value if their 1494 /// predicate is false. This allows to express arbitrary conjunctions, for 1495 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))" 1496 /// expressed as: 1497 /// cmp A 1498 /// ccmp B, inv(CB), CA 1499 /// check for CB flags 1500 /// 1501 /// In general we can create code for arbitrary "... (and (and A B) C)" 1502 /// sequences. We can also implement some "or" expressions, because "(or A B)" 1503 /// is equivalent to "not (and (not A) (not B))" and we can implement some 1504 /// negation operations: 1505 /// We can negate the results of a single comparison by inverting the flags 1506 /// used when the predicate fails and inverting the flags tested in the next 1507 /// instruction; We can also negate the results of the whole previous 1508 /// conditional compare sequence by inverting the flags tested in the next 1509 /// instruction. However there is no way to negate the result of a partial 1510 /// sequence. 1511 /// 1512 /// Therefore on encountering an "or" expression we can negate the subtree on 1513 /// one side and have to be able to push the negate to the leafs of the subtree 1514 /// on the other side (see also the comments in code). As complete example: 1515 /// "or (or (setCA (cmp A)) (setCB (cmp B))) 1516 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1517 /// is transformed to 1518 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D)))) 1519 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1520 /// and implemented as: 1521 /// cmp C 1522 /// ccmp D, inv(CD), CC 1523 /// ccmp A, CA, inv(CD) 1524 /// ccmp B, CB, inv(CA) 1525 /// check for CB flags 1526 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented 1527 /// by conditional compare sequences. 1528 /// @{ 1529 1530 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1531 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1532 ISD::CondCode CC, SDValue CCOp, 1533 AArch64CC::CondCode Predicate, 1534 AArch64CC::CondCode OutCC, 1535 const SDLoc &DL, SelectionDAG &DAG) { 1536 unsigned Opcode = 0; 1537 const bool FullFP16 = 1538 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1539 1540 if (LHS.getValueType().isFloatingPoint()) { 1541 assert(LHS.getValueType() != MVT::f128); 1542 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 1543 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1544 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1545 } 1546 Opcode = AArch64ISD::FCCMP; 1547 } else if (RHS.getOpcode() == ISD::SUB) { 1548 SDValue SubOp0 = RHS.getOperand(0); 1549 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1550 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1551 Opcode = AArch64ISD::CCMN; 1552 RHS = RHS.getOperand(1); 1553 } 1554 } 1555 if (Opcode == 0) 1556 Opcode = AArch64ISD::CCMP; 1557 1558 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1559 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1560 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1561 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1562 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1563 } 1564 1565 /// Returns true if @p Val is a tree of AND/OR/SETCC operations. 1566 /// CanPushNegate is set to true if we can push a negate operation through 1567 /// the tree in a was that we are left with AND operations and negate operations 1568 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to 1569 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be 1570 /// brought into such a form. 1571 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate, 1572 unsigned Depth = 0) { 1573 if (!Val.hasOneUse()) 1574 return false; 1575 unsigned Opcode = Val->getOpcode(); 1576 if (Opcode == ISD::SETCC) { 1577 if (Val->getOperand(0).getValueType() == MVT::f128) 1578 return false; 1579 CanNegate = true; 1580 return true; 1581 } 1582 // Protect against exponential runtime and stack overflow. 1583 if (Depth > 6) 1584 return false; 1585 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1586 SDValue O0 = Val->getOperand(0); 1587 SDValue O1 = Val->getOperand(1); 1588 bool CanNegateL; 1589 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1)) 1590 return false; 1591 bool CanNegateR; 1592 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1)) 1593 return false; 1594 1595 if (Opcode == ISD::OR) { 1596 // For an OR expression we need to be able to negate at least one side or 1597 // we cannot do the transformation at all. 1598 if (!CanNegateL && !CanNegateR) 1599 return false; 1600 // We can however change a (not (or x y)) to (and (not x) (not y)) if we 1601 // can negate the x and y subtrees. 1602 CanNegate = CanNegateL && CanNegateR; 1603 } else { 1604 // If the operands are OR expressions then we finally need to negate their 1605 // outputs, we can only do that for the operand with emitted last by 1606 // negating OutCC, not for both operands. 1607 bool NeedsNegOutL = O0->getOpcode() == ISD::OR; 1608 bool NeedsNegOutR = O1->getOpcode() == ISD::OR; 1609 if (NeedsNegOutL && NeedsNegOutR) 1610 return false; 1611 // We cannot negate an AND operation (it would become an OR), 1612 CanNegate = false; 1613 } 1614 return true; 1615 } 1616 return false; 1617 } 1618 1619 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1620 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1621 /// Tries to transform the given i1 producing node @p Val to a series compare 1622 /// and conditional compare operations. @returns an NZCV flags producing node 1623 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1624 /// transformation was not possible. 1625 /// On recursive invocations @p PushNegate may be set to true to have negation 1626 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate 1627 /// for the comparisons in the current subtree; @p Depth limits the search 1628 /// depth to avoid stack overflow. 1629 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val, 1630 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1631 AArch64CC::CondCode Predicate) { 1632 // We're at a tree leaf, produce a conditional comparison operation. 1633 unsigned Opcode = Val->getOpcode(); 1634 if (Opcode == ISD::SETCC) { 1635 SDValue LHS = Val->getOperand(0); 1636 SDValue RHS = Val->getOperand(1); 1637 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1638 bool isInteger = LHS.getValueType().isInteger(); 1639 if (Negate) 1640 CC = getSetCCInverse(CC, isInteger); 1641 SDLoc DL(Val); 1642 // Determine OutCC and handle FP special case. 1643 if (isInteger) { 1644 OutCC = changeIntCCToAArch64CC(CC); 1645 } else { 1646 assert(LHS.getValueType().isFloatingPoint()); 1647 AArch64CC::CondCode ExtraCC; 1648 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1649 // Some floating point conditions can't be tested with a single condition 1650 // code. Construct an additional comparison in this case. 1651 if (ExtraCC != AArch64CC::AL) { 1652 SDValue ExtraCmp; 1653 if (!CCOp.getNode()) 1654 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1655 else 1656 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1657 ExtraCC, DL, DAG); 1658 CCOp = ExtraCmp; 1659 Predicate = ExtraCC; 1660 } 1661 } 1662 1663 // Produce a normal comparison if we are first in the chain 1664 if (!CCOp) 1665 return emitComparison(LHS, RHS, CC, DL, DAG); 1666 // Otherwise produce a ccmp. 1667 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1668 DAG); 1669 } 1670 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) && 1671 "Valid conjunction/disjunction tree"); 1672 1673 // Check if both sides can be transformed. 1674 SDValue LHS = Val->getOperand(0); 1675 SDValue RHS = Val->getOperand(1); 1676 1677 // In case of an OR we need to negate our operands and the result. 1678 // (A v B) <=> not(not(A) ^ not(B)) 1679 bool NegateOpsAndResult = Opcode == ISD::OR; 1680 // We can negate the results of all previous operations by inverting the 1681 // predicate flags giving us a free negation for one side. The other side 1682 // must be negatable by itself. 1683 if (NegateOpsAndResult) { 1684 // See which side we can negate. 1685 bool CanNegateL; 1686 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL); 1687 assert(isValidL && "Valid conjunction/disjunction tree"); 1688 (void)isValidL; 1689 1690 #ifndef NDEBUG 1691 bool CanNegateR; 1692 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR); 1693 assert(isValidR && "Valid conjunction/disjunction tree"); 1694 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree"); 1695 #endif 1696 1697 // Order the side which we cannot negate to RHS so we can emit it first. 1698 if (!CanNegateL) 1699 std::swap(LHS, RHS); 1700 } else { 1701 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR; 1702 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) && 1703 "Valid conjunction/disjunction tree"); 1704 // Order the side where we need to negate the output flags to RHS so it 1705 // gets emitted first. 1706 if (NeedsNegOutL) 1707 std::swap(LHS, RHS); 1708 } 1709 1710 // Emit RHS. If we want to negate the tree we only need to push a negate 1711 // through if we are already in a PushNegate case, otherwise we can negate 1712 // the "flags to test" afterwards. 1713 AArch64CC::CondCode RHSCC; 1714 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate, 1715 CCOp, Predicate); 1716 if (NegateOpsAndResult && !Negate) 1717 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1718 // Emit LHS. We may need to negate it. 1719 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC, 1720 NegateOpsAndResult, CmpR, 1721 RHSCC); 1722 // If we transformed an OR to and AND then we have to negate the result 1723 // (or absorb the Negate parameter). 1724 if (NegateOpsAndResult && !Negate) 1725 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1726 return CmpL; 1727 } 1728 1729 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1730 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1731 /// \see emitConjunctionDisjunctionTreeRec(). 1732 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val, 1733 AArch64CC::CondCode &OutCC) { 1734 bool CanNegate; 1735 if (!isConjunctionDisjunctionTree(Val, CanNegate)) 1736 return SDValue(); 1737 1738 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(), 1739 AArch64CC::AL); 1740 } 1741 1742 /// @} 1743 1744 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1745 SDValue &AArch64cc, SelectionDAG &DAG, 1746 const SDLoc &dl) { 1747 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1748 EVT VT = RHS.getValueType(); 1749 uint64_t C = RHSC->getZExtValue(); 1750 if (!isLegalArithImmed(C)) { 1751 // Constant does not fit, try adjusting it by one? 1752 switch (CC) { 1753 default: 1754 break; 1755 case ISD::SETLT: 1756 case ISD::SETGE: 1757 if ((VT == MVT::i32 && C != 0x80000000 && 1758 isLegalArithImmed((uint32_t)(C - 1))) || 1759 (VT == MVT::i64 && C != 0x80000000ULL && 1760 isLegalArithImmed(C - 1ULL))) { 1761 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1762 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1763 RHS = DAG.getConstant(C, dl, VT); 1764 } 1765 break; 1766 case ISD::SETULT: 1767 case ISD::SETUGE: 1768 if ((VT == MVT::i32 && C != 0 && 1769 isLegalArithImmed((uint32_t)(C - 1))) || 1770 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1771 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1772 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1773 RHS = DAG.getConstant(C, dl, VT); 1774 } 1775 break; 1776 case ISD::SETLE: 1777 case ISD::SETGT: 1778 if ((VT == MVT::i32 && C != INT32_MAX && 1779 isLegalArithImmed((uint32_t)(C + 1))) || 1780 (VT == MVT::i64 && C != INT64_MAX && 1781 isLegalArithImmed(C + 1ULL))) { 1782 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1783 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1784 RHS = DAG.getConstant(C, dl, VT); 1785 } 1786 break; 1787 case ISD::SETULE: 1788 case ISD::SETUGT: 1789 if ((VT == MVT::i32 && C != UINT32_MAX && 1790 isLegalArithImmed((uint32_t)(C + 1))) || 1791 (VT == MVT::i64 && C != UINT64_MAX && 1792 isLegalArithImmed(C + 1ULL))) { 1793 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1794 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1795 RHS = DAG.getConstant(C, dl, VT); 1796 } 1797 break; 1798 } 1799 } 1800 } 1801 SDValue Cmp; 1802 AArch64CC::CondCode AArch64CC; 1803 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1804 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1805 1806 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1807 // For the i8 operand, the largest immediate is 255, so this can be easily 1808 // encoded in the compare instruction. For the i16 operand, however, the 1809 // largest immediate cannot be encoded in the compare. 1810 // Therefore, use a sign extending load and cmn to avoid materializing the 1811 // -1 constant. For example, 1812 // movz w1, #65535 1813 // ldrh w0, [x0, #0] 1814 // cmp w0, w1 1815 // > 1816 // ldrsh w0, [x0, #0] 1817 // cmn w0, #1 1818 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1819 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1820 // ensure both the LHS and RHS are truly zero extended and to make sure the 1821 // transformation is profitable. 1822 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1823 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1824 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1825 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1826 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1827 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1828 SDValue SExt = 1829 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1830 DAG.getValueType(MVT::i16)); 1831 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1832 RHS.getValueType()), 1833 CC, dl, DAG); 1834 AArch64CC = changeIntCCToAArch64CC(CC); 1835 } 1836 } 1837 1838 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 1839 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) { 1840 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 1841 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 1842 } 1843 } 1844 } 1845 1846 if (!Cmp) { 1847 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 1848 AArch64CC = changeIntCCToAArch64CC(CC); 1849 } 1850 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 1851 return Cmp; 1852 } 1853 1854 static std::pair<SDValue, SDValue> 1855 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 1856 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 1857 "Unsupported value type"); 1858 SDValue Value, Overflow; 1859 SDLoc DL(Op); 1860 SDValue LHS = Op.getOperand(0); 1861 SDValue RHS = Op.getOperand(1); 1862 unsigned Opc = 0; 1863 switch (Op.getOpcode()) { 1864 default: 1865 llvm_unreachable("Unknown overflow instruction!"); 1866 case ISD::SADDO: 1867 Opc = AArch64ISD::ADDS; 1868 CC = AArch64CC::VS; 1869 break; 1870 case ISD::UADDO: 1871 Opc = AArch64ISD::ADDS; 1872 CC = AArch64CC::HS; 1873 break; 1874 case ISD::SSUBO: 1875 Opc = AArch64ISD::SUBS; 1876 CC = AArch64CC::VS; 1877 break; 1878 case ISD::USUBO: 1879 Opc = AArch64ISD::SUBS; 1880 CC = AArch64CC::LO; 1881 break; 1882 // Multiply needs a little bit extra work. 1883 case ISD::SMULO: 1884 case ISD::UMULO: { 1885 CC = AArch64CC::NE; 1886 bool IsSigned = Op.getOpcode() == ISD::SMULO; 1887 if (Op.getValueType() == MVT::i32) { 1888 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1889 // For a 32 bit multiply with overflow check we want the instruction 1890 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 1891 // need to generate the following pattern: 1892 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 1893 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 1894 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 1895 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1896 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 1897 DAG.getConstant(0, DL, MVT::i64)); 1898 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 1899 // operation. We need to clear out the upper 32 bits, because we used a 1900 // widening multiply that wrote all 64 bits. In the end this should be a 1901 // noop. 1902 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 1903 if (IsSigned) { 1904 // The signed overflow check requires more than just a simple check for 1905 // any bit set in the upper 32 bits of the result. These bits could be 1906 // just the sign bits of a negative number. To perform the overflow 1907 // check we have to arithmetic shift right the 32nd bit of the result by 1908 // 31 bits. Then we compare the result to the upper 32 bits. 1909 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 1910 DAG.getConstant(32, DL, MVT::i64)); 1911 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 1912 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 1913 DAG.getConstant(31, DL, MVT::i64)); 1914 // It is important that LowerBits is last, otherwise the arithmetic 1915 // shift will not be folded into the compare (SUBS). 1916 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 1917 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1918 .getValue(1); 1919 } else { 1920 // The overflow check for unsigned multiply is easy. We only need to 1921 // check if any of the upper 32 bits are set. This can be done with a 1922 // CMP (shifted register). For that we need to generate the following 1923 // pattern: 1924 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 1925 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 1926 DAG.getConstant(32, DL, MVT::i64)); 1927 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1928 Overflow = 1929 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1930 DAG.getConstant(0, DL, MVT::i64), 1931 UpperBits).getValue(1); 1932 } 1933 break; 1934 } 1935 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 1936 // For the 64 bit multiply 1937 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1938 if (IsSigned) { 1939 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 1940 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 1941 DAG.getConstant(63, DL, MVT::i64)); 1942 // It is important that LowerBits is last, otherwise the arithmetic 1943 // shift will not be folded into the compare (SUBS). 1944 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1945 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1946 .getValue(1); 1947 } else { 1948 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 1949 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1950 Overflow = 1951 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1952 DAG.getConstant(0, DL, MVT::i64), 1953 UpperBits).getValue(1); 1954 } 1955 break; 1956 } 1957 } // switch (...) 1958 1959 if (Opc) { 1960 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 1961 1962 // Emit the AArch64 operation with overflow check. 1963 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 1964 Overflow = Value.getValue(1); 1965 } 1966 return std::make_pair(Value, Overflow); 1967 } 1968 1969 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 1970 RTLIB::Libcall Call) const { 1971 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1972 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 1973 } 1974 1975 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1976 SDValue Sel = Op.getOperand(0); 1977 SDValue Other = Op.getOperand(1); 1978 1979 // If neither operand is a SELECT_CC, give up. 1980 if (Sel.getOpcode() != ISD::SELECT_CC) 1981 std::swap(Sel, Other); 1982 if (Sel.getOpcode() != ISD::SELECT_CC) 1983 return Op; 1984 1985 // The folding we want to perform is: 1986 // (xor x, (select_cc a, b, cc, 0, -1) ) 1987 // --> 1988 // (csel x, (xor x, -1), cc ...) 1989 // 1990 // The latter will get matched to a CSINV instruction. 1991 1992 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 1993 SDValue LHS = Sel.getOperand(0); 1994 SDValue RHS = Sel.getOperand(1); 1995 SDValue TVal = Sel.getOperand(2); 1996 SDValue FVal = Sel.getOperand(3); 1997 SDLoc dl(Sel); 1998 1999 // FIXME: This could be generalized to non-integer comparisons. 2000 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2001 return Op; 2002 2003 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2004 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2005 2006 // The values aren't constants, this isn't the pattern we're looking for. 2007 if (!CFVal || !CTVal) 2008 return Op; 2009 2010 // We can commute the SELECT_CC by inverting the condition. This 2011 // might be needed to make this fit into a CSINV pattern. 2012 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2013 std::swap(TVal, FVal); 2014 std::swap(CTVal, CFVal); 2015 CC = ISD::getSetCCInverse(CC, true); 2016 } 2017 2018 // If the constants line up, perform the transform! 2019 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2020 SDValue CCVal; 2021 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2022 2023 FVal = Other; 2024 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2025 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2026 2027 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2028 CCVal, Cmp); 2029 } 2030 2031 return Op; 2032 } 2033 2034 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2035 EVT VT = Op.getValueType(); 2036 2037 // Let legalize expand this if it isn't a legal type yet. 2038 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2039 return SDValue(); 2040 2041 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2042 2043 unsigned Opc; 2044 bool ExtraOp = false; 2045 switch (Op.getOpcode()) { 2046 default: 2047 llvm_unreachable("Invalid code"); 2048 case ISD::ADDC: 2049 Opc = AArch64ISD::ADDS; 2050 break; 2051 case ISD::SUBC: 2052 Opc = AArch64ISD::SUBS; 2053 break; 2054 case ISD::ADDE: 2055 Opc = AArch64ISD::ADCS; 2056 ExtraOp = true; 2057 break; 2058 case ISD::SUBE: 2059 Opc = AArch64ISD::SBCS; 2060 ExtraOp = true; 2061 break; 2062 } 2063 2064 if (!ExtraOp) 2065 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2066 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2067 Op.getOperand(2)); 2068 } 2069 2070 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2071 // Let legalize expand this if it isn't a legal type yet. 2072 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2073 return SDValue(); 2074 2075 SDLoc dl(Op); 2076 AArch64CC::CondCode CC; 2077 // The actual operation that sets the overflow or carry flag. 2078 SDValue Value, Overflow; 2079 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2080 2081 // We use 0 and 1 as false and true values. 2082 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2083 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2084 2085 // We use an inverted condition, because the conditional select is inverted 2086 // too. This will allow it to be selected to a single instruction: 2087 // CSINC Wd, WZR, WZR, invert(cond). 2088 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2089 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2090 CCVal, Overflow); 2091 2092 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2093 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2094 } 2095 2096 // Prefetch operands are: 2097 // 1: Address to prefetch 2098 // 2: bool isWrite 2099 // 3: int locality (0 = no locality ... 3 = extreme locality) 2100 // 4: bool isDataCache 2101 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2102 SDLoc DL(Op); 2103 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2104 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2105 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2106 2107 bool IsStream = !Locality; 2108 // When the locality number is set 2109 if (Locality) { 2110 // The front-end should have filtered out the out-of-range values 2111 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2112 // The locality degree is the opposite of the cache speed. 2113 // Put the number the other way around. 2114 // The encoding starts at 0 for level 1 2115 Locality = 3 - Locality; 2116 } 2117 2118 // built the mask value encoding the expected behavior. 2119 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2120 (!IsData << 3) | // IsDataCache bit 2121 (Locality << 1) | // Cache level bits 2122 (unsigned)IsStream; // Stream bit 2123 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2124 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2125 } 2126 2127 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2128 SelectionDAG &DAG) const { 2129 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2130 2131 RTLIB::Libcall LC; 2132 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2133 2134 return LowerF128Call(Op, DAG, LC); 2135 } 2136 2137 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2138 SelectionDAG &DAG) const { 2139 if (Op.getOperand(0).getValueType() != MVT::f128) { 2140 // It's legal except when f128 is involved 2141 return Op; 2142 } 2143 2144 RTLIB::Libcall LC; 2145 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 2146 2147 // FP_ROUND node has a second operand indicating whether it is known to be 2148 // precise. That doesn't take part in the LibCall so we can't directly use 2149 // LowerF128Call. 2150 SDValue SrcVal = Op.getOperand(0); 2151 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 2152 SDLoc(Op)).first; 2153 } 2154 2155 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 2156 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2157 // Any additional optimization in this function should be recorded 2158 // in the cost tables. 2159 EVT InVT = Op.getOperand(0).getValueType(); 2160 EVT VT = Op.getValueType(); 2161 unsigned NumElts = InVT.getVectorNumElements(); 2162 2163 // f16 vectors are promoted to f32 before a conversion. 2164 if (InVT.getVectorElementType() == MVT::f16) { 2165 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2166 SDLoc dl(Op); 2167 return DAG.getNode( 2168 Op.getOpcode(), dl, Op.getValueType(), 2169 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2170 } 2171 2172 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2173 SDLoc dl(Op); 2174 SDValue Cv = 2175 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2176 Op.getOperand(0)); 2177 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2178 } 2179 2180 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2181 SDLoc dl(Op); 2182 MVT ExtVT = 2183 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2184 VT.getVectorNumElements()); 2185 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2186 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2187 } 2188 2189 // Type changing conversions are illegal. 2190 return Op; 2191 } 2192 2193 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2194 SelectionDAG &DAG) const { 2195 if (Op.getOperand(0).getValueType().isVector()) 2196 return LowerVectorFP_TO_INT(Op, DAG); 2197 2198 // f16 conversions are promoted to f32 when full fp16 is not supported. 2199 if (Op.getOperand(0).getValueType() == MVT::f16 && 2200 !Subtarget->hasFullFP16()) { 2201 SDLoc dl(Op); 2202 return DAG.getNode( 2203 Op.getOpcode(), dl, Op.getValueType(), 2204 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2205 } 2206 2207 if (Op.getOperand(0).getValueType() != MVT::f128) { 2208 // It's legal except when f128 is involved 2209 return Op; 2210 } 2211 2212 RTLIB::Libcall LC; 2213 if (Op.getOpcode() == ISD::FP_TO_SINT) 2214 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2215 else 2216 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2217 2218 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2219 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2220 } 2221 2222 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2223 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2224 // Any additional optimization in this function should be recorded 2225 // in the cost tables. 2226 EVT VT = Op.getValueType(); 2227 SDLoc dl(Op); 2228 SDValue In = Op.getOperand(0); 2229 EVT InVT = In.getValueType(); 2230 2231 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2232 MVT CastVT = 2233 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2234 InVT.getVectorNumElements()); 2235 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2236 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2237 } 2238 2239 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2240 unsigned CastOpc = 2241 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2242 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2243 In = DAG.getNode(CastOpc, dl, CastVT, In); 2244 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2245 } 2246 2247 return Op; 2248 } 2249 2250 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2251 SelectionDAG &DAG) const { 2252 if (Op.getValueType().isVector()) 2253 return LowerVectorINT_TO_FP(Op, DAG); 2254 2255 // f16 conversions are promoted to f32 when full fp16 is not supported. 2256 if (Op.getValueType() == MVT::f16 && 2257 !Subtarget->hasFullFP16()) { 2258 SDLoc dl(Op); 2259 return DAG.getNode( 2260 ISD::FP_ROUND, dl, MVT::f16, 2261 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2262 DAG.getIntPtrConstant(0, dl)); 2263 } 2264 2265 // i128 conversions are libcalls. 2266 if (Op.getOperand(0).getValueType() == MVT::i128) 2267 return SDValue(); 2268 2269 // Other conversions are legal, unless it's to the completely software-based 2270 // fp128. 2271 if (Op.getValueType() != MVT::f128) 2272 return Op; 2273 2274 RTLIB::Libcall LC; 2275 if (Op.getOpcode() == ISD::SINT_TO_FP) 2276 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2277 else 2278 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2279 2280 return LowerF128Call(Op, DAG, LC); 2281 } 2282 2283 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2284 SelectionDAG &DAG) const { 2285 // For iOS, we want to call an alternative entry point: __sincos_stret, 2286 // which returns the values in two S / D registers. 2287 SDLoc dl(Op); 2288 SDValue Arg = Op.getOperand(0); 2289 EVT ArgVT = Arg.getValueType(); 2290 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2291 2292 ArgListTy Args; 2293 ArgListEntry Entry; 2294 2295 Entry.Node = Arg; 2296 Entry.Ty = ArgTy; 2297 Entry.IsSExt = false; 2298 Entry.IsZExt = false; 2299 Args.push_back(Entry); 2300 2301 const char *LibcallName = 2302 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2303 SDValue Callee = 2304 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2305 2306 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2307 TargetLowering::CallLoweringInfo CLI(DAG); 2308 CLI.setDebugLoc(dl) 2309 .setChain(DAG.getEntryNode()) 2310 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2311 2312 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2313 return CallResult.first; 2314 } 2315 2316 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2317 if (Op.getValueType() != MVT::f16) 2318 return SDValue(); 2319 2320 assert(Op.getOperand(0).getValueType() == MVT::i16); 2321 SDLoc DL(Op); 2322 2323 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2324 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2325 return SDValue( 2326 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2327 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2328 0); 2329 } 2330 2331 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2332 if (OrigVT.getSizeInBits() >= 64) 2333 return OrigVT; 2334 2335 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2336 2337 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2338 switch (OrigSimpleTy) { 2339 default: llvm_unreachable("Unexpected Vector Type"); 2340 case MVT::v2i8: 2341 case MVT::v2i16: 2342 return MVT::v2i32; 2343 case MVT::v4i8: 2344 return MVT::v4i16; 2345 } 2346 } 2347 2348 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2349 const EVT &OrigTy, 2350 const EVT &ExtTy, 2351 unsigned ExtOpcode) { 2352 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2353 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2354 // 64-bits we need to insert a new extension so that it will be 64-bits. 2355 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2356 if (OrigTy.getSizeInBits() >= 64) 2357 return N; 2358 2359 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2360 EVT NewVT = getExtensionTo64Bits(OrigTy); 2361 2362 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2363 } 2364 2365 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2366 bool isSigned) { 2367 EVT VT = N->getValueType(0); 2368 2369 if (N->getOpcode() != ISD::BUILD_VECTOR) 2370 return false; 2371 2372 for (const SDValue &Elt : N->op_values()) { 2373 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2374 unsigned EltSize = VT.getScalarSizeInBits(); 2375 unsigned HalfSize = EltSize / 2; 2376 if (isSigned) { 2377 if (!isIntN(HalfSize, C->getSExtValue())) 2378 return false; 2379 } else { 2380 if (!isUIntN(HalfSize, C->getZExtValue())) 2381 return false; 2382 } 2383 continue; 2384 } 2385 return false; 2386 } 2387 2388 return true; 2389 } 2390 2391 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2392 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2393 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2394 N->getOperand(0)->getValueType(0), 2395 N->getValueType(0), 2396 N->getOpcode()); 2397 2398 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2399 EVT VT = N->getValueType(0); 2400 SDLoc dl(N); 2401 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2402 unsigned NumElts = VT.getVectorNumElements(); 2403 MVT TruncVT = MVT::getIntegerVT(EltSize); 2404 SmallVector<SDValue, 8> Ops; 2405 for (unsigned i = 0; i != NumElts; ++i) { 2406 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2407 const APInt &CInt = C->getAPIntValue(); 2408 // Element types smaller than 32 bits are not legal, so use i32 elements. 2409 // The values are implicitly truncated so sext vs. zext doesn't matter. 2410 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2411 } 2412 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2413 } 2414 2415 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2416 return N->getOpcode() == ISD::SIGN_EXTEND || 2417 isExtendedBUILD_VECTOR(N, DAG, true); 2418 } 2419 2420 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2421 return N->getOpcode() == ISD::ZERO_EXTEND || 2422 isExtendedBUILD_VECTOR(N, DAG, false); 2423 } 2424 2425 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2426 unsigned Opcode = N->getOpcode(); 2427 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2428 SDNode *N0 = N->getOperand(0).getNode(); 2429 SDNode *N1 = N->getOperand(1).getNode(); 2430 return N0->hasOneUse() && N1->hasOneUse() && 2431 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2432 } 2433 return false; 2434 } 2435 2436 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2437 unsigned Opcode = N->getOpcode(); 2438 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2439 SDNode *N0 = N->getOperand(0).getNode(); 2440 SDNode *N1 = N->getOperand(1).getNode(); 2441 return N0->hasOneUse() && N1->hasOneUse() && 2442 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2443 } 2444 return false; 2445 } 2446 2447 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2448 // Multiplications are only custom-lowered for 128-bit vectors so that 2449 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2450 EVT VT = Op.getValueType(); 2451 assert(VT.is128BitVector() && VT.isInteger() && 2452 "unexpected type for custom-lowering ISD::MUL"); 2453 SDNode *N0 = Op.getOperand(0).getNode(); 2454 SDNode *N1 = Op.getOperand(1).getNode(); 2455 unsigned NewOpc = 0; 2456 bool isMLA = false; 2457 bool isN0SExt = isSignExtended(N0, DAG); 2458 bool isN1SExt = isSignExtended(N1, DAG); 2459 if (isN0SExt && isN1SExt) 2460 NewOpc = AArch64ISD::SMULL; 2461 else { 2462 bool isN0ZExt = isZeroExtended(N0, DAG); 2463 bool isN1ZExt = isZeroExtended(N1, DAG); 2464 if (isN0ZExt && isN1ZExt) 2465 NewOpc = AArch64ISD::UMULL; 2466 else if (isN1SExt || isN1ZExt) { 2467 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2468 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2469 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2470 NewOpc = AArch64ISD::SMULL; 2471 isMLA = true; 2472 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2473 NewOpc = AArch64ISD::UMULL; 2474 isMLA = true; 2475 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2476 std::swap(N0, N1); 2477 NewOpc = AArch64ISD::UMULL; 2478 isMLA = true; 2479 } 2480 } 2481 2482 if (!NewOpc) { 2483 if (VT == MVT::v2i64) 2484 // Fall through to expand this. It is not legal. 2485 return SDValue(); 2486 else 2487 // Other vector multiplications are legal. 2488 return Op; 2489 } 2490 } 2491 2492 // Legalize to a S/UMULL instruction 2493 SDLoc DL(Op); 2494 SDValue Op0; 2495 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2496 if (!isMLA) { 2497 Op0 = skipExtensionForVectorMULL(N0, DAG); 2498 assert(Op0.getValueType().is64BitVector() && 2499 Op1.getValueType().is64BitVector() && 2500 "unexpected types for extended operands to VMULL"); 2501 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2502 } 2503 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2504 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2505 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2506 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2507 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2508 EVT Op1VT = Op1.getValueType(); 2509 return DAG.getNode(N0->getOpcode(), DL, VT, 2510 DAG.getNode(NewOpc, DL, VT, 2511 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2512 DAG.getNode(NewOpc, DL, VT, 2513 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2514 } 2515 2516 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2517 SelectionDAG &DAG) const { 2518 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2519 SDLoc dl(Op); 2520 switch (IntNo) { 2521 default: return SDValue(); // Don't custom lower most intrinsics. 2522 case Intrinsic::thread_pointer: { 2523 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2524 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2525 } 2526 case Intrinsic::aarch64_neon_abs: 2527 return DAG.getNode(ISD::ABS, dl, Op.getValueType(), 2528 Op.getOperand(1)); 2529 case Intrinsic::aarch64_neon_smax: 2530 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2531 Op.getOperand(1), Op.getOperand(2)); 2532 case Intrinsic::aarch64_neon_umax: 2533 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2534 Op.getOperand(1), Op.getOperand(2)); 2535 case Intrinsic::aarch64_neon_smin: 2536 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2537 Op.getOperand(1), Op.getOperand(2)); 2538 case Intrinsic::aarch64_neon_umin: 2539 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2540 Op.getOperand(1), Op.getOperand(2)); 2541 } 2542 } 2543 2544 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2545 SelectionDAG &DAG) const { 2546 DEBUG(dbgs() << "Custom lowering: "); 2547 DEBUG(Op.dump()); 2548 2549 switch (Op.getOpcode()) { 2550 default: 2551 llvm_unreachable("unimplemented operand"); 2552 return SDValue(); 2553 case ISD::BITCAST: 2554 return LowerBITCAST(Op, DAG); 2555 case ISD::GlobalAddress: 2556 return LowerGlobalAddress(Op, DAG); 2557 case ISD::GlobalTLSAddress: 2558 return LowerGlobalTLSAddress(Op, DAG); 2559 case ISD::SETCC: 2560 return LowerSETCC(Op, DAG); 2561 case ISD::BR_CC: 2562 return LowerBR_CC(Op, DAG); 2563 case ISD::SELECT: 2564 return LowerSELECT(Op, DAG); 2565 case ISD::SELECT_CC: 2566 return LowerSELECT_CC(Op, DAG); 2567 case ISD::JumpTable: 2568 return LowerJumpTable(Op, DAG); 2569 case ISD::ConstantPool: 2570 return LowerConstantPool(Op, DAG); 2571 case ISD::BlockAddress: 2572 return LowerBlockAddress(Op, DAG); 2573 case ISD::VASTART: 2574 return LowerVASTART(Op, DAG); 2575 case ISD::VACOPY: 2576 return LowerVACOPY(Op, DAG); 2577 case ISD::VAARG: 2578 return LowerVAARG(Op, DAG); 2579 case ISD::ADDC: 2580 case ISD::ADDE: 2581 case ISD::SUBC: 2582 case ISD::SUBE: 2583 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2584 case ISD::SADDO: 2585 case ISD::UADDO: 2586 case ISD::SSUBO: 2587 case ISD::USUBO: 2588 case ISD::SMULO: 2589 case ISD::UMULO: 2590 return LowerXALUO(Op, DAG); 2591 case ISD::FADD: 2592 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2593 case ISD::FSUB: 2594 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2595 case ISD::FMUL: 2596 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2597 case ISD::FDIV: 2598 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2599 case ISD::FP_ROUND: 2600 return LowerFP_ROUND(Op, DAG); 2601 case ISD::FP_EXTEND: 2602 return LowerFP_EXTEND(Op, DAG); 2603 case ISD::FRAMEADDR: 2604 return LowerFRAMEADDR(Op, DAG); 2605 case ISD::RETURNADDR: 2606 return LowerRETURNADDR(Op, DAG); 2607 case ISD::INSERT_VECTOR_ELT: 2608 return LowerINSERT_VECTOR_ELT(Op, DAG); 2609 case ISD::EXTRACT_VECTOR_ELT: 2610 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2611 case ISD::BUILD_VECTOR: 2612 return LowerBUILD_VECTOR(Op, DAG); 2613 case ISD::VECTOR_SHUFFLE: 2614 return LowerVECTOR_SHUFFLE(Op, DAG); 2615 case ISD::EXTRACT_SUBVECTOR: 2616 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2617 case ISD::SRA: 2618 case ISD::SRL: 2619 case ISD::SHL: 2620 return LowerVectorSRA_SRL_SHL(Op, DAG); 2621 case ISD::SHL_PARTS: 2622 return LowerShiftLeftParts(Op, DAG); 2623 case ISD::SRL_PARTS: 2624 case ISD::SRA_PARTS: 2625 return LowerShiftRightParts(Op, DAG); 2626 case ISD::CTPOP: 2627 return LowerCTPOP(Op, DAG); 2628 case ISD::FCOPYSIGN: 2629 return LowerFCOPYSIGN(Op, DAG); 2630 case ISD::AND: 2631 return LowerVectorAND(Op, DAG); 2632 case ISD::OR: 2633 return LowerVectorOR(Op, DAG); 2634 case ISD::XOR: 2635 return LowerXOR(Op, DAG); 2636 case ISD::PREFETCH: 2637 return LowerPREFETCH(Op, DAG); 2638 case ISD::SINT_TO_FP: 2639 case ISD::UINT_TO_FP: 2640 return LowerINT_TO_FP(Op, DAG); 2641 case ISD::FP_TO_SINT: 2642 case ISD::FP_TO_UINT: 2643 return LowerFP_TO_INT(Op, DAG); 2644 case ISD::FSINCOS: 2645 return LowerFSINCOS(Op, DAG); 2646 case ISD::MUL: 2647 return LowerMUL(Op, DAG); 2648 case ISD::INTRINSIC_WO_CHAIN: 2649 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2650 case ISD::VECREDUCE_ADD: 2651 case ISD::VECREDUCE_SMAX: 2652 case ISD::VECREDUCE_SMIN: 2653 case ISD::VECREDUCE_UMAX: 2654 case ISD::VECREDUCE_UMIN: 2655 case ISD::VECREDUCE_FMAX: 2656 case ISD::VECREDUCE_FMIN: 2657 return LowerVECREDUCE(Op, DAG); 2658 } 2659 } 2660 2661 //===----------------------------------------------------------------------===// 2662 // Calling Convention Implementation 2663 //===----------------------------------------------------------------------===// 2664 2665 #include "AArch64GenCallingConv.inc" 2666 2667 /// Selects the correct CCAssignFn for a given CallingConvention value. 2668 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2669 bool IsVarArg) const { 2670 switch (CC) { 2671 default: 2672 report_fatal_error("Unsupported calling convention."); 2673 case CallingConv::WebKit_JS: 2674 return CC_AArch64_WebKit_JS; 2675 case CallingConv::GHC: 2676 return CC_AArch64_GHC; 2677 case CallingConv::C: 2678 case CallingConv::Fast: 2679 case CallingConv::PreserveMost: 2680 case CallingConv::CXX_FAST_TLS: 2681 case CallingConv::Swift: 2682 if (Subtarget->isTargetWindows() && IsVarArg) 2683 return CC_AArch64_Win64_VarArg; 2684 if (!Subtarget->isTargetDarwin()) 2685 return CC_AArch64_AAPCS; 2686 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2687 case CallingConv::Win64: 2688 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 2689 } 2690 } 2691 2692 CCAssignFn * 2693 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 2694 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 2695 : RetCC_AArch64_AAPCS; 2696 } 2697 2698 SDValue AArch64TargetLowering::LowerFormalArguments( 2699 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2700 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2701 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2702 MachineFunction &MF = DAG.getMachineFunction(); 2703 MachineFrameInfo &MFI = MF.getFrameInfo(); 2704 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()); 2705 2706 // Assign locations to all of the incoming arguments. 2707 SmallVector<CCValAssign, 16> ArgLocs; 2708 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2709 *DAG.getContext()); 2710 2711 // At this point, Ins[].VT may already be promoted to i32. To correctly 2712 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2713 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2714 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2715 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2716 // LocVT. 2717 unsigned NumArgs = Ins.size(); 2718 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2719 unsigned CurArgIdx = 0; 2720 for (unsigned i = 0; i != NumArgs; ++i) { 2721 MVT ValVT = Ins[i].VT; 2722 if (Ins[i].isOrigArg()) { 2723 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2724 CurArgIdx = Ins[i].getOrigArgIndex(); 2725 2726 // Get type of the original argument. 2727 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2728 /*AllowUnknown*/ true); 2729 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2730 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2731 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2732 ValVT = MVT::i8; 2733 else if (ActualMVT == MVT::i16) 2734 ValVT = MVT::i16; 2735 } 2736 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2737 bool Res = 2738 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2739 assert(!Res && "Call operand has unhandled type"); 2740 (void)Res; 2741 } 2742 assert(ArgLocs.size() == Ins.size()); 2743 SmallVector<SDValue, 16> ArgValues; 2744 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2745 CCValAssign &VA = ArgLocs[i]; 2746 2747 if (Ins[i].Flags.isByVal()) { 2748 // Byval is used for HFAs in the PCS, but the system should work in a 2749 // non-compliant manner for larger structs. 2750 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2751 int Size = Ins[i].Flags.getByValSize(); 2752 unsigned NumRegs = (Size + 7) / 8; 2753 2754 // FIXME: This works on big-endian for composite byvals, which are the common 2755 // case. It should also work for fundamental types too. 2756 unsigned FrameIdx = 2757 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2758 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2759 InVals.push_back(FrameIdxN); 2760 2761 continue; 2762 } 2763 2764 if (VA.isRegLoc()) { 2765 // Arguments stored in registers. 2766 EVT RegVT = VA.getLocVT(); 2767 2768 SDValue ArgValue; 2769 const TargetRegisterClass *RC; 2770 2771 if (RegVT == MVT::i32) 2772 RC = &AArch64::GPR32RegClass; 2773 else if (RegVT == MVT::i64) 2774 RC = &AArch64::GPR64RegClass; 2775 else if (RegVT == MVT::f16) 2776 RC = &AArch64::FPR16RegClass; 2777 else if (RegVT == MVT::f32) 2778 RC = &AArch64::FPR32RegClass; 2779 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2780 RC = &AArch64::FPR64RegClass; 2781 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2782 RC = &AArch64::FPR128RegClass; 2783 else 2784 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2785 2786 // Transform the arguments in physical registers into virtual ones. 2787 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2788 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2789 2790 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2791 // to 64 bits. Insert an assert[sz]ext to capture this, then 2792 // truncate to the right size. 2793 switch (VA.getLocInfo()) { 2794 default: 2795 llvm_unreachable("Unknown loc info!"); 2796 case CCValAssign::Full: 2797 break; 2798 case CCValAssign::BCvt: 2799 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2800 break; 2801 case CCValAssign::AExt: 2802 case CCValAssign::SExt: 2803 case CCValAssign::ZExt: 2804 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2805 // nodes after our lowering. 2806 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2807 break; 2808 } 2809 2810 InVals.push_back(ArgValue); 2811 2812 } else { // VA.isRegLoc() 2813 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2814 unsigned ArgOffset = VA.getLocMemOffset(); 2815 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2816 2817 uint32_t BEAlign = 0; 2818 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2819 !Ins[i].Flags.isInConsecutiveRegs()) 2820 BEAlign = 8 - ArgSize; 2821 2822 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2823 2824 // Create load nodes to retrieve arguments from the stack. 2825 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2826 SDValue ArgValue; 2827 2828 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2829 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2830 MVT MemVT = VA.getValVT(); 2831 2832 switch (VA.getLocInfo()) { 2833 default: 2834 break; 2835 case CCValAssign::BCvt: 2836 MemVT = VA.getLocVT(); 2837 break; 2838 case CCValAssign::SExt: 2839 ExtType = ISD::SEXTLOAD; 2840 break; 2841 case CCValAssign::ZExt: 2842 ExtType = ISD::ZEXTLOAD; 2843 break; 2844 case CCValAssign::AExt: 2845 ExtType = ISD::EXTLOAD; 2846 break; 2847 } 2848 2849 ArgValue = DAG.getExtLoad( 2850 ExtType, DL, VA.getLocVT(), Chain, FIN, 2851 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2852 MemVT); 2853 2854 InVals.push_back(ArgValue); 2855 } 2856 } 2857 2858 // varargs 2859 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2860 if (isVarArg) { 2861 if (!Subtarget->isTargetDarwin() || IsWin64) { 2862 // The AAPCS variadic function ABI is identical to the non-variadic 2863 // one. As a result there may be more arguments in registers and we should 2864 // save them for future reference. 2865 // Win64 variadic functions also pass arguments in registers, but all float 2866 // arguments are passed in integer registers. 2867 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2868 } 2869 2870 // This will point to the next argument passed via stack. 2871 unsigned StackOffset = CCInfo.getNextStackOffset(); 2872 // We currently pass all varargs at 8-byte alignment. 2873 StackOffset = ((StackOffset + 7) & ~7); 2874 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 2875 } 2876 2877 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2878 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2879 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2880 // This is a non-standard ABI so by fiat I say we're allowed to make full 2881 // use of the stack area to be popped, which must be aligned to 16 bytes in 2882 // any case: 2883 StackArgSize = alignTo(StackArgSize, 16); 2884 2885 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2886 // a multiple of 16. 2887 FuncInfo->setArgumentStackToRestore(StackArgSize); 2888 2889 // This realignment carries over to the available bytes below. Our own 2890 // callers will guarantee the space is free by giving an aligned value to 2891 // CALLSEQ_START. 2892 } 2893 // Even if we're not expected to free up the space, it's useful to know how 2894 // much is there while considering tail calls (because we can reuse it). 2895 FuncInfo->setBytesInStackArgArea(StackArgSize); 2896 2897 return Chain; 2898 } 2899 2900 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2901 SelectionDAG &DAG, 2902 const SDLoc &DL, 2903 SDValue &Chain) const { 2904 MachineFunction &MF = DAG.getMachineFunction(); 2905 MachineFrameInfo &MFI = MF.getFrameInfo(); 2906 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2907 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2908 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()); 2909 2910 SmallVector<SDValue, 8> MemOps; 2911 2912 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2913 AArch64::X3, AArch64::X4, AArch64::X5, 2914 AArch64::X6, AArch64::X7 }; 2915 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2916 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2917 2918 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2919 int GPRIdx = 0; 2920 if (GPRSaveSize != 0) { 2921 if (IsWin64) { 2922 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 2923 if (GPRSaveSize & 15) 2924 // The extra size here, if triggered, will always be 8. 2925 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 2926 } else 2927 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 2928 2929 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2930 2931 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2932 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2933 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2934 SDValue Store = DAG.getStore( 2935 Val.getValue(1), DL, Val, FIN, 2936 IsWin64 2937 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 2938 GPRIdx, 2939 (i - FirstVariadicGPR) * 8) 2940 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 2941 MemOps.push_back(Store); 2942 FIN = 2943 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2944 } 2945 } 2946 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2947 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2948 2949 if (Subtarget->hasFPARMv8() && !IsWin64) { 2950 static const MCPhysReg FPRArgRegs[] = { 2951 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2952 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2953 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2954 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2955 2956 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2957 int FPRIdx = 0; 2958 if (FPRSaveSize != 0) { 2959 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 2960 2961 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2962 2963 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2964 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2965 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2966 2967 SDValue Store = DAG.getStore( 2968 Val.getValue(1), DL, Val, FIN, 2969 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 2970 MemOps.push_back(Store); 2971 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 2972 DAG.getConstant(16, DL, PtrVT)); 2973 } 2974 } 2975 FuncInfo->setVarArgsFPRIndex(FPRIdx); 2976 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 2977 } 2978 2979 if (!MemOps.empty()) { 2980 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2981 } 2982 } 2983 2984 /// LowerCallResult - Lower the result values of a call into the 2985 /// appropriate copies out of appropriate physical registers. 2986 SDValue AArch64TargetLowering::LowerCallResult( 2987 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2988 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2989 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2990 SDValue ThisVal) const { 2991 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 2992 ? RetCC_AArch64_WebKit_JS 2993 : RetCC_AArch64_AAPCS; 2994 // Assign locations to each value returned by this call. 2995 SmallVector<CCValAssign, 16> RVLocs; 2996 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2997 *DAG.getContext()); 2998 CCInfo.AnalyzeCallResult(Ins, RetCC); 2999 3000 // Copy all of the result registers out of their specified physreg. 3001 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3002 CCValAssign VA = RVLocs[i]; 3003 3004 // Pass 'this' value directly from the argument to return value, to avoid 3005 // reg unit interference 3006 if (i == 0 && isThisReturn) { 3007 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3008 "unexpected return calling convention register assignment"); 3009 InVals.push_back(ThisVal); 3010 continue; 3011 } 3012 3013 SDValue Val = 3014 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3015 Chain = Val.getValue(1); 3016 InFlag = Val.getValue(2); 3017 3018 switch (VA.getLocInfo()) { 3019 default: 3020 llvm_unreachable("Unknown loc info!"); 3021 case CCValAssign::Full: 3022 break; 3023 case CCValAssign::BCvt: 3024 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3025 break; 3026 } 3027 3028 InVals.push_back(Val); 3029 } 3030 3031 return Chain; 3032 } 3033 3034 /// Return true if the calling convention is one that we can guarantee TCO for. 3035 static bool canGuaranteeTCO(CallingConv::ID CC) { 3036 return CC == CallingConv::Fast; 3037 } 3038 3039 /// Return true if we might ever do TCO for calls with this calling convention. 3040 static bool mayTailCallThisCC(CallingConv::ID CC) { 3041 switch (CC) { 3042 case CallingConv::C: 3043 case CallingConv::PreserveMost: 3044 case CallingConv::Swift: 3045 return true; 3046 default: 3047 return canGuaranteeTCO(CC); 3048 } 3049 } 3050 3051 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3052 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3053 const SmallVectorImpl<ISD::OutputArg> &Outs, 3054 const SmallVectorImpl<SDValue> &OutVals, 3055 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3056 if (!mayTailCallThisCC(CalleeCC)) 3057 return false; 3058 3059 MachineFunction &MF = DAG.getMachineFunction(); 3060 const Function *CallerF = MF.getFunction(); 3061 CallingConv::ID CallerCC = CallerF->getCallingConv(); 3062 bool CCMatch = CallerCC == CalleeCC; 3063 3064 // Byval parameters hand the function a pointer directly into the stack area 3065 // we want to reuse during a tail call. Working around this *is* possible (see 3066 // X86) but less efficient and uglier in LowerCall. 3067 for (Function::const_arg_iterator i = CallerF->arg_begin(), 3068 e = CallerF->arg_end(); 3069 i != e; ++i) 3070 if (i->hasByValAttr()) 3071 return false; 3072 3073 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3074 return canGuaranteeTCO(CalleeCC) && CCMatch; 3075 3076 // Externally-defined functions with weak linkage should not be 3077 // tail-called on AArch64 when the OS does not support dynamic 3078 // pre-emption of symbols, as the AAELF spec requires normal calls 3079 // to undefined weak functions to be replaced with a NOP or jump to the 3080 // next instruction. The behaviour of branch instructions in this 3081 // situation (as used for tail calls) is implementation-defined, so we 3082 // cannot rely on the linker replacing the tail call with a return. 3083 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3084 const GlobalValue *GV = G->getGlobal(); 3085 const Triple &TT = getTargetMachine().getTargetTriple(); 3086 if (GV->hasExternalWeakLinkage() && 3087 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3088 return false; 3089 } 3090 3091 // Now we search for cases where we can use a tail call without changing the 3092 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3093 // concept. 3094 3095 // I want anyone implementing a new calling convention to think long and hard 3096 // about this assert. 3097 assert((!isVarArg || CalleeCC == CallingConv::C) && 3098 "Unexpected variadic calling convention"); 3099 3100 LLVMContext &C = *DAG.getContext(); 3101 if (isVarArg && !Outs.empty()) { 3102 // At least two cases here: if caller is fastcc then we can't have any 3103 // memory arguments (we'd be expected to clean up the stack afterwards). If 3104 // caller is C then we could potentially use its argument area. 3105 3106 // FIXME: for now we take the most conservative of these in both cases: 3107 // disallow all variadic memory operands. 3108 SmallVector<CCValAssign, 16> ArgLocs; 3109 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3110 3111 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3112 for (const CCValAssign &ArgLoc : ArgLocs) 3113 if (!ArgLoc.isRegLoc()) 3114 return false; 3115 } 3116 3117 // Check that the call results are passed in the same way. 3118 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3119 CCAssignFnForCall(CalleeCC, isVarArg), 3120 CCAssignFnForCall(CallerCC, isVarArg))) 3121 return false; 3122 // The callee has to preserve all registers the caller needs to preserve. 3123 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3124 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3125 if (!CCMatch) { 3126 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3127 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3128 return false; 3129 } 3130 3131 // Nothing more to check if the callee is taking no arguments 3132 if (Outs.empty()) 3133 return true; 3134 3135 SmallVector<CCValAssign, 16> ArgLocs; 3136 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3137 3138 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3139 3140 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3141 3142 // If the stack arguments for this call do not fit into our own save area then 3143 // the call cannot be made tail. 3144 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3145 return false; 3146 3147 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3148 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3149 return false; 3150 3151 return true; 3152 } 3153 3154 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3155 SelectionDAG &DAG, 3156 MachineFrameInfo &MFI, 3157 int ClobberedFI) const { 3158 SmallVector<SDValue, 8> ArgChains; 3159 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3160 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3161 3162 // Include the original chain at the beginning of the list. When this is 3163 // used by target LowerCall hooks, this helps legalize find the 3164 // CALLSEQ_BEGIN node. 3165 ArgChains.push_back(Chain); 3166 3167 // Add a chain value for each stack argument corresponding 3168 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 3169 UE = DAG.getEntryNode().getNode()->use_end(); 3170 U != UE; ++U) 3171 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3172 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3173 if (FI->getIndex() < 0) { 3174 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 3175 int64_t InLastByte = InFirstByte; 3176 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 3177 3178 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 3179 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 3180 ArgChains.push_back(SDValue(L, 1)); 3181 } 3182 3183 // Build a tokenfactor for all the chains. 3184 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3185 } 3186 3187 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 3188 bool TailCallOpt) const { 3189 return CallCC == CallingConv::Fast && TailCallOpt; 3190 } 3191 3192 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 3193 /// and add input and output parameter nodes. 3194 SDValue 3195 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 3196 SmallVectorImpl<SDValue> &InVals) const { 3197 SelectionDAG &DAG = CLI.DAG; 3198 SDLoc &DL = CLI.DL; 3199 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3200 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3201 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3202 SDValue Chain = CLI.Chain; 3203 SDValue Callee = CLI.Callee; 3204 bool &IsTailCall = CLI.IsTailCall; 3205 CallingConv::ID CallConv = CLI.CallConv; 3206 bool IsVarArg = CLI.IsVarArg; 3207 3208 MachineFunction &MF = DAG.getMachineFunction(); 3209 bool IsThisReturn = false; 3210 3211 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3212 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3213 bool IsSibCall = false; 3214 3215 if (IsTailCall) { 3216 // Check if it's really possible to do a tail call. 3217 IsTailCall = isEligibleForTailCallOptimization( 3218 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3219 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 3220 report_fatal_error("failed to perform tail call elimination on a call " 3221 "site marked musttail"); 3222 3223 // A sibling call is one where we're under the usual C ABI and not planning 3224 // to change that but can still do a tail call: 3225 if (!TailCallOpt && IsTailCall) 3226 IsSibCall = true; 3227 3228 if (IsTailCall) 3229 ++NumTailCalls; 3230 } 3231 3232 // Analyze operands of the call, assigning locations to each operand. 3233 SmallVector<CCValAssign, 16> ArgLocs; 3234 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3235 *DAG.getContext()); 3236 3237 if (IsVarArg) { 3238 // Handle fixed and variable vector arguments differently. 3239 // Variable vector arguments always go into memory. 3240 unsigned NumArgs = Outs.size(); 3241 3242 for (unsigned i = 0; i != NumArgs; ++i) { 3243 MVT ArgVT = Outs[i].VT; 3244 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3245 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3246 /*IsVarArg=*/ !Outs[i].IsFixed); 3247 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3248 assert(!Res && "Call operand has unhandled type"); 3249 (void)Res; 3250 } 3251 } else { 3252 // At this point, Outs[].VT may already be promoted to i32. To correctly 3253 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3254 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3255 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3256 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3257 // LocVT. 3258 unsigned NumArgs = Outs.size(); 3259 for (unsigned i = 0; i != NumArgs; ++i) { 3260 MVT ValVT = Outs[i].VT; 3261 // Get type of the original argument. 3262 EVT ActualVT = getValueType(DAG.getDataLayout(), 3263 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3264 /*AllowUnknown*/ true); 3265 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3266 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3267 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3268 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3269 ValVT = MVT::i8; 3270 else if (ActualMVT == MVT::i16) 3271 ValVT = MVT::i16; 3272 3273 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3274 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3275 assert(!Res && "Call operand has unhandled type"); 3276 (void)Res; 3277 } 3278 } 3279 3280 // Get a count of how many bytes are to be pushed on the stack. 3281 unsigned NumBytes = CCInfo.getNextStackOffset(); 3282 3283 if (IsSibCall) { 3284 // Since we're not changing the ABI to make this a tail call, the memory 3285 // operands are already available in the caller's incoming argument space. 3286 NumBytes = 0; 3287 } 3288 3289 // FPDiff is the byte offset of the call's argument area from the callee's. 3290 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3291 // by this amount for a tail call. In a sibling call it must be 0 because the 3292 // caller will deallocate the entire stack and the callee still expects its 3293 // arguments to begin at SP+0. Completely unused for non-tail calls. 3294 int FPDiff = 0; 3295 3296 if (IsTailCall && !IsSibCall) { 3297 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3298 3299 // Since callee will pop argument stack as a tail call, we must keep the 3300 // popped size 16-byte aligned. 3301 NumBytes = alignTo(NumBytes, 16); 3302 3303 // FPDiff will be negative if this tail call requires more space than we 3304 // would automatically have in our incoming argument space. Positive if we 3305 // can actually shrink the stack. 3306 FPDiff = NumReusableBytes - NumBytes; 3307 3308 // The stack pointer must be 16-byte aligned at all times it's used for a 3309 // memory operation, which in practice means at *all* times and in 3310 // particular across call boundaries. Therefore our own arguments started at 3311 // a 16-byte aligned SP and the delta applied for the tail call should 3312 // satisfy the same constraint. 3313 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3314 } 3315 3316 // Adjust the stack pointer for the new arguments... 3317 // These operations are automatically eliminated by the prolog/epilog pass 3318 if (!IsSibCall) 3319 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 3320 3321 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3322 getPointerTy(DAG.getDataLayout())); 3323 3324 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3325 SmallVector<SDValue, 8> MemOpChains; 3326 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3327 3328 // Walk the register/memloc assignments, inserting copies/loads. 3329 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3330 ++i, ++realArgIdx) { 3331 CCValAssign &VA = ArgLocs[i]; 3332 SDValue Arg = OutVals[realArgIdx]; 3333 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3334 3335 // Promote the value if needed. 3336 switch (VA.getLocInfo()) { 3337 default: 3338 llvm_unreachable("Unknown loc info!"); 3339 case CCValAssign::Full: 3340 break; 3341 case CCValAssign::SExt: 3342 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3343 break; 3344 case CCValAssign::ZExt: 3345 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3346 break; 3347 case CCValAssign::AExt: 3348 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3349 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3350 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3351 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3352 } 3353 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3354 break; 3355 case CCValAssign::BCvt: 3356 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3357 break; 3358 case CCValAssign::FPExt: 3359 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3360 break; 3361 } 3362 3363 if (VA.isRegLoc()) { 3364 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 3365 Outs[0].VT == MVT::i64) { 3366 assert(VA.getLocVT() == MVT::i64 && 3367 "unexpected calling convention register assignment"); 3368 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3369 "unexpected use of 'returned'"); 3370 IsThisReturn = true; 3371 } 3372 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3373 } else { 3374 assert(VA.isMemLoc()); 3375 3376 SDValue DstAddr; 3377 MachinePointerInfo DstInfo; 3378 3379 // FIXME: This works on big-endian for composite byvals, which are the 3380 // common case. It should also work for fundamental types too. 3381 uint32_t BEAlign = 0; 3382 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3383 : VA.getValVT().getSizeInBits(); 3384 OpSize = (OpSize + 7) / 8; 3385 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3386 !Flags.isInConsecutiveRegs()) { 3387 if (OpSize < 8) 3388 BEAlign = 8 - OpSize; 3389 } 3390 unsigned LocMemOffset = VA.getLocMemOffset(); 3391 int32_t Offset = LocMemOffset + BEAlign; 3392 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3393 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3394 3395 if (IsTailCall) { 3396 Offset = Offset + FPDiff; 3397 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 3398 3399 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3400 DstInfo = 3401 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3402 3403 // Make sure any stack arguments overlapping with where we're storing 3404 // are loaded before this eventual operation. Otherwise they'll be 3405 // clobbered. 3406 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3407 } else { 3408 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3409 3410 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3411 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3412 LocMemOffset); 3413 } 3414 3415 if (Outs[i].Flags.isByVal()) { 3416 SDValue SizeNode = 3417 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3418 SDValue Cpy = DAG.getMemcpy( 3419 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3420 /*isVol = */ false, /*AlwaysInline = */ false, 3421 /*isTailCall = */ false, 3422 DstInfo, MachinePointerInfo()); 3423 3424 MemOpChains.push_back(Cpy); 3425 } else { 3426 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3427 // promoted to a legal register type i32, we should truncate Arg back to 3428 // i1/i8/i16. 3429 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3430 VA.getValVT() == MVT::i16) 3431 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3432 3433 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 3434 MemOpChains.push_back(Store); 3435 } 3436 } 3437 } 3438 3439 if (!MemOpChains.empty()) 3440 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3441 3442 // Build a sequence of copy-to-reg nodes chained together with token chain 3443 // and flag operands which copy the outgoing args into the appropriate regs. 3444 SDValue InFlag; 3445 for (auto &RegToPass : RegsToPass) { 3446 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3447 RegToPass.second, InFlag); 3448 InFlag = Chain.getValue(1); 3449 } 3450 3451 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3452 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3453 // node so that legalize doesn't hack it. 3454 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3455 auto GV = G->getGlobal(); 3456 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) == 3457 AArch64II::MO_GOT) { 3458 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3459 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3460 } else { 3461 const GlobalValue *GV = G->getGlobal(); 3462 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3463 } 3464 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3465 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3466 Subtarget->isTargetMachO()) { 3467 const char *Sym = S->getSymbol(); 3468 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3469 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3470 } else { 3471 const char *Sym = S->getSymbol(); 3472 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3473 } 3474 } 3475 3476 // We don't usually want to end the call-sequence here because we would tidy 3477 // the frame up *after* the call, however in the ABI-changing tail-call case 3478 // we've carefully laid out the parameters so that when sp is reset they'll be 3479 // in the correct location. 3480 if (IsTailCall && !IsSibCall) { 3481 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3482 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3483 InFlag = Chain.getValue(1); 3484 } 3485 3486 std::vector<SDValue> Ops; 3487 Ops.push_back(Chain); 3488 Ops.push_back(Callee); 3489 3490 if (IsTailCall) { 3491 // Each tail call may have to adjust the stack by a different amount, so 3492 // this information must travel along with the operation for eventual 3493 // consumption by emitEpilogue. 3494 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3495 } 3496 3497 // Add argument registers to the end of the list so that they are known live 3498 // into the call. 3499 for (auto &RegToPass : RegsToPass) 3500 Ops.push_back(DAG.getRegister(RegToPass.first, 3501 RegToPass.second.getValueType())); 3502 3503 // Add a register mask operand representing the call-preserved registers. 3504 const uint32_t *Mask; 3505 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3506 if (IsThisReturn) { 3507 // For 'this' returns, use the X0-preserving mask if applicable 3508 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3509 if (!Mask) { 3510 IsThisReturn = false; 3511 Mask = TRI->getCallPreservedMask(MF, CallConv); 3512 } 3513 } else 3514 Mask = TRI->getCallPreservedMask(MF, CallConv); 3515 3516 assert(Mask && "Missing call preserved mask for calling convention"); 3517 Ops.push_back(DAG.getRegisterMask(Mask)); 3518 3519 if (InFlag.getNode()) 3520 Ops.push_back(InFlag); 3521 3522 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3523 3524 // If we're doing a tall call, use a TC_RETURN here rather than an 3525 // actual call instruction. 3526 if (IsTailCall) { 3527 MF.getFrameInfo().setHasTailCall(); 3528 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3529 } 3530 3531 // Returns a chain and a flag for retval copy to use. 3532 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3533 InFlag = Chain.getValue(1); 3534 3535 uint64_t CalleePopBytes = 3536 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3537 3538 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3539 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3540 InFlag, DL); 3541 if (!Ins.empty()) 3542 InFlag = Chain.getValue(1); 3543 3544 // Handle result values, copying them out of physregs into vregs that we 3545 // return. 3546 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3547 InVals, IsThisReturn, 3548 IsThisReturn ? OutVals[0] : SDValue()); 3549 } 3550 3551 bool AArch64TargetLowering::CanLowerReturn( 3552 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3553 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3554 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3555 ? RetCC_AArch64_WebKit_JS 3556 : RetCC_AArch64_AAPCS; 3557 SmallVector<CCValAssign, 16> RVLocs; 3558 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3559 return CCInfo.CheckReturn(Outs, RetCC); 3560 } 3561 3562 SDValue 3563 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3564 bool isVarArg, 3565 const SmallVectorImpl<ISD::OutputArg> &Outs, 3566 const SmallVectorImpl<SDValue> &OutVals, 3567 const SDLoc &DL, SelectionDAG &DAG) const { 3568 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3569 ? RetCC_AArch64_WebKit_JS 3570 : RetCC_AArch64_AAPCS; 3571 SmallVector<CCValAssign, 16> RVLocs; 3572 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3573 *DAG.getContext()); 3574 CCInfo.AnalyzeReturn(Outs, RetCC); 3575 3576 // Copy the result values into the output registers. 3577 SDValue Flag; 3578 SmallVector<SDValue, 4> RetOps(1, Chain); 3579 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3580 ++i, ++realRVLocIdx) { 3581 CCValAssign &VA = RVLocs[i]; 3582 assert(VA.isRegLoc() && "Can only return in registers!"); 3583 SDValue Arg = OutVals[realRVLocIdx]; 3584 3585 switch (VA.getLocInfo()) { 3586 default: 3587 llvm_unreachable("Unknown loc info!"); 3588 case CCValAssign::Full: 3589 if (Outs[i].ArgVT == MVT::i1) { 3590 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3591 // value. This is strictly redundant on Darwin (which uses "zeroext 3592 // i1"), but will be optimised out before ISel. 3593 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3594 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3595 } 3596 break; 3597 case CCValAssign::BCvt: 3598 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3599 break; 3600 } 3601 3602 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3603 Flag = Chain.getValue(1); 3604 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3605 } 3606 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3607 const MCPhysReg *I = 3608 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3609 if (I) { 3610 for (; *I; ++I) { 3611 if (AArch64::GPR64RegClass.contains(*I)) 3612 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3613 else if (AArch64::FPR64RegClass.contains(*I)) 3614 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3615 else 3616 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3617 } 3618 } 3619 3620 RetOps[0] = Chain; // Update chain. 3621 3622 // Add the flag if we have it. 3623 if (Flag.getNode()) 3624 RetOps.push_back(Flag); 3625 3626 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3627 } 3628 3629 //===----------------------------------------------------------------------===// 3630 // Other Lowering Code 3631 //===----------------------------------------------------------------------===// 3632 3633 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 3634 SelectionDAG &DAG, 3635 unsigned Flag) const { 3636 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag); 3637 } 3638 3639 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 3640 SelectionDAG &DAG, 3641 unsigned Flag) const { 3642 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 3643 } 3644 3645 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 3646 SelectionDAG &DAG, 3647 unsigned Flag) const { 3648 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 3649 N->getOffset(), Flag); 3650 } 3651 3652 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 3653 SelectionDAG &DAG, 3654 unsigned Flag) const { 3655 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 3656 } 3657 3658 // (loadGOT sym) 3659 template <class NodeTy> 3660 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const { 3661 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 3662 SDLoc DL(N); 3663 EVT Ty = getPointerTy(DAG.getDataLayout()); 3664 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT); 3665 // FIXME: Once remat is capable of dealing with instructions with register 3666 // operands, expand this into two nodes instead of using a wrapper node. 3667 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 3668 } 3669 3670 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 3671 template <class NodeTy> 3672 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG) 3673 const { 3674 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 3675 SDLoc DL(N); 3676 EVT Ty = getPointerTy(DAG.getDataLayout()); 3677 const unsigned char MO_NC = AArch64II::MO_NC; 3678 return DAG.getNode( 3679 AArch64ISD::WrapperLarge, DL, Ty, 3680 getTargetNode(N, Ty, DAG, AArch64II::MO_G3), 3681 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC), 3682 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC), 3683 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC)); 3684 } 3685 3686 // (addlow (adrp %hi(sym)) %lo(sym)) 3687 template <class NodeTy> 3688 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const { 3689 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 3690 SDLoc DL(N); 3691 EVT Ty = getPointerTy(DAG.getDataLayout()); 3692 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE); 3693 SDValue Lo = getTargetNode(N, Ty, DAG, 3694 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3695 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 3696 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 3697 } 3698 3699 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3700 SelectionDAG &DAG) const { 3701 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3702 const GlobalValue *GV = GN->getGlobal(); 3703 unsigned char OpFlags = 3704 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3705 3706 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3707 "unexpected offset in global node"); 3708 3709 // This also catches the large code model case for Darwin. 3710 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3711 return getGOT(GN, DAG); 3712 } 3713 3714 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3715 return getAddrLarge(GN, DAG); 3716 } else { 3717 return getAddr(GN, DAG); 3718 } 3719 } 3720 3721 /// \brief Convert a TLS address reference into the correct sequence of loads 3722 /// and calls to compute the variable's address (for Darwin, currently) and 3723 /// return an SDValue containing the final node. 3724 3725 /// Darwin only has one TLS scheme which must be capable of dealing with the 3726 /// fully general situation, in the worst case. This means: 3727 /// + "extern __thread" declaration. 3728 /// + Defined in a possibly unknown dynamic library. 3729 /// 3730 /// The general system is that each __thread variable has a [3 x i64] descriptor 3731 /// which contains information used by the runtime to calculate the address. The 3732 /// only part of this the compiler needs to know about is the first xword, which 3733 /// contains a function pointer that must be called with the address of the 3734 /// entire descriptor in "x0". 3735 /// 3736 /// Since this descriptor may be in a different unit, in general even the 3737 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3738 /// is: 3739 /// adrp x0, _var@TLVPPAGE 3740 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3741 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3742 /// ; the function pointer 3743 /// blr x1 ; Uses descriptor address in x0 3744 /// ; Address of _var is now in x0. 3745 /// 3746 /// If the address of _var's descriptor *is* known to the linker, then it can 3747 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3748 /// a slight efficiency gain. 3749 SDValue 3750 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3751 SelectionDAG &DAG) const { 3752 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3753 3754 SDLoc DL(Op); 3755 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3756 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3757 3758 SDValue TLVPAddr = 3759 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3760 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3761 3762 // The first entry in the descriptor is a function pointer that we must call 3763 // to obtain the address of the variable. 3764 SDValue Chain = DAG.getEntryNode(); 3765 SDValue FuncTLVGet = DAG.getLoad( 3766 MVT::i64, DL, Chain, DescAddr, 3767 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3768 /* Alignment = */ 8, 3769 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant | 3770 MachineMemOperand::MODereferenceable); 3771 Chain = FuncTLVGet.getValue(1); 3772 3773 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3774 MFI.setAdjustsStack(true); 3775 3776 // TLS calls preserve all registers except those that absolutely must be 3777 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3778 // silly). 3779 const uint32_t *Mask = 3780 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3781 3782 // Finally, we can make the call. This is just a degenerate version of a 3783 // normal AArch64 call node: x0 takes the address of the descriptor, and 3784 // returns the address of the variable in this thread. 3785 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3786 Chain = 3787 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3788 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3789 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3790 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3791 } 3792 3793 /// When accessing thread-local variables under either the general-dynamic or 3794 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3795 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3796 /// is a function pointer to carry out the resolution. 3797 /// 3798 /// The sequence is: 3799 /// adrp x0, :tlsdesc:var 3800 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3801 /// add x0, x0, #:tlsdesc_lo12:var 3802 /// .tlsdesccall var 3803 /// blr x1 3804 /// (TPIDR_EL0 offset now in x0) 3805 /// 3806 /// The above sequence must be produced unscheduled, to enable the linker to 3807 /// optimize/relax this sequence. 3808 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3809 /// above sequence, and expanded really late in the compilation flow, to ensure 3810 /// the sequence is produced as per above. 3811 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 3812 const SDLoc &DL, 3813 SelectionDAG &DAG) const { 3814 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3815 3816 SDValue Chain = DAG.getEntryNode(); 3817 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3818 3819 Chain = 3820 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 3821 SDValue Glue = Chain.getValue(1); 3822 3823 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3824 } 3825 3826 SDValue 3827 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3828 SelectionDAG &DAG) const { 3829 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3830 assert(Subtarget->useSmallAddressing() && 3831 "ELF TLS only supported in small memory model"); 3832 // Different choices can be made for the maximum size of the TLS area for a 3833 // module. For the small address model, the default TLS size is 16MiB and the 3834 // maximum TLS size is 4GiB. 3835 // FIXME: add -mtls-size command line option and make it control the 16MiB 3836 // vs. 4GiB code sequence generation. 3837 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3838 3839 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3840 3841 if (DAG.getTarget().Options.EmulatedTLS) 3842 return LowerToTLSEmulatedModel(GA, DAG); 3843 3844 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3845 if (Model == TLSModel::LocalDynamic) 3846 Model = TLSModel::GeneralDynamic; 3847 } 3848 3849 SDValue TPOff; 3850 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3851 SDLoc DL(Op); 3852 const GlobalValue *GV = GA->getGlobal(); 3853 3854 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3855 3856 if (Model == TLSModel::LocalExec) { 3857 SDValue HiVar = DAG.getTargetGlobalAddress( 3858 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3859 SDValue LoVar = DAG.getTargetGlobalAddress( 3860 GV, DL, PtrVT, 0, 3861 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3862 3863 SDValue TPWithOff_lo = 3864 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3865 HiVar, 3866 DAG.getTargetConstant(0, DL, MVT::i32)), 3867 0); 3868 SDValue TPWithOff = 3869 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3870 LoVar, 3871 DAG.getTargetConstant(0, DL, MVT::i32)), 3872 0); 3873 return TPWithOff; 3874 } else if (Model == TLSModel::InitialExec) { 3875 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3876 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3877 } else if (Model == TLSModel::LocalDynamic) { 3878 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3879 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3880 // the beginning of the module's TLS region, followed by a DTPREL offset 3881 // calculation. 3882 3883 // These accesses will need deduplicating if there's more than one. 3884 AArch64FunctionInfo *MFI = 3885 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3886 MFI->incNumLocalDynamicTLSAccesses(); 3887 3888 // The call needs a relocation too for linker relaxation. It doesn't make 3889 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3890 // the address. 3891 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3892 AArch64II::MO_TLS); 3893 3894 // Now we can calculate the offset from TPIDR_EL0 to this module's 3895 // thread-local area. 3896 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3897 3898 // Now use :dtprel_whatever: operations to calculate this variable's offset 3899 // in its thread-storage area. 3900 SDValue HiVar = DAG.getTargetGlobalAddress( 3901 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3902 SDValue LoVar = DAG.getTargetGlobalAddress( 3903 GV, DL, MVT::i64, 0, 3904 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3905 3906 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3907 DAG.getTargetConstant(0, DL, MVT::i32)), 3908 0); 3909 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3910 DAG.getTargetConstant(0, DL, MVT::i32)), 3911 0); 3912 } else if (Model == TLSModel::GeneralDynamic) { 3913 // The call needs a relocation too for linker relaxation. It doesn't make 3914 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3915 // the address. 3916 SDValue SymAddr = 3917 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3918 3919 // Finally we can make a call to calculate the offset from tpidr_el0. 3920 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3921 } else 3922 llvm_unreachable("Unsupported ELF TLS access model"); 3923 3924 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3925 } 3926 3927 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3928 SelectionDAG &DAG) const { 3929 if (Subtarget->isTargetDarwin()) 3930 return LowerDarwinGlobalTLSAddress(Op, DAG); 3931 if (Subtarget->isTargetELF()) 3932 return LowerELFGlobalTLSAddress(Op, DAG); 3933 3934 llvm_unreachable("Unexpected platform trying to use TLS"); 3935 } 3936 3937 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3938 SDValue Chain = Op.getOperand(0); 3939 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3940 SDValue LHS = Op.getOperand(2); 3941 SDValue RHS = Op.getOperand(3); 3942 SDValue Dest = Op.getOperand(4); 3943 SDLoc dl(Op); 3944 3945 // Handle f128 first, since lowering it will result in comparing the return 3946 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3947 // is expecting to deal with. 3948 if (LHS.getValueType() == MVT::f128) { 3949 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3950 3951 // If softenSetCCOperands returned a scalar, we need to compare the result 3952 // against zero to select between true and false values. 3953 if (!RHS.getNode()) { 3954 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3955 CC = ISD::SETNE; 3956 } 3957 } 3958 3959 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 3960 // instruction. 3961 unsigned Opc = LHS.getOpcode(); 3962 if (LHS.getResNo() == 1 && isOneConstant(RHS) && 3963 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3964 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 3965 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 3966 "Unexpected condition code."); 3967 // Only lower legal XALUO ops. 3968 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 3969 return SDValue(); 3970 3971 // The actual operation with overflow check. 3972 AArch64CC::CondCode OFCC; 3973 SDValue Value, Overflow; 3974 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 3975 3976 if (CC == ISD::SETNE) 3977 OFCC = getInvertedCondCode(OFCC); 3978 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 3979 3980 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3981 Overflow); 3982 } 3983 3984 if (LHS.getValueType().isInteger()) { 3985 assert((LHS.getValueType() == RHS.getValueType()) && 3986 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3987 3988 // If the RHS of the comparison is zero, we can potentially fold this 3989 // to a specialized branch. 3990 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 3991 if (RHSC && RHSC->getZExtValue() == 0) { 3992 if (CC == ISD::SETEQ) { 3993 // See if we can use a TBZ to fold in an AND as well. 3994 // TBZ has a smaller branch displacement than CBZ. If the offset is 3995 // out of bounds, a late MI-layer pass rewrites branches. 3996 // 403.gcc is an example that hits this case. 3997 if (LHS.getOpcode() == ISD::AND && 3998 isa<ConstantSDNode>(LHS.getOperand(1)) && 3999 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4000 SDValue Test = LHS.getOperand(0); 4001 uint64_t Mask = LHS.getConstantOperandVal(1); 4002 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 4003 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4004 Dest); 4005 } 4006 4007 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 4008 } else if (CC == ISD::SETNE) { 4009 // See if we can use a TBZ to fold in an AND as well. 4010 // TBZ has a smaller branch displacement than CBZ. If the offset is 4011 // out of bounds, a late MI-layer pass rewrites branches. 4012 // 403.gcc is an example that hits this case. 4013 if (LHS.getOpcode() == ISD::AND && 4014 isa<ConstantSDNode>(LHS.getOperand(1)) && 4015 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4016 SDValue Test = LHS.getOperand(0); 4017 uint64_t Mask = LHS.getConstantOperandVal(1); 4018 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 4019 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4020 Dest); 4021 } 4022 4023 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 4024 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 4025 // Don't combine AND since emitComparison converts the AND to an ANDS 4026 // (a.k.a. TST) and the test in the test bit and branch instruction 4027 // becomes redundant. This would also increase register pressure. 4028 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4029 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 4030 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4031 } 4032 } 4033 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 4034 LHS.getOpcode() != ISD::AND) { 4035 // Don't combine AND since emitComparison converts the AND to an ANDS 4036 // (a.k.a. TST) and the test in the test bit and branch instruction 4037 // becomes redundant. This would also increase register pressure. 4038 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4039 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 4040 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4041 } 4042 4043 SDValue CCVal; 4044 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4045 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4046 Cmp); 4047 } 4048 4049 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4050 LHS.getValueType() == MVT::f64); 4051 4052 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4053 // clean. Some of them require two branches to implement. 4054 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4055 AArch64CC::CondCode CC1, CC2; 4056 changeFPCCToAArch64CC(CC, CC1, CC2); 4057 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4058 SDValue BR1 = 4059 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 4060 if (CC2 != AArch64CC::AL) { 4061 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4062 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 4063 Cmp); 4064 } 4065 4066 return BR1; 4067 } 4068 4069 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 4070 SelectionDAG &DAG) const { 4071 EVT VT = Op.getValueType(); 4072 SDLoc DL(Op); 4073 4074 SDValue In1 = Op.getOperand(0); 4075 SDValue In2 = Op.getOperand(1); 4076 EVT SrcVT = In2.getValueType(); 4077 4078 if (SrcVT.bitsLT(VT)) 4079 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 4080 else if (SrcVT.bitsGT(VT)) 4081 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 4082 4083 EVT VecVT; 4084 uint64_t EltMask; 4085 SDValue VecVal1, VecVal2; 4086 4087 auto setVecVal = [&] (int Idx) { 4088 if (!VT.isVector()) { 4089 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4090 DAG.getUNDEF(VecVT), In1); 4091 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4092 DAG.getUNDEF(VecVT), In2); 4093 } else { 4094 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 4095 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 4096 } 4097 }; 4098 4099 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 4100 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 4101 EltMask = 0x80000000ULL; 4102 setVecVal(AArch64::ssub); 4103 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 4104 VecVT = MVT::v2i64; 4105 4106 // We want to materialize a mask with the high bit set, but the AdvSIMD 4107 // immediate moves cannot materialize that in a single instruction for 4108 // 64-bit elements. Instead, materialize zero and then negate it. 4109 EltMask = 0; 4110 4111 setVecVal(AArch64::dsub); 4112 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 4113 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 4114 EltMask = 0x8000ULL; 4115 setVecVal(AArch64::hsub); 4116 } else { 4117 llvm_unreachable("Invalid type for copysign!"); 4118 } 4119 4120 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 4121 4122 // If we couldn't materialize the mask above, then the mask vector will be 4123 // the zero vector, and we need to negate it here. 4124 if (VT == MVT::f64 || VT == MVT::v2f64) { 4125 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 4126 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 4127 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 4128 } 4129 4130 SDValue Sel = 4131 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 4132 4133 if (VT == MVT::f16) 4134 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 4135 if (VT == MVT::f32) 4136 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 4137 else if (VT == MVT::f64) 4138 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 4139 else 4140 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 4141 } 4142 4143 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 4144 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 4145 Attribute::NoImplicitFloat)) 4146 return SDValue(); 4147 4148 if (!Subtarget->hasNEON()) 4149 return SDValue(); 4150 4151 // While there is no integer popcount instruction, it can 4152 // be more efficiently lowered to the following sequence that uses 4153 // AdvSIMD registers/instructions as long as the copies to/from 4154 // the AdvSIMD registers are cheap. 4155 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 4156 // CNT V0.8B, V0.8B // 8xbyte pop-counts 4157 // ADDV B0, V0.8B // sum 8xbyte pop-counts 4158 // UMOV X0, V0.B[0] // copy byte result back to integer reg 4159 SDValue Val = Op.getOperand(0); 4160 SDLoc DL(Op); 4161 EVT VT = Op.getValueType(); 4162 4163 if (VT == MVT::i32) 4164 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 4165 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 4166 4167 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 4168 SDValue UaddLV = DAG.getNode( 4169 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 4170 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 4171 4172 if (VT == MVT::i64) 4173 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 4174 return UaddLV; 4175 } 4176 4177 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 4178 4179 if (Op.getValueType().isVector()) 4180 return LowerVSETCC(Op, DAG); 4181 4182 SDValue LHS = Op.getOperand(0); 4183 SDValue RHS = Op.getOperand(1); 4184 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 4185 SDLoc dl(Op); 4186 4187 // We chose ZeroOrOneBooleanContents, so use zero and one. 4188 EVT VT = Op.getValueType(); 4189 SDValue TVal = DAG.getConstant(1, dl, VT); 4190 SDValue FVal = DAG.getConstant(0, dl, VT); 4191 4192 // Handle f128 first, since one possible outcome is a normal integer 4193 // comparison which gets picked up by the next if statement. 4194 if (LHS.getValueType() == MVT::f128) { 4195 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4196 4197 // If softenSetCCOperands returned a scalar, use it. 4198 if (!RHS.getNode()) { 4199 assert(LHS.getValueType() == Op.getValueType() && 4200 "Unexpected setcc expansion!"); 4201 return LHS; 4202 } 4203 } 4204 4205 if (LHS.getValueType().isInteger()) { 4206 SDValue CCVal; 4207 SDValue Cmp = 4208 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 4209 4210 // Note that we inverted the condition above, so we reverse the order of 4211 // the true and false operands here. This will allow the setcc to be 4212 // matched to a single CSINC instruction. 4213 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 4214 } 4215 4216 // Now we know we're dealing with FP values. 4217 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4218 LHS.getValueType() == MVT::f64); 4219 4220 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 4221 // and do the comparison. 4222 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4223 4224 AArch64CC::CondCode CC1, CC2; 4225 changeFPCCToAArch64CC(CC, CC1, CC2); 4226 if (CC2 == AArch64CC::AL) { 4227 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 4228 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4229 4230 // Note that we inverted the condition above, so we reverse the order of 4231 // the true and false operands here. This will allow the setcc to be 4232 // matched to a single CSINC instruction. 4233 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 4234 } else { 4235 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 4236 // totally clean. Some of them require two CSELs to implement. As is in 4237 // this case, we emit the first CSEL and then emit a second using the output 4238 // of the first as the RHS. We're effectively OR'ing the two CC's together. 4239 4240 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 4241 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4242 SDValue CS1 = 4243 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4244 4245 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4246 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4247 } 4248 } 4249 4250 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 4251 SDValue RHS, SDValue TVal, 4252 SDValue FVal, const SDLoc &dl, 4253 SelectionDAG &DAG) const { 4254 // Handle f128 first, because it will result in a comparison of some RTLIB 4255 // call result against zero. 4256 if (LHS.getValueType() == MVT::f128) { 4257 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4258 4259 // If softenSetCCOperands returned a scalar, we need to compare the result 4260 // against zero to select between true and false values. 4261 if (!RHS.getNode()) { 4262 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4263 CC = ISD::SETNE; 4264 } 4265 } 4266 4267 // Also handle f16, for which we need to do a f32 comparison. 4268 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 4269 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 4270 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 4271 } 4272 4273 // Next, handle integers. 4274 if (LHS.getValueType().isInteger()) { 4275 assert((LHS.getValueType() == RHS.getValueType()) && 4276 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4277 4278 unsigned Opcode = AArch64ISD::CSEL; 4279 4280 // If both the TVal and the FVal are constants, see if we can swap them in 4281 // order to for a CSINV or CSINC out of them. 4282 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4283 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4284 4285 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4286 std::swap(TVal, FVal); 4287 std::swap(CTVal, CFVal); 4288 CC = ISD::getSetCCInverse(CC, true); 4289 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4290 std::swap(TVal, FVal); 4291 std::swap(CTVal, CFVal); 4292 CC = ISD::getSetCCInverse(CC, true); 4293 } else if (TVal.getOpcode() == ISD::XOR) { 4294 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4295 // with a CSINV rather than a CSEL. 4296 if (isAllOnesConstant(TVal.getOperand(1))) { 4297 std::swap(TVal, FVal); 4298 std::swap(CTVal, CFVal); 4299 CC = ISD::getSetCCInverse(CC, true); 4300 } 4301 } else if (TVal.getOpcode() == ISD::SUB) { 4302 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4303 // that we can match with a CSNEG rather than a CSEL. 4304 if (isNullConstant(TVal.getOperand(0))) { 4305 std::swap(TVal, FVal); 4306 std::swap(CTVal, CFVal); 4307 CC = ISD::getSetCCInverse(CC, true); 4308 } 4309 } else if (CTVal && CFVal) { 4310 const int64_t TrueVal = CTVal->getSExtValue(); 4311 const int64_t FalseVal = CFVal->getSExtValue(); 4312 bool Swap = false; 4313 4314 // If both TVal and FVal are constants, see if FVal is the 4315 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4316 // instead of a CSEL in that case. 4317 if (TrueVal == ~FalseVal) { 4318 Opcode = AArch64ISD::CSINV; 4319 } else if (TrueVal == -FalseVal) { 4320 Opcode = AArch64ISD::CSNEG; 4321 } else if (TVal.getValueType() == MVT::i32) { 4322 // If our operands are only 32-bit wide, make sure we use 32-bit 4323 // arithmetic for the check whether we can use CSINC. This ensures that 4324 // the addition in the check will wrap around properly in case there is 4325 // an overflow (which would not be the case if we do the check with 4326 // 64-bit arithmetic). 4327 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4328 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4329 4330 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4331 Opcode = AArch64ISD::CSINC; 4332 4333 if (TrueVal32 > FalseVal32) { 4334 Swap = true; 4335 } 4336 } 4337 // 64-bit check whether we can use CSINC. 4338 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4339 Opcode = AArch64ISD::CSINC; 4340 4341 if (TrueVal > FalseVal) { 4342 Swap = true; 4343 } 4344 } 4345 4346 // Swap TVal and FVal if necessary. 4347 if (Swap) { 4348 std::swap(TVal, FVal); 4349 std::swap(CTVal, CFVal); 4350 CC = ISD::getSetCCInverse(CC, true); 4351 } 4352 4353 if (Opcode != AArch64ISD::CSEL) { 4354 // Drop FVal since we can get its value by simply inverting/negating 4355 // TVal. 4356 FVal = TVal; 4357 } 4358 } 4359 4360 // Avoid materializing a constant when possible by reusing a known value in 4361 // a register. However, don't perform this optimization if the known value 4362 // is one, zero or negative one in the case of a CSEL. We can always 4363 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 4364 // FVal, respectively. 4365 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 4366 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 4367 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 4368 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4369 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 4370 // "a != C ? x : a" to avoid materializing C. 4371 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 4372 TVal = LHS; 4373 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 4374 FVal = LHS; 4375 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 4376 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 4377 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 4378 // avoid materializing C. 4379 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4380 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 4381 Opcode = AArch64ISD::CSINV; 4382 TVal = LHS; 4383 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 4384 } 4385 } 4386 4387 SDValue CCVal; 4388 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4389 EVT VT = TVal.getValueType(); 4390 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4391 } 4392 4393 // Now we know we're dealing with FP values. 4394 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4395 LHS.getValueType() == MVT::f64); 4396 assert(LHS.getValueType() == RHS.getValueType()); 4397 EVT VT = TVal.getValueType(); 4398 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4399 4400 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4401 // clean. Some of them require two CSELs to implement. 4402 AArch64CC::CondCode CC1, CC2; 4403 changeFPCCToAArch64CC(CC, CC1, CC2); 4404 4405 if (DAG.getTarget().Options.UnsafeFPMath) { 4406 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 4407 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 4408 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 4409 if (RHSVal && RHSVal->isZero()) { 4410 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 4411 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 4412 4413 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 4414 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 4415 TVal = LHS; 4416 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 4417 CFVal && CFVal->isZero() && 4418 FVal.getValueType() == LHS.getValueType()) 4419 FVal = LHS; 4420 } 4421 } 4422 4423 // Emit first, and possibly only, CSEL. 4424 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4425 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4426 4427 // If we need a second CSEL, emit it, using the output of the first as the 4428 // RHS. We're effectively OR'ing the two CC's together. 4429 if (CC2 != AArch64CC::AL) { 4430 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4431 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4432 } 4433 4434 // Otherwise, return the output of the first CSEL. 4435 return CS1; 4436 } 4437 4438 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4439 SelectionDAG &DAG) const { 4440 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4441 SDValue LHS = Op.getOperand(0); 4442 SDValue RHS = Op.getOperand(1); 4443 SDValue TVal = Op.getOperand(2); 4444 SDValue FVal = Op.getOperand(3); 4445 SDLoc DL(Op); 4446 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4447 } 4448 4449 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4450 SelectionDAG &DAG) const { 4451 SDValue CCVal = Op->getOperand(0); 4452 SDValue TVal = Op->getOperand(1); 4453 SDValue FVal = Op->getOperand(2); 4454 SDLoc DL(Op); 4455 4456 unsigned Opc = CCVal.getOpcode(); 4457 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4458 // instruction. 4459 if (CCVal.getResNo() == 1 && 4460 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4461 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4462 // Only lower legal XALUO ops. 4463 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4464 return SDValue(); 4465 4466 AArch64CC::CondCode OFCC; 4467 SDValue Value, Overflow; 4468 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4469 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4470 4471 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4472 CCVal, Overflow); 4473 } 4474 4475 // Lower it the same way as we would lower a SELECT_CC node. 4476 ISD::CondCode CC; 4477 SDValue LHS, RHS; 4478 if (CCVal.getOpcode() == ISD::SETCC) { 4479 LHS = CCVal.getOperand(0); 4480 RHS = CCVal.getOperand(1); 4481 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4482 } else { 4483 LHS = CCVal; 4484 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4485 CC = ISD::SETNE; 4486 } 4487 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4488 } 4489 4490 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4491 SelectionDAG &DAG) const { 4492 // Jump table entries as PC relative offsets. No additional tweaking 4493 // is necessary here. Just get the address of the jump table. 4494 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4495 4496 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4497 !Subtarget->isTargetMachO()) { 4498 return getAddrLarge(JT, DAG); 4499 } 4500 return getAddr(JT, DAG); 4501 } 4502 4503 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4504 SelectionDAG &DAG) const { 4505 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4506 4507 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4508 // Use the GOT for the large code model on iOS. 4509 if (Subtarget->isTargetMachO()) { 4510 return getGOT(CP, DAG); 4511 } 4512 return getAddrLarge(CP, DAG); 4513 } else { 4514 return getAddr(CP, DAG); 4515 } 4516 } 4517 4518 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4519 SelectionDAG &DAG) const { 4520 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 4521 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4522 !Subtarget->isTargetMachO()) { 4523 return getAddrLarge(BA, DAG); 4524 } else { 4525 return getAddr(BA, DAG); 4526 } 4527 } 4528 4529 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4530 SelectionDAG &DAG) const { 4531 AArch64FunctionInfo *FuncInfo = 4532 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4533 4534 SDLoc DL(Op); 4535 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4536 getPointerTy(DAG.getDataLayout())); 4537 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4538 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4539 MachinePointerInfo(SV)); 4540 } 4541 4542 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 4543 SelectionDAG &DAG) const { 4544 AArch64FunctionInfo *FuncInfo = 4545 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4546 4547 SDLoc DL(Op); 4548 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 4549 ? FuncInfo->getVarArgsGPRIndex() 4550 : FuncInfo->getVarArgsStackIndex(), 4551 getPointerTy(DAG.getDataLayout())); 4552 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4553 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4554 MachinePointerInfo(SV)); 4555 } 4556 4557 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4558 SelectionDAG &DAG) const { 4559 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4560 // Standard, section B.3. 4561 MachineFunction &MF = DAG.getMachineFunction(); 4562 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4563 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4564 SDLoc DL(Op); 4565 4566 SDValue Chain = Op.getOperand(0); 4567 SDValue VAList = Op.getOperand(1); 4568 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4569 SmallVector<SDValue, 4> MemOps; 4570 4571 // void *__stack at offset 0 4572 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4573 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4574 MachinePointerInfo(SV), /* Alignment = */ 8)); 4575 4576 // void *__gr_top at offset 8 4577 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4578 if (GPRSize > 0) { 4579 SDValue GRTop, GRTopAddr; 4580 4581 GRTopAddr = 4582 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4583 4584 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4585 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4586 DAG.getConstant(GPRSize, DL, PtrVT)); 4587 4588 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4589 MachinePointerInfo(SV, 8), 4590 /* Alignment = */ 8)); 4591 } 4592 4593 // void *__vr_top at offset 16 4594 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4595 if (FPRSize > 0) { 4596 SDValue VRTop, VRTopAddr; 4597 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4598 DAG.getConstant(16, DL, PtrVT)); 4599 4600 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4601 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4602 DAG.getConstant(FPRSize, DL, PtrVT)); 4603 4604 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4605 MachinePointerInfo(SV, 16), 4606 /* Alignment = */ 8)); 4607 } 4608 4609 // int __gr_offs at offset 24 4610 SDValue GROffsAddr = 4611 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4612 MemOps.push_back(DAG.getStore( 4613 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 4614 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 4615 4616 // int __vr_offs at offset 28 4617 SDValue VROffsAddr = 4618 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4619 MemOps.push_back(DAG.getStore( 4620 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 4621 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 4622 4623 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4624 } 4625 4626 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4627 SelectionDAG &DAG) const { 4628 MachineFunction &MF = DAG.getMachineFunction(); 4629 4630 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) 4631 return LowerWin64_VASTART(Op, DAG); 4632 else if (Subtarget->isTargetDarwin()) 4633 return LowerDarwin_VASTART(Op, DAG); 4634 else 4635 return LowerAAPCS_VASTART(Op, DAG); 4636 } 4637 4638 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4639 SelectionDAG &DAG) const { 4640 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4641 // pointer. 4642 SDLoc DL(Op); 4643 unsigned VaListSize = 4644 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32; 4645 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4646 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4647 4648 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4649 Op.getOperand(2), 4650 DAG.getConstant(VaListSize, DL, MVT::i32), 4651 8, false, false, false, MachinePointerInfo(DestSV), 4652 MachinePointerInfo(SrcSV)); 4653 } 4654 4655 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4656 assert(Subtarget->isTargetDarwin() && 4657 "automatic va_arg instruction only works on Darwin"); 4658 4659 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4660 EVT VT = Op.getValueType(); 4661 SDLoc DL(Op); 4662 SDValue Chain = Op.getOperand(0); 4663 SDValue Addr = Op.getOperand(1); 4664 unsigned Align = Op.getConstantOperandVal(3); 4665 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4666 4667 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V)); 4668 Chain = VAList.getValue(1); 4669 4670 if (Align > 8) { 4671 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4672 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4673 DAG.getConstant(Align - 1, DL, PtrVT)); 4674 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4675 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4676 } 4677 4678 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4679 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4680 4681 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4682 // up to 64 bits. At the very least, we have to increase the striding of the 4683 // vaargs list to match this, and for FP values we need to introduce 4684 // FP_ROUND nodes as well. 4685 if (VT.isInteger() && !VT.isVector()) 4686 ArgSize = 8; 4687 bool NeedFPTrunc = false; 4688 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4689 ArgSize = 8; 4690 NeedFPTrunc = true; 4691 } 4692 4693 // Increment the pointer, VAList, to the next vaarg 4694 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4695 DAG.getConstant(ArgSize, DL, PtrVT)); 4696 // Store the incremented VAList to the legalized pointer 4697 SDValue APStore = 4698 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 4699 4700 // Load the actual argument out of the pointer VAList 4701 if (NeedFPTrunc) { 4702 // Load the value as an f64. 4703 SDValue WideFP = 4704 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 4705 // Round the value down to an f32. 4706 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4707 DAG.getIntPtrConstant(1, DL)); 4708 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4709 // Merge the rounded value with the chain output of the load. 4710 return DAG.getMergeValues(Ops, DL); 4711 } 4712 4713 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 4714 } 4715 4716 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4717 SelectionDAG &DAG) const { 4718 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4719 MFI.setFrameAddressIsTaken(true); 4720 4721 EVT VT = Op.getValueType(); 4722 SDLoc DL(Op); 4723 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4724 SDValue FrameAddr = 4725 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4726 while (Depth--) 4727 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4728 MachinePointerInfo()); 4729 return FrameAddr; 4730 } 4731 4732 // FIXME? Maybe this could be a TableGen attribute on some registers and 4733 // this table could be generated automatically from RegInfo. 4734 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4735 SelectionDAG &DAG) const { 4736 unsigned Reg = StringSwitch<unsigned>(RegName) 4737 .Case("sp", AArch64::SP) 4738 .Case("x18", AArch64::X18) 4739 .Case("w18", AArch64::W18) 4740 .Default(0); 4741 if ((Reg == AArch64::X18 || Reg == AArch64::W18) && 4742 !Subtarget->isX18Reserved()) 4743 Reg = 0; 4744 if (Reg) 4745 return Reg; 4746 report_fatal_error(Twine("Invalid register name \"" 4747 + StringRef(RegName) + "\".")); 4748 } 4749 4750 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4751 SelectionDAG &DAG) const { 4752 MachineFunction &MF = DAG.getMachineFunction(); 4753 MachineFrameInfo &MFI = MF.getFrameInfo(); 4754 MFI.setReturnAddressIsTaken(true); 4755 4756 EVT VT = Op.getValueType(); 4757 SDLoc DL(Op); 4758 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4759 if (Depth) { 4760 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4761 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4762 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4763 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4764 MachinePointerInfo()); 4765 } 4766 4767 // Return LR, which contains the return address. Mark it an implicit live-in. 4768 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4769 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4770 } 4771 4772 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4773 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4774 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4775 SelectionDAG &DAG) const { 4776 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4777 EVT VT = Op.getValueType(); 4778 unsigned VTBits = VT.getSizeInBits(); 4779 SDLoc dl(Op); 4780 SDValue ShOpLo = Op.getOperand(0); 4781 SDValue ShOpHi = Op.getOperand(1); 4782 SDValue ShAmt = Op.getOperand(2); 4783 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4784 4785 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4786 4787 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4788 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4789 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4790 4791 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4792 // is "undef". We wanted 0, so CSEL it directly. 4793 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4794 ISD::SETEQ, dl, DAG); 4795 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4796 HiBitsForLo = 4797 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4798 HiBitsForLo, CCVal, Cmp); 4799 4800 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4801 DAG.getConstant(VTBits, dl, MVT::i64)); 4802 4803 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4804 SDValue LoForNormalShift = 4805 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4806 4807 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4808 dl, DAG); 4809 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4810 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4811 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4812 LoForNormalShift, CCVal, Cmp); 4813 4814 // AArch64 shifts larger than the register width are wrapped rather than 4815 // clamped, so we can't just emit "hi >> x". 4816 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4817 SDValue HiForBigShift = 4818 Opc == ISD::SRA 4819 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4820 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4821 : DAG.getConstant(0, dl, VT); 4822 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4823 HiForNormalShift, CCVal, Cmp); 4824 4825 SDValue Ops[2] = { Lo, Hi }; 4826 return DAG.getMergeValues(Ops, dl); 4827 } 4828 4829 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4830 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4831 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4832 SelectionDAG &DAG) const { 4833 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4834 EVT VT = Op.getValueType(); 4835 unsigned VTBits = VT.getSizeInBits(); 4836 SDLoc dl(Op); 4837 SDValue ShOpLo = Op.getOperand(0); 4838 SDValue ShOpHi = Op.getOperand(1); 4839 SDValue ShAmt = Op.getOperand(2); 4840 4841 assert(Op.getOpcode() == ISD::SHL_PARTS); 4842 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4843 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4844 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4845 4846 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4847 // is "undef". We wanted 0, so CSEL it directly. 4848 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4849 ISD::SETEQ, dl, DAG); 4850 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4851 LoBitsForHi = 4852 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4853 LoBitsForHi, CCVal, Cmp); 4854 4855 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4856 DAG.getConstant(VTBits, dl, MVT::i64)); 4857 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4858 SDValue HiForNormalShift = 4859 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4860 4861 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4862 4863 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4864 dl, DAG); 4865 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4866 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4867 HiForNormalShift, CCVal, Cmp); 4868 4869 // AArch64 shifts of larger than register sizes are wrapped rather than 4870 // clamped, so we can't just emit "lo << a" if a is too big. 4871 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4872 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4873 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4874 LoForNormalShift, CCVal, Cmp); 4875 4876 SDValue Ops[2] = { Lo, Hi }; 4877 return DAG.getMergeValues(Ops, dl); 4878 } 4879 4880 bool AArch64TargetLowering::isOffsetFoldingLegal( 4881 const GlobalAddressSDNode *GA) const { 4882 DEBUG(dbgs() << "Skipping offset folding global address: "); 4883 DEBUG(GA->dump()); 4884 DEBUG(dbgs() << "AArch64 doesn't support folding offsets into global " 4885 "addresses\n"); 4886 return false; 4887 } 4888 4889 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4890 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4891 // FIXME: We should be able to handle f128 as well with a clever lowering. 4892 if (Imm.isPosZero() && (VT == MVT::f16 || VT == MVT::f64 || VT == MVT::f32)) { 4893 DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n"); 4894 return true; 4895 } 4896 4897 StringRef FPType; 4898 bool IsLegal = false; 4899 SmallString<128> ImmStrVal; 4900 Imm.toString(ImmStrVal); 4901 4902 if (VT == MVT::f64) { 4903 FPType = "f64"; 4904 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1; 4905 } else if (VT == MVT::f32) { 4906 FPType = "f32"; 4907 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1; 4908 } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) { 4909 FPType = "f16"; 4910 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1; 4911 } 4912 4913 if (IsLegal) { 4914 DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n"); 4915 return true; 4916 } 4917 4918 if (!FPType.empty()) 4919 DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n"); 4920 else 4921 DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n"); 4922 4923 return false; 4924 } 4925 4926 //===----------------------------------------------------------------------===// 4927 // AArch64 Optimization Hooks 4928 //===----------------------------------------------------------------------===// 4929 4930 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 4931 SDValue Operand, SelectionDAG &DAG, 4932 int &ExtraSteps) { 4933 EVT VT = Operand.getValueType(); 4934 if (ST->hasNEON() && 4935 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 4936 VT == MVT::f32 || VT == MVT::v1f32 || 4937 VT == MVT::v2f32 || VT == MVT::v4f32)) { 4938 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 4939 // For the reciprocal estimates, convergence is quadratic, so the number 4940 // of digits is doubled after each iteration. In ARMv8, the accuracy of 4941 // the initial estimate is 2^-8. Thus the number of extra steps to refine 4942 // the result for float (23 mantissa bits) is 2 and for double (52 4943 // mantissa bits) is 3. 4944 ExtraSteps = VT == MVT::f64 ? 3 : 2; 4945 4946 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 4947 } 4948 4949 return SDValue(); 4950 } 4951 4952 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 4953 SelectionDAG &DAG, int Enabled, 4954 int &ExtraSteps, 4955 bool &UseOneConst, 4956 bool Reciprocal) const { 4957 if (Enabled == ReciprocalEstimate::Enabled || 4958 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 4959 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 4960 DAG, ExtraSteps)) { 4961 SDLoc DL(Operand); 4962 EVT VT = Operand.getValueType(); 4963 4964 SDNodeFlags Flags; 4965 Flags.setUnsafeAlgebra(true); 4966 4967 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 4968 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 4969 for (int i = ExtraSteps; i > 0; --i) { 4970 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 4971 Flags); 4972 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 4973 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 4974 } 4975 4976 if (!Reciprocal) { 4977 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 4978 VT); 4979 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 4980 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 4981 4982 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 4983 // Correct the result if the operand is 0.0. 4984 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 4985 VT, Eq, Operand, Estimate); 4986 } 4987 4988 ExtraSteps = 0; 4989 return Estimate; 4990 } 4991 4992 return SDValue(); 4993 } 4994 4995 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 4996 SelectionDAG &DAG, int Enabled, 4997 int &ExtraSteps) const { 4998 if (Enabled == ReciprocalEstimate::Enabled) 4999 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 5000 DAG, ExtraSteps)) { 5001 SDLoc DL(Operand); 5002 EVT VT = Operand.getValueType(); 5003 5004 SDNodeFlags Flags; 5005 Flags.setUnsafeAlgebra(true); 5006 5007 // Newton reciprocal iteration: E * (2 - X * E) 5008 // AArch64 reciprocal iteration instruction: (2 - M * N) 5009 for (int i = ExtraSteps; i > 0; --i) { 5010 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 5011 Estimate, Flags); 5012 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5013 } 5014 5015 ExtraSteps = 0; 5016 return Estimate; 5017 } 5018 5019 return SDValue(); 5020 } 5021 5022 //===----------------------------------------------------------------------===// 5023 // AArch64 Inline Assembly Support 5024 //===----------------------------------------------------------------------===// 5025 5026 // Table of Constraints 5027 // TODO: This is the current set of constraints supported by ARM for the 5028 // compiler, not all of them may make sense, e.g. S may be difficult to support. 5029 // 5030 // r - A general register 5031 // w - An FP/SIMD register of some size in the range v0-v31 5032 // x - An FP/SIMD register of some size in the range v0-v15 5033 // I - Constant that can be used with an ADD instruction 5034 // J - Constant that can be used with a SUB instruction 5035 // K - Constant that can be used with a 32-bit logical instruction 5036 // L - Constant that can be used with a 64-bit logical instruction 5037 // M - Constant that can be used as a 32-bit MOV immediate 5038 // N - Constant that can be used as a 64-bit MOV immediate 5039 // Q - A memory reference with base register and no offset 5040 // S - A symbolic address 5041 // Y - Floating point constant zero 5042 // Z - Integer constant zero 5043 // 5044 // Note that general register operands will be output using their 64-bit x 5045 // register name, whatever the size of the variable, unless the asm operand 5046 // is prefixed by the %w modifier. Floating-point and SIMD register operands 5047 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 5048 // %q modifier. 5049 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5050 // At this point, we have to lower this constraint to something else, so we 5051 // lower it to an "r" or "w". However, by doing this we will force the result 5052 // to be in register, while the X constraint is much more permissive. 5053 // 5054 // Although we are correct (we are free to emit anything, without 5055 // constraints), we might break use cases that would expect us to be more 5056 // efficient and emit something else. 5057 if (!Subtarget->hasFPARMv8()) 5058 return "r"; 5059 5060 if (ConstraintVT.isFloatingPoint()) 5061 return "w"; 5062 5063 if (ConstraintVT.isVector() && 5064 (ConstraintVT.getSizeInBits() == 64 || 5065 ConstraintVT.getSizeInBits() == 128)) 5066 return "w"; 5067 5068 return "r"; 5069 } 5070 5071 /// getConstraintType - Given a constraint letter, return the type of 5072 /// constraint it is for this target. 5073 AArch64TargetLowering::ConstraintType 5074 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 5075 if (Constraint.size() == 1) { 5076 switch (Constraint[0]) { 5077 default: 5078 break; 5079 case 'z': 5080 return C_Other; 5081 case 'x': 5082 case 'w': 5083 return C_RegisterClass; 5084 // An address with a single base register. Due to the way we 5085 // currently handle addresses it is the same as 'r'. 5086 case 'Q': 5087 return C_Memory; 5088 } 5089 } 5090 return TargetLowering::getConstraintType(Constraint); 5091 } 5092 5093 /// Examine constraint type and operand type and determine a weight value. 5094 /// This object must already have been set up with the operand type 5095 /// and the current alternative constraint selected. 5096 TargetLowering::ConstraintWeight 5097 AArch64TargetLowering::getSingleConstraintMatchWeight( 5098 AsmOperandInfo &info, const char *constraint) const { 5099 ConstraintWeight weight = CW_Invalid; 5100 Value *CallOperandVal = info.CallOperandVal; 5101 // If we don't have a value, we can't do a match, 5102 // but allow it at the lowest weight. 5103 if (!CallOperandVal) 5104 return CW_Default; 5105 Type *type = CallOperandVal->getType(); 5106 // Look at the constraint type. 5107 switch (*constraint) { 5108 default: 5109 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 5110 break; 5111 case 'x': 5112 case 'w': 5113 if (type->isFloatingPointTy() || type->isVectorTy()) 5114 weight = CW_Register; 5115 break; 5116 case 'z': 5117 weight = CW_Constant; 5118 break; 5119 } 5120 return weight; 5121 } 5122 5123 std::pair<unsigned, const TargetRegisterClass *> 5124 AArch64TargetLowering::getRegForInlineAsmConstraint( 5125 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 5126 if (Constraint.size() == 1) { 5127 switch (Constraint[0]) { 5128 case 'r': 5129 if (VT.getSizeInBits() == 64) 5130 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 5131 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 5132 case 'w': 5133 if (VT.getSizeInBits() == 16) 5134 return std::make_pair(0U, &AArch64::FPR16RegClass); 5135 if (VT.getSizeInBits() == 32) 5136 return std::make_pair(0U, &AArch64::FPR32RegClass); 5137 if (VT.getSizeInBits() == 64) 5138 return std::make_pair(0U, &AArch64::FPR64RegClass); 5139 if (VT.getSizeInBits() == 128) 5140 return std::make_pair(0U, &AArch64::FPR128RegClass); 5141 break; 5142 // The instructions that this constraint is designed for can 5143 // only take 128-bit registers so just use that regclass. 5144 case 'x': 5145 if (VT.getSizeInBits() == 128) 5146 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 5147 break; 5148 } 5149 } 5150 if (StringRef("{cc}").equals_lower(Constraint)) 5151 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 5152 5153 // Use the default implementation in TargetLowering to convert the register 5154 // constraint into a member of a register class. 5155 std::pair<unsigned, const TargetRegisterClass *> Res; 5156 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 5157 5158 // Not found as a standard register? 5159 if (!Res.second) { 5160 unsigned Size = Constraint.size(); 5161 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 5162 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 5163 int RegNo; 5164 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 5165 if (!Failed && RegNo >= 0 && RegNo <= 31) { 5166 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 5167 // By default we'll emit v0-v31 for this unless there's a modifier where 5168 // we'll emit the correct register as well. 5169 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 5170 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 5171 Res.second = &AArch64::FPR64RegClass; 5172 } else { 5173 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 5174 Res.second = &AArch64::FPR128RegClass; 5175 } 5176 } 5177 } 5178 } 5179 5180 return Res; 5181 } 5182 5183 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 5184 /// vector. If it is invalid, don't add anything to Ops. 5185 void AArch64TargetLowering::LowerAsmOperandForConstraint( 5186 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 5187 SelectionDAG &DAG) const { 5188 SDValue Result; 5189 5190 // Currently only support length 1 constraints. 5191 if (Constraint.length() != 1) 5192 return; 5193 5194 char ConstraintLetter = Constraint[0]; 5195 switch (ConstraintLetter) { 5196 default: 5197 break; 5198 5199 // This set of constraints deal with valid constants for various instructions. 5200 // Validate and return a target constant for them if we can. 5201 case 'z': { 5202 // 'z' maps to xzr or wzr so it needs an input of 0. 5203 if (!isNullConstant(Op)) 5204 return; 5205 5206 if (Op.getValueType() == MVT::i64) 5207 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 5208 else 5209 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 5210 break; 5211 } 5212 5213 case 'I': 5214 case 'J': 5215 case 'K': 5216 case 'L': 5217 case 'M': 5218 case 'N': 5219 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 5220 if (!C) 5221 return; 5222 5223 // Grab the value and do some validation. 5224 uint64_t CVal = C->getZExtValue(); 5225 switch (ConstraintLetter) { 5226 // The I constraint applies only to simple ADD or SUB immediate operands: 5227 // i.e. 0 to 4095 with optional shift by 12 5228 // The J constraint applies only to ADD or SUB immediates that would be 5229 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 5230 // instruction [or vice versa], in other words -1 to -4095 with optional 5231 // left shift by 12. 5232 case 'I': 5233 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 5234 break; 5235 return; 5236 case 'J': { 5237 uint64_t NVal = -C->getSExtValue(); 5238 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 5239 CVal = C->getSExtValue(); 5240 break; 5241 } 5242 return; 5243 } 5244 // The K and L constraints apply *only* to logical immediates, including 5245 // what used to be the MOVI alias for ORR (though the MOVI alias has now 5246 // been removed and MOV should be used). So these constraints have to 5247 // distinguish between bit patterns that are valid 32-bit or 64-bit 5248 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 5249 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 5250 // versa. 5251 case 'K': 5252 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5253 break; 5254 return; 5255 case 'L': 5256 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5257 break; 5258 return; 5259 // The M and N constraints are a superset of K and L respectively, for use 5260 // with the MOV (immediate) alias. As well as the logical immediates they 5261 // also match 32 or 64-bit immediates that can be loaded either using a 5262 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 5263 // (M) or 64-bit 0x1234000000000000 (N) etc. 5264 // As a note some of this code is liberally stolen from the asm parser. 5265 case 'M': { 5266 if (!isUInt<32>(CVal)) 5267 return; 5268 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5269 break; 5270 if ((CVal & 0xFFFF) == CVal) 5271 break; 5272 if ((CVal & 0xFFFF0000ULL) == CVal) 5273 break; 5274 uint64_t NCVal = ~(uint32_t)CVal; 5275 if ((NCVal & 0xFFFFULL) == NCVal) 5276 break; 5277 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5278 break; 5279 return; 5280 } 5281 case 'N': { 5282 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5283 break; 5284 if ((CVal & 0xFFFFULL) == CVal) 5285 break; 5286 if ((CVal & 0xFFFF0000ULL) == CVal) 5287 break; 5288 if ((CVal & 0xFFFF00000000ULL) == CVal) 5289 break; 5290 if ((CVal & 0xFFFF000000000000ULL) == CVal) 5291 break; 5292 uint64_t NCVal = ~CVal; 5293 if ((NCVal & 0xFFFFULL) == NCVal) 5294 break; 5295 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5296 break; 5297 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 5298 break; 5299 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 5300 break; 5301 return; 5302 } 5303 default: 5304 return; 5305 } 5306 5307 // All assembler immediates are 64-bit integers. 5308 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 5309 break; 5310 } 5311 5312 if (Result.getNode()) { 5313 Ops.push_back(Result); 5314 return; 5315 } 5316 5317 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 5318 } 5319 5320 //===----------------------------------------------------------------------===// 5321 // AArch64 Advanced SIMD Support 5322 //===----------------------------------------------------------------------===// 5323 5324 /// WidenVector - Given a value in the V64 register class, produce the 5325 /// equivalent value in the V128 register class. 5326 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 5327 EVT VT = V64Reg.getValueType(); 5328 unsigned NarrowSize = VT.getVectorNumElements(); 5329 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5330 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 5331 SDLoc DL(V64Reg); 5332 5333 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 5334 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 5335 } 5336 5337 /// getExtFactor - Determine the adjustment factor for the position when 5338 /// generating an "extract from vector registers" instruction. 5339 static unsigned getExtFactor(SDValue &V) { 5340 EVT EltType = V.getValueType().getVectorElementType(); 5341 return EltType.getSizeInBits() / 8; 5342 } 5343 5344 /// NarrowVector - Given a value in the V128 register class, produce the 5345 /// equivalent value in the V64 register class. 5346 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 5347 EVT VT = V128Reg.getValueType(); 5348 unsigned WideSize = VT.getVectorNumElements(); 5349 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5350 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 5351 SDLoc DL(V128Reg); 5352 5353 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 5354 } 5355 5356 // Gather data to see if the operation can be modelled as a 5357 // shuffle in combination with VEXTs. 5358 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 5359 SelectionDAG &DAG) const { 5360 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5361 DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 5362 SDLoc dl(Op); 5363 EVT VT = Op.getValueType(); 5364 unsigned NumElts = VT.getVectorNumElements(); 5365 5366 struct ShuffleSourceInfo { 5367 SDValue Vec; 5368 unsigned MinElt; 5369 unsigned MaxElt; 5370 5371 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5372 // be compatible with the shuffle we intend to construct. As a result 5373 // ShuffleVec will be some sliding window into the original Vec. 5374 SDValue ShuffleVec; 5375 5376 // Code should guarantee that element i in Vec starts at element "WindowBase 5377 // + i * WindowScale in ShuffleVec". 5378 int WindowBase; 5379 int WindowScale; 5380 5381 ShuffleSourceInfo(SDValue Vec) 5382 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 5383 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 5384 5385 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5386 }; 5387 5388 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5389 // node. 5390 SmallVector<ShuffleSourceInfo, 2> Sources; 5391 for (unsigned i = 0; i < NumElts; ++i) { 5392 SDValue V = Op.getOperand(i); 5393 if (V.isUndef()) 5394 continue; 5395 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5396 !isa<ConstantSDNode>(V.getOperand(1))) { 5397 DEBUG(dbgs() << "Reshuffle failed: " 5398 "a shuffle can only come from building a vector from " 5399 "various elements of other vectors, provided their " 5400 "indices are constant\n"); 5401 return SDValue(); 5402 } 5403 5404 // Add this element source to the list if it's not already there. 5405 SDValue SourceVec = V.getOperand(0); 5406 auto Source = find(Sources, SourceVec); 5407 if (Source == Sources.end()) 5408 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5409 5410 // Update the minimum and maximum lane number seen. 5411 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5412 Source->MinElt = std::min(Source->MinElt, EltNo); 5413 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5414 } 5415 5416 if (Sources.size() > 2) { 5417 DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at " 5418 "most two source vectors are involved\n"); 5419 return SDValue(); 5420 } 5421 5422 // Find out the smallest element size among result and two sources, and use 5423 // it as element size to build the shuffle_vector. 5424 EVT SmallestEltTy = VT.getVectorElementType(); 5425 for (auto &Source : Sources) { 5426 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5427 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5428 SmallestEltTy = SrcEltTy; 5429 } 5430 } 5431 unsigned ResMultiplier = 5432 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 5433 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5434 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5435 5436 // If the source vector is too wide or too narrow, we may nevertheless be able 5437 // to construct a compatible shuffle either by concatenating it with UNDEF or 5438 // extracting a suitable range of elements. 5439 for (auto &Src : Sources) { 5440 EVT SrcVT = Src.ShuffleVec.getValueType(); 5441 5442 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5443 continue; 5444 5445 // This stage of the search produces a source with the same element type as 5446 // the original, but with a total width matching the BUILD_VECTOR output. 5447 EVT EltVT = SrcVT.getVectorElementType(); 5448 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5449 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5450 5451 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5452 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5453 // We can pad out the smaller vector for free, so if it's part of a 5454 // shuffle... 5455 Src.ShuffleVec = 5456 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5457 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5458 continue; 5459 } 5460 5461 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5462 5463 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5464 DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 5465 return SDValue(); 5466 } 5467 5468 if (Src.MinElt >= NumSrcElts) { 5469 // The extraction can just take the second half 5470 Src.ShuffleVec = 5471 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5472 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5473 Src.WindowBase = -NumSrcElts; 5474 } else if (Src.MaxElt < NumSrcElts) { 5475 // The extraction can just take the first half 5476 Src.ShuffleVec = 5477 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5478 DAG.getConstant(0, dl, MVT::i64)); 5479 } else { 5480 // An actual VEXT is needed 5481 SDValue VEXTSrc1 = 5482 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5483 DAG.getConstant(0, dl, MVT::i64)); 5484 SDValue VEXTSrc2 = 5485 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5486 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5487 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5488 5489 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5490 VEXTSrc2, 5491 DAG.getConstant(Imm, dl, MVT::i32)); 5492 Src.WindowBase = -Src.MinElt; 5493 } 5494 } 5495 5496 // Another possible incompatibility occurs from the vector element types. We 5497 // can fix this by bitcasting the source vectors to the same type we intend 5498 // for the shuffle. 5499 for (auto &Src : Sources) { 5500 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5501 if (SrcEltTy == SmallestEltTy) 5502 continue; 5503 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5504 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5505 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5506 Src.WindowBase *= Src.WindowScale; 5507 } 5508 5509 // Final sanity check before we try to actually produce a shuffle. 5510 DEBUG( 5511 for (auto Src : Sources) 5512 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5513 ); 5514 5515 // The stars all align, our next step is to produce the mask for the shuffle. 5516 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5517 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 5518 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5519 SDValue Entry = Op.getOperand(i); 5520 if (Entry.isUndef()) 5521 continue; 5522 5523 auto Src = find(Sources, Entry.getOperand(0)); 5524 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5525 5526 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5527 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5528 // segment. 5529 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5530 int BitsDefined = 5531 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 5532 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5533 5534 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5535 // starting at the appropriate offset. 5536 int *LaneMask = &Mask[i * ResMultiplier]; 5537 5538 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5539 ExtractBase += NumElts * (Src - Sources.begin()); 5540 for (int j = 0; j < LanesDefined; ++j) 5541 LaneMask[j] = ExtractBase + j; 5542 } 5543 5544 // Final check before we try to produce nonsense... 5545 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 5546 DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 5547 return SDValue(); 5548 } 5549 5550 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5551 for (unsigned i = 0; i < Sources.size(); ++i) 5552 ShuffleOps[i] = Sources[i].ShuffleVec; 5553 5554 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5555 ShuffleOps[1], Mask); 5556 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5557 5558 DEBUG( 5559 dbgs() << "Reshuffle, creating node: "; 5560 Shuffle.dump(); 5561 dbgs() << "Reshuffle, creating node: "; 5562 V.dump(); 5563 ); 5564 5565 return V; 5566 } 5567 5568 // check if an EXT instruction can handle the shuffle mask when the 5569 // vector sources of the shuffle are the same. 5570 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5571 unsigned NumElts = VT.getVectorNumElements(); 5572 5573 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5574 if (M[0] < 0) 5575 return false; 5576 5577 Imm = M[0]; 5578 5579 // If this is a VEXT shuffle, the immediate value is the index of the first 5580 // element. The other shuffle indices must be the successive elements after 5581 // the first one. 5582 unsigned ExpectedElt = Imm; 5583 for (unsigned i = 1; i < NumElts; ++i) { 5584 // Increment the expected index. If it wraps around, just follow it 5585 // back to index zero and keep going. 5586 ++ExpectedElt; 5587 if (ExpectedElt == NumElts) 5588 ExpectedElt = 0; 5589 5590 if (M[i] < 0) 5591 continue; // ignore UNDEF indices 5592 if (ExpectedElt != static_cast<unsigned>(M[i])) 5593 return false; 5594 } 5595 5596 return true; 5597 } 5598 5599 // check if an EXT instruction can handle the shuffle mask when the 5600 // vector sources of the shuffle are different. 5601 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5602 unsigned &Imm) { 5603 // Look for the first non-undef element. 5604 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 5605 5606 // Benefit form APInt to handle overflow when calculating expected element. 5607 unsigned NumElts = VT.getVectorNumElements(); 5608 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5609 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5610 // The following shuffle indices must be the successive elements after the 5611 // first real element. 5612 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5613 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5614 if (FirstWrongElt != M.end()) 5615 return false; 5616 5617 // The index of an EXT is the first element if it is not UNDEF. 5618 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5619 // value of the first element. E.g. 5620 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5621 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5622 // ExpectedElt is the last mask index plus 1. 5623 Imm = ExpectedElt.getZExtValue(); 5624 5625 // There are two difference cases requiring to reverse input vectors. 5626 // For example, for vector <4 x i32> we have the following cases, 5627 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5628 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5629 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5630 // to reverse two input vectors. 5631 if (Imm < NumElts) 5632 ReverseEXT = true; 5633 else 5634 Imm -= NumElts; 5635 5636 return true; 5637 } 5638 5639 /// isREVMask - Check if a vector shuffle corresponds to a REV 5640 /// instruction with the specified blocksize. (The order of the elements 5641 /// within each block of the vector is reversed.) 5642 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5643 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5644 "Only possible block sizes for REV are: 16, 32, 64"); 5645 5646 unsigned EltSz = VT.getScalarSizeInBits(); 5647 if (EltSz == 64) 5648 return false; 5649 5650 unsigned NumElts = VT.getVectorNumElements(); 5651 unsigned BlockElts = M[0] + 1; 5652 // If the first shuffle index is UNDEF, be optimistic. 5653 if (M[0] < 0) 5654 BlockElts = BlockSize / EltSz; 5655 5656 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5657 return false; 5658 5659 for (unsigned i = 0; i < NumElts; ++i) { 5660 if (M[i] < 0) 5661 continue; // ignore UNDEF indices 5662 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5663 return false; 5664 } 5665 5666 return true; 5667 } 5668 5669 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5670 unsigned NumElts = VT.getVectorNumElements(); 5671 WhichResult = (M[0] == 0 ? 0 : 1); 5672 unsigned Idx = WhichResult * NumElts / 2; 5673 for (unsigned i = 0; i != NumElts; i += 2) { 5674 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5675 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5676 return false; 5677 Idx += 1; 5678 } 5679 5680 return true; 5681 } 5682 5683 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5684 unsigned NumElts = VT.getVectorNumElements(); 5685 WhichResult = (M[0] == 0 ? 0 : 1); 5686 for (unsigned i = 0; i != NumElts; ++i) { 5687 if (M[i] < 0) 5688 continue; // ignore UNDEF indices 5689 if ((unsigned)M[i] != 2 * i + WhichResult) 5690 return false; 5691 } 5692 5693 return true; 5694 } 5695 5696 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5697 unsigned NumElts = VT.getVectorNumElements(); 5698 WhichResult = (M[0] == 0 ? 0 : 1); 5699 for (unsigned i = 0; i < NumElts; i += 2) { 5700 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5701 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5702 return false; 5703 } 5704 return true; 5705 } 5706 5707 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5708 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5709 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5710 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5711 unsigned NumElts = VT.getVectorNumElements(); 5712 WhichResult = (M[0] == 0 ? 0 : 1); 5713 unsigned Idx = WhichResult * NumElts / 2; 5714 for (unsigned i = 0; i != NumElts; i += 2) { 5715 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5716 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5717 return false; 5718 Idx += 1; 5719 } 5720 5721 return true; 5722 } 5723 5724 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5725 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5726 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5727 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5728 unsigned Half = VT.getVectorNumElements() / 2; 5729 WhichResult = (M[0] == 0 ? 0 : 1); 5730 for (unsigned j = 0; j != 2; ++j) { 5731 unsigned Idx = WhichResult; 5732 for (unsigned i = 0; i != Half; ++i) { 5733 int MIdx = M[i + j * Half]; 5734 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5735 return false; 5736 Idx += 2; 5737 } 5738 } 5739 5740 return true; 5741 } 5742 5743 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5744 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5745 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5746 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5747 unsigned NumElts = VT.getVectorNumElements(); 5748 WhichResult = (M[0] == 0 ? 0 : 1); 5749 for (unsigned i = 0; i < NumElts; i += 2) { 5750 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5751 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5752 return false; 5753 } 5754 return true; 5755 } 5756 5757 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5758 bool &DstIsLeft, int &Anomaly) { 5759 if (M.size() != static_cast<size_t>(NumInputElements)) 5760 return false; 5761 5762 int NumLHSMatch = 0, NumRHSMatch = 0; 5763 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5764 5765 for (int i = 0; i < NumInputElements; ++i) { 5766 if (M[i] == -1) { 5767 ++NumLHSMatch; 5768 ++NumRHSMatch; 5769 continue; 5770 } 5771 5772 if (M[i] == i) 5773 ++NumLHSMatch; 5774 else 5775 LastLHSMismatch = i; 5776 5777 if (M[i] == i + NumInputElements) 5778 ++NumRHSMatch; 5779 else 5780 LastRHSMismatch = i; 5781 } 5782 5783 if (NumLHSMatch == NumInputElements - 1) { 5784 DstIsLeft = true; 5785 Anomaly = LastLHSMismatch; 5786 return true; 5787 } else if (NumRHSMatch == NumInputElements - 1) { 5788 DstIsLeft = false; 5789 Anomaly = LastRHSMismatch; 5790 return true; 5791 } 5792 5793 return false; 5794 } 5795 5796 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5797 if (VT.getSizeInBits() != 128) 5798 return false; 5799 5800 unsigned NumElts = VT.getVectorNumElements(); 5801 5802 for (int I = 0, E = NumElts / 2; I != E; I++) { 5803 if (Mask[I] != I) 5804 return false; 5805 } 5806 5807 int Offset = NumElts / 2; 5808 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5809 if (Mask[I] != I + SplitLHS * Offset) 5810 return false; 5811 } 5812 5813 return true; 5814 } 5815 5816 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5817 SDLoc DL(Op); 5818 EVT VT = Op.getValueType(); 5819 SDValue V0 = Op.getOperand(0); 5820 SDValue V1 = Op.getOperand(1); 5821 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5822 5823 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5824 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5825 return SDValue(); 5826 5827 bool SplitV0 = V0.getValueSizeInBits() == 128; 5828 5829 if (!isConcatMask(Mask, VT, SplitV0)) 5830 return SDValue(); 5831 5832 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5833 VT.getVectorNumElements() / 2); 5834 if (SplitV0) { 5835 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5836 DAG.getConstant(0, DL, MVT::i64)); 5837 } 5838 if (V1.getValueSizeInBits() == 128) { 5839 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5840 DAG.getConstant(0, DL, MVT::i64)); 5841 } 5842 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5843 } 5844 5845 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5846 /// the specified operations to build the shuffle. 5847 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5848 SDValue RHS, SelectionDAG &DAG, 5849 const SDLoc &dl) { 5850 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5851 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5852 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5853 5854 enum { 5855 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5856 OP_VREV, 5857 OP_VDUP0, 5858 OP_VDUP1, 5859 OP_VDUP2, 5860 OP_VDUP3, 5861 OP_VEXT1, 5862 OP_VEXT2, 5863 OP_VEXT3, 5864 OP_VUZPL, // VUZP, left result 5865 OP_VUZPR, // VUZP, right result 5866 OP_VZIPL, // VZIP, left result 5867 OP_VZIPR, // VZIP, right result 5868 OP_VTRNL, // VTRN, left result 5869 OP_VTRNR // VTRN, right result 5870 }; 5871 5872 if (OpNum == OP_COPY) { 5873 if (LHSID == (1 * 9 + 2) * 9 + 3) 5874 return LHS; 5875 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5876 return RHS; 5877 } 5878 5879 SDValue OpLHS, OpRHS; 5880 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5881 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5882 EVT VT = OpLHS.getValueType(); 5883 5884 switch (OpNum) { 5885 default: 5886 llvm_unreachable("Unknown shuffle opcode!"); 5887 case OP_VREV: 5888 // VREV divides the vector in half and swaps within the half. 5889 if (VT.getVectorElementType() == MVT::i32 || 5890 VT.getVectorElementType() == MVT::f32) 5891 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5892 // vrev <4 x i16> -> REV32 5893 if (VT.getVectorElementType() == MVT::i16 || 5894 VT.getVectorElementType() == MVT::f16) 5895 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5896 // vrev <4 x i8> -> REV16 5897 assert(VT.getVectorElementType() == MVT::i8); 5898 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5899 case OP_VDUP0: 5900 case OP_VDUP1: 5901 case OP_VDUP2: 5902 case OP_VDUP3: { 5903 EVT EltTy = VT.getVectorElementType(); 5904 unsigned Opcode; 5905 if (EltTy == MVT::i8) 5906 Opcode = AArch64ISD::DUPLANE8; 5907 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5908 Opcode = AArch64ISD::DUPLANE16; 5909 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5910 Opcode = AArch64ISD::DUPLANE32; 5911 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5912 Opcode = AArch64ISD::DUPLANE64; 5913 else 5914 llvm_unreachable("Invalid vector element type?"); 5915 5916 if (VT.getSizeInBits() == 64) 5917 OpLHS = WidenVector(OpLHS, DAG); 5918 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5919 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5920 } 5921 case OP_VEXT1: 5922 case OP_VEXT2: 5923 case OP_VEXT3: { 5924 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5925 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5926 DAG.getConstant(Imm, dl, MVT::i32)); 5927 } 5928 case OP_VUZPL: 5929 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5930 OpRHS); 5931 case OP_VUZPR: 5932 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5933 OpRHS); 5934 case OP_VZIPL: 5935 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5936 OpRHS); 5937 case OP_VZIPR: 5938 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5939 OpRHS); 5940 case OP_VTRNL: 5941 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5942 OpRHS); 5943 case OP_VTRNR: 5944 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5945 OpRHS); 5946 } 5947 } 5948 5949 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5950 SelectionDAG &DAG) { 5951 // Check to see if we can use the TBL instruction. 5952 SDValue V1 = Op.getOperand(0); 5953 SDValue V2 = Op.getOperand(1); 5954 SDLoc DL(Op); 5955 5956 EVT EltVT = Op.getValueType().getVectorElementType(); 5957 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5958 5959 SmallVector<SDValue, 8> TBLMask; 5960 for (int Val : ShuffleMask) { 5961 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 5962 unsigned Offset = Byte + Val * BytesPerElt; 5963 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 5964 } 5965 } 5966 5967 MVT IndexVT = MVT::v8i8; 5968 unsigned IndexLen = 8; 5969 if (Op.getValueSizeInBits() == 128) { 5970 IndexVT = MVT::v16i8; 5971 IndexLen = 16; 5972 } 5973 5974 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 5975 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 5976 5977 SDValue Shuffle; 5978 if (V2.getNode()->isUndef()) { 5979 if (IndexLen == 8) 5980 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 5981 Shuffle = DAG.getNode( 5982 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5983 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5984 DAG.getBuildVector(IndexVT, DL, 5985 makeArrayRef(TBLMask.data(), IndexLen))); 5986 } else { 5987 if (IndexLen == 8) { 5988 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 5989 Shuffle = DAG.getNode( 5990 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5991 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5992 DAG.getBuildVector(IndexVT, DL, 5993 makeArrayRef(TBLMask.data(), IndexLen))); 5994 } else { 5995 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 5996 // cannot currently represent the register constraints on the input 5997 // table registers. 5998 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 5999 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 6000 // IndexLen)); 6001 Shuffle = DAG.getNode( 6002 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6003 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 6004 V2Cst, DAG.getBuildVector(IndexVT, DL, 6005 makeArrayRef(TBLMask.data(), IndexLen))); 6006 } 6007 } 6008 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 6009 } 6010 6011 static unsigned getDUPLANEOp(EVT EltType) { 6012 if (EltType == MVT::i8) 6013 return AArch64ISD::DUPLANE8; 6014 if (EltType == MVT::i16 || EltType == MVT::f16) 6015 return AArch64ISD::DUPLANE16; 6016 if (EltType == MVT::i32 || EltType == MVT::f32) 6017 return AArch64ISD::DUPLANE32; 6018 if (EltType == MVT::i64 || EltType == MVT::f64) 6019 return AArch64ISD::DUPLANE64; 6020 6021 llvm_unreachable("Invalid vector element type?"); 6022 } 6023 6024 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 6025 SelectionDAG &DAG) const { 6026 SDLoc dl(Op); 6027 EVT VT = Op.getValueType(); 6028 6029 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6030 6031 // Convert shuffles that are directly supported on NEON to target-specific 6032 // DAG nodes, instead of keeping them as shuffles and matching them again 6033 // during code selection. This is more efficient and avoids the possibility 6034 // of inconsistencies between legalization and selection. 6035 ArrayRef<int> ShuffleMask = SVN->getMask(); 6036 6037 SDValue V1 = Op.getOperand(0); 6038 SDValue V2 = Op.getOperand(1); 6039 6040 if (SVN->isSplat()) { 6041 int Lane = SVN->getSplatIndex(); 6042 // If this is undef splat, generate it via "just" vdup, if possible. 6043 if (Lane == -1) 6044 Lane = 0; 6045 6046 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 6047 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 6048 V1.getOperand(0)); 6049 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 6050 // constant. If so, we can just reference the lane's definition directly. 6051 if (V1.getOpcode() == ISD::BUILD_VECTOR && 6052 !isa<ConstantSDNode>(V1.getOperand(Lane))) 6053 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 6054 6055 // Otherwise, duplicate from the lane of the input vector. 6056 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 6057 6058 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 6059 // to make a vector of the same size as this SHUFFLE. We can ignore the 6060 // extract entirely, and canonicalise the concat using WidenVector. 6061 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 6062 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 6063 V1 = V1.getOperand(0); 6064 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 6065 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 6066 Lane -= Idx * VT.getVectorNumElements() / 2; 6067 V1 = WidenVector(V1.getOperand(Idx), DAG); 6068 } else if (VT.getSizeInBits() == 64) 6069 V1 = WidenVector(V1, DAG); 6070 6071 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 6072 } 6073 6074 if (isREVMask(ShuffleMask, VT, 64)) 6075 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 6076 if (isREVMask(ShuffleMask, VT, 32)) 6077 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 6078 if (isREVMask(ShuffleMask, VT, 16)) 6079 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 6080 6081 bool ReverseEXT = false; 6082 unsigned Imm; 6083 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 6084 if (ReverseEXT) 6085 std::swap(V1, V2); 6086 Imm *= getExtFactor(V1); 6087 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 6088 DAG.getConstant(Imm, dl, MVT::i32)); 6089 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 6090 Imm *= getExtFactor(V1); 6091 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 6092 DAG.getConstant(Imm, dl, MVT::i32)); 6093 } 6094 6095 unsigned WhichResult; 6096 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 6097 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6098 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6099 } 6100 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 6101 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6102 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6103 } 6104 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 6105 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6106 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6107 } 6108 6109 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6110 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6111 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6112 } 6113 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6114 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6115 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6116 } 6117 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6118 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6119 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6120 } 6121 6122 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 6123 return Concat; 6124 6125 bool DstIsLeft; 6126 int Anomaly; 6127 int NumInputElements = V1.getValueType().getVectorNumElements(); 6128 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 6129 SDValue DstVec = DstIsLeft ? V1 : V2; 6130 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 6131 6132 SDValue SrcVec = V1; 6133 int SrcLane = ShuffleMask[Anomaly]; 6134 if (SrcLane >= NumInputElements) { 6135 SrcVec = V2; 6136 SrcLane -= VT.getVectorNumElements(); 6137 } 6138 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 6139 6140 EVT ScalarVT = VT.getVectorElementType(); 6141 6142 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 6143 ScalarVT = MVT::i32; 6144 6145 return DAG.getNode( 6146 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 6147 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 6148 DstLaneV); 6149 } 6150 6151 // If the shuffle is not directly supported and it has 4 elements, use 6152 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6153 unsigned NumElts = VT.getVectorNumElements(); 6154 if (NumElts == 4) { 6155 unsigned PFIndexes[4]; 6156 for (unsigned i = 0; i != 4; ++i) { 6157 if (ShuffleMask[i] < 0) 6158 PFIndexes[i] = 8; 6159 else 6160 PFIndexes[i] = ShuffleMask[i]; 6161 } 6162 6163 // Compute the index in the perfect shuffle table. 6164 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6165 PFIndexes[2] * 9 + PFIndexes[3]; 6166 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6167 unsigned Cost = (PFEntry >> 30); 6168 6169 if (Cost <= 4) 6170 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6171 } 6172 6173 return GenerateTBL(Op, ShuffleMask, DAG); 6174 } 6175 6176 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 6177 APInt &UndefBits) { 6178 EVT VT = BVN->getValueType(0); 6179 APInt SplatBits, SplatUndef; 6180 unsigned SplatBitSize; 6181 bool HasAnyUndefs; 6182 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6183 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 6184 6185 for (unsigned i = 0; i < NumSplats; ++i) { 6186 CnstBits <<= SplatBitSize; 6187 UndefBits <<= SplatBitSize; 6188 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 6189 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 6190 } 6191 6192 return true; 6193 } 6194 6195 return false; 6196 } 6197 6198 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 6199 SelectionDAG &DAG) const { 6200 BuildVectorSDNode *BVN = 6201 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6202 SDValue LHS = Op.getOperand(0); 6203 SDLoc dl(Op); 6204 EVT VT = Op.getValueType(); 6205 6206 if (!BVN) 6207 return Op; 6208 6209 APInt CnstBits(VT.getSizeInBits(), 0); 6210 APInt UndefBits(VT.getSizeInBits(), 0); 6211 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6212 // We only have BIC vector immediate instruction, which is and-not. 6213 CnstBits = ~CnstBits; 6214 6215 // We make use of a little bit of goto ickiness in order to avoid having to 6216 // duplicate the immediate matching logic for the undef toggled case. 6217 bool SecondTry = false; 6218 AttemptModImm: 6219 6220 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6221 CnstBits = CnstBits.zextOrTrunc(64); 6222 uint64_t CnstVal = CnstBits.getZExtValue(); 6223 6224 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6225 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6226 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6227 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6228 DAG.getConstant(CnstVal, dl, MVT::i32), 6229 DAG.getConstant(0, dl, MVT::i32)); 6230 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6231 } 6232 6233 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6234 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6235 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6236 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6237 DAG.getConstant(CnstVal, dl, MVT::i32), 6238 DAG.getConstant(8, dl, MVT::i32)); 6239 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6240 } 6241 6242 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6243 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6244 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6245 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6246 DAG.getConstant(CnstVal, dl, MVT::i32), 6247 DAG.getConstant(16, dl, MVT::i32)); 6248 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6249 } 6250 6251 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6252 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6253 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6254 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6255 DAG.getConstant(CnstVal, dl, MVT::i32), 6256 DAG.getConstant(24, dl, MVT::i32)); 6257 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6258 } 6259 6260 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6261 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6262 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6263 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6264 DAG.getConstant(CnstVal, dl, MVT::i32), 6265 DAG.getConstant(0, dl, MVT::i32)); 6266 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6267 } 6268 6269 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6270 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6271 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6272 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 6273 DAG.getConstant(CnstVal, dl, MVT::i32), 6274 DAG.getConstant(8, dl, MVT::i32)); 6275 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6276 } 6277 } 6278 6279 if (SecondTry) 6280 goto FailedModImm; 6281 SecondTry = true; 6282 CnstBits = ~UndefBits; 6283 goto AttemptModImm; 6284 } 6285 6286 // We can always fall back to a non-immediate AND. 6287 FailedModImm: 6288 return Op; 6289 } 6290 6291 // Specialized code to quickly find if PotentialBVec is a BuildVector that 6292 // consists of only the same constant int value, returned in reference arg 6293 // ConstVal 6294 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 6295 uint64_t &ConstVal) { 6296 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 6297 if (!Bvec) 6298 return false; 6299 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 6300 if (!FirstElt) 6301 return false; 6302 EVT VT = Bvec->getValueType(0); 6303 unsigned NumElts = VT.getVectorNumElements(); 6304 for (unsigned i = 1; i < NumElts; ++i) 6305 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 6306 return false; 6307 ConstVal = FirstElt->getZExtValue(); 6308 return true; 6309 } 6310 6311 static unsigned getIntrinsicID(const SDNode *N) { 6312 unsigned Opcode = N->getOpcode(); 6313 switch (Opcode) { 6314 default: 6315 return Intrinsic::not_intrinsic; 6316 case ISD::INTRINSIC_WO_CHAIN: { 6317 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 6318 if (IID < Intrinsic::num_intrinsics) 6319 return IID; 6320 return Intrinsic::not_intrinsic; 6321 } 6322 } 6323 } 6324 6325 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 6326 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 6327 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 6328 // Also, logical shift right -> sri, with the same structure. 6329 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 6330 EVT VT = N->getValueType(0); 6331 6332 if (!VT.isVector()) 6333 return SDValue(); 6334 6335 SDLoc DL(N); 6336 6337 // Is the first op an AND? 6338 const SDValue And = N->getOperand(0); 6339 if (And.getOpcode() != ISD::AND) 6340 return SDValue(); 6341 6342 // Is the second op an shl or lshr? 6343 SDValue Shift = N->getOperand(1); 6344 // This will have been turned into: AArch64ISD::VSHL vector, #shift 6345 // or AArch64ISD::VLSHR vector, #shift 6346 unsigned ShiftOpc = Shift.getOpcode(); 6347 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 6348 return SDValue(); 6349 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 6350 6351 // Is the shift amount constant? 6352 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 6353 if (!C2node) 6354 return SDValue(); 6355 6356 // Is the and mask vector all constant? 6357 uint64_t C1; 6358 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 6359 return SDValue(); 6360 6361 // Is C1 == ~C2, taking into account how much one can shift elements of a 6362 // particular size? 6363 uint64_t C2 = C2node->getZExtValue(); 6364 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 6365 if (C2 > ElemSizeInBits) 6366 return SDValue(); 6367 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 6368 if ((C1 & ElemMask) != (~C2 & ElemMask)) 6369 return SDValue(); 6370 6371 SDValue X = And.getOperand(0); 6372 SDValue Y = Shift.getOperand(0); 6373 6374 unsigned Intrin = 6375 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 6376 SDValue ResultSLI = 6377 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6378 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 6379 Shift.getOperand(1)); 6380 6381 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 6382 DEBUG(N->dump(&DAG)); 6383 DEBUG(dbgs() << "into: \n"); 6384 DEBUG(ResultSLI->dump(&DAG)); 6385 6386 ++NumShiftInserts; 6387 return ResultSLI; 6388 } 6389 6390 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 6391 SelectionDAG &DAG) const { 6392 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 6393 if (EnableAArch64SlrGeneration) { 6394 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 6395 return Res; 6396 } 6397 6398 BuildVectorSDNode *BVN = 6399 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 6400 SDValue LHS = Op.getOperand(1); 6401 SDLoc dl(Op); 6402 EVT VT = Op.getValueType(); 6403 6404 // OR commutes, so try swapping the operands. 6405 if (!BVN) { 6406 LHS = Op.getOperand(0); 6407 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6408 } 6409 if (!BVN) 6410 return Op; 6411 6412 APInt CnstBits(VT.getSizeInBits(), 0); 6413 APInt UndefBits(VT.getSizeInBits(), 0); 6414 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6415 // We make use of a little bit of goto ickiness in order to avoid having to 6416 // duplicate the immediate matching logic for the undef toggled case. 6417 bool SecondTry = false; 6418 AttemptModImm: 6419 6420 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6421 CnstBits = CnstBits.zextOrTrunc(64); 6422 uint64_t CnstVal = CnstBits.getZExtValue(); 6423 6424 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6425 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6426 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6427 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6428 DAG.getConstant(CnstVal, dl, MVT::i32), 6429 DAG.getConstant(0, dl, MVT::i32)); 6430 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6431 } 6432 6433 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6434 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6435 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6436 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6437 DAG.getConstant(CnstVal, dl, MVT::i32), 6438 DAG.getConstant(8, dl, MVT::i32)); 6439 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6440 } 6441 6442 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6443 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6444 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6445 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6446 DAG.getConstant(CnstVal, dl, MVT::i32), 6447 DAG.getConstant(16, dl, MVT::i32)); 6448 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6449 } 6450 6451 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6452 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6453 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6454 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6455 DAG.getConstant(CnstVal, dl, MVT::i32), 6456 DAG.getConstant(24, dl, MVT::i32)); 6457 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6458 } 6459 6460 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6461 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6462 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6463 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6464 DAG.getConstant(CnstVal, dl, MVT::i32), 6465 DAG.getConstant(0, dl, MVT::i32)); 6466 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6467 } 6468 6469 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6470 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6471 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6472 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6473 DAG.getConstant(CnstVal, dl, MVT::i32), 6474 DAG.getConstant(8, dl, MVT::i32)); 6475 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6476 } 6477 } 6478 6479 if (SecondTry) 6480 goto FailedModImm; 6481 SecondTry = true; 6482 CnstBits = UndefBits; 6483 goto AttemptModImm; 6484 } 6485 6486 // We can always fall back to a non-immediate OR. 6487 FailedModImm: 6488 return Op; 6489 } 6490 6491 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6492 // be truncated to fit element width. 6493 static SDValue NormalizeBuildVector(SDValue Op, 6494 SelectionDAG &DAG) { 6495 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6496 SDLoc dl(Op); 6497 EVT VT = Op.getValueType(); 6498 EVT EltTy= VT.getVectorElementType(); 6499 6500 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6501 return Op; 6502 6503 SmallVector<SDValue, 16> Ops; 6504 for (SDValue Lane : Op->ops()) { 6505 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6506 APInt LowBits(EltTy.getSizeInBits(), 6507 CstLane->getZExtValue()); 6508 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6509 } 6510 Ops.push_back(Lane); 6511 } 6512 return DAG.getBuildVector(VT, dl, Ops); 6513 } 6514 6515 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6516 SelectionDAG &DAG) const { 6517 SDLoc dl(Op); 6518 EVT VT = Op.getValueType(); 6519 Op = NormalizeBuildVector(Op, DAG); 6520 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6521 6522 APInt CnstBits(VT.getSizeInBits(), 0); 6523 APInt UndefBits(VT.getSizeInBits(), 0); 6524 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6525 // We make use of a little bit of goto ickiness in order to avoid having to 6526 // duplicate the immediate matching logic for the undef toggled case. 6527 bool SecondTry = false; 6528 AttemptModImm: 6529 6530 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6531 CnstBits = CnstBits.zextOrTrunc(64); 6532 uint64_t CnstVal = CnstBits.getZExtValue(); 6533 6534 // Certain magic vector constants (used to express things like NOT 6535 // and NEG) are passed through unmodified. This allows codegen patterns 6536 // for these operations to match. Special-purpose patterns will lower 6537 // these immediates to MOVIs if it proves necessary. 6538 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6539 return Op; 6540 6541 // The many faces of MOVI... 6542 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6543 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6544 if (VT.getSizeInBits() == 128) { 6545 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6546 DAG.getConstant(CnstVal, dl, MVT::i32)); 6547 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6548 } 6549 6550 // Support the V64 version via subregister insertion. 6551 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6552 DAG.getConstant(CnstVal, dl, MVT::i32)); 6553 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6554 } 6555 6556 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6557 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6558 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6559 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6560 DAG.getConstant(CnstVal, dl, MVT::i32), 6561 DAG.getConstant(0, dl, MVT::i32)); 6562 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6563 } 6564 6565 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6566 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6567 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6568 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6569 DAG.getConstant(CnstVal, dl, MVT::i32), 6570 DAG.getConstant(8, dl, MVT::i32)); 6571 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6572 } 6573 6574 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6575 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6576 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6577 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6578 DAG.getConstant(CnstVal, dl, MVT::i32), 6579 DAG.getConstant(16, dl, MVT::i32)); 6580 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6581 } 6582 6583 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6584 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6585 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6586 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6587 DAG.getConstant(CnstVal, dl, MVT::i32), 6588 DAG.getConstant(24, dl, MVT::i32)); 6589 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6590 } 6591 6592 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6593 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6594 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6595 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6596 DAG.getConstant(CnstVal, dl, MVT::i32), 6597 DAG.getConstant(0, dl, MVT::i32)); 6598 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6599 } 6600 6601 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6602 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6603 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6604 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6605 DAG.getConstant(CnstVal, dl, MVT::i32), 6606 DAG.getConstant(8, dl, MVT::i32)); 6607 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6608 } 6609 6610 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6611 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6612 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6613 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6614 DAG.getConstant(CnstVal, dl, MVT::i32), 6615 DAG.getConstant(264, dl, MVT::i32)); 6616 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6617 } 6618 6619 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6620 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6621 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6622 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6623 DAG.getConstant(CnstVal, dl, MVT::i32), 6624 DAG.getConstant(272, dl, MVT::i32)); 6625 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6626 } 6627 6628 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6629 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6631 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6632 DAG.getConstant(CnstVal, dl, MVT::i32)); 6633 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6634 } 6635 6636 // The few faces of FMOV... 6637 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6638 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6639 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6640 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6641 DAG.getConstant(CnstVal, dl, MVT::i32)); 6642 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6643 } 6644 6645 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6646 VT.getSizeInBits() == 128) { 6647 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6648 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6649 DAG.getConstant(CnstVal, dl, MVT::i32)); 6650 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6651 } 6652 6653 // The many faces of MVNI... 6654 CnstVal = ~CnstVal; 6655 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6656 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6657 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6658 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6659 DAG.getConstant(CnstVal, dl, MVT::i32), 6660 DAG.getConstant(0, dl, MVT::i32)); 6661 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6662 } 6663 6664 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6665 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6666 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6667 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6668 DAG.getConstant(CnstVal, dl, MVT::i32), 6669 DAG.getConstant(8, dl, MVT::i32)); 6670 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6671 } 6672 6673 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6674 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6675 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6676 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6677 DAG.getConstant(CnstVal, dl, MVT::i32), 6678 DAG.getConstant(16, dl, MVT::i32)); 6679 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6680 } 6681 6682 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6683 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6684 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6685 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6686 DAG.getConstant(CnstVal, dl, MVT::i32), 6687 DAG.getConstant(24, dl, MVT::i32)); 6688 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6689 } 6690 6691 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6692 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6693 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6694 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6695 DAG.getConstant(CnstVal, dl, MVT::i32), 6696 DAG.getConstant(0, dl, MVT::i32)); 6697 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6698 } 6699 6700 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6701 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6702 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6703 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6704 DAG.getConstant(CnstVal, dl, MVT::i32), 6705 DAG.getConstant(8, dl, MVT::i32)); 6706 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6707 } 6708 6709 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6710 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6711 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6712 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6713 DAG.getConstant(CnstVal, dl, MVT::i32), 6714 DAG.getConstant(264, dl, MVT::i32)); 6715 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6716 } 6717 6718 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6719 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6720 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6721 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6722 DAG.getConstant(CnstVal, dl, MVT::i32), 6723 DAG.getConstant(272, dl, MVT::i32)); 6724 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6725 } 6726 } 6727 6728 if (SecondTry) 6729 goto FailedModImm; 6730 SecondTry = true; 6731 CnstBits = UndefBits; 6732 goto AttemptModImm; 6733 } 6734 FailedModImm: 6735 6736 // Scan through the operands to find some interesting properties we can 6737 // exploit: 6738 // 1) If only one value is used, we can use a DUP, or 6739 // 2) if only the low element is not undef, we can just insert that, or 6740 // 3) if only one constant value is used (w/ some non-constant lanes), 6741 // we can splat the constant value into the whole vector then fill 6742 // in the non-constant lanes. 6743 // 4) FIXME: If different constant values are used, but we can intelligently 6744 // select the values we'll be overwriting for the non-constant 6745 // lanes such that we can directly materialize the vector 6746 // some other way (MOVI, e.g.), we can be sneaky. 6747 unsigned NumElts = VT.getVectorNumElements(); 6748 bool isOnlyLowElement = true; 6749 bool usesOnlyOneValue = true; 6750 bool usesOnlyOneConstantValue = true; 6751 bool isConstant = true; 6752 unsigned NumConstantLanes = 0; 6753 SDValue Value; 6754 SDValue ConstantValue; 6755 for (unsigned i = 0; i < NumElts; ++i) { 6756 SDValue V = Op.getOperand(i); 6757 if (V.isUndef()) 6758 continue; 6759 if (i > 0) 6760 isOnlyLowElement = false; 6761 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6762 isConstant = false; 6763 6764 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6765 ++NumConstantLanes; 6766 if (!ConstantValue.getNode()) 6767 ConstantValue = V; 6768 else if (ConstantValue != V) 6769 usesOnlyOneConstantValue = false; 6770 } 6771 6772 if (!Value.getNode()) 6773 Value = V; 6774 else if (V != Value) 6775 usesOnlyOneValue = false; 6776 } 6777 6778 if (!Value.getNode()) { 6779 DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 6780 return DAG.getUNDEF(VT); 6781 } 6782 6783 if (isOnlyLowElement) { 6784 DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 6785 "SCALAR_TO_VECTOR node\n"); 6786 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6787 } 6788 6789 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6790 // i32 and try again. 6791 if (usesOnlyOneValue) { 6792 if (!isConstant) { 6793 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6794 Value.getValueType() != VT) { 6795 DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 6796 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6797 } 6798 6799 // This is actually a DUPLANExx operation, which keeps everything vectory. 6800 6801 SDValue Lane = Value.getOperand(1); 6802 Value = Value.getOperand(0); 6803 if (Value.getValueSizeInBits() == 64) { 6804 DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 6805 "widening it\n"); 6806 Value = WidenVector(Value, DAG); 6807 } 6808 6809 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6810 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6811 } 6812 6813 if (VT.getVectorElementType().isFloatingPoint()) { 6814 SmallVector<SDValue, 8> Ops; 6815 EVT EltTy = VT.getVectorElementType(); 6816 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6817 "Unsupported floating-point vector type"); 6818 DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 6819 "BITCASTS, and try again\n"); 6820 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6821 for (unsigned i = 0; i < NumElts; ++i) 6822 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6823 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6824 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6825 DEBUG( 6826 dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 6827 Val.dump(); 6828 ); 6829 Val = LowerBUILD_VECTOR(Val, DAG); 6830 if (Val.getNode()) 6831 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6832 } 6833 } 6834 6835 // If there was only one constant value used and for more than one lane, 6836 // start by splatting that value, then replace the non-constant lanes. This 6837 // is better than the default, which will perform a separate initialization 6838 // for each lane. 6839 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6840 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6841 // Now insert the non-constant lanes. 6842 for (unsigned i = 0; i < NumElts; ++i) { 6843 SDValue V = Op.getOperand(i); 6844 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6845 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6846 // Note that type legalization likely mucked about with the VT of the 6847 // source operand, so we may have to convert it here before inserting. 6848 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6849 } 6850 } 6851 return Val; 6852 } 6853 6854 // This will generate a load from the constant pool. 6855 if (isConstant) { 6856 DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 6857 "expansion\n"); 6858 return SDValue(); 6859 } 6860 6861 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6862 if (NumElts >= 4) { 6863 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6864 return shuffle; 6865 } 6866 6867 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6868 // know the default expansion would otherwise fall back on something even 6869 // worse. For a vector with one or two non-undef values, that's 6870 // scalar_to_vector for the elements followed by a shuffle (provided the 6871 // shuffle is valid for the target) and materialization element by element 6872 // on the stack followed by a load for everything else. 6873 if (!isConstant && !usesOnlyOneValue) { 6874 DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 6875 "of INSERT_VECTOR_ELT\n"); 6876 6877 SDValue Vec = DAG.getUNDEF(VT); 6878 SDValue Op0 = Op.getOperand(0); 6879 unsigned i = 0; 6880 6881 // Use SCALAR_TO_VECTOR for lane zero to 6882 // a) Avoid a RMW dependency on the full vector register, and 6883 // b) Allow the register coalescer to fold away the copy if the 6884 // value is already in an S or D register, and we're forced to emit an 6885 // INSERT_SUBREG that we can't fold anywhere. 6886 // 6887 // We also allow types like i8 and i16 which are illegal scalar but legal 6888 // vector element types. After type-legalization the inserted value is 6889 // extended (i32) and it is safe to cast them to the vector type by ignoring 6890 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 6891 if (!Op0.isUndef()) { 6892 DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 6893 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 6894 ++i; 6895 } 6896 DEBUG( 6897 if (i < NumElts) 6898 dbgs() << "Creating nodes for the other vector elements:\n"; 6899 ); 6900 for (; i < NumElts; ++i) { 6901 SDValue V = Op.getOperand(i); 6902 if (V.isUndef()) 6903 continue; 6904 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6905 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6906 } 6907 return Vec; 6908 } 6909 6910 DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 6911 "better alternative\n"); 6912 return SDValue(); 6913 } 6914 6915 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6916 SelectionDAG &DAG) const { 6917 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6918 6919 // Check for non-constant or out of range lane. 6920 EVT VT = Op.getOperand(0).getValueType(); 6921 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6922 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6923 return SDValue(); 6924 6925 6926 // Insertion/extraction are legal for V128 types. 6927 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6928 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6929 VT == MVT::v8f16) 6930 return Op; 6931 6932 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6933 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6934 return SDValue(); 6935 6936 // For V64 types, we perform insertion by expanding the value 6937 // to a V128 type and perform the insertion on that. 6938 SDLoc DL(Op); 6939 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6940 EVT WideTy = WideVec.getValueType(); 6941 6942 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6943 Op.getOperand(1), Op.getOperand(2)); 6944 // Re-narrow the resultant vector. 6945 return NarrowVector(Node, DAG); 6946 } 6947 6948 SDValue 6949 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6950 SelectionDAG &DAG) const { 6951 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6952 6953 // Check for non-constant or out of range lane. 6954 EVT VT = Op.getOperand(0).getValueType(); 6955 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6956 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6957 return SDValue(); 6958 6959 6960 // Insertion/extraction are legal for V128 types. 6961 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6962 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6963 VT == MVT::v8f16) 6964 return Op; 6965 6966 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6967 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6968 return SDValue(); 6969 6970 // For V64 types, we perform extraction by expanding the value 6971 // to a V128 type and perform the extraction on that. 6972 SDLoc DL(Op); 6973 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6974 EVT WideTy = WideVec.getValueType(); 6975 6976 EVT ExtrTy = WideTy.getVectorElementType(); 6977 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 6978 ExtrTy = MVT::i32; 6979 6980 // For extractions, we just return the result directly. 6981 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 6982 Op.getOperand(1)); 6983 } 6984 6985 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 6986 SelectionDAG &DAG) const { 6987 EVT VT = Op.getOperand(0).getValueType(); 6988 SDLoc dl(Op); 6989 // Just in case... 6990 if (!VT.isVector()) 6991 return SDValue(); 6992 6993 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6994 if (!Cst) 6995 return SDValue(); 6996 unsigned Val = Cst->getZExtValue(); 6997 6998 unsigned Size = Op.getValueSizeInBits(); 6999 7000 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 7001 if (Val == 0) 7002 return Op; 7003 7004 // If this is extracting the upper 64-bits of a 128-bit vector, we match 7005 // that directly. 7006 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 7007 return Op; 7008 7009 return SDValue(); 7010 } 7011 7012 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7013 if (VT.getVectorNumElements() == 4 && 7014 (VT.is128BitVector() || VT.is64BitVector())) { 7015 unsigned PFIndexes[4]; 7016 for (unsigned i = 0; i != 4; ++i) { 7017 if (M[i] < 0) 7018 PFIndexes[i] = 8; 7019 else 7020 PFIndexes[i] = M[i]; 7021 } 7022 7023 // Compute the index in the perfect shuffle table. 7024 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7025 PFIndexes[2] * 9 + PFIndexes[3]; 7026 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7027 unsigned Cost = (PFEntry >> 30); 7028 7029 if (Cost <= 4) 7030 return true; 7031 } 7032 7033 bool DummyBool; 7034 int DummyInt; 7035 unsigned DummyUnsigned; 7036 7037 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 7038 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 7039 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 7040 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 7041 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 7042 isZIPMask(M, VT, DummyUnsigned) || 7043 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 7044 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 7045 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 7046 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 7047 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 7048 } 7049 7050 /// getVShiftImm - Check if this is a valid build_vector for the immediate 7051 /// operand of a vector shift operation, where all the elements of the 7052 /// build_vector must have the same constant integer value. 7053 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 7054 // Ignore bit_converts. 7055 while (Op.getOpcode() == ISD::BITCAST) 7056 Op = Op.getOperand(0); 7057 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7058 APInt SplatBits, SplatUndef; 7059 unsigned SplatBitSize; 7060 bool HasAnyUndefs; 7061 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 7062 HasAnyUndefs, ElementBits) || 7063 SplatBitSize > ElementBits) 7064 return false; 7065 Cnt = SplatBits.getSExtValue(); 7066 return true; 7067 } 7068 7069 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 7070 /// operand of a vector shift left operation. That value must be in the range: 7071 /// 0 <= Value < ElementBits for a left shift; or 7072 /// 0 <= Value <= ElementBits for a long left shift. 7073 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 7074 assert(VT.isVector() && "vector shift count is not a vector type"); 7075 int64_t ElementBits = VT.getScalarSizeInBits(); 7076 if (!getVShiftImm(Op, ElementBits, Cnt)) 7077 return false; 7078 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 7079 } 7080 7081 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 7082 /// operand of a vector shift right operation. The value must be in the range: 7083 /// 1 <= Value <= ElementBits for a right shift; or 7084 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 7085 assert(VT.isVector() && "vector shift count is not a vector type"); 7086 int64_t ElementBits = VT.getScalarSizeInBits(); 7087 if (!getVShiftImm(Op, ElementBits, Cnt)) 7088 return false; 7089 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 7090 } 7091 7092 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 7093 SelectionDAG &DAG) const { 7094 EVT VT = Op.getValueType(); 7095 SDLoc DL(Op); 7096 int64_t Cnt; 7097 7098 if (!Op.getOperand(1).getValueType().isVector()) 7099 return Op; 7100 unsigned EltSize = VT.getScalarSizeInBits(); 7101 7102 switch (Op.getOpcode()) { 7103 default: 7104 llvm_unreachable("unexpected shift opcode"); 7105 7106 case ISD::SHL: 7107 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 7108 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 7109 DAG.getConstant(Cnt, DL, MVT::i32)); 7110 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7111 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 7112 MVT::i32), 7113 Op.getOperand(0), Op.getOperand(1)); 7114 case ISD::SRA: 7115 case ISD::SRL: 7116 // Right shift immediate 7117 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 7118 unsigned Opc = 7119 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 7120 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 7121 DAG.getConstant(Cnt, DL, MVT::i32)); 7122 } 7123 7124 // Right shift register. Note, there is not a shift right register 7125 // instruction, but the shift left register instruction takes a signed 7126 // value, where negative numbers specify a right shift. 7127 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 7128 : Intrinsic::aarch64_neon_ushl; 7129 // negate the shift amount 7130 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 7131 SDValue NegShiftLeft = 7132 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7133 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 7134 NegShift); 7135 return NegShiftLeft; 7136 } 7137 7138 return SDValue(); 7139 } 7140 7141 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 7142 AArch64CC::CondCode CC, bool NoNans, EVT VT, 7143 const SDLoc &dl, SelectionDAG &DAG) { 7144 EVT SrcVT = LHS.getValueType(); 7145 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 7146 "function only supposed to emit natural comparisons"); 7147 7148 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 7149 APInt CnstBits(VT.getSizeInBits(), 0); 7150 APInt UndefBits(VT.getSizeInBits(), 0); 7151 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 7152 bool IsZero = IsCnst && (CnstBits == 0); 7153 7154 if (SrcVT.getVectorElementType().isFloatingPoint()) { 7155 switch (CC) { 7156 default: 7157 return SDValue(); 7158 case AArch64CC::NE: { 7159 SDValue Fcmeq; 7160 if (IsZero) 7161 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7162 else 7163 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7164 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 7165 } 7166 case AArch64CC::EQ: 7167 if (IsZero) 7168 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7169 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7170 case AArch64CC::GE: 7171 if (IsZero) 7172 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 7173 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 7174 case AArch64CC::GT: 7175 if (IsZero) 7176 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 7177 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 7178 case AArch64CC::LS: 7179 if (IsZero) 7180 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 7181 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 7182 case AArch64CC::LT: 7183 if (!NoNans) 7184 return SDValue(); 7185 // If we ignore NaNs then we can use to the MI implementation. 7186 LLVM_FALLTHROUGH; 7187 case AArch64CC::MI: 7188 if (IsZero) 7189 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 7190 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 7191 } 7192 } 7193 7194 switch (CC) { 7195 default: 7196 return SDValue(); 7197 case AArch64CC::NE: { 7198 SDValue Cmeq; 7199 if (IsZero) 7200 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7201 else 7202 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7203 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 7204 } 7205 case AArch64CC::EQ: 7206 if (IsZero) 7207 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7208 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7209 case AArch64CC::GE: 7210 if (IsZero) 7211 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 7212 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 7213 case AArch64CC::GT: 7214 if (IsZero) 7215 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 7216 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 7217 case AArch64CC::LE: 7218 if (IsZero) 7219 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 7220 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 7221 case AArch64CC::LS: 7222 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 7223 case AArch64CC::LO: 7224 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 7225 case AArch64CC::LT: 7226 if (IsZero) 7227 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 7228 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 7229 case AArch64CC::HI: 7230 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 7231 case AArch64CC::HS: 7232 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 7233 } 7234 } 7235 7236 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 7237 SelectionDAG &DAG) const { 7238 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7239 SDValue LHS = Op.getOperand(0); 7240 SDValue RHS = Op.getOperand(1); 7241 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 7242 SDLoc dl(Op); 7243 7244 if (LHS.getValueType().getVectorElementType().isInteger()) { 7245 assert(LHS.getValueType() == RHS.getValueType()); 7246 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 7247 SDValue Cmp = 7248 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 7249 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7250 } 7251 7252 if (LHS.getValueType().getVectorElementType() == MVT::f16) 7253 return SDValue(); 7254 7255 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 7256 LHS.getValueType().getVectorElementType() == MVT::f64); 7257 7258 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 7259 // clean. Some of them require two branches to implement. 7260 AArch64CC::CondCode CC1, CC2; 7261 bool ShouldInvert; 7262 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 7263 7264 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 7265 SDValue Cmp = 7266 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 7267 if (!Cmp.getNode()) 7268 return SDValue(); 7269 7270 if (CC2 != AArch64CC::AL) { 7271 SDValue Cmp2 = 7272 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 7273 if (!Cmp2.getNode()) 7274 return SDValue(); 7275 7276 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 7277 } 7278 7279 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7280 7281 if (ShouldInvert) 7282 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 7283 7284 return Cmp; 7285 } 7286 7287 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 7288 SelectionDAG &DAG) { 7289 SDValue VecOp = ScalarOp.getOperand(0); 7290 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 7291 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 7292 DAG.getConstant(0, DL, MVT::i64)); 7293 } 7294 7295 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 7296 SelectionDAG &DAG) const { 7297 SDLoc dl(Op); 7298 switch (Op.getOpcode()) { 7299 case ISD::VECREDUCE_ADD: 7300 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 7301 case ISD::VECREDUCE_SMAX: 7302 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 7303 case ISD::VECREDUCE_SMIN: 7304 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 7305 case ISD::VECREDUCE_UMAX: 7306 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 7307 case ISD::VECREDUCE_UMIN: 7308 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 7309 case ISD::VECREDUCE_FMAX: { 7310 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 7311 return DAG.getNode( 7312 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7313 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 7314 Op.getOperand(0)); 7315 } 7316 case ISD::VECREDUCE_FMIN: { 7317 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 7318 return DAG.getNode( 7319 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7320 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 7321 Op.getOperand(0)); 7322 } 7323 default: 7324 llvm_unreachable("Unhandled reduction"); 7325 } 7326 } 7327 7328 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 7329 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 7330 /// specified in the intrinsic calls. 7331 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 7332 const CallInst &I, 7333 unsigned Intrinsic) const { 7334 auto &DL = I.getModule()->getDataLayout(); 7335 switch (Intrinsic) { 7336 case Intrinsic::aarch64_neon_ld2: 7337 case Intrinsic::aarch64_neon_ld3: 7338 case Intrinsic::aarch64_neon_ld4: 7339 case Intrinsic::aarch64_neon_ld1x2: 7340 case Intrinsic::aarch64_neon_ld1x3: 7341 case Intrinsic::aarch64_neon_ld1x4: 7342 case Intrinsic::aarch64_neon_ld2lane: 7343 case Intrinsic::aarch64_neon_ld3lane: 7344 case Intrinsic::aarch64_neon_ld4lane: 7345 case Intrinsic::aarch64_neon_ld2r: 7346 case Intrinsic::aarch64_neon_ld3r: 7347 case Intrinsic::aarch64_neon_ld4r: { 7348 Info.opc = ISD::INTRINSIC_W_CHAIN; 7349 // Conservatively set memVT to the entire set of vectors loaded. 7350 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 7351 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 7352 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 7353 Info.offset = 0; 7354 Info.align = 0; 7355 Info.vol = false; // volatile loads with NEON intrinsics not supported 7356 Info.readMem = true; 7357 Info.writeMem = false; 7358 return true; 7359 } 7360 case Intrinsic::aarch64_neon_st2: 7361 case Intrinsic::aarch64_neon_st3: 7362 case Intrinsic::aarch64_neon_st4: 7363 case Intrinsic::aarch64_neon_st1x2: 7364 case Intrinsic::aarch64_neon_st1x3: 7365 case Intrinsic::aarch64_neon_st1x4: 7366 case Intrinsic::aarch64_neon_st2lane: 7367 case Intrinsic::aarch64_neon_st3lane: 7368 case Intrinsic::aarch64_neon_st4lane: { 7369 Info.opc = ISD::INTRINSIC_VOID; 7370 // Conservatively set memVT to the entire set of vectors stored. 7371 unsigned NumElts = 0; 7372 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 7373 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 7374 if (!ArgTy->isVectorTy()) 7375 break; 7376 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 7377 } 7378 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 7379 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 7380 Info.offset = 0; 7381 Info.align = 0; 7382 Info.vol = false; // volatile stores with NEON intrinsics not supported 7383 Info.readMem = false; 7384 Info.writeMem = true; 7385 return true; 7386 } 7387 case Intrinsic::aarch64_ldaxr: 7388 case Intrinsic::aarch64_ldxr: { 7389 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 7390 Info.opc = ISD::INTRINSIC_W_CHAIN; 7391 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7392 Info.ptrVal = I.getArgOperand(0); 7393 Info.offset = 0; 7394 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7395 Info.vol = true; 7396 Info.readMem = true; 7397 Info.writeMem = false; 7398 return true; 7399 } 7400 case Intrinsic::aarch64_stlxr: 7401 case Intrinsic::aarch64_stxr: { 7402 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 7403 Info.opc = ISD::INTRINSIC_W_CHAIN; 7404 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7405 Info.ptrVal = I.getArgOperand(1); 7406 Info.offset = 0; 7407 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7408 Info.vol = true; 7409 Info.readMem = false; 7410 Info.writeMem = true; 7411 return true; 7412 } 7413 case Intrinsic::aarch64_ldaxp: 7414 case Intrinsic::aarch64_ldxp: 7415 Info.opc = ISD::INTRINSIC_W_CHAIN; 7416 Info.memVT = MVT::i128; 7417 Info.ptrVal = I.getArgOperand(0); 7418 Info.offset = 0; 7419 Info.align = 16; 7420 Info.vol = true; 7421 Info.readMem = true; 7422 Info.writeMem = false; 7423 return true; 7424 case Intrinsic::aarch64_stlxp: 7425 case Intrinsic::aarch64_stxp: 7426 Info.opc = ISD::INTRINSIC_W_CHAIN; 7427 Info.memVT = MVT::i128; 7428 Info.ptrVal = I.getArgOperand(2); 7429 Info.offset = 0; 7430 Info.align = 16; 7431 Info.vol = true; 7432 Info.readMem = false; 7433 Info.writeMem = true; 7434 return true; 7435 default: 7436 break; 7437 } 7438 7439 return false; 7440 } 7441 7442 // Truncations from 64-bit GPR to 32-bit GPR is free. 7443 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 7444 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7445 return false; 7446 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7447 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7448 return NumBits1 > NumBits2; 7449 } 7450 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 7451 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7452 return false; 7453 unsigned NumBits1 = VT1.getSizeInBits(); 7454 unsigned NumBits2 = VT2.getSizeInBits(); 7455 return NumBits1 > NumBits2; 7456 } 7457 7458 /// Check if it is profitable to hoist instruction in then/else to if. 7459 /// Not profitable if I and it's user can form a FMA instruction 7460 /// because we prefer FMSUB/FMADD. 7461 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 7462 if (I->getOpcode() != Instruction::FMul) 7463 return true; 7464 7465 if (!I->hasOneUse()) 7466 return true; 7467 7468 Instruction *User = I->user_back(); 7469 7470 if (User && 7471 !(User->getOpcode() == Instruction::FSub || 7472 User->getOpcode() == Instruction::FAdd)) 7473 return true; 7474 7475 const TargetOptions &Options = getTargetMachine().Options; 7476 const DataLayout &DL = I->getModule()->getDataLayout(); 7477 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 7478 7479 return !(isFMAFasterThanFMulAndFAdd(VT) && 7480 isOperationLegalOrCustom(ISD::FMA, VT) && 7481 (Options.AllowFPOpFusion == FPOpFusion::Fast || 7482 Options.UnsafeFPMath)); 7483 } 7484 7485 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 7486 // 64-bit GPR. 7487 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 7488 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7489 return false; 7490 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7491 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7492 return NumBits1 == 32 && NumBits2 == 64; 7493 } 7494 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 7495 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7496 return false; 7497 unsigned NumBits1 = VT1.getSizeInBits(); 7498 unsigned NumBits2 = VT2.getSizeInBits(); 7499 return NumBits1 == 32 && NumBits2 == 64; 7500 } 7501 7502 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7503 EVT VT1 = Val.getValueType(); 7504 if (isZExtFree(VT1, VT2)) { 7505 return true; 7506 } 7507 7508 if (Val.getOpcode() != ISD::LOAD) 7509 return false; 7510 7511 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7512 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7513 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7514 VT1.getSizeInBits() <= 32); 7515 } 7516 7517 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7518 if (isa<FPExtInst>(Ext)) 7519 return false; 7520 7521 // Vector types are not free. 7522 if (Ext->getType()->isVectorTy()) 7523 return false; 7524 7525 for (const Use &U : Ext->uses()) { 7526 // The extension is free if we can fold it with a left shift in an 7527 // addressing mode or an arithmetic operation: add, sub, and cmp. 7528 7529 // Is there a shift? 7530 const Instruction *Instr = cast<Instruction>(U.getUser()); 7531 7532 // Is this a constant shift? 7533 switch (Instr->getOpcode()) { 7534 case Instruction::Shl: 7535 if (!isa<ConstantInt>(Instr->getOperand(1))) 7536 return false; 7537 break; 7538 case Instruction::GetElementPtr: { 7539 gep_type_iterator GTI = gep_type_begin(Instr); 7540 auto &DL = Ext->getModule()->getDataLayout(); 7541 std::advance(GTI, U.getOperandNo()-1); 7542 Type *IdxTy = GTI.getIndexedType(); 7543 // This extension will end up with a shift because of the scaling factor. 7544 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7545 // Get the shift amount based on the scaling factor: 7546 // log2(sizeof(IdxTy)) - log2(8). 7547 uint64_t ShiftAmt = 7548 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7549 // Is the constant foldable in the shift of the addressing mode? 7550 // I.e., shift amount is between 1 and 4 inclusive. 7551 if (ShiftAmt == 0 || ShiftAmt > 4) 7552 return false; 7553 break; 7554 } 7555 case Instruction::Trunc: 7556 // Check if this is a noop. 7557 // trunc(sext ty1 to ty2) to ty1. 7558 if (Instr->getType() == Ext->getOperand(0)->getType()) 7559 continue; 7560 LLVM_FALLTHROUGH; 7561 default: 7562 return false; 7563 } 7564 7565 // At this point we can use the bfm family, so this extension is free 7566 // for that use. 7567 } 7568 return true; 7569 } 7570 7571 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7572 unsigned &RequiredAligment) const { 7573 if (!LoadedType.isSimple() || 7574 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7575 return false; 7576 // Cyclone supports unaligned accesses. 7577 RequiredAligment = 0; 7578 unsigned NumBits = LoadedType.getSizeInBits(); 7579 return NumBits == 32 || NumBits == 64; 7580 } 7581 7582 /// A helper function for determining the number of interleaved accesses we 7583 /// will generate when lowering accesses of the given type. 7584 unsigned 7585 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 7586 const DataLayout &DL) const { 7587 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 7588 } 7589 7590 MachineMemOperand::Flags 7591 AArch64TargetLowering::getMMOFlags(const Instruction &I) const { 7592 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 7593 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 7594 return MOStridedAccess; 7595 return MachineMemOperand::MONone; 7596 } 7597 7598 bool AArch64TargetLowering::isLegalInterleavedAccessType( 7599 VectorType *VecTy, const DataLayout &DL) const { 7600 7601 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7602 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 7603 7604 // Ensure the number of vector elements is greater than 1. 7605 if (VecTy->getNumElements() < 2) 7606 return false; 7607 7608 // Ensure the element type is legal. 7609 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 7610 return false; 7611 7612 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 7613 // 128 will be split into multiple interleaved accesses. 7614 return VecSize == 64 || VecSize % 128 == 0; 7615 } 7616 7617 /// \brief Lower an interleaved load into a ldN intrinsic. 7618 /// 7619 /// E.g. Lower an interleaved load (Factor = 2): 7620 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7621 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7622 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7623 /// 7624 /// Into: 7625 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7626 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7627 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7628 bool AArch64TargetLowering::lowerInterleavedLoad( 7629 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7630 ArrayRef<unsigned> Indices, unsigned Factor) const { 7631 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7632 "Invalid interleave factor"); 7633 assert(!Shuffles.empty() && "Empty shufflevector input"); 7634 assert(Shuffles.size() == Indices.size() && 7635 "Unmatched number of shufflevectors and indices"); 7636 7637 const DataLayout &DL = LI->getModule()->getDataLayout(); 7638 7639 VectorType *VecTy = Shuffles[0]->getType(); 7640 7641 // Skip if we do not have NEON and skip illegal vector types. We can 7642 // "legalize" wide vector types into multiple interleaved accesses as long as 7643 // the vector types are divisible by 128. 7644 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 7645 return false; 7646 7647 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 7648 7649 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7650 // load integer vectors first and then convert to pointer vectors. 7651 Type *EltTy = VecTy->getVectorElementType(); 7652 if (EltTy->isPointerTy()) 7653 VecTy = 7654 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7655 7656 IRBuilder<> Builder(LI); 7657 7658 // The base address of the load. 7659 Value *BaseAddr = LI->getPointerOperand(); 7660 7661 if (NumLoads > 1) { 7662 // If we're going to generate more than one load, reset the sub-vector type 7663 // to something legal. 7664 VecTy = VectorType::get(VecTy->getVectorElementType(), 7665 VecTy->getVectorNumElements() / NumLoads); 7666 7667 // We will compute the pointer operand of each load from the original base 7668 // address using GEPs. Cast the base address to a pointer to the scalar 7669 // element type. 7670 BaseAddr = Builder.CreateBitCast( 7671 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 7672 LI->getPointerAddressSpace())); 7673 } 7674 7675 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7676 Type *Tys[2] = {VecTy, PtrTy}; 7677 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7678 Intrinsic::aarch64_neon_ld3, 7679 Intrinsic::aarch64_neon_ld4}; 7680 Function *LdNFunc = 7681 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7682 7683 // Holds sub-vectors extracted from the load intrinsic return values. The 7684 // sub-vectors are associated with the shufflevector instructions they will 7685 // replace. 7686 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 7687 7688 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 7689 7690 // If we're generating more than one load, compute the base address of 7691 // subsequent loads as an offset from the previous. 7692 if (LoadCount > 0) 7693 BaseAddr = Builder.CreateConstGEP1_32( 7694 BaseAddr, VecTy->getVectorNumElements() * Factor); 7695 7696 CallInst *LdN = Builder.CreateCall( 7697 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 7698 7699 // Extract and store the sub-vectors returned by the load intrinsic. 7700 for (unsigned i = 0; i < Shuffles.size(); i++) { 7701 ShuffleVectorInst *SVI = Shuffles[i]; 7702 unsigned Index = Indices[i]; 7703 7704 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7705 7706 // Convert the integer vector to pointer vector if the element is pointer. 7707 if (EltTy->isPointerTy()) 7708 SubVec = Builder.CreateIntToPtr( 7709 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 7710 VecTy->getVectorNumElements())); 7711 SubVecs[SVI].push_back(SubVec); 7712 } 7713 } 7714 7715 // Replace uses of the shufflevector instructions with the sub-vectors 7716 // returned by the load intrinsic. If a shufflevector instruction is 7717 // associated with more than one sub-vector, those sub-vectors will be 7718 // concatenated into a single wide vector. 7719 for (ShuffleVectorInst *SVI : Shuffles) { 7720 auto &SubVec = SubVecs[SVI]; 7721 auto *WideVec = 7722 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 7723 SVI->replaceAllUsesWith(WideVec); 7724 } 7725 7726 return true; 7727 } 7728 7729 /// \brief Lower an interleaved store into a stN intrinsic. 7730 /// 7731 /// E.g. Lower an interleaved store (Factor = 3): 7732 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7733 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7734 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7735 /// 7736 /// Into: 7737 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7738 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7739 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7740 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7741 /// 7742 /// Note that the new shufflevectors will be removed and we'll only generate one 7743 /// st3 instruction in CodeGen. 7744 /// 7745 /// Example for a more general valid mask (Factor 3). Lower: 7746 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 7747 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 7748 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7749 /// 7750 /// Into: 7751 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 7752 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 7753 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 7754 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7755 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7756 ShuffleVectorInst *SVI, 7757 unsigned Factor) const { 7758 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7759 "Invalid interleave factor"); 7760 7761 VectorType *VecTy = SVI->getType(); 7762 assert(VecTy->getVectorNumElements() % Factor == 0 && 7763 "Invalid interleaved store"); 7764 7765 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 7766 Type *EltTy = VecTy->getVectorElementType(); 7767 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 7768 7769 const DataLayout &DL = SI->getModule()->getDataLayout(); 7770 7771 // Skip if we do not have NEON and skip illegal vector types. We can 7772 // "legalize" wide vector types into multiple interleaved accesses as long as 7773 // the vector types are divisible by 128. 7774 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 7775 return false; 7776 7777 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 7778 7779 Value *Op0 = SVI->getOperand(0); 7780 Value *Op1 = SVI->getOperand(1); 7781 IRBuilder<> Builder(SI); 7782 7783 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7784 // vectors to integer vectors. 7785 if (EltTy->isPointerTy()) { 7786 Type *IntTy = DL.getIntPtrType(EltTy); 7787 unsigned NumOpElts = 7788 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7789 7790 // Convert to the corresponding integer vector. 7791 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7792 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7793 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7794 7795 SubVecTy = VectorType::get(IntTy, LaneLen); 7796 } 7797 7798 // The base address of the store. 7799 Value *BaseAddr = SI->getPointerOperand(); 7800 7801 if (NumStores > 1) { 7802 // If we're going to generate more than one store, reset the lane length 7803 // and sub-vector type to something legal. 7804 LaneLen /= NumStores; 7805 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 7806 7807 // We will compute the pointer operand of each store from the original base 7808 // address using GEPs. Cast the base address to a pointer to the scalar 7809 // element type. 7810 BaseAddr = Builder.CreateBitCast( 7811 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 7812 SI->getPointerAddressSpace())); 7813 } 7814 7815 auto Mask = SVI->getShuffleMask(); 7816 7817 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7818 Type *Tys[2] = {SubVecTy, PtrTy}; 7819 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7820 Intrinsic::aarch64_neon_st3, 7821 Intrinsic::aarch64_neon_st4}; 7822 Function *StNFunc = 7823 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7824 7825 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 7826 7827 SmallVector<Value *, 5> Ops; 7828 7829 // Split the shufflevector operands into sub vectors for the new stN call. 7830 for (unsigned i = 0; i < Factor; i++) { 7831 unsigned IdxI = StoreCount * LaneLen * Factor + i; 7832 if (Mask[IdxI] >= 0) { 7833 Ops.push_back(Builder.CreateShuffleVector( 7834 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 7835 } else { 7836 unsigned StartMask = 0; 7837 for (unsigned j = 1; j < LaneLen; j++) { 7838 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 7839 if (Mask[IdxJ * Factor + IdxI] >= 0) { 7840 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 7841 break; 7842 } 7843 } 7844 // Note: Filling undef gaps with random elements is ok, since 7845 // those elements were being written anyway (with undefs). 7846 // In the case of all undefs we're defaulting to using elems from 0 7847 // Note: StartMask cannot be negative, it's checked in 7848 // isReInterleaveMask 7849 Ops.push_back(Builder.CreateShuffleVector( 7850 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 7851 } 7852 } 7853 7854 // If we generating more than one store, we compute the base address of 7855 // subsequent stores as an offset from the previous. 7856 if (StoreCount > 0) 7857 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 7858 7859 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 7860 Builder.CreateCall(StNFunc, Ops); 7861 } 7862 return true; 7863 } 7864 7865 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7866 unsigned AlignCheck) { 7867 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7868 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7869 } 7870 7871 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7872 unsigned SrcAlign, bool IsMemset, 7873 bool ZeroMemset, 7874 bool MemcpyStrSrc, 7875 MachineFunction &MF) const { 7876 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7877 // instruction to materialize the v2i64 zero and one store (with restrictive 7878 // addressing mode). Just do two i64 store of zero-registers. 7879 bool Fast; 7880 const Function *F = MF.getFunction(); 7881 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7882 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7883 (memOpAlign(SrcAlign, DstAlign, 16) || 7884 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7885 return MVT::f128; 7886 7887 if (Size >= 8 && 7888 (memOpAlign(SrcAlign, DstAlign, 8) || 7889 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7890 return MVT::i64; 7891 7892 if (Size >= 4 && 7893 (memOpAlign(SrcAlign, DstAlign, 4) || 7894 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7895 return MVT::i32; 7896 7897 return MVT::Other; 7898 } 7899 7900 // 12-bit optionally shifted immediates are legal for adds. 7901 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7902 if (Immed == std::numeric_limits<int64_t>::min()) { 7903 DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n"); 7904 return false; 7905 } 7906 // Same encoding for add/sub, just flip the sign. 7907 Immed = std::abs(Immed); 7908 bool IsLegal = ((Immed >> 12) == 0 || 7909 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7910 DEBUG(dbgs() << "Is " << Immed << " legal add imm: " << 7911 (IsLegal ? "yes" : "no") << "\n"); 7912 return IsLegal; 7913 } 7914 7915 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7916 // immediates is the same as for an add or a sub. 7917 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7918 return isLegalAddImmediate(Immed); 7919 } 7920 7921 /// isLegalAddressingMode - Return true if the addressing mode represented 7922 /// by AM is legal for this target, for a load/store of the specified type. 7923 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7924 const AddrMode &AM, Type *Ty, 7925 unsigned AS, Instruction *I) const { 7926 // AArch64 has five basic addressing modes: 7927 // reg 7928 // reg + 9-bit signed offset 7929 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7930 // reg1 + reg2 7931 // reg + SIZE_IN_BYTES * reg 7932 7933 // No global is ever allowed as a base. 7934 if (AM.BaseGV) 7935 return false; 7936 7937 // No reg+reg+imm addressing. 7938 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7939 return false; 7940 7941 // check reg + imm case: 7942 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7943 uint64_t NumBytes = 0; 7944 if (Ty->isSized()) { 7945 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7946 NumBytes = NumBits / 8; 7947 if (!isPowerOf2_64(NumBits)) 7948 NumBytes = 0; 7949 } 7950 7951 if (!AM.Scale) { 7952 int64_t Offset = AM.BaseOffs; 7953 7954 // 9-bit signed offset 7955 if (isInt<9>(Offset)) 7956 return true; 7957 7958 // 12-bit unsigned offset 7959 unsigned shift = Log2_64(NumBytes); 7960 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 7961 // Must be a multiple of NumBytes (NumBytes is a power of 2) 7962 (Offset >> shift) << shift == Offset) 7963 return true; 7964 return false; 7965 } 7966 7967 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 7968 7969 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 7970 } 7971 7972 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 7973 const AddrMode &AM, Type *Ty, 7974 unsigned AS) const { 7975 // Scaling factors are not free at all. 7976 // Operands | Rt Latency 7977 // ------------------------------------------- 7978 // Rt, [Xn, Xm] | 4 7979 // ------------------------------------------- 7980 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 7981 // Rt, [Xn, Wm, <extend> #imm] | 7982 if (isLegalAddressingMode(DL, AM, Ty, AS)) 7983 // Scale represents reg2 * scale, thus account for 1 if 7984 // it is not equal to 0 or 1. 7985 return AM.Scale != 0 && AM.Scale != 1; 7986 return -1; 7987 } 7988 7989 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7990 VT = VT.getScalarType(); 7991 7992 if (!VT.isSimple()) 7993 return false; 7994 7995 switch (VT.getSimpleVT().SimpleTy) { 7996 case MVT::f32: 7997 case MVT::f64: 7998 return true; 7999 default: 8000 break; 8001 } 8002 8003 return false; 8004 } 8005 8006 const MCPhysReg * 8007 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 8008 // LR is a callee-save register, but we must treat it as clobbered by any call 8009 // site. Hence we include LR in the scratch registers, which are in turn added 8010 // as implicit-defs for stackmaps and patchpoints. 8011 static const MCPhysReg ScratchRegs[] = { 8012 AArch64::X16, AArch64::X17, AArch64::LR, 0 8013 }; 8014 return ScratchRegs; 8015 } 8016 8017 bool 8018 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 8019 EVT VT = N->getValueType(0); 8020 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 8021 // it with shift to let it be lowered to UBFX. 8022 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 8023 isa<ConstantSDNode>(N->getOperand(1))) { 8024 uint64_t TruncMask = N->getConstantOperandVal(1); 8025 if (isMask_64(TruncMask) && 8026 N->getOperand(0).getOpcode() == ISD::SRL && 8027 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 8028 return false; 8029 } 8030 return true; 8031 } 8032 8033 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 8034 Type *Ty) const { 8035 assert(Ty->isIntegerTy()); 8036 8037 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 8038 if (BitSize == 0) 8039 return false; 8040 8041 int64_t Val = Imm.getSExtValue(); 8042 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 8043 return true; 8044 8045 if ((int64_t)Val < 0) 8046 Val = ~Val; 8047 if (BitSize == 32) 8048 Val &= (1LL << 32) - 1; 8049 8050 unsigned LZ = countLeadingZeros((uint64_t)Val); 8051 unsigned Shift = (63 - LZ) / 16; 8052 // MOVZ is free so return true for one or fewer MOVK. 8053 return Shift < 3; 8054 } 8055 8056 /// Turn vector tests of the signbit in the form of: 8057 /// xor (sra X, elt_size(X)-1), -1 8058 /// into: 8059 /// cmge X, X, #0 8060 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 8061 const AArch64Subtarget *Subtarget) { 8062 EVT VT = N->getValueType(0); 8063 if (!Subtarget->hasNEON() || !VT.isVector()) 8064 return SDValue(); 8065 8066 // There must be a shift right algebraic before the xor, and the xor must be a 8067 // 'not' operation. 8068 SDValue Shift = N->getOperand(0); 8069 SDValue Ones = N->getOperand(1); 8070 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 8071 !ISD::isBuildVectorAllOnes(Ones.getNode())) 8072 return SDValue(); 8073 8074 // The shift should be smearing the sign bit across each vector element. 8075 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 8076 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 8077 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 8078 return SDValue(); 8079 8080 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 8081 } 8082 8083 // Generate SUBS and CSEL for integer abs. 8084 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 8085 EVT VT = N->getValueType(0); 8086 8087 SDValue N0 = N->getOperand(0); 8088 SDValue N1 = N->getOperand(1); 8089 SDLoc DL(N); 8090 8091 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 8092 // and change it to SUB and CSEL. 8093 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 8094 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 8095 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 8096 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 8097 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 8098 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 8099 N0.getOperand(0)); 8100 // Generate SUBS & CSEL. 8101 SDValue Cmp = 8102 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 8103 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 8104 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 8105 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 8106 SDValue(Cmp.getNode(), 1)); 8107 } 8108 return SDValue(); 8109 } 8110 8111 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 8112 TargetLowering::DAGCombinerInfo &DCI, 8113 const AArch64Subtarget *Subtarget) { 8114 if (DCI.isBeforeLegalizeOps()) 8115 return SDValue(); 8116 8117 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 8118 return Cmp; 8119 8120 return performIntegerAbsCombine(N, DAG); 8121 } 8122 8123 SDValue 8124 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8125 SelectionDAG &DAG, 8126 std::vector<SDNode *> *Created) const { 8127 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 8128 if (isIntDivCheap(N->getValueType(0), Attr)) 8129 return SDValue(N,0); // Lower SDIV as SDIV 8130 8131 // fold (sdiv X, pow2) 8132 EVT VT = N->getValueType(0); 8133 if ((VT != MVT::i32 && VT != MVT::i64) || 8134 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 8135 return SDValue(); 8136 8137 SDLoc DL(N); 8138 SDValue N0 = N->getOperand(0); 8139 unsigned Lg2 = Divisor.countTrailingZeros(); 8140 SDValue Zero = DAG.getConstant(0, DL, VT); 8141 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 8142 8143 // Add (N0 < 0) ? Pow2 - 1 : 0; 8144 SDValue CCVal; 8145 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 8146 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 8147 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 8148 8149 if (Created) { 8150 Created->push_back(Cmp.getNode()); 8151 Created->push_back(Add.getNode()); 8152 Created->push_back(CSel.getNode()); 8153 } 8154 8155 // Divide by pow2. 8156 SDValue SRA = 8157 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 8158 8159 // If we're dividing by a positive value, we're done. Otherwise, we must 8160 // negate the result. 8161 if (Divisor.isNonNegative()) 8162 return SRA; 8163 8164 if (Created) 8165 Created->push_back(SRA.getNode()); 8166 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 8167 } 8168 8169 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 8170 TargetLowering::DAGCombinerInfo &DCI, 8171 const AArch64Subtarget *Subtarget) { 8172 if (DCI.isBeforeLegalizeOps()) 8173 return SDValue(); 8174 8175 // The below optimizations require a constant RHS. 8176 if (!isa<ConstantSDNode>(N->getOperand(1))) 8177 return SDValue(); 8178 8179 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 8180 const APInt &ConstValue = C->getAPIntValue(); 8181 8182 // Multiplication of a power of two plus/minus one can be done more 8183 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 8184 // future CPUs have a cheaper MADD instruction, this may need to be 8185 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 8186 // 64-bit is 5 cycles, so this is always a win. 8187 // More aggressively, some multiplications N0 * C can be lowered to 8188 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 8189 // e.g. 6=3*2=(2+1)*2. 8190 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 8191 // which equals to (1+2)*16-(1+2). 8192 SDValue N0 = N->getOperand(0); 8193 // TrailingZeroes is used to test if the mul can be lowered to 8194 // shift+add+shift. 8195 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 8196 if (TrailingZeroes) { 8197 // Conservatively do not lower to shift+add+shift if the mul might be 8198 // folded into smul or umul. 8199 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 8200 isZeroExtended(N0.getNode(), DAG))) 8201 return SDValue(); 8202 // Conservatively do not lower to shift+add+shift if the mul might be 8203 // folded into madd or msub. 8204 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 8205 N->use_begin()->getOpcode() == ISD::SUB)) 8206 return SDValue(); 8207 } 8208 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 8209 // and shift+add+shift. 8210 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 8211 8212 unsigned ShiftAmt, AddSubOpc; 8213 // Is the shifted value the LHS operand of the add/sub? 8214 bool ShiftValUseIsN0 = true; 8215 // Do we need to negate the result? 8216 bool NegateResult = false; 8217 8218 if (ConstValue.isNonNegative()) { 8219 // (mul x, 2^N + 1) => (add (shl x, N), x) 8220 // (mul x, 2^N - 1) => (sub (shl x, N), x) 8221 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 8222 APInt SCVMinus1 = ShiftedConstValue - 1; 8223 APInt CVPlus1 = ConstValue + 1; 8224 if (SCVMinus1.isPowerOf2()) { 8225 ShiftAmt = SCVMinus1.logBase2(); 8226 AddSubOpc = ISD::ADD; 8227 } else if (CVPlus1.isPowerOf2()) { 8228 ShiftAmt = CVPlus1.logBase2(); 8229 AddSubOpc = ISD::SUB; 8230 } else 8231 return SDValue(); 8232 } else { 8233 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 8234 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 8235 APInt CVNegPlus1 = -ConstValue + 1; 8236 APInt CVNegMinus1 = -ConstValue - 1; 8237 if (CVNegPlus1.isPowerOf2()) { 8238 ShiftAmt = CVNegPlus1.logBase2(); 8239 AddSubOpc = ISD::SUB; 8240 ShiftValUseIsN0 = false; 8241 } else if (CVNegMinus1.isPowerOf2()) { 8242 ShiftAmt = CVNegMinus1.logBase2(); 8243 AddSubOpc = ISD::ADD; 8244 NegateResult = true; 8245 } else 8246 return SDValue(); 8247 } 8248 8249 SDLoc DL(N); 8250 EVT VT = N->getValueType(0); 8251 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 8252 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 8253 8254 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 8255 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 8256 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 8257 assert(!(NegateResult && TrailingZeroes) && 8258 "NegateResult and TrailingZeroes cannot both be true for now."); 8259 // Negate the result. 8260 if (NegateResult) 8261 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 8262 // Shift the result. 8263 if (TrailingZeroes) 8264 return DAG.getNode(ISD::SHL, DL, VT, Res, 8265 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 8266 return Res; 8267 } 8268 8269 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 8270 SelectionDAG &DAG) { 8271 // Take advantage of vector comparisons producing 0 or -1 in each lane to 8272 // optimize away operation when it's from a constant. 8273 // 8274 // The general transformation is: 8275 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 8276 // AND(VECTOR_CMP(x,y), constant2) 8277 // constant2 = UNARYOP(constant) 8278 8279 // Early exit if this isn't a vector operation, the operand of the 8280 // unary operation isn't a bitwise AND, or if the sizes of the operations 8281 // aren't the same. 8282 EVT VT = N->getValueType(0); 8283 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 8284 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 8285 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 8286 return SDValue(); 8287 8288 // Now check that the other operand of the AND is a constant. We could 8289 // make the transformation for non-constant splats as well, but it's unclear 8290 // that would be a benefit as it would not eliminate any operations, just 8291 // perform one more step in scalar code before moving to the vector unit. 8292 if (BuildVectorSDNode *BV = 8293 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 8294 // Bail out if the vector isn't a constant. 8295 if (!BV->isConstant()) 8296 return SDValue(); 8297 8298 // Everything checks out. Build up the new and improved node. 8299 SDLoc DL(N); 8300 EVT IntVT = BV->getValueType(0); 8301 // Create a new constant of the appropriate type for the transformed 8302 // DAG. 8303 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 8304 // The AND node needs bitcasts to/from an integer vector type around it. 8305 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 8306 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 8307 N->getOperand(0)->getOperand(0), MaskConst); 8308 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 8309 return Res; 8310 } 8311 8312 return SDValue(); 8313 } 8314 8315 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 8316 const AArch64Subtarget *Subtarget) { 8317 // First try to optimize away the conversion when it's conditionally from 8318 // a constant. Vectors only. 8319 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 8320 return Res; 8321 8322 EVT VT = N->getValueType(0); 8323 if (VT != MVT::f32 && VT != MVT::f64) 8324 return SDValue(); 8325 8326 // Only optimize when the source and destination types have the same width. 8327 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 8328 return SDValue(); 8329 8330 // If the result of an integer load is only used by an integer-to-float 8331 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 8332 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 8333 SDValue N0 = N->getOperand(0); 8334 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8335 // Do not change the width of a volatile load. 8336 !cast<LoadSDNode>(N0)->isVolatile()) { 8337 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8338 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8339 LN0->getPointerInfo(), LN0->getAlignment(), 8340 LN0->getMemOperand()->getFlags()); 8341 8342 // Make sure successors of the original load stay after it by updating them 8343 // to use the new Chain. 8344 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 8345 8346 unsigned Opcode = 8347 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 8348 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 8349 } 8350 8351 return SDValue(); 8352 } 8353 8354 /// Fold a floating-point multiply by power of two into floating-point to 8355 /// fixed-point conversion. 8356 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 8357 TargetLowering::DAGCombinerInfo &DCI, 8358 const AArch64Subtarget *Subtarget) { 8359 if (!Subtarget->hasNEON()) 8360 return SDValue(); 8361 8362 SDValue Op = N->getOperand(0); 8363 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 8364 Op.getOpcode() != ISD::FMUL) 8365 return SDValue(); 8366 8367 SDValue ConstVec = Op->getOperand(1); 8368 if (!isa<BuildVectorSDNode>(ConstVec)) 8369 return SDValue(); 8370 8371 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 8372 uint32_t FloatBits = FloatTy.getSizeInBits(); 8373 if (FloatBits != 32 && FloatBits != 64) 8374 return SDValue(); 8375 8376 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 8377 uint32_t IntBits = IntTy.getSizeInBits(); 8378 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 8379 return SDValue(); 8380 8381 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 8382 if (IntBits > FloatBits) 8383 return SDValue(); 8384 8385 BitVector UndefElements; 8386 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 8387 int32_t Bits = IntBits == 64 ? 64 : 32; 8388 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 8389 if (C == -1 || C == 0 || C > Bits) 8390 return SDValue(); 8391 8392 MVT ResTy; 8393 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8394 switch (NumLanes) { 8395 default: 8396 return SDValue(); 8397 case 2: 8398 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 8399 break; 8400 case 4: 8401 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 8402 break; 8403 } 8404 8405 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 8406 return SDValue(); 8407 8408 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 8409 "Illegal vector type after legalization"); 8410 8411 SDLoc DL(N); 8412 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8413 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 8414 : Intrinsic::aarch64_neon_vcvtfp2fxu; 8415 SDValue FixConv = 8416 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 8417 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 8418 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 8419 // We can handle smaller integers by generating an extra trunc. 8420 if (IntBits < FloatBits) 8421 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 8422 8423 return FixConv; 8424 } 8425 8426 /// Fold a floating-point divide by power of two into fixed-point to 8427 /// floating-point conversion. 8428 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 8429 TargetLowering::DAGCombinerInfo &DCI, 8430 const AArch64Subtarget *Subtarget) { 8431 if (!Subtarget->hasNEON()) 8432 return SDValue(); 8433 8434 SDValue Op = N->getOperand(0); 8435 unsigned Opc = Op->getOpcode(); 8436 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 8437 !Op.getOperand(0).getValueType().isSimple() || 8438 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 8439 return SDValue(); 8440 8441 SDValue ConstVec = N->getOperand(1); 8442 if (!isa<BuildVectorSDNode>(ConstVec)) 8443 return SDValue(); 8444 8445 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 8446 int32_t IntBits = IntTy.getSizeInBits(); 8447 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 8448 return SDValue(); 8449 8450 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 8451 int32_t FloatBits = FloatTy.getSizeInBits(); 8452 if (FloatBits != 32 && FloatBits != 64) 8453 return SDValue(); 8454 8455 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 8456 if (IntBits > FloatBits) 8457 return SDValue(); 8458 8459 BitVector UndefElements; 8460 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 8461 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 8462 if (C == -1 || C == 0 || C > FloatBits) 8463 return SDValue(); 8464 8465 MVT ResTy; 8466 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8467 switch (NumLanes) { 8468 default: 8469 return SDValue(); 8470 case 2: 8471 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 8472 break; 8473 case 4: 8474 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 8475 break; 8476 } 8477 8478 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 8479 return SDValue(); 8480 8481 SDLoc DL(N); 8482 SDValue ConvInput = Op.getOperand(0); 8483 bool IsSigned = Opc == ISD::SINT_TO_FP; 8484 if (IntBits < FloatBits) 8485 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 8486 ResTy, ConvInput); 8487 8488 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 8489 : Intrinsic::aarch64_neon_vcvtfxu2fp; 8490 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 8491 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 8492 DAG.getConstant(C, DL, MVT::i32)); 8493 } 8494 8495 /// An EXTR instruction is made up of two shifts, ORed together. This helper 8496 /// searches for and classifies those shifts. 8497 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 8498 bool &FromHi) { 8499 if (N.getOpcode() == ISD::SHL) 8500 FromHi = false; 8501 else if (N.getOpcode() == ISD::SRL) 8502 FromHi = true; 8503 else 8504 return false; 8505 8506 if (!isa<ConstantSDNode>(N.getOperand(1))) 8507 return false; 8508 8509 ShiftAmount = N->getConstantOperandVal(1); 8510 Src = N->getOperand(0); 8511 return true; 8512 } 8513 8514 /// EXTR instruction extracts a contiguous chunk of bits from two existing 8515 /// registers viewed as a high/low pair. This function looks for the pattern: 8516 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 8517 /// with an EXTR. Can't quite be done in TableGen because the two immediates 8518 /// aren't independent. 8519 static SDValue tryCombineToEXTR(SDNode *N, 8520 TargetLowering::DAGCombinerInfo &DCI) { 8521 SelectionDAG &DAG = DCI.DAG; 8522 SDLoc DL(N); 8523 EVT VT = N->getValueType(0); 8524 8525 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 8526 8527 if (VT != MVT::i32 && VT != MVT::i64) 8528 return SDValue(); 8529 8530 SDValue LHS; 8531 uint32_t ShiftLHS = 0; 8532 bool LHSFromHi = false; 8533 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 8534 return SDValue(); 8535 8536 SDValue RHS; 8537 uint32_t ShiftRHS = 0; 8538 bool RHSFromHi = false; 8539 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 8540 return SDValue(); 8541 8542 // If they're both trying to come from the high part of the register, they're 8543 // not really an EXTR. 8544 if (LHSFromHi == RHSFromHi) 8545 return SDValue(); 8546 8547 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 8548 return SDValue(); 8549 8550 if (LHSFromHi) { 8551 std::swap(LHS, RHS); 8552 std::swap(ShiftLHS, ShiftRHS); 8553 } 8554 8555 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 8556 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 8557 } 8558 8559 static SDValue tryCombineToBSL(SDNode *N, 8560 TargetLowering::DAGCombinerInfo &DCI) { 8561 EVT VT = N->getValueType(0); 8562 SelectionDAG &DAG = DCI.DAG; 8563 SDLoc DL(N); 8564 8565 if (!VT.isVector()) 8566 return SDValue(); 8567 8568 SDValue N0 = N->getOperand(0); 8569 if (N0.getOpcode() != ISD::AND) 8570 return SDValue(); 8571 8572 SDValue N1 = N->getOperand(1); 8573 if (N1.getOpcode() != ISD::AND) 8574 return SDValue(); 8575 8576 // We only have to look for constant vectors here since the general, variable 8577 // case can be handled in TableGen. 8578 unsigned Bits = VT.getScalarSizeInBits(); 8579 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 8580 for (int i = 1; i >= 0; --i) 8581 for (int j = 1; j >= 0; --j) { 8582 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 8583 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 8584 if (!BVN0 || !BVN1) 8585 continue; 8586 8587 bool FoundMatch = true; 8588 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 8589 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 8590 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 8591 if (!CN0 || !CN1 || 8592 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 8593 FoundMatch = false; 8594 break; 8595 } 8596 } 8597 8598 if (FoundMatch) 8599 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 8600 N0->getOperand(1 - i), N1->getOperand(1 - j)); 8601 } 8602 8603 return SDValue(); 8604 } 8605 8606 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8607 const AArch64Subtarget *Subtarget) { 8608 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 8609 SelectionDAG &DAG = DCI.DAG; 8610 EVT VT = N->getValueType(0); 8611 8612 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8613 return SDValue(); 8614 8615 if (SDValue Res = tryCombineToEXTR(N, DCI)) 8616 return Res; 8617 8618 if (SDValue Res = tryCombineToBSL(N, DCI)) 8619 return Res; 8620 8621 return SDValue(); 8622 } 8623 8624 static SDValue performSRLCombine(SDNode *N, 8625 TargetLowering::DAGCombinerInfo &DCI) { 8626 SelectionDAG &DAG = DCI.DAG; 8627 EVT VT = N->getValueType(0); 8628 if (VT != MVT::i32 && VT != MVT::i64) 8629 return SDValue(); 8630 8631 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 8632 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 8633 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 8634 SDValue N0 = N->getOperand(0); 8635 if (N0.getOpcode() == ISD::BSWAP) { 8636 SDLoc DL(N); 8637 SDValue N1 = N->getOperand(1); 8638 SDValue N00 = N0.getOperand(0); 8639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 8640 uint64_t ShiftAmt = C->getZExtValue(); 8641 if (VT == MVT::i32 && ShiftAmt == 16 && 8642 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 8643 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8644 if (VT == MVT::i64 && ShiftAmt == 32 && 8645 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 8646 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8647 } 8648 } 8649 return SDValue(); 8650 } 8651 8652 static SDValue performBitcastCombine(SDNode *N, 8653 TargetLowering::DAGCombinerInfo &DCI, 8654 SelectionDAG &DAG) { 8655 // Wait 'til after everything is legalized to try this. That way we have 8656 // legal vector types and such. 8657 if (DCI.isBeforeLegalizeOps()) 8658 return SDValue(); 8659 8660 // Remove extraneous bitcasts around an extract_subvector. 8661 // For example, 8662 // (v4i16 (bitconvert 8663 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 8664 // becomes 8665 // (extract_subvector ((v8i16 ...), (i64 4))) 8666 8667 // Only interested in 64-bit vectors as the ultimate result. 8668 EVT VT = N->getValueType(0); 8669 if (!VT.isVector()) 8670 return SDValue(); 8671 if (VT.getSimpleVT().getSizeInBits() != 64) 8672 return SDValue(); 8673 // Is the operand an extract_subvector starting at the beginning or halfway 8674 // point of the vector? A low half may also come through as an 8675 // EXTRACT_SUBREG, so look for that, too. 8676 SDValue Op0 = N->getOperand(0); 8677 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 8678 !(Op0->isMachineOpcode() && 8679 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 8680 return SDValue(); 8681 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 8682 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8683 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 8684 return SDValue(); 8685 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 8686 if (idx != AArch64::dsub) 8687 return SDValue(); 8688 // The dsub reference is equivalent to a lane zero subvector reference. 8689 idx = 0; 8690 } 8691 // Look through the bitcast of the input to the extract. 8692 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 8693 return SDValue(); 8694 SDValue Source = Op0->getOperand(0)->getOperand(0); 8695 // If the source type has twice the number of elements as our destination 8696 // type, we know this is an extract of the high or low half of the vector. 8697 EVT SVT = Source->getValueType(0); 8698 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 8699 return SDValue(); 8700 8701 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 8702 8703 // Create the simplified form to just extract the low or high half of the 8704 // vector directly rather than bothering with the bitcasts. 8705 SDLoc dl(N); 8706 unsigned NumElements = VT.getVectorNumElements(); 8707 if (idx) { 8708 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8709 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8710 } else { 8711 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8712 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8713 Source, SubReg), 8714 0); 8715 } 8716 } 8717 8718 static SDValue performConcatVectorsCombine(SDNode *N, 8719 TargetLowering::DAGCombinerInfo &DCI, 8720 SelectionDAG &DAG) { 8721 SDLoc dl(N); 8722 EVT VT = N->getValueType(0); 8723 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8724 8725 // Optimize concat_vectors of truncated vectors, where the intermediate 8726 // type is illegal, to avoid said illegality, e.g., 8727 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8728 // (v2i16 (truncate (v2i64))))) 8729 // -> 8730 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8731 // (v4i32 (bitcast (v2i64))), 8732 // <0, 2, 4, 6>))) 8733 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8734 // on both input and result type, so we might generate worse code. 8735 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8736 if (N->getNumOperands() == 2 && 8737 N0->getOpcode() == ISD::TRUNCATE && 8738 N1->getOpcode() == ISD::TRUNCATE) { 8739 SDValue N00 = N0->getOperand(0); 8740 SDValue N10 = N1->getOperand(0); 8741 EVT N00VT = N00.getValueType(); 8742 8743 if (N00VT == N10.getValueType() && 8744 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8745 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8746 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8747 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8748 for (size_t i = 0; i < Mask.size(); ++i) 8749 Mask[i] = i * 2; 8750 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8751 DAG.getVectorShuffle( 8752 MidVT, dl, 8753 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8754 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8755 } 8756 } 8757 8758 // Wait 'til after everything is legalized to try this. That way we have 8759 // legal vector types and such. 8760 if (DCI.isBeforeLegalizeOps()) 8761 return SDValue(); 8762 8763 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8764 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8765 // canonicalise to that. 8766 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8767 assert(VT.getScalarSizeInBits() == 64); 8768 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8769 DAG.getConstant(0, dl, MVT::i64)); 8770 } 8771 8772 // Canonicalise concat_vectors so that the right-hand vector has as few 8773 // bit-casts as possible before its real operation. The primary matching 8774 // destination for these operations will be the narrowing "2" instructions, 8775 // which depend on the operation being performed on this right-hand vector. 8776 // For example, 8777 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8778 // becomes 8779 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8780 8781 if (N1->getOpcode() != ISD::BITCAST) 8782 return SDValue(); 8783 SDValue RHS = N1->getOperand(0); 8784 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8785 // If the RHS is not a vector, this is not the pattern we're looking for. 8786 if (!RHSTy.isVector()) 8787 return SDValue(); 8788 8789 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8790 8791 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8792 RHSTy.getVectorNumElements() * 2); 8793 return DAG.getNode(ISD::BITCAST, dl, VT, 8794 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8795 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8796 RHS)); 8797 } 8798 8799 static SDValue tryCombineFixedPointConvert(SDNode *N, 8800 TargetLowering::DAGCombinerInfo &DCI, 8801 SelectionDAG &DAG) { 8802 // Wait 'til after everything is legalized to try this. That way we have 8803 // legal vector types and such. 8804 if (DCI.isBeforeLegalizeOps()) 8805 return SDValue(); 8806 // Transform a scalar conversion of a value from a lane extract into a 8807 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8808 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8809 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8810 // 8811 // The second form interacts better with instruction selection and the 8812 // register allocator to avoid cross-class register copies that aren't 8813 // coalescable due to a lane reference. 8814 8815 // Check the operand and see if it originates from a lane extract. 8816 SDValue Op1 = N->getOperand(1); 8817 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8818 // Yep, no additional predication needed. Perform the transform. 8819 SDValue IID = N->getOperand(0); 8820 SDValue Shift = N->getOperand(2); 8821 SDValue Vec = Op1.getOperand(0); 8822 SDValue Lane = Op1.getOperand(1); 8823 EVT ResTy = N->getValueType(0); 8824 EVT VecResTy; 8825 SDLoc DL(N); 8826 8827 // The vector width should be 128 bits by the time we get here, even 8828 // if it started as 64 bits (the extract_vector handling will have 8829 // done so). 8830 assert(Vec.getValueSizeInBits() == 128 && 8831 "unexpected vector size on extract_vector_elt!"); 8832 if (Vec.getValueType() == MVT::v4i32) 8833 VecResTy = MVT::v4f32; 8834 else if (Vec.getValueType() == MVT::v2i64) 8835 VecResTy = MVT::v2f64; 8836 else 8837 llvm_unreachable("unexpected vector type!"); 8838 8839 SDValue Convert = 8840 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8841 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8842 } 8843 return SDValue(); 8844 } 8845 8846 // AArch64 high-vector "long" operations are formed by performing the non-high 8847 // version on an extract_subvector of each operand which gets the high half: 8848 // 8849 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8850 // 8851 // However, there are cases which don't have an extract_high explicitly, but 8852 // have another operation that can be made compatible with one for free. For 8853 // example: 8854 // 8855 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8856 // 8857 // This routine does the actual conversion of such DUPs, once outer routines 8858 // have determined that everything else is in order. 8859 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8860 // similarly here. 8861 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8862 switch (N.getOpcode()) { 8863 case AArch64ISD::DUP: 8864 case AArch64ISD::DUPLANE8: 8865 case AArch64ISD::DUPLANE16: 8866 case AArch64ISD::DUPLANE32: 8867 case AArch64ISD::DUPLANE64: 8868 case AArch64ISD::MOVI: 8869 case AArch64ISD::MOVIshift: 8870 case AArch64ISD::MOVIedit: 8871 case AArch64ISD::MOVImsl: 8872 case AArch64ISD::MVNIshift: 8873 case AArch64ISD::MVNImsl: 8874 break; 8875 default: 8876 // FMOV could be supported, but isn't very useful, as it would only occur 8877 // if you passed a bitcast' floating point immediate to an eligible long 8878 // integer op (addl, smull, ...). 8879 return SDValue(); 8880 } 8881 8882 MVT NarrowTy = N.getSimpleValueType(); 8883 if (!NarrowTy.is64BitVector()) 8884 return SDValue(); 8885 8886 MVT ElementTy = NarrowTy.getVectorElementType(); 8887 unsigned NumElems = NarrowTy.getVectorNumElements(); 8888 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8889 8890 SDLoc dl(N); 8891 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8892 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8893 DAG.getConstant(NumElems, dl, MVT::i64)); 8894 } 8895 8896 static bool isEssentiallyExtractSubvector(SDValue N) { 8897 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8898 return true; 8899 8900 return N.getOpcode() == ISD::BITCAST && 8901 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8902 } 8903 8904 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8905 struct GenericSetCCInfo { 8906 const SDValue *Opnd0; 8907 const SDValue *Opnd1; 8908 ISD::CondCode CC; 8909 }; 8910 8911 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8912 struct AArch64SetCCInfo { 8913 const SDValue *Cmp; 8914 AArch64CC::CondCode CC; 8915 }; 8916 8917 /// \brief Helper structure to keep track of SetCC information. 8918 union SetCCInfo { 8919 GenericSetCCInfo Generic; 8920 AArch64SetCCInfo AArch64; 8921 }; 8922 8923 /// \brief Helper structure to be able to read SetCC information. If set to 8924 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8925 /// GenericSetCCInfo. 8926 struct SetCCInfoAndKind { 8927 SetCCInfo Info; 8928 bool IsAArch64; 8929 }; 8930 8931 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8932 /// an 8933 /// AArch64 lowered one. 8934 /// \p SetCCInfo is filled accordingly. 8935 /// \post SetCCInfo is meanginfull only when this function returns true. 8936 /// \return True when Op is a kind of SET_CC operation. 8937 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8938 // If this is a setcc, this is straight forward. 8939 if (Op.getOpcode() == ISD::SETCC) { 8940 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8941 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8942 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8943 SetCCInfo.IsAArch64 = false; 8944 return true; 8945 } 8946 // Otherwise, check if this is a matching csel instruction. 8947 // In other words: 8948 // - csel 1, 0, cc 8949 // - csel 0, 1, !cc 8950 if (Op.getOpcode() != AArch64ISD::CSEL) 8951 return false; 8952 // Set the information about the operands. 8953 // TODO: we want the operands of the Cmp not the csel 8954 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8955 SetCCInfo.IsAArch64 = true; 8956 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8957 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8958 8959 // Check that the operands matches the constraints: 8960 // (1) Both operands must be constants. 8961 // (2) One must be 1 and the other must be 0. 8962 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 8963 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8964 8965 // Check (1). 8966 if (!TValue || !FValue) 8967 return false; 8968 8969 // Check (2). 8970 if (!TValue->isOne()) { 8971 // Update the comparison when we are interested in !cc. 8972 std::swap(TValue, FValue); 8973 SetCCInfo.Info.AArch64.CC = 8974 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 8975 } 8976 return TValue->isOne() && FValue->isNullValue(); 8977 } 8978 8979 // Returns true if Op is setcc or zext of setcc. 8980 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 8981 if (isSetCC(Op, Info)) 8982 return true; 8983 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 8984 isSetCC(Op->getOperand(0), Info)); 8985 } 8986 8987 // The folding we want to perform is: 8988 // (add x, [zext] (setcc cc ...) ) 8989 // --> 8990 // (csel x, (add x, 1), !cc ...) 8991 // 8992 // The latter will get matched to a CSINC instruction. 8993 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 8994 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 8995 SDValue LHS = Op->getOperand(0); 8996 SDValue RHS = Op->getOperand(1); 8997 SetCCInfoAndKind InfoAndKind; 8998 8999 // If neither operand is a SET_CC, give up. 9000 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 9001 std::swap(LHS, RHS); 9002 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 9003 return SDValue(); 9004 } 9005 9006 // FIXME: This could be generatized to work for FP comparisons. 9007 EVT CmpVT = InfoAndKind.IsAArch64 9008 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 9009 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 9010 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 9011 return SDValue(); 9012 9013 SDValue CCVal; 9014 SDValue Cmp; 9015 SDLoc dl(Op); 9016 if (InfoAndKind.IsAArch64) { 9017 CCVal = DAG.getConstant( 9018 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 9019 MVT::i32); 9020 Cmp = *InfoAndKind.Info.AArch64.Cmp; 9021 } else 9022 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 9023 *InfoAndKind.Info.Generic.Opnd1, 9024 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 9025 CCVal, DAG, dl); 9026 9027 EVT VT = Op->getValueType(0); 9028 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 9029 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 9030 } 9031 9032 // The basic add/sub long vector instructions have variants with "2" on the end 9033 // which act on the high-half of their inputs. They are normally matched by 9034 // patterns like: 9035 // 9036 // (add (zeroext (extract_high LHS)), 9037 // (zeroext (extract_high RHS))) 9038 // -> uaddl2 vD, vN, vM 9039 // 9040 // However, if one of the extracts is something like a duplicate, this 9041 // instruction can still be used profitably. This function puts the DAG into a 9042 // more appropriate form for those patterns to trigger. 9043 static SDValue performAddSubLongCombine(SDNode *N, 9044 TargetLowering::DAGCombinerInfo &DCI, 9045 SelectionDAG &DAG) { 9046 if (DCI.isBeforeLegalizeOps()) 9047 return SDValue(); 9048 9049 MVT VT = N->getSimpleValueType(0); 9050 if (!VT.is128BitVector()) { 9051 if (N->getOpcode() == ISD::ADD) 9052 return performSetccAddFolding(N, DAG); 9053 return SDValue(); 9054 } 9055 9056 // Make sure both branches are extended in the same way. 9057 SDValue LHS = N->getOperand(0); 9058 SDValue RHS = N->getOperand(1); 9059 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 9060 LHS.getOpcode() != ISD::SIGN_EXTEND) || 9061 LHS.getOpcode() != RHS.getOpcode()) 9062 return SDValue(); 9063 9064 unsigned ExtType = LHS.getOpcode(); 9065 9066 // It's not worth doing if at least one of the inputs isn't already an 9067 // extract, but we don't know which it'll be so we have to try both. 9068 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 9069 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 9070 if (!RHS.getNode()) 9071 return SDValue(); 9072 9073 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 9074 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 9075 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 9076 if (!LHS.getNode()) 9077 return SDValue(); 9078 9079 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 9080 } 9081 9082 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 9083 } 9084 9085 // Massage DAGs which we can use the high-half "long" operations on into 9086 // something isel will recognize better. E.g. 9087 // 9088 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 9089 // (aarch64_neon_umull (extract_high (v2i64 vec))) 9090 // (extract_high (v2i64 (dup128 scalar))))) 9091 // 9092 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 9093 TargetLowering::DAGCombinerInfo &DCI, 9094 SelectionDAG &DAG) { 9095 if (DCI.isBeforeLegalizeOps()) 9096 return SDValue(); 9097 9098 SDValue LHS = N->getOperand(1); 9099 SDValue RHS = N->getOperand(2); 9100 assert(LHS.getValueType().is64BitVector() && 9101 RHS.getValueType().is64BitVector() && 9102 "unexpected shape for long operation"); 9103 9104 // Either node could be a DUP, but it's not worth doing both of them (you'd 9105 // just as well use the non-high version) so look for a corresponding extract 9106 // operation on the other "wing". 9107 if (isEssentiallyExtractSubvector(LHS)) { 9108 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 9109 if (!RHS.getNode()) 9110 return SDValue(); 9111 } else if (isEssentiallyExtractSubvector(RHS)) { 9112 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 9113 if (!LHS.getNode()) 9114 return SDValue(); 9115 } 9116 9117 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 9118 N->getOperand(0), LHS, RHS); 9119 } 9120 9121 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 9122 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 9123 unsigned ElemBits = ElemTy.getSizeInBits(); 9124 9125 int64_t ShiftAmount; 9126 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 9127 APInt SplatValue, SplatUndef; 9128 unsigned SplatBitSize; 9129 bool HasAnyUndefs; 9130 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 9131 HasAnyUndefs, ElemBits) || 9132 SplatBitSize != ElemBits) 9133 return SDValue(); 9134 9135 ShiftAmount = SplatValue.getSExtValue(); 9136 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 9137 ShiftAmount = CVN->getSExtValue(); 9138 } else 9139 return SDValue(); 9140 9141 unsigned Opcode; 9142 bool IsRightShift; 9143 switch (IID) { 9144 default: 9145 llvm_unreachable("Unknown shift intrinsic"); 9146 case Intrinsic::aarch64_neon_sqshl: 9147 Opcode = AArch64ISD::SQSHL_I; 9148 IsRightShift = false; 9149 break; 9150 case Intrinsic::aarch64_neon_uqshl: 9151 Opcode = AArch64ISD::UQSHL_I; 9152 IsRightShift = false; 9153 break; 9154 case Intrinsic::aarch64_neon_srshl: 9155 Opcode = AArch64ISD::SRSHR_I; 9156 IsRightShift = true; 9157 break; 9158 case Intrinsic::aarch64_neon_urshl: 9159 Opcode = AArch64ISD::URSHR_I; 9160 IsRightShift = true; 9161 break; 9162 case Intrinsic::aarch64_neon_sqshlu: 9163 Opcode = AArch64ISD::SQSHLU_I; 9164 IsRightShift = false; 9165 break; 9166 } 9167 9168 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 9169 SDLoc dl(N); 9170 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 9171 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 9172 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 9173 SDLoc dl(N); 9174 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 9175 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 9176 } 9177 9178 return SDValue(); 9179 } 9180 9181 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 9182 // the intrinsics must be legal and take an i32, this means there's almost 9183 // certainly going to be a zext in the DAG which we can eliminate. 9184 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 9185 SDValue AndN = N->getOperand(2); 9186 if (AndN.getOpcode() != ISD::AND) 9187 return SDValue(); 9188 9189 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 9190 if (!CMask || CMask->getZExtValue() != Mask) 9191 return SDValue(); 9192 9193 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 9194 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 9195 } 9196 9197 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 9198 SelectionDAG &DAG) { 9199 SDLoc dl(N); 9200 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 9201 DAG.getNode(Opc, dl, 9202 N->getOperand(1).getSimpleValueType(), 9203 N->getOperand(1)), 9204 DAG.getConstant(0, dl, MVT::i64)); 9205 } 9206 9207 static SDValue performIntrinsicCombine(SDNode *N, 9208 TargetLowering::DAGCombinerInfo &DCI, 9209 const AArch64Subtarget *Subtarget) { 9210 SelectionDAG &DAG = DCI.DAG; 9211 unsigned IID = getIntrinsicID(N); 9212 switch (IID) { 9213 default: 9214 break; 9215 case Intrinsic::aarch64_neon_vcvtfxs2fp: 9216 case Intrinsic::aarch64_neon_vcvtfxu2fp: 9217 return tryCombineFixedPointConvert(N, DCI, DAG); 9218 case Intrinsic::aarch64_neon_saddv: 9219 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 9220 case Intrinsic::aarch64_neon_uaddv: 9221 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 9222 case Intrinsic::aarch64_neon_sminv: 9223 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 9224 case Intrinsic::aarch64_neon_uminv: 9225 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 9226 case Intrinsic::aarch64_neon_smaxv: 9227 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 9228 case Intrinsic::aarch64_neon_umaxv: 9229 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 9230 case Intrinsic::aarch64_neon_fmax: 9231 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 9232 N->getOperand(1), N->getOperand(2)); 9233 case Intrinsic::aarch64_neon_fmin: 9234 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 9235 N->getOperand(1), N->getOperand(2)); 9236 case Intrinsic::aarch64_neon_fmaxnm: 9237 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 9238 N->getOperand(1), N->getOperand(2)); 9239 case Intrinsic::aarch64_neon_fminnm: 9240 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 9241 N->getOperand(1), N->getOperand(2)); 9242 case Intrinsic::aarch64_neon_smull: 9243 case Intrinsic::aarch64_neon_umull: 9244 case Intrinsic::aarch64_neon_pmull: 9245 case Intrinsic::aarch64_neon_sqdmull: 9246 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 9247 case Intrinsic::aarch64_neon_sqshl: 9248 case Intrinsic::aarch64_neon_uqshl: 9249 case Intrinsic::aarch64_neon_sqshlu: 9250 case Intrinsic::aarch64_neon_srshl: 9251 case Intrinsic::aarch64_neon_urshl: 9252 return tryCombineShiftImm(IID, N, DAG); 9253 case Intrinsic::aarch64_crc32b: 9254 case Intrinsic::aarch64_crc32cb: 9255 return tryCombineCRC32(0xff, N, DAG); 9256 case Intrinsic::aarch64_crc32h: 9257 case Intrinsic::aarch64_crc32ch: 9258 return tryCombineCRC32(0xffff, N, DAG); 9259 } 9260 return SDValue(); 9261 } 9262 9263 static SDValue performExtendCombine(SDNode *N, 9264 TargetLowering::DAGCombinerInfo &DCI, 9265 SelectionDAG &DAG) { 9266 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 9267 // we can convert that DUP into another extract_high (of a bigger DUP), which 9268 // helps the backend to decide that an sabdl2 would be useful, saving a real 9269 // extract_high operation. 9270 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 9271 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 9272 SDNode *ABDNode = N->getOperand(0).getNode(); 9273 unsigned IID = getIntrinsicID(ABDNode); 9274 if (IID == Intrinsic::aarch64_neon_sabd || 9275 IID == Intrinsic::aarch64_neon_uabd) { 9276 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 9277 if (!NewABD.getNode()) 9278 return SDValue(); 9279 9280 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 9281 NewABD); 9282 } 9283 } 9284 9285 // This is effectively a custom type legalization for AArch64. 9286 // 9287 // Type legalization will split an extend of a small, legal, type to a larger 9288 // illegal type by first splitting the destination type, often creating 9289 // illegal source types, which then get legalized in isel-confusing ways, 9290 // leading to really terrible codegen. E.g., 9291 // %result = v8i32 sext v8i8 %value 9292 // becomes 9293 // %losrc = extract_subreg %value, ... 9294 // %hisrc = extract_subreg %value, ... 9295 // %lo = v4i32 sext v4i8 %losrc 9296 // %hi = v4i32 sext v4i8 %hisrc 9297 // Things go rapidly downhill from there. 9298 // 9299 // For AArch64, the [sz]ext vector instructions can only go up one element 9300 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 9301 // take two instructions. 9302 // 9303 // This implies that the most efficient way to do the extend from v8i8 9304 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 9305 // the normal splitting to happen for the v8i16->v8i32. 9306 9307 // This is pre-legalization to catch some cases where the default 9308 // type legalization will create ill-tempered code. 9309 if (!DCI.isBeforeLegalizeOps()) 9310 return SDValue(); 9311 9312 // We're only interested in cleaning things up for non-legal vector types 9313 // here. If both the source and destination are legal, things will just 9314 // work naturally without any fiddling. 9315 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9316 EVT ResVT = N->getValueType(0); 9317 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 9318 return SDValue(); 9319 // If the vector type isn't a simple VT, it's beyond the scope of what 9320 // we're worried about here. Let legalization do its thing and hope for 9321 // the best. 9322 SDValue Src = N->getOperand(0); 9323 EVT SrcVT = Src->getValueType(0); 9324 if (!ResVT.isSimple() || !SrcVT.isSimple()) 9325 return SDValue(); 9326 9327 // If the source VT is a 64-bit vector, we can play games and get the 9328 // better results we want. 9329 if (SrcVT.getSizeInBits() != 64) 9330 return SDValue(); 9331 9332 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 9333 unsigned ElementCount = SrcVT.getVectorNumElements(); 9334 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 9335 SDLoc DL(N); 9336 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 9337 9338 // Now split the rest of the operation into two halves, each with a 64 9339 // bit source. 9340 EVT LoVT, HiVT; 9341 SDValue Lo, Hi; 9342 unsigned NumElements = ResVT.getVectorNumElements(); 9343 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 9344 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 9345 ResVT.getVectorElementType(), NumElements / 2); 9346 9347 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 9348 LoVT.getVectorNumElements()); 9349 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 9350 DAG.getConstant(0, DL, MVT::i64)); 9351 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 9352 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 9353 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 9354 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 9355 9356 // Now combine the parts back together so we still have a single result 9357 // like the combiner expects. 9358 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 9359 } 9360 9361 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 9362 SDValue SplatVal, unsigned NumVecElts) { 9363 unsigned OrigAlignment = St.getAlignment(); 9364 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 9365 9366 // Create scalar stores. This is at least as good as the code sequence for a 9367 // split unaligned store which is a dup.s, ext.b, and two stores. 9368 // Most of the time the three stores should be replaced by store pair 9369 // instructions (stp). 9370 SDLoc DL(&St); 9371 SDValue BasePtr = St.getBasePtr(); 9372 uint64_t BaseOffset = 0; 9373 9374 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 9375 SDValue NewST1 = 9376 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 9377 OrigAlignment, St.getMemOperand()->getFlags()); 9378 9379 // As this in ISel, we will not merge this add which may degrade results. 9380 if (BasePtr->getOpcode() == ISD::ADD && 9381 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 9382 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 9383 BasePtr = BasePtr->getOperand(0); 9384 } 9385 9386 unsigned Offset = EltOffset; 9387 while (--NumVecElts) { 9388 unsigned Alignment = MinAlign(OrigAlignment, Offset); 9389 SDValue OffsetPtr = 9390 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9391 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 9392 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 9393 PtrInfo.getWithOffset(Offset), Alignment, 9394 St.getMemOperand()->getFlags()); 9395 Offset += EltOffset; 9396 } 9397 return NewST1; 9398 } 9399 9400 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 9401 /// load store optimizer pass will merge them to store pair stores. This should 9402 /// be better than a movi to create the vector zero followed by a vector store 9403 /// if the zero constant is not re-used, since one instructions and one register 9404 /// live range will be removed. 9405 /// 9406 /// For example, the final generated code should be: 9407 /// 9408 /// stp xzr, xzr, [x0] 9409 /// 9410 /// instead of: 9411 /// 9412 /// movi v0.2d, #0 9413 /// str q0, [x0] 9414 /// 9415 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 9416 SDValue StVal = St.getValue(); 9417 EVT VT = StVal.getValueType(); 9418 9419 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 9420 // 2, 3 or 4 i32 elements. 9421 int NumVecElts = VT.getVectorNumElements(); 9422 if (!(((NumVecElts == 2 || NumVecElts == 3) && 9423 VT.getVectorElementType().getSizeInBits() == 64) || 9424 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 9425 VT.getVectorElementType().getSizeInBits() == 32))) 9426 return SDValue(); 9427 9428 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 9429 return SDValue(); 9430 9431 // If the zero constant has more than one use then the vector store could be 9432 // better since the constant mov will be amortized and stp q instructions 9433 // should be able to be formed. 9434 if (!StVal.hasOneUse()) 9435 return SDValue(); 9436 9437 // If the immediate offset of the address operand is too large for the stp 9438 // instruction, then bail out. 9439 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 9440 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 9441 if (Offset < -512 || Offset > 504) 9442 return SDValue(); 9443 } 9444 9445 for (int I = 0; I < NumVecElts; ++I) { 9446 SDValue EltVal = StVal.getOperand(I); 9447 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 9448 return SDValue(); 9449 } 9450 9451 // Use a CopyFromReg WZR/XZR here to prevent 9452 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 9453 SDLoc DL(&St); 9454 unsigned ZeroReg; 9455 EVT ZeroVT; 9456 if (VT.getVectorElementType().getSizeInBits() == 32) { 9457 ZeroReg = AArch64::WZR; 9458 ZeroVT = MVT::i32; 9459 } else { 9460 ZeroReg = AArch64::XZR; 9461 ZeroVT = MVT::i64; 9462 } 9463 SDValue SplatVal = 9464 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 9465 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 9466 } 9467 9468 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 9469 /// value. The load store optimizer pass will merge them to store pair stores. 9470 /// This has better performance than a splat of the scalar followed by a split 9471 /// vector store. Even if the stores are not merged it is four stores vs a dup, 9472 /// followed by an ext.b and two stores. 9473 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 9474 SDValue StVal = St.getValue(); 9475 EVT VT = StVal.getValueType(); 9476 9477 // Don't replace floating point stores, they possibly won't be transformed to 9478 // stp because of the store pair suppress pass. 9479 if (VT.isFloatingPoint()) 9480 return SDValue(); 9481 9482 // We can express a splat as store pair(s) for 2 or 4 elements. 9483 unsigned NumVecElts = VT.getVectorNumElements(); 9484 if (NumVecElts != 4 && NumVecElts != 2) 9485 return SDValue(); 9486 9487 // Check that this is a splat. 9488 // Make sure that each of the relevant vector element locations are inserted 9489 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 9490 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 9491 SDValue SplatVal; 9492 for (unsigned I = 0; I < NumVecElts; ++I) { 9493 // Check for insert vector elements. 9494 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 9495 return SDValue(); 9496 9497 // Check that same value is inserted at each vector element. 9498 if (I == 0) 9499 SplatVal = StVal.getOperand(1); 9500 else if (StVal.getOperand(1) != SplatVal) 9501 return SDValue(); 9502 9503 // Check insert element index. 9504 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 9505 if (!CIndex) 9506 return SDValue(); 9507 uint64_t IndexVal = CIndex->getZExtValue(); 9508 if (IndexVal >= NumVecElts) 9509 return SDValue(); 9510 IndexNotInserted.reset(IndexVal); 9511 9512 StVal = StVal.getOperand(0); 9513 } 9514 // Check that all vector element locations were inserted to. 9515 if (IndexNotInserted.any()) 9516 return SDValue(); 9517 9518 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 9519 } 9520 9521 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 9522 SelectionDAG &DAG, 9523 const AArch64Subtarget *Subtarget) { 9524 if (!DCI.isBeforeLegalize()) 9525 return SDValue(); 9526 9527 StoreSDNode *S = cast<StoreSDNode>(N); 9528 if (S->isVolatile() || S->isIndexed()) 9529 return SDValue(); 9530 9531 SDValue StVal = S->getValue(); 9532 EVT VT = StVal.getValueType(); 9533 if (!VT.isVector()) 9534 return SDValue(); 9535 9536 // If we get a splat of zeros, convert this vector store to a store of 9537 // scalars. They will be merged into store pairs of xzr thereby removing one 9538 // instruction and one register. 9539 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 9540 return ReplacedZeroSplat; 9541 9542 // FIXME: The logic for deciding if an unaligned store should be split should 9543 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 9544 // a call to that function here. 9545 9546 if (!Subtarget->isMisaligned128StoreSlow()) 9547 return SDValue(); 9548 9549 // Don't split at -Oz. 9550 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 9551 return SDValue(); 9552 9553 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 9554 // those up regresses performance on micro-benchmarks and olden/bh. 9555 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 9556 return SDValue(); 9557 9558 // Split unaligned 16B stores. They are terrible for performance. 9559 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 9560 // extensions can use this to mark that it does not want splitting to happen 9561 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 9562 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 9563 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 9564 S->getAlignment() <= 2) 9565 return SDValue(); 9566 9567 // If we get a splat of a scalar convert this vector store to a store of 9568 // scalars. They will be merged into store pairs thereby removing two 9569 // instructions. 9570 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 9571 return ReplacedSplat; 9572 9573 SDLoc DL(S); 9574 unsigned NumElts = VT.getVectorNumElements() / 2; 9575 // Split VT into two. 9576 EVT HalfVT = 9577 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 9578 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9579 DAG.getConstant(0, DL, MVT::i64)); 9580 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9581 DAG.getConstant(NumElts, DL, MVT::i64)); 9582 SDValue BasePtr = S->getBasePtr(); 9583 SDValue NewST1 = 9584 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 9585 S->getAlignment(), S->getMemOperand()->getFlags()); 9586 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9587 DAG.getConstant(8, DL, MVT::i64)); 9588 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 9589 S->getPointerInfo(), S->getAlignment(), 9590 S->getMemOperand()->getFlags()); 9591 } 9592 9593 /// Target-specific DAG combine function for post-increment LD1 (lane) and 9594 /// post-increment LD1R. 9595 static SDValue performPostLD1Combine(SDNode *N, 9596 TargetLowering::DAGCombinerInfo &DCI, 9597 bool IsLaneOp) { 9598 if (DCI.isBeforeLegalizeOps()) 9599 return SDValue(); 9600 9601 SelectionDAG &DAG = DCI.DAG; 9602 EVT VT = N->getValueType(0); 9603 9604 unsigned LoadIdx = IsLaneOp ? 1 : 0; 9605 SDNode *LD = N->getOperand(LoadIdx).getNode(); 9606 // If it is not LOAD, can not do such combine. 9607 if (LD->getOpcode() != ISD::LOAD) 9608 return SDValue(); 9609 9610 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 9611 EVT MemVT = LoadSDN->getMemoryVT(); 9612 // Check if memory operand is the same type as the vector element. 9613 if (MemVT != VT.getVectorElementType()) 9614 return SDValue(); 9615 9616 // Check if there are other uses. If so, do not combine as it will introduce 9617 // an extra load. 9618 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 9619 ++UI) { 9620 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 9621 continue; 9622 if (*UI != N) 9623 return SDValue(); 9624 } 9625 9626 SDValue Addr = LD->getOperand(1); 9627 SDValue Vector = N->getOperand(0); 9628 // Search for a use of the address operand that is an increment. 9629 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 9630 Addr.getNode()->use_end(); UI != UE; ++UI) { 9631 SDNode *User = *UI; 9632 if (User->getOpcode() != ISD::ADD 9633 || UI.getUse().getResNo() != Addr.getResNo()) 9634 continue; 9635 9636 // Check that the add is independent of the load. Otherwise, folding it 9637 // would create a cycle. 9638 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 9639 continue; 9640 // Also check that add is not used in the vector operand. This would also 9641 // create a cycle. 9642 if (User->isPredecessorOf(Vector.getNode())) 9643 continue; 9644 9645 // If the increment is a constant, it must match the memory ref size. 9646 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9647 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9648 uint32_t IncVal = CInc->getZExtValue(); 9649 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 9650 if (IncVal != NumBytes) 9651 continue; 9652 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9653 } 9654 9655 // Finally, check that the vector doesn't depend on the load. 9656 // Again, this would create a cycle. 9657 // The load depending on the vector is fine, as that's the case for the 9658 // LD1*post we'll eventually generate anyway. 9659 if (LoadSDN->isPredecessorOf(Vector.getNode())) 9660 continue; 9661 9662 SmallVector<SDValue, 8> Ops; 9663 Ops.push_back(LD->getOperand(0)); // Chain 9664 if (IsLaneOp) { 9665 Ops.push_back(Vector); // The vector to be inserted 9666 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 9667 } 9668 Ops.push_back(Addr); 9669 Ops.push_back(Inc); 9670 9671 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 9672 SDVTList SDTys = DAG.getVTList(Tys); 9673 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 9674 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 9675 MemVT, 9676 LoadSDN->getMemOperand()); 9677 9678 // Update the uses. 9679 SDValue NewResults[] = { 9680 SDValue(LD, 0), // The result of load 9681 SDValue(UpdN.getNode(), 2) // Chain 9682 }; 9683 DCI.CombineTo(LD, NewResults); 9684 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 9685 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 9686 9687 break; 9688 } 9689 return SDValue(); 9690 } 9691 9692 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 9693 /// address translation. 9694 static bool performTBISimplification(SDValue Addr, 9695 TargetLowering::DAGCombinerInfo &DCI, 9696 SelectionDAG &DAG) { 9697 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 9698 KnownBits Known; 9699 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9700 !DCI.isBeforeLegalizeOps()); 9701 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9702 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 9703 DCI.CommitTargetLoweringOpt(TLO); 9704 return true; 9705 } 9706 return false; 9707 } 9708 9709 static SDValue performSTORECombine(SDNode *N, 9710 TargetLowering::DAGCombinerInfo &DCI, 9711 SelectionDAG &DAG, 9712 const AArch64Subtarget *Subtarget) { 9713 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 9714 return Split; 9715 9716 if (Subtarget->supportsAddressTopByteIgnored() && 9717 performTBISimplification(N->getOperand(2), DCI, DAG)) 9718 return SDValue(N, 0); 9719 9720 return SDValue(); 9721 } 9722 9723 9724 /// Target-specific DAG combine function for NEON load/store intrinsics 9725 /// to merge base address updates. 9726 static SDValue performNEONPostLDSTCombine(SDNode *N, 9727 TargetLowering::DAGCombinerInfo &DCI, 9728 SelectionDAG &DAG) { 9729 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9730 return SDValue(); 9731 9732 unsigned AddrOpIdx = N->getNumOperands() - 1; 9733 SDValue Addr = N->getOperand(AddrOpIdx); 9734 9735 // Search for a use of the address operand that is an increment. 9736 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9737 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9738 SDNode *User = *UI; 9739 if (User->getOpcode() != ISD::ADD || 9740 UI.getUse().getResNo() != Addr.getResNo()) 9741 continue; 9742 9743 // Check that the add is independent of the load/store. Otherwise, folding 9744 // it would create a cycle. 9745 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9746 continue; 9747 9748 // Find the new opcode for the updating load/store. 9749 bool IsStore = false; 9750 bool IsLaneOp = false; 9751 bool IsDupOp = false; 9752 unsigned NewOpc = 0; 9753 unsigned NumVecs = 0; 9754 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9755 switch (IntNo) { 9756 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9757 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9758 NumVecs = 2; break; 9759 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9760 NumVecs = 3; break; 9761 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9762 NumVecs = 4; break; 9763 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9764 NumVecs = 2; IsStore = true; break; 9765 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9766 NumVecs = 3; IsStore = true; break; 9767 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9768 NumVecs = 4; IsStore = true; break; 9769 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9770 NumVecs = 2; break; 9771 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9772 NumVecs = 3; break; 9773 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9774 NumVecs = 4; break; 9775 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9776 NumVecs = 2; IsStore = true; break; 9777 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9778 NumVecs = 3; IsStore = true; break; 9779 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9780 NumVecs = 4; IsStore = true; break; 9781 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9782 NumVecs = 2; IsDupOp = true; break; 9783 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9784 NumVecs = 3; IsDupOp = true; break; 9785 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9786 NumVecs = 4; IsDupOp = true; break; 9787 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9788 NumVecs = 2; IsLaneOp = true; break; 9789 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9790 NumVecs = 3; IsLaneOp = true; break; 9791 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9792 NumVecs = 4; IsLaneOp = true; break; 9793 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9794 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9795 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9796 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9797 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9798 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9799 } 9800 9801 EVT VecTy; 9802 if (IsStore) 9803 VecTy = N->getOperand(2).getValueType(); 9804 else 9805 VecTy = N->getValueType(0); 9806 9807 // If the increment is a constant, it must match the memory ref size. 9808 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9809 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9810 uint32_t IncVal = CInc->getZExtValue(); 9811 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9812 if (IsLaneOp || IsDupOp) 9813 NumBytes /= VecTy.getVectorNumElements(); 9814 if (IncVal != NumBytes) 9815 continue; 9816 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9817 } 9818 SmallVector<SDValue, 8> Ops; 9819 Ops.push_back(N->getOperand(0)); // Incoming chain 9820 // Load lane and store have vector list as input. 9821 if (IsLaneOp || IsStore) 9822 for (unsigned i = 2; i < AddrOpIdx; ++i) 9823 Ops.push_back(N->getOperand(i)); 9824 Ops.push_back(Addr); // Base register 9825 Ops.push_back(Inc); 9826 9827 // Return Types. 9828 EVT Tys[6]; 9829 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9830 unsigned n; 9831 for (n = 0; n < NumResultVecs; ++n) 9832 Tys[n] = VecTy; 9833 Tys[n++] = MVT::i64; // Type of write back register 9834 Tys[n] = MVT::Other; // Type of the chain 9835 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9836 9837 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9838 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9839 MemInt->getMemoryVT(), 9840 MemInt->getMemOperand()); 9841 9842 // Update the uses. 9843 std::vector<SDValue> NewResults; 9844 for (unsigned i = 0; i < NumResultVecs; ++i) { 9845 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9846 } 9847 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9848 DCI.CombineTo(N, NewResults); 9849 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9850 9851 break; 9852 } 9853 return SDValue(); 9854 } 9855 9856 // Checks to see if the value is the prescribed width and returns information 9857 // about its extension mode. 9858 static 9859 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9860 ExtType = ISD::NON_EXTLOAD; 9861 switch(V.getNode()->getOpcode()) { 9862 default: 9863 return false; 9864 case ISD::LOAD: { 9865 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9866 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9867 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9868 ExtType = LoadNode->getExtensionType(); 9869 return true; 9870 } 9871 return false; 9872 } 9873 case ISD::AssertSext: { 9874 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9875 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9876 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9877 ExtType = ISD::SEXTLOAD; 9878 return true; 9879 } 9880 return false; 9881 } 9882 case ISD::AssertZext: { 9883 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9884 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9885 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9886 ExtType = ISD::ZEXTLOAD; 9887 return true; 9888 } 9889 return false; 9890 } 9891 case ISD::Constant: 9892 case ISD::TargetConstant: { 9893 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9894 1LL << (width - 1); 9895 } 9896 } 9897 9898 return true; 9899 } 9900 9901 // This function does a whole lot of voodoo to determine if the tests are 9902 // equivalent without and with a mask. Essentially what happens is that given a 9903 // DAG resembling: 9904 // 9905 // +-------------+ +-------------+ +-------------+ +-------------+ 9906 // | Input | | AddConstant | | CompConstant| | CC | 9907 // +-------------+ +-------------+ +-------------+ +-------------+ 9908 // | | | | 9909 // V V | +----------+ 9910 // +-------------+ +----+ | | 9911 // | ADD | |0xff| | | 9912 // +-------------+ +----+ | | 9913 // | | | | 9914 // V V | | 9915 // +-------------+ | | 9916 // | AND | | | 9917 // +-------------+ | | 9918 // | | | 9919 // +-----+ | | 9920 // | | | 9921 // V V V 9922 // +-------------+ 9923 // | CMP | 9924 // +-------------+ 9925 // 9926 // The AND node may be safely removed for some combinations of inputs. In 9927 // particular we need to take into account the extension type of the Input, 9928 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9929 // width of the input (this can work for any width inputs, the above graph is 9930 // specific to 8 bits. 9931 // 9932 // The specific equations were worked out by generating output tables for each 9933 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9934 // problem was simplified by working with 4 bit inputs, which means we only 9935 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9936 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9937 // patterns present in both extensions (0,7). For every distinct set of 9938 // AddConstant and CompConstants bit patterns we can consider the masked and 9939 // unmasked versions to be equivalent if the result of this function is true for 9940 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9941 // 9942 // sub w8, w0, w1 9943 // and w10, w8, #0x0f 9944 // cmp w8, w2 9945 // cset w9, AArch64CC 9946 // cmp w10, w2 9947 // cset w11, AArch64CC 9948 // cmp w9, w11 9949 // cset w0, eq 9950 // ret 9951 // 9952 // Since the above function shows when the outputs are equivalent it defines 9953 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9954 // would be expensive to run during compiles. The equations below were written 9955 // in a test harness that confirmed they gave equivalent outputs to the above 9956 // for all inputs function, so they can be used determine if the removal is 9957 // legal instead. 9958 // 9959 // isEquivalentMaskless() is the code for testing if the AND can be removed 9960 // factored out of the DAG recognition as the DAG can take several forms. 9961 9962 static bool isEquivalentMaskless(unsigned CC, unsigned width, 9963 ISD::LoadExtType ExtType, int AddConstant, 9964 int CompConstant) { 9965 // By being careful about our equations and only writing the in term 9966 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 9967 // make them generally applicable to all bit widths. 9968 int MaxUInt = (1 << width); 9969 9970 // For the purposes of these comparisons sign extending the type is 9971 // equivalent to zero extending the add and displacing it by half the integer 9972 // width. Provided we are careful and make sure our equations are valid over 9973 // the whole range we can just adjust the input and avoid writing equations 9974 // for sign extended inputs. 9975 if (ExtType == ISD::SEXTLOAD) 9976 AddConstant -= (1 << (width-1)); 9977 9978 switch(CC) { 9979 case AArch64CC::LE: 9980 case AArch64CC::GT: 9981 if ((AddConstant == 0) || 9982 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 9983 (AddConstant >= 0 && CompConstant < 0) || 9984 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 9985 return true; 9986 break; 9987 case AArch64CC::LT: 9988 case AArch64CC::GE: 9989 if ((AddConstant == 0) || 9990 (AddConstant >= 0 && CompConstant <= 0) || 9991 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 9992 return true; 9993 break; 9994 case AArch64CC::HI: 9995 case AArch64CC::LS: 9996 if ((AddConstant >= 0 && CompConstant < 0) || 9997 (AddConstant <= 0 && CompConstant >= -1 && 9998 CompConstant < AddConstant + MaxUInt)) 9999 return true; 10000 break; 10001 case AArch64CC::PL: 10002 case AArch64CC::MI: 10003 if ((AddConstant == 0) || 10004 (AddConstant > 0 && CompConstant <= 0) || 10005 (AddConstant < 0 && CompConstant <= AddConstant)) 10006 return true; 10007 break; 10008 case AArch64CC::LO: 10009 case AArch64CC::HS: 10010 if ((AddConstant >= 0 && CompConstant <= 0) || 10011 (AddConstant <= 0 && CompConstant >= 0 && 10012 CompConstant <= AddConstant + MaxUInt)) 10013 return true; 10014 break; 10015 case AArch64CC::EQ: 10016 case AArch64CC::NE: 10017 if ((AddConstant > 0 && CompConstant < 0) || 10018 (AddConstant < 0 && CompConstant >= 0 && 10019 CompConstant < AddConstant + MaxUInt) || 10020 (AddConstant >= 0 && CompConstant >= 0 && 10021 CompConstant >= AddConstant) || 10022 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 10023 return true; 10024 break; 10025 case AArch64CC::VS: 10026 case AArch64CC::VC: 10027 case AArch64CC::AL: 10028 case AArch64CC::NV: 10029 return true; 10030 case AArch64CC::Invalid: 10031 break; 10032 } 10033 10034 return false; 10035 } 10036 10037 static 10038 SDValue performCONDCombine(SDNode *N, 10039 TargetLowering::DAGCombinerInfo &DCI, 10040 SelectionDAG &DAG, unsigned CCIndex, 10041 unsigned CmpIndex) { 10042 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 10043 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 10044 unsigned CondOpcode = SubsNode->getOpcode(); 10045 10046 if (CondOpcode != AArch64ISD::SUBS) 10047 return SDValue(); 10048 10049 // There is a SUBS feeding this condition. Is it fed by a mask we can 10050 // use? 10051 10052 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 10053 unsigned MaskBits = 0; 10054 10055 if (AndNode->getOpcode() != ISD::AND) 10056 return SDValue(); 10057 10058 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 10059 uint32_t CNV = CN->getZExtValue(); 10060 if (CNV == 255) 10061 MaskBits = 8; 10062 else if (CNV == 65535) 10063 MaskBits = 16; 10064 } 10065 10066 if (!MaskBits) 10067 return SDValue(); 10068 10069 SDValue AddValue = AndNode->getOperand(0); 10070 10071 if (AddValue.getOpcode() != ISD::ADD) 10072 return SDValue(); 10073 10074 // The basic dag structure is correct, grab the inputs and validate them. 10075 10076 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 10077 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 10078 SDValue SubsInputValue = SubsNode->getOperand(1); 10079 10080 // The mask is present and the provenance of all the values is a smaller type, 10081 // lets see if the mask is superfluous. 10082 10083 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 10084 !isa<ConstantSDNode>(SubsInputValue.getNode())) 10085 return SDValue(); 10086 10087 ISD::LoadExtType ExtType; 10088 10089 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 10090 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 10091 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 10092 return SDValue(); 10093 10094 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 10095 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 10096 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 10097 return SDValue(); 10098 10099 // The AND is not necessary, remove it. 10100 10101 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 10102 SubsNode->getValueType(1)); 10103 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 10104 10105 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 10106 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 10107 10108 return SDValue(N, 0); 10109 } 10110 10111 // Optimize compare with zero and branch. 10112 static SDValue performBRCONDCombine(SDNode *N, 10113 TargetLowering::DAGCombinerInfo &DCI, 10114 SelectionDAG &DAG) { 10115 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 10116 N = NV.getNode(); 10117 SDValue Chain = N->getOperand(0); 10118 SDValue Dest = N->getOperand(1); 10119 SDValue CCVal = N->getOperand(2); 10120 SDValue Cmp = N->getOperand(3); 10121 10122 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 10123 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 10124 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 10125 return SDValue(); 10126 10127 unsigned CmpOpc = Cmp.getOpcode(); 10128 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 10129 return SDValue(); 10130 10131 // Only attempt folding if there is only one use of the flag and no use of the 10132 // value. 10133 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 10134 return SDValue(); 10135 10136 SDValue LHS = Cmp.getOperand(0); 10137 SDValue RHS = Cmp.getOperand(1); 10138 10139 assert(LHS.getValueType() == RHS.getValueType() && 10140 "Expected the value type to be the same for both operands!"); 10141 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 10142 return SDValue(); 10143 10144 if (isNullConstant(LHS)) 10145 std::swap(LHS, RHS); 10146 10147 if (!isNullConstant(RHS)) 10148 return SDValue(); 10149 10150 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 10151 LHS.getOpcode() == ISD::SRL) 10152 return SDValue(); 10153 10154 // Fold the compare into the branch instruction. 10155 SDValue BR; 10156 if (CC == AArch64CC::EQ) 10157 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 10158 else 10159 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 10160 10161 // Do not add new nodes to DAG combiner worklist. 10162 DCI.CombineTo(N, BR, false); 10163 10164 return SDValue(); 10165 } 10166 10167 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 10168 // as well as whether the test should be inverted. This code is required to 10169 // catch these cases (as opposed to standard dag combines) because 10170 // AArch64ISD::TBZ is matched during legalization. 10171 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 10172 SelectionDAG &DAG) { 10173 10174 if (!Op->hasOneUse()) 10175 return Op; 10176 10177 // We don't handle undef/constant-fold cases below, as they should have 10178 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 10179 // etc.) 10180 10181 // (tbz (trunc x), b) -> (tbz x, b) 10182 // This case is just here to enable more of the below cases to be caught. 10183 if (Op->getOpcode() == ISD::TRUNCATE && 10184 Bit < Op->getValueType(0).getSizeInBits()) { 10185 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10186 } 10187 10188 if (Op->getNumOperands() != 2) 10189 return Op; 10190 10191 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 10192 if (!C) 10193 return Op; 10194 10195 switch (Op->getOpcode()) { 10196 default: 10197 return Op; 10198 10199 // (tbz (and x, m), b) -> (tbz x, b) 10200 case ISD::AND: 10201 if ((C->getZExtValue() >> Bit) & 1) 10202 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10203 return Op; 10204 10205 // (tbz (shl x, c), b) -> (tbz x, b-c) 10206 case ISD::SHL: 10207 if (C->getZExtValue() <= Bit && 10208 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 10209 Bit = Bit - C->getZExtValue(); 10210 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10211 } 10212 return Op; 10213 10214 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 10215 case ISD::SRA: 10216 Bit = Bit + C->getZExtValue(); 10217 if (Bit >= Op->getValueType(0).getSizeInBits()) 10218 Bit = Op->getValueType(0).getSizeInBits() - 1; 10219 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10220 10221 // (tbz (srl x, c), b) -> (tbz x, b+c) 10222 case ISD::SRL: 10223 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 10224 Bit = Bit + C->getZExtValue(); 10225 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10226 } 10227 return Op; 10228 10229 // (tbz (xor x, -1), b) -> (tbnz x, b) 10230 case ISD::XOR: 10231 if ((C->getZExtValue() >> Bit) & 1) 10232 Invert = !Invert; 10233 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 10234 } 10235 } 10236 10237 // Optimize test single bit zero/non-zero and branch. 10238 static SDValue performTBZCombine(SDNode *N, 10239 TargetLowering::DAGCombinerInfo &DCI, 10240 SelectionDAG &DAG) { 10241 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10242 bool Invert = false; 10243 SDValue TestSrc = N->getOperand(1); 10244 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 10245 10246 if (TestSrc == NewTestSrc) 10247 return SDValue(); 10248 10249 unsigned NewOpc = N->getOpcode(); 10250 if (Invert) { 10251 if (NewOpc == AArch64ISD::TBZ) 10252 NewOpc = AArch64ISD::TBNZ; 10253 else { 10254 assert(NewOpc == AArch64ISD::TBNZ); 10255 NewOpc = AArch64ISD::TBZ; 10256 } 10257 } 10258 10259 SDLoc DL(N); 10260 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 10261 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 10262 } 10263 10264 // vselect (v1i1 setcc) -> 10265 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 10266 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 10267 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 10268 // such VSELECT. 10269 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 10270 SDValue N0 = N->getOperand(0); 10271 EVT CCVT = N0.getValueType(); 10272 10273 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 10274 CCVT.getVectorElementType() != MVT::i1) 10275 return SDValue(); 10276 10277 EVT ResVT = N->getValueType(0); 10278 EVT CmpVT = N0.getOperand(0).getValueType(); 10279 // Only combine when the result type is of the same size as the compared 10280 // operands. 10281 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 10282 return SDValue(); 10283 10284 SDValue IfTrue = N->getOperand(1); 10285 SDValue IfFalse = N->getOperand(2); 10286 SDValue SetCC = 10287 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 10288 N0.getOperand(0), N0.getOperand(1), 10289 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10290 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 10291 IfTrue, IfFalse); 10292 } 10293 10294 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 10295 /// the compare-mask instructions rather than going via NZCV, even if LHS and 10296 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 10297 /// with a vector one followed by a DUP shuffle on the result. 10298 static SDValue performSelectCombine(SDNode *N, 10299 TargetLowering::DAGCombinerInfo &DCI) { 10300 SelectionDAG &DAG = DCI.DAG; 10301 SDValue N0 = N->getOperand(0); 10302 EVT ResVT = N->getValueType(0); 10303 10304 if (N0.getOpcode() != ISD::SETCC) 10305 return SDValue(); 10306 10307 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 10308 // scalar SetCCResultType. We also don't expect vectors, because we assume 10309 // that selects fed by vector SETCCs are canonicalized to VSELECT. 10310 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 10311 "Scalar-SETCC feeding SELECT has unexpected result type!"); 10312 10313 // If NumMaskElts == 0, the comparison is larger than select result. The 10314 // largest real NEON comparison is 64-bits per lane, which means the result is 10315 // at most 32-bits and an illegal vector. Just bail out for now. 10316 EVT SrcVT = N0.getOperand(0).getValueType(); 10317 10318 // Don't try to do this optimization when the setcc itself has i1 operands. 10319 // There are no legal vectors of i1, so this would be pointless. 10320 if (SrcVT == MVT::i1) 10321 return SDValue(); 10322 10323 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 10324 if (!ResVT.isVector() || NumMaskElts == 0) 10325 return SDValue(); 10326 10327 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 10328 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 10329 10330 // Also bail out if the vector CCVT isn't the same size as ResVT. 10331 // This can happen if the SETCC operand size doesn't divide the ResVT size 10332 // (e.g., f64 vs v3f32). 10333 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 10334 return SDValue(); 10335 10336 // Make sure we didn't create illegal types, if we're not supposed to. 10337 assert(DCI.isBeforeLegalize() || 10338 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 10339 10340 // First perform a vector comparison, where lane 0 is the one we're interested 10341 // in. 10342 SDLoc DL(N0); 10343 SDValue LHS = 10344 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 10345 SDValue RHS = 10346 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 10347 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 10348 10349 // Now duplicate the comparison mask we want across all other lanes. 10350 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 10351 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 10352 Mask = DAG.getNode(ISD::BITCAST, DL, 10353 ResVT.changeVectorElementTypeToInteger(), Mask); 10354 10355 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 10356 } 10357 10358 /// Get rid of unnecessary NVCASTs (that don't change the type). 10359 static SDValue performNVCASTCombine(SDNode *N) { 10360 if (N->getValueType(0) == N->getOperand(0).getValueType()) 10361 return N->getOperand(0); 10362 10363 return SDValue(); 10364 } 10365 10366 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 10367 DAGCombinerInfo &DCI) const { 10368 SelectionDAG &DAG = DCI.DAG; 10369 switch (N->getOpcode()) { 10370 default: 10371 DEBUG(dbgs() << "Custom combining: skipping\n"); 10372 break; 10373 case ISD::ADD: 10374 case ISD::SUB: 10375 return performAddSubLongCombine(N, DCI, DAG); 10376 case ISD::XOR: 10377 return performXorCombine(N, DAG, DCI, Subtarget); 10378 case ISD::MUL: 10379 return performMulCombine(N, DAG, DCI, Subtarget); 10380 case ISD::SINT_TO_FP: 10381 case ISD::UINT_TO_FP: 10382 return performIntToFpCombine(N, DAG, Subtarget); 10383 case ISD::FP_TO_SINT: 10384 case ISD::FP_TO_UINT: 10385 return performFpToIntCombine(N, DAG, DCI, Subtarget); 10386 case ISD::FDIV: 10387 return performFDivCombine(N, DAG, DCI, Subtarget); 10388 case ISD::OR: 10389 return performORCombine(N, DCI, Subtarget); 10390 case ISD::SRL: 10391 return performSRLCombine(N, DCI); 10392 case ISD::INTRINSIC_WO_CHAIN: 10393 return performIntrinsicCombine(N, DCI, Subtarget); 10394 case ISD::ANY_EXTEND: 10395 case ISD::ZERO_EXTEND: 10396 case ISD::SIGN_EXTEND: 10397 return performExtendCombine(N, DCI, DAG); 10398 case ISD::BITCAST: 10399 return performBitcastCombine(N, DCI, DAG); 10400 case ISD::CONCAT_VECTORS: 10401 return performConcatVectorsCombine(N, DCI, DAG); 10402 case ISD::SELECT: 10403 return performSelectCombine(N, DCI); 10404 case ISD::VSELECT: 10405 return performVSelectCombine(N, DCI.DAG); 10406 case ISD::LOAD: 10407 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 10408 return SDValue(N, 0); 10409 break; 10410 case ISD::STORE: 10411 return performSTORECombine(N, DCI, DAG, Subtarget); 10412 case AArch64ISD::BRCOND: 10413 return performBRCONDCombine(N, DCI, DAG); 10414 case AArch64ISD::TBNZ: 10415 case AArch64ISD::TBZ: 10416 return performTBZCombine(N, DCI, DAG); 10417 case AArch64ISD::CSEL: 10418 return performCONDCombine(N, DCI, DAG, 2, 3); 10419 case AArch64ISD::DUP: 10420 return performPostLD1Combine(N, DCI, false); 10421 case AArch64ISD::NVCAST: 10422 return performNVCASTCombine(N); 10423 case ISD::INSERT_VECTOR_ELT: 10424 return performPostLD1Combine(N, DCI, true); 10425 case ISD::INTRINSIC_VOID: 10426 case ISD::INTRINSIC_W_CHAIN: 10427 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10428 case Intrinsic::aarch64_neon_ld2: 10429 case Intrinsic::aarch64_neon_ld3: 10430 case Intrinsic::aarch64_neon_ld4: 10431 case Intrinsic::aarch64_neon_ld1x2: 10432 case Intrinsic::aarch64_neon_ld1x3: 10433 case Intrinsic::aarch64_neon_ld1x4: 10434 case Intrinsic::aarch64_neon_ld2lane: 10435 case Intrinsic::aarch64_neon_ld3lane: 10436 case Intrinsic::aarch64_neon_ld4lane: 10437 case Intrinsic::aarch64_neon_ld2r: 10438 case Intrinsic::aarch64_neon_ld3r: 10439 case Intrinsic::aarch64_neon_ld4r: 10440 case Intrinsic::aarch64_neon_st2: 10441 case Intrinsic::aarch64_neon_st3: 10442 case Intrinsic::aarch64_neon_st4: 10443 case Intrinsic::aarch64_neon_st1x2: 10444 case Intrinsic::aarch64_neon_st1x3: 10445 case Intrinsic::aarch64_neon_st1x4: 10446 case Intrinsic::aarch64_neon_st2lane: 10447 case Intrinsic::aarch64_neon_st3lane: 10448 case Intrinsic::aarch64_neon_st4lane: 10449 return performNEONPostLDSTCombine(N, DCI, DAG); 10450 default: 10451 break; 10452 } 10453 } 10454 return SDValue(); 10455 } 10456 10457 // Check if the return value is used as only a return value, as otherwise 10458 // we can't perform a tail-call. In particular, we need to check for 10459 // target ISD nodes that are returns and any other "odd" constructs 10460 // that the generic analysis code won't necessarily catch. 10461 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 10462 SDValue &Chain) const { 10463 if (N->getNumValues() != 1) 10464 return false; 10465 if (!N->hasNUsesOfValue(1, 0)) 10466 return false; 10467 10468 SDValue TCChain = Chain; 10469 SDNode *Copy = *N->use_begin(); 10470 if (Copy->getOpcode() == ISD::CopyToReg) { 10471 // If the copy has a glue operand, we conservatively assume it isn't safe to 10472 // perform a tail call. 10473 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 10474 MVT::Glue) 10475 return false; 10476 TCChain = Copy->getOperand(0); 10477 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 10478 return false; 10479 10480 bool HasRet = false; 10481 for (SDNode *Node : Copy->uses()) { 10482 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 10483 return false; 10484 HasRet = true; 10485 } 10486 10487 if (!HasRet) 10488 return false; 10489 10490 Chain = TCChain; 10491 return true; 10492 } 10493 10494 // Return whether the an instruction can potentially be optimized to a tail 10495 // call. This will cause the optimizers to attempt to move, or duplicate, 10496 // return instructions to help enable tail call optimizations for this 10497 // instruction. 10498 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10499 return CI->isTailCall(); 10500 } 10501 10502 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 10503 SDValue &Offset, 10504 ISD::MemIndexedMode &AM, 10505 bool &IsInc, 10506 SelectionDAG &DAG) const { 10507 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 10508 return false; 10509 10510 Base = Op->getOperand(0); 10511 // All of the indexed addressing mode instructions take a signed 10512 // 9 bit immediate offset. 10513 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 10514 int64_t RHSC = RHS->getSExtValue(); 10515 if (Op->getOpcode() == ISD::SUB) 10516 RHSC = -(uint64_t)RHSC; 10517 if (!isInt<9>(RHSC)) 10518 return false; 10519 IsInc = (Op->getOpcode() == ISD::ADD); 10520 Offset = Op->getOperand(1); 10521 return true; 10522 } 10523 return false; 10524 } 10525 10526 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10527 SDValue &Offset, 10528 ISD::MemIndexedMode &AM, 10529 SelectionDAG &DAG) const { 10530 EVT VT; 10531 SDValue Ptr; 10532 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10533 VT = LD->getMemoryVT(); 10534 Ptr = LD->getBasePtr(); 10535 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10536 VT = ST->getMemoryVT(); 10537 Ptr = ST->getBasePtr(); 10538 } else 10539 return false; 10540 10541 bool IsInc; 10542 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 10543 return false; 10544 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 10545 return true; 10546 } 10547 10548 bool AArch64TargetLowering::getPostIndexedAddressParts( 10549 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10550 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10551 EVT VT; 10552 SDValue Ptr; 10553 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10554 VT = LD->getMemoryVT(); 10555 Ptr = LD->getBasePtr(); 10556 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10557 VT = ST->getMemoryVT(); 10558 Ptr = ST->getBasePtr(); 10559 } else 10560 return false; 10561 10562 bool IsInc; 10563 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10564 return false; 10565 // Post-indexing updates the base, so it's not a valid transform 10566 // if that's not the same as the load's pointer. 10567 if (Ptr != Base) 10568 return false; 10569 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10570 return true; 10571 } 10572 10573 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10574 SelectionDAG &DAG) { 10575 SDLoc DL(N); 10576 SDValue Op = N->getOperand(0); 10577 10578 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10579 return; 10580 10581 Op = SDValue( 10582 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10583 DAG.getUNDEF(MVT::i32), Op, 10584 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10585 0); 10586 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10587 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10588 } 10589 10590 static void ReplaceReductionResults(SDNode *N, 10591 SmallVectorImpl<SDValue> &Results, 10592 SelectionDAG &DAG, unsigned InterOp, 10593 unsigned AcrossOp) { 10594 EVT LoVT, HiVT; 10595 SDValue Lo, Hi; 10596 SDLoc dl(N); 10597 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10598 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10599 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10600 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10601 Results.push_back(SplitVal); 10602 } 10603 10604 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 10605 SDLoc DL(N); 10606 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 10607 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 10608 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 10609 DAG.getConstant(64, DL, MVT::i64))); 10610 return std::make_pair(Lo, Hi); 10611 } 10612 10613 static void ReplaceCMP_SWAP_128Results(SDNode *N, 10614 SmallVectorImpl<SDValue> & Results, 10615 SelectionDAG &DAG) { 10616 assert(N->getValueType(0) == MVT::i128 && 10617 "AtomicCmpSwap on types less than 128 should be legal"); 10618 auto Desired = splitInt128(N->getOperand(2), DAG); 10619 auto New = splitInt128(N->getOperand(3), DAG); 10620 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 10621 New.first, New.second, N->getOperand(0)}; 10622 SDNode *CmpSwap = DAG.getMachineNode( 10623 AArch64::CMP_SWAP_128, SDLoc(N), 10624 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 10625 10626 MachineFunction &MF = DAG.getMachineFunction(); 10627 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 10628 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 10629 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 10630 10631 Results.push_back(SDValue(CmpSwap, 0)); 10632 Results.push_back(SDValue(CmpSwap, 1)); 10633 Results.push_back(SDValue(CmpSwap, 3)); 10634 } 10635 10636 void AArch64TargetLowering::ReplaceNodeResults( 10637 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10638 switch (N->getOpcode()) { 10639 default: 10640 llvm_unreachable("Don't know how to custom expand this"); 10641 case ISD::BITCAST: 10642 ReplaceBITCASTResults(N, Results, DAG); 10643 return; 10644 case ISD::VECREDUCE_ADD: 10645 case ISD::VECREDUCE_SMAX: 10646 case ISD::VECREDUCE_SMIN: 10647 case ISD::VECREDUCE_UMAX: 10648 case ISD::VECREDUCE_UMIN: 10649 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 10650 return; 10651 10652 case AArch64ISD::SADDV: 10653 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10654 return; 10655 case AArch64ISD::UADDV: 10656 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10657 return; 10658 case AArch64ISD::SMINV: 10659 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10660 return; 10661 case AArch64ISD::UMINV: 10662 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10663 return; 10664 case AArch64ISD::SMAXV: 10665 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10666 return; 10667 case AArch64ISD::UMAXV: 10668 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10669 return; 10670 case ISD::FP_TO_UINT: 10671 case ISD::FP_TO_SINT: 10672 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10673 // Let normal code take care of it by not adding anything to Results. 10674 return; 10675 case ISD::ATOMIC_CMP_SWAP: 10676 ReplaceCMP_SWAP_128Results(N, Results, DAG); 10677 return; 10678 } 10679 } 10680 10681 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10682 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 10683 return TargetLowering::useLoadStackGuardNode(); 10684 return true; 10685 } 10686 10687 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10688 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10689 // reciprocal if there are three or more FDIVs. 10690 return 3; 10691 } 10692 10693 TargetLoweringBase::LegalizeTypeAction 10694 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10695 MVT SVT = VT.getSimpleVT(); 10696 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10697 // v4i16, v2i32 instead of to promote. 10698 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10699 || SVT == MVT::v1f32) 10700 return TypeWidenVector; 10701 10702 return TargetLoweringBase::getPreferredVectorAction(VT); 10703 } 10704 10705 // Loads and stores less than 128-bits are already atomic; ones above that 10706 // are doomed anyway, so defer to the default libcall and blame the OS when 10707 // things go wrong. 10708 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10709 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10710 return Size == 128; 10711 } 10712 10713 // Loads and stores less than 128-bits are already atomic; ones above that 10714 // are doomed anyway, so defer to the default libcall and blame the OS when 10715 // things go wrong. 10716 TargetLowering::AtomicExpansionKind 10717 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10718 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10719 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10720 } 10721 10722 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10723 TargetLowering::AtomicExpansionKind 10724 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10725 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10726 if (Size > 128) return AtomicExpansionKind::None; 10727 // Nand not supported in LSE. 10728 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 10729 // Leave 128 bits to LLSC. 10730 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 10731 } 10732 10733 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10734 AtomicCmpXchgInst *AI) const { 10735 // If subtarget has LSE, leave cmpxchg intact for codegen. 10736 if (Subtarget->hasLSE()) return false; 10737 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 10738 // implement cmpxchg without spilling. If the address being exchanged is also 10739 // on the stack and close enough to the spill slot, this can lead to a 10740 // situation where the monitor always gets cleared and the atomic operation 10741 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 10742 return getTargetMachine().getOptLevel() != 0; 10743 } 10744 10745 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10746 AtomicOrdering Ord) const { 10747 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10748 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10749 bool IsAcquire = isAcquireOrStronger(Ord); 10750 10751 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10752 // intrinsic must return {i64, i64} and we have to recombine them into a 10753 // single i128 here. 10754 if (ValTy->getPrimitiveSizeInBits() == 128) { 10755 Intrinsic::ID Int = 10756 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10757 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 10758 10759 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10760 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10761 10762 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10763 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10764 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10765 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10766 return Builder.CreateOr( 10767 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10768 } 10769 10770 Type *Tys[] = { Addr->getType() }; 10771 Intrinsic::ID Int = 10772 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10773 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 10774 10775 return Builder.CreateTruncOrBitCast( 10776 Builder.CreateCall(Ldxr, Addr), 10777 cast<PointerType>(Addr->getType())->getElementType()); 10778 } 10779 10780 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10781 IRBuilder<> &Builder) const { 10782 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10783 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10784 } 10785 10786 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10787 Value *Val, Value *Addr, 10788 AtomicOrdering Ord) const { 10789 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10790 bool IsRelease = isReleaseOrStronger(Ord); 10791 10792 // Since the intrinsics must have legal type, the i128 intrinsics take two 10793 // parameters: "i64, i64". We must marshal Val into the appropriate form 10794 // before the call. 10795 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10796 Intrinsic::ID Int = 10797 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10798 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10799 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10800 10801 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10802 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10803 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10804 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10805 } 10806 10807 Intrinsic::ID Int = 10808 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10809 Type *Tys[] = { Addr->getType() }; 10810 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10811 10812 return Builder.CreateCall(Stxr, 10813 {Builder.CreateZExtOrBitCast( 10814 Val, Stxr->getFunctionType()->getParamType(0)), 10815 Addr}); 10816 } 10817 10818 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10819 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10820 return Ty->isArrayTy(); 10821 } 10822 10823 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10824 EVT) const { 10825 return false; 10826 } 10827 10828 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 10829 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10830 Function *ThreadPointerFunc = 10831 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10832 return IRB.CreatePointerCast( 10833 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset), 10834 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10835 } 10836 10837 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 10838 // Android provides a fixed TLS slot for the stack cookie. See the definition 10839 // of TLS_SLOT_STACK_GUARD in 10840 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10841 if (Subtarget->isTargetAndroid()) 10842 return UseTlsOffset(IRB, 0x28); 10843 10844 // Fuchsia is similar. 10845 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 10846 if (Subtarget->isTargetFuchsia()) 10847 return UseTlsOffset(IRB, -0x10); 10848 10849 return TargetLowering::getIRStackGuard(IRB); 10850 } 10851 10852 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10853 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10854 // definition of TLS_SLOT_SAFESTACK in 10855 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10856 if (Subtarget->isTargetAndroid()) 10857 return UseTlsOffset(IRB, 0x48); 10858 10859 // Fuchsia is similar. 10860 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 10861 if (Subtarget->isTargetFuchsia()) 10862 return UseTlsOffset(IRB, -0x8); 10863 10864 return TargetLowering::getSafeStackPointerLocation(IRB); 10865 } 10866 10867 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 10868 const Instruction &AndI) const { 10869 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 10870 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 10871 // may be beneficial to sink in other cases, but we would have to check that 10872 // the cmp would not get folded into the br to form a cbz for these to be 10873 // beneficial. 10874 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 10875 if (!Mask) 10876 return false; 10877 return Mask->getValue().isPowerOf2(); 10878 } 10879 10880 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10881 // Update IsSplitCSR in AArch64unctionInfo. 10882 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10883 AFI->setIsSplitCSR(true); 10884 } 10885 10886 void AArch64TargetLowering::insertCopiesSplitCSR( 10887 MachineBasicBlock *Entry, 10888 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10889 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10890 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10891 if (!IStart) 10892 return; 10893 10894 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10895 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10896 MachineBasicBlock::iterator MBBI = Entry->begin(); 10897 for (const MCPhysReg *I = IStart; *I; ++I) { 10898 const TargetRegisterClass *RC = nullptr; 10899 if (AArch64::GPR64RegClass.contains(*I)) 10900 RC = &AArch64::GPR64RegClass; 10901 else if (AArch64::FPR64RegClass.contains(*I)) 10902 RC = &AArch64::FPR64RegClass; 10903 else 10904 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10905 10906 unsigned NewVR = MRI->createVirtualRegister(RC); 10907 // Create copy from CSR to a virtual register. 10908 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10909 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10910 // nounwind. If we want to generalize this later, we may need to emit 10911 // CFI pseudo-instructions. 10912 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10913 Attribute::NoUnwind) && 10914 "Function should be nounwind in insertCopiesSplitCSR!"); 10915 Entry->addLiveIn(*I); 10916 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10917 .addReg(*I); 10918 10919 // Insert the copy-back instructions right before the terminator. 10920 for (auto *Exit : Exits) 10921 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10922 TII->get(TargetOpcode::COPY), *I) 10923 .addReg(NewVR); 10924 } 10925 } 10926 10927 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 10928 // Integer division on AArch64 is expensive. However, when aggressively 10929 // optimizing for code size, we prefer to use a div instruction, as it is 10930 // usually smaller than the alternative sequence. 10931 // The exception to this is vector division. Since AArch64 doesn't have vector 10932 // integer division, leaving the division as-is is a loss even in terms of 10933 // size, because it will have to be scalarized, while the alternative code 10934 // sequence can be performed in vector form. 10935 bool OptSize = 10936 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 10937 return OptSize && !VT.isVector(); 10938 } 10939 10940 unsigned 10941 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 10942 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 10943 return getPointerTy(DL).getSizeInBits(); 10944 10945 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 10946 } 10947